Esempio n. 1
0
 IClassInfoGraphNode addClassInfoGraphNode(ObjectSpace objectSpace, IMemberInfo memberInfo, NodeType nodeType) {
     var classInfoGraphNode =(IClassInfoGraphNode)objectSpace.CreateObject(TypesInfo.Instance.ClassInfoGraphNodeType);
     classInfoGraphNode.Name = memberInfo.Name;
     classInfoGraphNode.TypeName = getSerializedType(memberInfo).Name;
     classInfoGraphNode.NodeType=nodeType;            
     return classInfoGraphNode;
 }
 void generate(ObjectSpace objectSpace, Type typeToSerialize) {
     if (!SerializationConfigurationQuery.ConfigurationExists(objectSpace.Session, typeToSerialize))
     {
         var serializationConfiguration =
             (ISerializationConfiguration)
             objectSpace.CreateObject(TypesInfo.Instance.SerializationConfigurationType);
         serializationConfiguration.TypeToSerialize = typeToSerialize;                
         Generate(serializationConfiguration);
     }
 }
        IEnumerable<IClassInfoGraphNode> GetGraph(ObjectSpace objectSpace, Type typeToSerialize, Action<IList<IMemberInfo>> action)
        {
            var classInfoGraphNodes = new List<IClassInfoGraphNode>();

            IList<IMemberInfo> memberInfos = GetMemberInfos(typeToSerialize);
            if (action != null)
                action.Invoke(memberInfos);
            foreach (IMemberInfo memberInfo in memberInfos)
            {
                var classInfoGraphNode =
                    (IClassInfoGraphNode)objectSpace.CreateObject(TypesInfo.Instance.ClassInfoGraphNodeType);
                classInfoGraphNode.Name = memberInfo.Name;
                classInfoGraphNodes.Add(classInfoGraphNode);
                if (memberInfo.MemberTypeInfo.IsPersistent)
                    Generate(classInfoGraphNode, memberInfo.MemberTypeInfo, objectSpace, action);
                else if (memberInfo.MemberTypeInfo.IsListType)
                {
                    string name = memberInfo.Owner.Name;
                    Generate(classInfoGraphNode, memberInfo.ListElementTypeInfo, objectSpace, infos => infos.Remove(infos.Where(info => info.Name == name).Single()));
                }
            }
            return classInfoGraphNodes;
        }
Esempio n. 4
0
 private void CreateMarketingData()
 {
     Tracing.Tracer.LogText("Creating Customers and Testimonials");
     try {
         XDocument doc = XDocument.Load(GetEmbeddedResourceStream("Testimonials.xml"));
         foreach (XElement el in doc.Root.Elements())
         {
             XAttribute firstName = el.Attribute("FirstName");
             if (firstName != null)
             {
                 Customer customer = ObjectSpace.FindObject <Customer>(new BinaryOperator("FirstName", firstName.Value));
                 if (customer == null)
                 {
                     customer           = ObjectSpace.CreateObject <Customer>();
                     customer.FirstName = firstName.Value;
                     customer.Email     = customer.FirstName + "@company.com";
                     XAttribute lastName = el.Attribute("LastName");
                     if (lastName != null)
                     {
                         customer.LastName = lastName.Value;
                     }
                     XAttribute company = el.Attribute("Company");
                     if (company != null)
                     {
                         customer.Company = company.Value;
                     }
                     XAttribute occupation = el.Attribute("Occupation");
                     if (occupation != null)
                     {
                         customer.Occupation = occupation.Value;
                     }
                     XAttribute photo = el.Attribute("Photo");
                     if (photo != null)
                     {
                         customer.Photo = GetEmbeddedResourceByteArray(photo.Value);
                     }
                     else
                     {
                         customer.Photo = GetEmbeddedResourceByteArray("Unknown-user.png");
                     }
                     Testimonial testimonial = ObjectSpace.CreateObject <Testimonial>();
                     XAttribute  quote       = el.Attribute("Quote");
                     if (quote != null)
                     {
                         testimonial.Quote = quote.Value;
                     }
                     XAttribute highlight = el.Attribute("Highlight");
                     if (highlight != null)
                     {
                         testimonial.Highlight = highlight.Value;
                     }
                     XAttribute tags = el.Attribute("Tags");
                     if (tags != null)
                     {
                         testimonial.Tags = tags.Value;
                     }
                     XAttribute caseStudyUrl = el.Attribute("CaseStudyUrl");
                     if (caseStudyUrl != null)
                     {
                         testimonial.CaseStudyUrl = caseStudyUrl.Value;
                     }
                     testimonial.Customer = customer;
                 }
             }
             ObjectSpace.CommitChanges();
         }
     }
     catch (Exception ex) {
         Tracing.Tracer.LogError(ex);
     }
 }
Esempio n. 5
0
        private DevExpress.ExpressApp.Security.Strategy.SecuritySystemRole CreateSecurityDemoRole()
        {
            DevExpress.ExpressApp.Security.Strategy.SecuritySystemRole securityDemoRole = ObjectSpace.FindObject <DevExpress.ExpressApp.Security.Strategy.SecuritySystemRole>(new BinaryOperator("Name", "Demo"));
            if (securityDemoRole == null)
            {
                securityDemoRole      = ObjectSpace.CreateObject <DevExpress.ExpressApp.Security.Strategy.SecuritySystemRole>();
                securityDemoRole.Name = "Demo";

                // Type Operation Permissions
                SecuritySystemTypePermissionObject fullAccessPermission = ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                fullAccessPermission.TargetType    = typeof(FullAccessObject);
                fullAccessPermission.AllowCreate   = true;
                fullAccessPermission.AllowDelete   = true;
                fullAccessPermission.AllowNavigate = true;
                fullAccessPermission.AllowRead     = true;
                fullAccessPermission.AllowWrite    = true;
                fullAccessPermission.Save();
                securityDemoRole.TypePermissions.Add(fullAccessPermission);
                SecuritySystemTypePermissionObject protectedContentPermission = ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                protectedContentPermission.TargetType    = typeof(ProtectedContentObject);
                protectedContentPermission.AllowNavigate = true;
                protectedContentPermission.Save();
                securityDemoRole.TypePermissions.Add(protectedContentPermission);
                SecuritySystemTypePermissionObject readOnlyPermission = ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                readOnlyPermission.TargetType    = typeof(ReadOnlyObject);
                readOnlyPermission.AllowNavigate = true;
                readOnlyPermission.AllowRead     = true;
                readOnlyPermission.Save();
                securityDemoRole.TypePermissions.Add(readOnlyPermission);

                SecuritySystemTypePermissionObject irremovablePermission = ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                irremovablePermission.TargetType    = typeof(IrremovableObject);
                irremovablePermission.AllowCreate   = true;
                irremovablePermission.AllowNavigate = true;
                irremovablePermission.AllowRead     = true;
                irremovablePermission.AllowWrite    = true;
                irremovablePermission.Save();
                securityDemoRole.TypePermissions.Add(irremovablePermission);
                SecuritySystemTypePermissionObject uncreatablePermission = ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                uncreatablePermission.TargetType    = typeof(UncreatableObject);
                uncreatablePermission.AllowDelete   = true;
                uncreatablePermission.AllowNavigate = true;
                uncreatablePermission.AllowRead     = true;
                uncreatablePermission.AllowWrite    = true;
                uncreatablePermission.Save();
                securityDemoRole.TypePermissions.Add(uncreatablePermission);

                // Member Operation Permissions
                SecuritySystemTypePermissionObject navigateMemberLevelOperationObjectPermission = ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                navigateMemberLevelOperationObjectPermission.TargetType    = typeof(MemberLevelSecurityObject);
                navigateMemberLevelOperationObjectPermission.AllowCreate   = true;
                navigateMemberLevelOperationObjectPermission.AllowDelete   = true;
                navigateMemberLevelOperationObjectPermission.AllowNavigate = true;
                navigateMemberLevelOperationObjectPermission.Save();
                securityDemoRole.TypePermissions.Add(navigateMemberLevelOperationObjectPermission);

                SecuritySystemMemberPermissionsObject readWriteMemberPermission = ObjectSpace.CreateObject <SecuritySystemMemberPermissionsObject>();
                //readWriteMemberPermission.TargetType = typeof(MemberLevelSecurityObject);
                readWriteMemberPermission.Members    = "ReadWriteProperty; Name; oid; Oid; OptimisticLockField"; // TODO - Slava D - service fields - XPO responsibility
                readWriteMemberPermission.AllowRead  = true;
                readWriteMemberPermission.AllowWrite = true;
                readWriteMemberPermission.Save();
                navigateMemberLevelOperationObjectPermission.MemberPermissions.Add(readWriteMemberPermission);
                //securityDemoRole.TypePermissions.Add(readWriteMemberPermission);

                SecuritySystemMemberPermissionsObject protectedContentMemberPermission = ObjectSpace.CreateObject <SecuritySystemMemberPermissionsObject>();
                //protectedContentMemberPermission.TargetType = typeof(MemberLevelSecurityObject);
                protectedContentMemberPermission.Members = "ProtectedContentProperty; ProtectedContentCollection";
                protectedContentMemberPermission.Save();
                navigateMemberLevelOperationObjectPermission.MemberPermissions.Add(protectedContentMemberPermission);
                //securityDemoRole.TypePermissions.Add(protectedContentMemberPermission);

                SecuritySystemMemberPermissionsObject readOnlyMemberPermission = ObjectSpace.CreateObject <SecuritySystemMemberPermissionsObject>();
                //readOnlyMemberPermission.TargetType = typeof(MemberLevelSecurityObject);
                readOnlyMemberPermission.Members   = "ReadOnlyProperty; ReadOnlyCollection";
                readOnlyMemberPermission.AllowRead = true;
                readOnlyMemberPermission.Save();
                navigateMemberLevelOperationObjectPermission.MemberPermissions.Add(readOnlyMemberPermission);
                //securityDemoRole.TypePermissions.Add(readOnlyMemberPermission);

                SecuritySystemTypePermissionObject memberLevelReferencedObject1Permission = ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                memberLevelReferencedObject1Permission.TargetType  = typeof(MemberLevelReferencedObject1);
                memberLevelReferencedObject1Permission.AllowRead   = true;
                memberLevelReferencedObject1Permission.AllowWrite  = true;
                memberLevelReferencedObject1Permission.AllowCreate = true;
                memberLevelReferencedObject1Permission.AllowDelete = true;
                memberLevelReferencedObject1Permission.Save();
                securityDemoRole.TypePermissions.Add(memberLevelReferencedObject1Permission);

                SecuritySystemTypePermissionObject memberLevelReferencedObject2Permission = ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                memberLevelReferencedObject2Permission.TargetType  = typeof(MemberLevelReferencedObject2);
                memberLevelReferencedObject2Permission.AllowRead   = true;
                memberLevelReferencedObject2Permission.AllowWrite  = true;
                memberLevelReferencedObject2Permission.AllowCreate = true;
                memberLevelReferencedObject2Permission.AllowDelete = true;
                memberLevelReferencedObject2Permission.Save();
                securityDemoRole.TypePermissions.Add(memberLevelReferencedObject2Permission);



                // Object Operation Permissions
                SecuritySystemTypePermissionObject navigateObjectLevelSecurityObjectPermission = ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                navigateObjectLevelSecurityObjectPermission.TargetType    = typeof(ObjectLevelSecurityObject);
                navigateObjectLevelSecurityObjectPermission.AllowNavigate = true;
                navigateObjectLevelSecurityObjectPermission.Save();
                securityDemoRole.TypePermissions.Add(navigateObjectLevelSecurityObjectPermission);

                SecuritySystemObjectPermissionsObject fullAccessObjectPermission = ObjectSpace.CreateObject <SecuritySystemObjectPermissionsObject>();
                //fullAccessObjectPermission.TargetType = typeof(ObjectLevelSecurityObject);
                fullAccessObjectPermission.Criteria = "[Name] Like '%Fully Accessible%'";
                //fullAccessObjectPermission.AllowCreate = true;
                fullAccessObjectPermission.AllowDelete   = true;
                fullAccessObjectPermission.AllowNavigate = true;
                fullAccessObjectPermission.AllowRead     = true;
                fullAccessObjectPermission.AllowWrite    = true;
                fullAccessObjectPermission.Save();
                navigateObjectLevelSecurityObjectPermission.ObjectPermissions.Add(fullAccessObjectPermission);
                //securityDemoRole.TypePermissions.Add(fullAccessObjectPermission);

                SecuritySystemObjectPermissionsObject protectedContentObjectPermission = ObjectSpace.CreateObject <SecuritySystemObjectPermissionsObject>();
                //protectedContentObjectPermission.TargetType = typeof(ObjectLevelSecurityObject);
                protectedContentObjectPermission.Criteria      = "[Name] Like '%Protected%'";
                protectedContentObjectPermission.AllowNavigate = true;
                protectedContentObjectPermission.Save();
                navigateObjectLevelSecurityObjectPermission.ObjectPermissions.Add(protectedContentObjectPermission);
                //securityDemoRole.TypePermissions.Add(protectedContentObjectPermission);

                SecuritySystemObjectPermissionsObject readOnlyObjectPermission = ObjectSpace.CreateObject <SecuritySystemObjectPermissionsObject>();
                //readOnlyObjectPermission.TargetType = typeof(ObjectLevelSecurityObject);
                readOnlyObjectPermission.Criteria      = "[Name] Like '%Read-Only%'";
                readOnlyObjectPermission.AllowNavigate = true;
                readOnlyObjectPermission.AllowRead     = true;
                readOnlyObjectPermission.Save();
                navigateObjectLevelSecurityObjectPermission.ObjectPermissions.Add(readOnlyObjectPermission);
                //securityDemoRole.TypePermissions.Add(readOnlyObjectPermission);

                SecuritySystemObjectPermissionsObject irremovableObjectPermission = ObjectSpace.CreateObject <SecuritySystemObjectPermissionsObject>();
                //irremovableObjectPermission.TargetType = typeof(ObjectLevelSecurityObject);
                irremovableObjectPermission.Criteria = "[Name] Like '%Protected Deletion%'";
                //irremovableObjectPermission.AllowCreate = true;
                irremovableObjectPermission.AllowNavigate = true;
                irremovableObjectPermission.AllowRead     = true;
                irremovableObjectPermission.AllowWrite    = true;
                irremovableObjectPermission.Save();
                navigateObjectLevelSecurityObjectPermission.ObjectPermissions.Add(irremovableObjectPermission);
                //securityDemoRole.TypePermissions.Add(irremovableObjectPermission);

                securityDemoRole.Save();
            }
            return(securityDemoRole);
        }
Esempio n. 6
0
        private void InitContactsLocation()
        {
            Contact contactMary = FindTellitson();

            if (contactMary != null && LocationIsEmpty(contactMary))
            {
                if (contactMary.Location == null)
                {
                    contactMary.Location = ObjectSpace.CreateObject <Location>();
                }

                contactMary.Location.Contact   = contactMary;
                contactMary.Location.Latitude  = 40.620610;
                contactMary.Location.Longitude = -73.935242;
            }

            Contact contactJohn = FindContact("John", "Nilsen");

            if (contactJohn != null && LocationIsEmpty(contactJohn))
            {
                if (contactJohn.Location == null)
                {
                    contactJohn.Location = ObjectSpace.CreateObject <Location>();
                }

                contactJohn.Location.Contact   = contactJohn;
                contactJohn.Location.Latitude  = 40.711510;
                contactJohn.Location.Longitude = -73.845252;
            }

            Contact contactJanete = FindJanete();

            if (contactJanete != null && LocationIsEmpty(contactJanete))
            {
                if (contactJanete.Location == null)
                {
                    contactJanete.Location = ObjectSpace.CreateObject <Location>();
                }

                contactJanete.Location.Contact   = contactJanete;
                contactJanete.Location.Latitude  = 40.710410;
                contactJanete.Location.Longitude = -73.963262;
            }

            Contact contactKarl = FindContact("Karl", "Jablonski");

            if (contactKarl != null && LocationIsEmpty(contactKarl))
            {
                if (contactKarl.Manager == null)
                {
                    contactKarl.Manager = contactJanete;
                }
                if (contactKarl.Location == null)
                {
                    contactKarl.Location = ObjectSpace.CreateObject <Location>();
                }

                contactKarl.Location.Contact   = contactKarl;
                contactKarl.Location.Latitude  = 40.792613;
                contactKarl.Location.Longitude = -73.925142;
            }

            ObjectSpace.CommitChanges();
        }
Esempio n. 7
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
            UpdateAnalysisCriteriaColumn();

            // PermissionPolicyRole defaultRole = CreateDefaultRole();

            UpdateStatus("CreateContacts", "", "Creating contacts, departments and positions in the database...");

            ObjectSpace.CommitChanges();
            try {
                CreateDepartments();
                CreateContacts();
            }
            catch (Exception e) {
                Tracing.Tracer.LogText("Cannot initialize contacts, departments and positions from the XML file.");
                Tracing.Tracer.LogError(e);
            }
            InitContactsLocation();


            UpdateStatus("CreatePayments", "", "Creating payments, resumes and scheduler events in the database...");
            IList <Contact> topTenContacts = ObjectSpace.GetObjects <Contact>();

            ObjectSpace.SetCollectionSorting(topTenContacts, new SortProperty[] { new SortProperty("LastName", DevExpress.Xpo.DB.SortingDirection.Ascending) });
            ObjectSpace.SetTopReturnedObjectsCount(topTenContacts, 10);
            string[] notes =
            {
                "works with customers until their problems are resolved and often goes an extra step to help upset customers be completely surprised by how far we will go to satisfy customers",
                "is very good at making team members feel included. The inclusion has improved the team's productivity dramatically",
                "is very good at sharing knowledge and information during a problem to increase the chance it will be resolved quickly",
                "actively elicits feedback from customers and works to resolve their problems",
                "creates an inclusive work environment where everyone feels they are a part of the team",
                "consistently keeps up on new trends in the industry and applies these new practices to every day work",
                "is clearly not a short term thinker - the ability to set short and long term business goals is a great asset to the company",
                "seems to want to achieve all of the goals in the last few weeks before annual performance review time, but does not consistently work towards the goals throughout the year",
                "does not yet delegate effectively and has a tendency to be overloaded with tasks which should be handed off to subordinates",
                "to be discussed with the top management..."
            };
            for (int i = 0; i < topTenContacts.Count; i++)
            {
                Contact contact = topTenContacts[i];
                if (ObjectSpace.FindObject <Paycheck>(CriteriaOperator.Parse("Employee=?", contact)) == null)
                {
                    PayrollSampleDataGenerator.GenerateContactPaychecks(ObjectSpace, contact);
                    ObjectSpace.CommitChanges();
                }
                Resume resume = ObjectSpace.FindObject <Resume>(CriteriaOperator.Parse("Contact=?", contact));
                if (resume == null)
                {
                    resume = ObjectSpace.CreateObject <Resume>();
                    FileData file = ObjectSpace.CreateObject <FileData>();
                    try {
                        Stream stream = FindContactResume(contact);
                        if (stream != null)
                        {
                            file.LoadFromStream(string.Format("{0}.pdf", contact.FullName), stream);
                        }
                    }
                    catch (Exception e) {
                        Tracing.Tracer.LogText("Cannot initialize FileData for the contact {0}.", contact.FullName);
                        Tracing.Tracer.LogError(e);
                    }
                    resume.File    = file;
                    resume.Contact = contact;
                }
                Contact reviewerContact = i < 5 ? FindTellitson() : FindJanete();
                Note    note            = ObjectSpace.FindObject <Note>(CriteriaOperator.Parse("Contains(Text, ?)", contact.FullName));
                if (note == null)
                {
                    note          = ObjectSpace.CreateObject <Note>();
                    note.Author   = reviewerContact.FullName;
                    note.Text     = string.Format("<span style='color:#000000;font-family:Tahoma;font-size:8pt;'><b>{0}</b> \r\n{1}</span>", contact.FullName, notes[i]);
                    note.DateTime = DateTime.Now.AddDays(i * (-1));
                }
#if !EASYTEST
                Event appointment = ObjectSpace.FindObject <Event>(CriteriaOperator.Parse("Contains(Subject, ?)", contact.FullName));
                if (appointment == null)
                {
                    appointment             = ObjectSpace.CreateObject <Event>();
                    appointment.Subject     = string.Format("{0} - performance review", contact.FullName);
                    appointment.Description = string.Format("{0} \r\n{1}", contact.FullName, notes[i]);
                    appointment.StartOn     = note.DateTime.AddDays(5).AddHours(12);
                    appointment.EndOn       = appointment.StartOn.AddHours(2);
                    appointment.Location    = "101";
                    appointment.AllDay      = false;
                    appointment.Status      = 0;
                    appointment.Label       = i % 2 == 0 ? 2 : 5;
                    Resource reviewerContactResource = ObjectSpace.FindObject <Resource>(CriteriaOperator.Parse("Contains(Caption, ?)", reviewerContact.FullName));
                    if (reviewerContactResource == null)
                    {
                        reviewerContactResource         = ObjectSpace.CreateObject <Resource>();
                        reviewerContactResource.Caption = reviewerContact.FullName;
                        reviewerContactResource.Color   = reviewerContact == FindTellitson() ? Color.AliceBlue : Color.LightCoral;
                    }
                    appointment.Resources.Add(reviewerContactResource);
                }
#endif
            }

            ObjectSpace.CommitChanges();

            UpdateStatus("CreateTasks", "", "Creating demo tasks in the database...");

#if EASYTEST
            Contact contactMary = FindTellitson();
            Contact contactJohn = FindContact("John", "Nilsen");
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Review reports'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject            = "Review reports";
                task.AssignedTo         = contactJohn;
                task.StartDate          = DateTime.Parse("May 03, 2008");
                task.DueDate            = DateTime.Parse("September 06, 2008");
                task.Status             = DevExpress.Persistent.Base.General.TaskStatus.InProgress;
                task.Priority           = Priority.High;
                task.EstimatedWorkHours = 60;
                task.Description        = "Analyse the reports and assign new tasks to employees.";
            }

            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Fix breakfast'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject            = "Fix breakfast";
                task.AssignedTo         = contactMary;
                task.StartDate          = DateTime.Parse("May 03, 2008");
                task.DueDate            = DateTime.Parse("May 04, 2008");
                task.Status             = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority           = Priority.Low;
                task.EstimatedWorkHours = 1;
                task.ActualWorkHours    = 3;
                task.Description        = "The Development Department - by 9 a.m.\r\nThe R&QA Department - by 10 a.m.";
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task1'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject            = "Task1";
                task.AssignedTo         = contactJohn;
                task.StartDate          = DateTime.Parse("June 03, 2008");
                task.DueDate            = DateTime.Parse("June 06, 2008");
                task.Status             = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority           = Priority.High;
                task.EstimatedWorkHours = 10;
                task.ActualWorkHours    = 15;
                task.Description        = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task2'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject            = "Task2";
                task.AssignedTo         = contactJohn;
                task.StartDate          = DateTime.Parse("July 03, 2008");
                task.DueDate            = DateTime.Parse("July 06, 2008");
                task.Status             = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority           = Priority.Low;
                task.EstimatedWorkHours = 8;
                task.ActualWorkHours    = 16;
                task.Description        = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
            }
#endif
#if !EASYTEST
            IList <Contact>  contacts = ObjectSpace.GetObjects <Contact>();
            IList <DemoTask> taskList = GenerateTask(contacts);
            if (taskList.Count > 0)
            {
                Random rndGenerator = new Random();
                foreach (Contact contact in contacts)
                {
                    if (taskList.Count == 1)
                    {
                        contact.Tasks.Add(taskList[0]);
                    }
                    else if (taskList.Count == 2)
                    {
                        contact.Tasks.Add(taskList[0]);
                        contact.Tasks.Add(taskList[1]);
                    }
                    else
                    {
                        int index = rndGenerator.Next(1, taskList.Count - 2);
                        contact.Tasks.Add(taskList[index]);
                        contact.Tasks.Add(taskList[index - 1]);
                        contact.Tasks.Add(taskList[index + 1]);
                    }
                }
            }
#endif
            UpdateStatus("CreateAnalysis", "", "Creating analysis reports in the database...");
            CreateDataToBeAnalysed();
            UpdateStatus("CreateSecurityData", "", "Creating users and roles in the database...");
            #region Create a User for the Simple Security Strategy
            //// If a simple user named 'Sam' doesn't exist in the database, create this simple user
            //SecuritySimpleUser adminUser = ObjectSpace.FindObject<SecuritySimpleUser>(new BinaryOperator("UserName", "Sam"));
            //if(adminUser == null) {
            //    adminUser = ObjectSpace.CreateObject<SecuritySimpleUser>();
            //    adminUser.UserName = "******";
            //}
            //// Make the user an administrator
            //adminUser.IsAdministrator = true;
            //// Set a password if the standard authentication type is used
            //adminUser.SetPassword("");
            #endregion

            #region Create Users for the Complex Security Strategy
            // If a user named 'Sam' doesn't exist in the database, create this user
            PermissionPolicyUser user1 = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "Sam"));
            if (user1 == null)
            {
                user1          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                user1.UserName = "******";
                // Set a password if the standard authentication type is used
                user1.SetPassword("");
            }
            // If a user named 'John' doesn't exist in the database, create this user
            PermissionPolicyUser user2 = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "John"));
            if (user2 == null)
            {
                user2          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                user2.UserName = "******";
                // Set a password if the standard authentication type is used
                user2.SetPassword("");
            }
            // If a role with the Administrators name doesn't exist in the database, create this role
            PermissionPolicyRole adminRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Administrators"));
            if (adminRole == null)
            {
                adminRole      = ObjectSpace.CreateObject <PermissionPolicyRole>();
                adminRole.Name = "Administrators";
            }
            adminRole.IsAdministrative = true;

            // If a role with the Users name doesn't exist in the database, create this role
            PermissionPolicyRole userRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Users"));
            if (userRole == null)
            {
                userRole                  = ObjectSpace.CreateObject <PermissionPolicyRole>();
                userRole.Name             = "Users";
                userRole.PermissionPolicy = SecurityPermissionPolicy.AllowAllByDefault;
                userRole.AddNavigationPermission("Application/NavigationItems/Items/Default/Items/PermissionPolicyRole_ListView", SecurityPermissionState.Deny);
                userRole.AddNavigationPermission("Application/NavigationItems/Items/Default/Items/PermissionPolicyUser_ListView", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyRole>(SecurityOperations.FullAccess, SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyUser>(SecurityOperations.FullAccess, SecurityPermissionState.Deny);
                userRole.AddObjectPermission <PermissionPolicyUser>(SecurityOperations.ReadOnlyAccess, "[Oid] = CurrentUserId()", SecurityPermissionState.Allow);
                userRole.AddMemberPermission <PermissionPolicyUser>(SecurityOperations.Write, "ChangePasswordOnFirstLogon", null, SecurityPermissionState.Allow);
                userRole.AddMemberPermission <PermissionPolicyUser>(SecurityOperations.Write, "StoredPassword", null, SecurityPermissionState.Allow);
                userRole.AddTypePermission <PermissionPolicyRole>(SecurityOperations.Read, SecurityPermissionState.Allow);
                userRole.AddTypePermission <PermissionPolicyTypePermissionObject>("Write;Delete;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyMemberPermissionsObject>("Write;Delete;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyObjectPermissionsObject>("Write;Delete;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyNavigationPermissionObject>("Write;Delete;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyActionPermissionObject>("Write;Delete;Create", SecurityPermissionState.Deny);
            }

            // Add the Administrators role to the user1
            user1.Roles.Add(adminRole);
            // Add the Users role to the user2
            user2.Roles.Add(userRole);
            #endregion

            ObjectSpace.CommitChanges();
        }
Esempio n. 8
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
            UpdateAnalysisCriteriaColumn();

            // PermissionPolicyRole defaultRole = CreateDefaultRole();

            UpdateStatus("CreateContacts", "", "Creating contacts, departments and positions in the database...");
            Position developerPosition = ObjectSpace.FindObject <Position>(CriteriaOperator.Parse("Title == 'Developer'"));

            if (developerPosition == null)
            {
                developerPosition       = ObjectSpace.CreateObject <Position>();
                developerPosition.Title = "Developer";
            }
            Position managerPosition = ObjectSpace.FindObject <Position>(CriteriaOperator.Parse("Title == 'Manager'"));

            if (managerPosition == null)
            {
                managerPosition       = ObjectSpace.CreateObject <Position>();
                managerPosition.Title = "Manager";
            }

            Department devDepartment = ObjectSpace.FindObject <Department>(CriteriaOperator.Parse("Title == 'Development Department'"));

            if (devDepartment == null)
            {
                devDepartment        = ObjectSpace.CreateObject <Department>();
                devDepartment.Title  = "Development Department";
                devDepartment.Office = "205";
                devDepartment.Positions.Add(developerPosition);
                devDepartment.Positions.Add(managerPosition);
            }
            Department seoDepartment = ObjectSpace.FindObject <Department>(CriteriaOperator.Parse("Title == 'SEO'"));

            if (seoDepartment == null)
            {
                seoDepartment        = ObjectSpace.CreateObject <Department>();
                seoDepartment.Title  = "SEO";
                seoDepartment.Office = "703";
                seoDepartment.Positions.Add(developerPosition);
                seoDepartment.Positions.Add(managerPosition);
            }
            ObjectSpace.CommitChanges();

            try {
                DataTable employeesTable = GetEmployeesDataTable();
                foreach (DataRow employee in employeesTable.Rows)
                {
                    string  email   = Convert.ToString(employee["EmailAddress"]);
                    Contact contact = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("Email=?", email));
                    if (contact == null)
                    {
                        contact           = ObjectSpace.CreateObject <Contact>();
                        contact.Email     = email;
                        contact.FirstName = Convert.ToString(employee["FirstName"]);
                        contact.LastName  = Convert.ToString(employee["LastName"]);
                        contact.Birthday  = Convert.ToDateTime(employee["BirthDate"]);
                        contact.Photo     = Convert.FromBase64String(Convert.ToString(employee["ImageData"]));
                        string titleOfCourtesyText = Convert.ToString(employee["Title"]).ToLower();
                        if (!string.IsNullOrEmpty(titleOfCourtesyText))
                        {
                            titleOfCourtesyText = titleOfCourtesyText.Replace(".", "");
                            TitleOfCourtesy titleOfCourtesy;
                            if (Enum.TryParse <TitleOfCourtesy>(titleOfCourtesyText, true, out titleOfCourtesy))
                            {
                                contact.TitleOfCourtesy = titleOfCourtesy;
                            }
                        }
                        PhoneNumber phoneNumber = ObjectSpace.CreateObject <PhoneNumber>();
                        phoneNumber.Party     = contact;
                        phoneNumber.Number    = Convert.ToString(employee["Phone"]);
                        phoneNumber.PhoneType = "Work";

                        Address address = ObjectSpace.CreateObject <Address>();
                        contact.Address1      = address;
                        address.ZipPostal     = Convert.ToString(employee["PostalCode"]);
                        address.Street        = Convert.ToString(employee["AddressLine1"]);
                        address.City          = Convert.ToString(employee["City"]);
                        address.StateProvince = Convert.ToString(employee["StateProvinceName"]);
                        string  countryName = Convert.ToString(employee["CountryRegionName"]);
                        Country country     = ObjectSpace.FindObject <Country>(CriteriaOperator.Parse("Name=?", countryName), true);
                        if (country == null)
                        {
                            country      = ObjectSpace.CreateObject <Country>();
                            country.Name = countryName;
                        }
                        address.Country = country;

                        string     departmentTitle = Convert.ToString(employee["GroupName"]);
                        Department department      = ObjectSpace.FindObject <Department>(CriteriaOperator.Parse("Title=?", departmentTitle), true);
                        if (department == null)
                        {
                            department       = ObjectSpace.CreateObject <Department>();
                            department.Title = departmentTitle;
                            Random rnd = new Random();
                            department.Office = string.Format("{0}0{0}", rnd.Next(1, 7), rnd.Next(9));
                        }
                        contact.Department = department;

                        string   positionTitle = Convert.ToString(employee["JobTitle"]);
                        Position position      = ObjectSpace.FindObject <Position>(CriteriaOperator.Parse("Title=?", positionTitle), true);
                        if (position == null)
                        {
                            position       = ObjectSpace.CreateObject <Position>();
                            position.Title = positionTitle;
                            position.Departments.Add(department);
                        }
                        contact.Position = position;
                    }
                }
                ObjectSpace.CommitChanges();
            }
            catch (Exception e) {
                Tracing.Tracer.LogText("Cannot initialize contacts, departments and positions from the XML file.");
                Tracing.Tracer.LogError(e);
            }


            Contact contactMary = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Mary' && LastName == 'Tellitson'"));

            if (contactMary != null && LocationIsEmpty(contactMary))
            {
                if (contactMary.Location == null)
                {
                    contactMary.Location = ObjectSpace.CreateObject <Location>();
                }

                contactMary.Location.Contact   = contactMary;
                contactMary.Location.Latitude  = 40.620610;
                contactMary.Location.Longitude = -73.935242;
            }

            Contact contactJohn = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'John' && LastName == 'Nilsen'"));

            if (contactJohn != null && LocationIsEmpty(contactJohn))
            {
                if (contactJohn.Location == null)
                {
                    contactJohn.Location = ObjectSpace.CreateObject <Location>();
                }

                contactJohn.Location.Contact   = contactJohn;
                contactJohn.Location.Latitude  = 40.711510;
                contactJohn.Location.Longitude = -73.845252;
            }

            Contact contactJanete = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Janete' && LastName == 'Limeira'"));

            if (contactJanete != null && LocationIsEmpty(contactJanete))
            {
                if (contactJanete.Location == null)
                {
                    contactJanete.Location = ObjectSpace.CreateObject <Location>();
                }

                contactJanete.Location.Contact   = contactJanete;
                contactJanete.Location.Latitude  = 40.710410;
                contactJanete.Location.Longitude = -73.963262;
            }

            Contact contactKarl = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Karl' && LastName == 'Jablonski'"));

            if (contactKarl != null && LocationIsEmpty(contactKarl))
            {
                if (contactKarl.Manager == null)
                {
                    contactKarl.Manager = contactJanete;
                }
                if (contactKarl.Location == null)
                {
                    contactKarl.Location = ObjectSpace.CreateObject <Location>();
                }

                contactKarl.Location.Contact   = contactKarl;
                contactKarl.Location.Latitude  = 40.792613;
                contactKarl.Location.Longitude = -73.925142;
            }


            ObjectSpace.CommitChanges();


            UpdateStatus("CreatePayments", "", "Creating payments, resumes and scheduler events in the database...");
            IList <Contact> topTenContacts = ObjectSpace.GetObjects <Contact>();

            ObjectSpace.SetCollectionSorting(topTenContacts, new SortProperty[] { new SortProperty("LastName", DevExpress.Xpo.DB.SortingDirection.Ascending) });
            ObjectSpace.SetTopReturnedObjectsCount(topTenContacts, 10);
            string[] notes =
            {
                "works with customers until their problems are resolved and often goes an extra step to help upset customers be completely surprised by how far we will go to satisfy customers",
                "is very good at making team members feel included. The inclusion has improved the team's productivity dramatically",
                "is very good at sharing knowledge and information during a problem to increase the chance it will be resolved quickly",
                "actively elicits feedback from customers and works to resolve their problems",
                "creates an inclusive work environment where everyone feels they are a part of the team",
                "consistently keeps up on new trends in the industry and applies these new practices to every day work",
                "is clearly not a short term thinker - the ability to set short and long term business goals is a great asset to the company",
                "seems to want to achieve all of the goals in the last few weeks before annual performance review time, but does not consistently work towards the goals throughout the year",
                "does not yet delegate effectively and has a tendency to be overloaded with tasks which should be handed off to subordinates",
                "to be discussed with the top management..."
            };
            for (int i = 0; i < topTenContacts.Count; i++)
            {
                Contact contact = topTenContacts[i];
                Payment payment = ObjectSpace.FindObject <Payment>(CriteriaOperator.Parse("Contact=?", contact));
                if (payment == null)
                {
                    payment         = ObjectSpace.CreateObject <Payment>();
                    payment.Contact = contact;
                    payment.Hours   = new Random().Next(10, 40);
                    payment.Rate    = new Random().Next(30, 50) + new Random().Next(5, 20);
                }
                Resume resume = ObjectSpace.FindObject <Resume>(CriteriaOperator.Parse("Contact=?", contact));
                if (resume == null)
                {
                    resume = ObjectSpace.CreateObject <Resume>();
                    FileData file = ObjectSpace.CreateObject <FileData>();
                    try {
                        file.LoadFromStream(string.Format("{0}_Photo.png", contact.FullName), new MemoryStream(contact.Photo));
                    }
                    catch (Exception e) {
                        Tracing.Tracer.LogText("Cannot initialize FileData for the contact {0}.", contact.FullName);
                        Tracing.Tracer.LogError(e);
                    }
                    resume.File    = file;
                    resume.Contact = contact;
                }
                Contact reviewerContact = i < 5 ? contactMary : contactJanete;
                Note    note            = ObjectSpace.FindObject <Note>(CriteriaOperator.Parse("Contains(Text, ?)", contact.FullName));
                if (note == null)
                {
                    note          = ObjectSpace.CreateObject <Note>();
                    note.Author   = reviewerContact.FullName;
                    note.Text     = string.Format("{0} \r\n{1}", contact.FullName, notes[i]);
                    note.DateTime = DateTime.Now.AddDays(i * (-1));
                }
#if !EASYTEST
                Event appointment = ObjectSpace.FindObject <Event>(CriteriaOperator.Parse("Contains(Subject, ?)", contact.FullName));
                if (appointment == null)
                {
                    appointment             = ObjectSpace.CreateObject <Event>();
                    appointment.Subject     = string.Format("{0} - performance review", contact.FullName);
                    appointment.Description = note.Text;
                    appointment.StartOn     = note.DateTime.AddDays(5).AddHours(12);
                    appointment.EndOn       = appointment.StartOn.AddHours(2);
                    appointment.Location    = "101";
                    appointment.AllDay      = false;
                    appointment.Status      = 0;
                    appointment.Label       = i % 2 == 0 ? 2 : 5;
                    Resource reviewerContactResource = ObjectSpace.FindObject <Resource>(CriteriaOperator.Parse("Contains(Caption, ?)", reviewerContact.FullName));
                    if (reviewerContactResource == null)
                    {
                        reviewerContactResource         = ObjectSpace.CreateObject <Resource>();
                        reviewerContactResource.Caption = reviewerContact.FullName;
                        reviewerContactResource.Color   = reviewerContact == contactMary ? Color.AliceBlue : Color.LightCoral;
                    }
                    appointment.Resources.Add(reviewerContactResource);
                }
#endif
            }

            ObjectSpace.CommitChanges();

            UpdateStatus("CreateTasks", "", "Creating demo tasks in the database...");


            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Review reports'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Review reports";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("May 03, 2008");
                task.DueDate       = DateTime.Parse("September 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.InProgress;
                task.Priority      = Priority.High;
                task.EstimatedWork = 60;
                task.Description   = "Analyse the reports and assign new tasks to employees.";
            }

            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Fix breakfast'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Fix breakfast";
                task.AssignedTo    = contactMary;
                task.StartDate     = DateTime.Parse("May 03, 2008");
                task.DueDate       = DateTime.Parse("May 04, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.Low;
                task.EstimatedWork = 1;
                task.ActualWork    = 3;
                task.Description   = "The Development Department - by 9 a.m.\r\nThe R&QA Department - by 10 a.m.";
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task1'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Task1";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("June 03, 2008");
                task.DueDate       = DateTime.Parse("June 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.High;
                task.EstimatedWork = 10;
                task.ActualWork    = 15;
                task.Description   = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task2'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Task2";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("July 03, 2008");
                task.DueDate       = DateTime.Parse("July 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.Low;
                task.EstimatedWork = 8;
                task.ActualWork    = 16;
                task.Description   = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
            }
            UpdateStatus("CreateAnalysis", "", "Creating analysis reports in the database...");
            CreateDataToBeAnalysed();
            UpdateStatus("CreateSecurityData", "", "Creating users and roles in the database...");
            #region Create a User for the Simple Security Strategy
            //// If a simple user named 'Sam' doesn't exist in the database, create this simple user
            //SecuritySimpleUser adminUser = ObjectSpace.FindObject<SecuritySimpleUser>(new BinaryOperator("UserName", "Sam"));
            //if(adminUser == null) {
            //    adminUser = ObjectSpace.CreateObject<SecuritySimpleUser>();
            //    adminUser.UserName = "******";
            //}
            //// Make the user an administrator
            //adminUser.IsAdministrator = true;
            //// Set a password if the standard authentication type is used
            //adminUser.SetPassword("");
            #endregion

            #region Create Users for the Complex Security Strategy
            // If a user named 'Sam' doesn't exist in the database, create this user
            PermissionPolicyUser user1 = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "Sam"));
            if (user1 == null)
            {
                user1          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                user1.UserName = "******";
                // Set a password if the standard authentication type is used
                user1.SetPassword("");
            }
            // If a user named 'John' doesn't exist in the database, create this user
            PermissionPolicyUser user2 = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "John"));
            if (user2 == null)
            {
                user2          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                user2.UserName = "******";
                // Set a password if the standard authentication type is used
                user2.SetPassword("");
            }
            // If a role with the Administrators name doesn't exist in the database, create this role
            PermissionPolicyRole adminRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Administrators"));
            if (adminRole == null)
            {
                adminRole      = ObjectSpace.CreateObject <PermissionPolicyRole>();
                adminRole.Name = "Administrators";
            }
            adminRole.IsAdministrative = true;

            // If a role with the Users name doesn't exist in the database, create this role
            PermissionPolicyRole userRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Users"));
            if (userRole == null)
            {
                userRole                  = ObjectSpace.CreateObject <PermissionPolicyRole>();
                userRole.Name             = "Users";
                userRole.PermissionPolicy = SecurityPermissionPolicy.AllowAllByDefault;
                userRole.AddNavigationPermission("Application/NavigationItems/Items/Default/Items/PermissionPolicyRole_ListView", SecurityPermissionState.Deny);
                userRole.AddNavigationPermission("Application/NavigationItems/Items/Default/Items/PermissionPolicyUser_ListView", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyRole>(SecurityOperations.FullAccess, SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyUser>(SecurityOperations.FullAccess, SecurityPermissionState.Deny);
                userRole.AddObjectPermission <PermissionPolicyUser>(SecurityOperations.ReadOnlyAccess, "[Oid] = CurrentUserId()", SecurityPermissionState.Allow);
                userRole.AddMemberPermission <PermissionPolicyUser>(SecurityOperations.Write, "ChangePasswordOnFirstLogon", null, SecurityPermissionState.Allow);
                userRole.AddMemberPermission <PermissionPolicyUser>(SecurityOperations.Write, "StoredPassword", null, SecurityPermissionState.Allow);
                userRole.AddTypePermission <PermissionPolicyRole>(SecurityOperations.Read, SecurityPermissionState.Allow);
                userRole.AddTypePermission <PermissionPolicyTypePermissionObject>("Write;Delete;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyMemberPermissionsObject>("Write;Delete;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyObjectPermissionsObject>("Write;Delete;Create", SecurityPermissionState.Deny);
            }

            // Add the Administrators role to the user1
            user1.Roles.Add(adminRole);
            // Add the Users role to the user2
            user2.Roles.Add(userRole);
            #endregion

            ObjectSpace.CommitChanges();
        }
Esempio n. 9
0
        public static XPCollection<AccountTransactionTracking> CreateStudentClassTransactionTrackingData(ObjectSpace objectSpace, string classCode, string semesterName)
        {
            try
            {
                using (XPCollection<AccountTransactionTracking> xpw = new XPCollection<AccountTransactionTracking>(objectSpace.Session,
                               new BinaryOperator("Student.StudentClass.ClassCode", classCode)))
                {
                    objectSpace.Delete(xpw);
                    objectSpace.CommitChanges();

                    StudentClass studentClass = objectSpace.FindObject<StudentClass>(
                        new BinaryOperator("ClassCode", classCode));
                    Semester semester = objectSpace.FindObject<Semester>(
                        new BinaryOperator("SemesterName", semesterName));
                    DateTime semesterLastDate = semester.StartDate.AddDays(semester.NumberOfWeek * 7);

                    decimal beforedebtvalue=0;
                    decimal requestvalue= 0;
                    decimal paidvalue = 0;

                    if (studentClass != null && semester != null)
                    {
                        foreach (Student student in studentClass.Students)
                        {
                            beforedebtvalue = 0;
                            requestvalue = 0;
                            paidvalue = 0;
                            foreach (AccountTransaction accTrans in student.AccountTransactions)
                            {
                                if ((accTrans.Semester != null &&
                                    Convert.ToInt32(accTrans.Semester.SemesterName)<Convert.ToInt32(semester.SemesterName)))
                                //||accTrans.TransactingDate< semester.StartDate)
                                    beforedebtvalue += accTrans.MoneyAmount;
                                else if (//accTrans.TransactingDate <= semesterLastDate ||
                                    (accTrans.Semester!=null && accTrans.Semester.SemesterName ==semester.SemesterName))
                                {
                                    if (accTrans.MoneyAmount < 0) //money has to paid
                                    {
                                        requestvalue += (-accTrans.MoneyAmount);
                                    }
                                    else //money has paid
                                    {
                                        paidvalue += accTrans.MoneyAmount;
                                    }
                                }
                            }

                            AccountTransactionTracking accTracking = objectSpace.CreateObject<AccountTransactionTracking>();
                            accTracking.Student = student;
                            accTracking.Semester = semester;
                            accTracking.BeforeDebtValue = -beforedebtvalue;
                            accTracking.PaidValue= paidvalue;
                            accTracking.RequestValue = requestvalue;
                            accTracking.Save();
                        }
                        objectSpace.CommitChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException("Lỗi thực hiện: " + ex.Message);
            }
            return new XPCollection<AccountTransactionTracking>(objectSpace.Session,
                       new BinaryOperator("Student.StudentClass.ClassCode", classCode));
        }
Esempio n. 10
0
        void ImportStudentAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace      objectSpace      = Application.CreateObjectSpace();
            CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(MyImportResult));
            int count = 0;
            int iLine = 0;

            if ((collectionSource.Collection as XPBaseCollection) != null)
            {
                ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
            }

            foreach (StudentFile actFile in View.SelectedObjects)
            {
                if (actFile.Note == "")
                {
                    throw new UserFriendlyException("Vui lòng thêm thông tin Ghi chú trước khi import!!!");
                }

                string tempStudentFile;
                string tempStudentFolderPath;
                string tempStudentLogFile;
                string templogname = "";
                if (HttpContext.Current != null)
                {
                    tempStudentFolderPath = HttpContext.Current.Request.MapPath("~/tempFolder");
                    tempStudentFile       = HttpContext.Current.Request.MapPath("~/tempFolder/" + actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = HttpContext.Current.Request.MapPath("~/tempFolder/" + templogname);
                }
                else
                {
                    tempStudentFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder");
                    tempStudentFile       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", templogname);
                }

                if (!Directory.Exists(tempStudentFolderPath))
                {
                    Directory.CreateDirectory(tempStudentFolderPath);
                }

                using (System.IO.FileStream fileStream = new FileStream(tempStudentFile, FileMode.OpenOrCreate))
                {
                    Dictionary <string, int>    columnIndexs = new Dictionary <string, int>();
                    Dictionary <string, object> valueIndexs  = new Dictionary <string, object>();
                    valueIndexs.Add("MSSV", "");
                    valueIndexs.Add("HO", "");
                    valueIndexs.Add("TEN", "");
                    valueIndexs.Add("NGAYSINH", "");
                    valueIndexs.Add("LOP", "");
                    valueIndexs.Add("PHAI", "");
                    valueIndexs.Add("DANTOC", "");
                    valueIndexs.Add("NOISINH", "");
                    valueIndexs.Add("MATKHAU", "");
                    valueIndexs.Add("KHOA", "");
                    valueIndexs.Add("MANGANH", "");
                    valueIndexs.Add("TENNGANH", "");
                    valueIndexs.Add("MAKHOA", "");
                    valueIndexs.Add("TENKHOA", "");
                    valueIndexs.Add("NHHKNHAPHOC", "");
                    valueIndexs.Add("NHHKTOTNGHIEP", "");

                    columnIndexs.Add("MSSV", -1);
                    columnIndexs.Add("HO", -1);
                    columnIndexs.Add("TEN", -1);
                    columnIndexs.Add("NGAYSINH", -1);
                    columnIndexs.Add("LOP", -1);
                    columnIndexs.Add("PHAI", -1);
                    columnIndexs.Add("DANTOC", -1);
                    columnIndexs.Add("NOISINH", -1);
                    columnIndexs.Add("MATKHAU", -1);
                    columnIndexs.Add("KHOA", -1);
                    columnIndexs.Add("MANGANH", -1);
                    columnIndexs.Add("TENNGANH", -1);
                    columnIndexs.Add("MAKHOA", -1);
                    columnIndexs.Add("TENKHOA", -1);
                    columnIndexs.Add("NHHKNHAPHOC", -1);
                    columnIndexs.Add("NHHKTOTNGHIEP", -1);

                    // open xls file
                    actFile.CsvFile.SaveToStream(fileStream);
                    fileStream.Close();
                    Workbook  book  = Workbook.Open(tempStudentFile);
                    Worksheet sheet = book.Worksheets[0];


                    bool foundHeader = false;

                    Row row;
                    //Tìm dòng chứa TEN cột
                    for (iLine = sheet.Cells.FirstRowIndex;
                         iLine <= sheet.Cells.LastRowIndex && !foundHeader; iLine++)
                    {
                        row = sheet.Cells.GetRow(iLine);
                        for (int colIndex = row.FirstColIndex;
                             colIndex <= row.LastColIndex; colIndex++)
                        {
                            Cell cell = row.GetCell(colIndex);
                            if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                            {
                                columnIndexs[cell.Value.ToString().ToUpper().Trim()] = colIndex; //Đã tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                            }
                        }
                        if (!columnIndexs.Values.Contains(-1))
                        {
                            foundHeader = true;
                        }
                        else
                        {
                            for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
                            {
                                Cell cell = row.GetCell(colIndex);
                                if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                                {
                                    columnIndexs[cell.Value.ToString().ToUpper().Trim()] = -1; //không tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                                }
                            }
                        }
                    }
                    if (!foundHeader)
                    {
                        throw new UserFriendlyException("Lỗi cấu trúc file");
                    }

                    using (System.IO.StreamWriter fileStreamlog = new System.IO.StreamWriter(tempStudentLogFile, true))
                    {
                        fileStreamlog.WriteLine("<html><header><title>" + actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log </title>	"+
                                                "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" +
                                                "</head><body>\r\n<table border=\"1px\"> <tr><Th>DÒNG</Th><th>TÌNH TRẠNG</th><th>THÔNG ĐIỆP</th></Tr>");
                        //Các dòng sau đó đều là dòng dữ liệu

                        List <Student>      listStudent        = new List <Student>();
                        List <Department>   listDepartments    = new List <Department>();
                        List <Branch>       listBranchs        = new List <Branch>();
                        List <Semester>     listSemesters      = new List <Semester>();
                        List <StudentClass> listStudentClasses = new List <StudentClass>();

                        for (; iLine <= sheet.Cells.LastRowIndex; iLine++)
                        {
                            row = sheet.Cells.GetRow(iLine);
                            try
                            {
                                foreach (var column in columnIndexs)
                                {
                                    Cell cell = row.GetCell(column.Value);
                                    valueIndexs[column.Key] = cell.Value;
                                }

                                if (valueIndexs["MSSV"] == null || valueIndexs["TEN"] == null || valueIndexs["LOP"] == null || valueIndexs["MATKHAU"] == null)
                                {
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                            string.Format("Can not import line with  [MSSV or TEN or LOP or MATKHAU] is NULL on {0:dd-mm-yy HH:MM:ss}", DateTime.Now));
                                    continue;
                                }
                                //tạo khoa
                                Department dept;
                                if (valueIndexs["MAKHOA"] == null)
                                {
                                    dept = null;
                                }
                                else
                                {
                                    dept = listDepartments.Find(l => l.DepartmentCode == valueIndexs["MAKHOA"].ToString());
                                    if (dept == null)
                                    {
                                        dept = objectSpace.FindObject <Department>(new BinaryOperator("DepartmentCode", valueIndexs["MAKHOA"].ToString()));
                                    }
                                    if (dept != null)
                                    {
                                        if (valueIndexs["TENKHOA"] == null || dept.DepartmentName != valueIndexs["TENKHOA"].ToString())
                                        {
                                            fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                    string.Format("Department: \"{0}\" has name \"{1}\" different to \"{2}\" on {3:dd-mm-yy HH:MM:ss}",
                                                                                  dept.DepartmentCode, dept.DepartmentName, valueIndexs["TENKHOA"], DateTime.Now));
                                        }
                                        if (!listDepartments.Contains(dept))
                                        {
                                            listDepartments.Add(dept);
                                        }
                                    }
                                    else
                                    {
                                        dept = objectSpace.CreateObject <Department>();
                                        dept.DepartmentCode = valueIndexs["MAKHOA"].ToString();
                                        dept.DepartmentName = valueIndexs["TENKHOA"] == null ? null : valueIndexs["TENKHOA"].ToString();
                                        dept.Save();
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create new department: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}",
                                                                              dept.DepartmentCode, dept.DepartmentName, DateTime.Now));
                                        listDepartments.Add(dept);
                                    }
                                }
                                Branch branch;
                                if (valueIndexs["MANGANH"] == null)
                                {
                                    branch = null;
                                }
                                else
                                {
                                    branch = listBranchs.Find(l => l.BranchCode == valueIndexs["MANGANH"].ToString().Trim());
                                    if (branch == null)
                                    {
                                        branch = objectSpace.FindObject <Branch>(new BinaryOperator("BranchCode", valueIndexs["MANGANH"].ToString().Trim()));
                                    }
                                    if (branch != null)
                                    {
                                        if (valueIndexs["TENNGANH"] == null || branch.BranchName != valueIndexs["TENNGANH"].ToString())
                                        {
                                            fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                    string.Format("Branch: \"{0}\" has name \"{1}\" different to \"{2}\" on {3:dd-mm-yy HH:MM:ss}",
                                                                                  branch.BranchCode, branch.BranchName, valueIndexs["TENNGANH"], DateTime.Now));
                                        }
                                        if (!listBranchs.Contains(branch))
                                        {
                                            listBranchs.Add(branch);
                                        }
                                    }
                                    else
                                    {
                                        branch = objectSpace.CreateObject <Branch>();

                                        branch.BranchCode = valueIndexs["MANGANH"].ToString().Trim();
                                        branch.BranchName = valueIndexs["TENNGANH"] == null?null:valueIndexs["TENNGANH"].ToString().Trim();
                                        branch.Department = dept;
                                        branch.Save();
                                        listBranchs.Add(branch);
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create new branch: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}",
                                                                              branch.BranchCode, branch.BranchName, DateTime.Now));
                                    }
                                }
                                Semester semester;
                                if (valueIndexs["NHHKNHAPHOC"] == null)
                                {
                                    semester = null;
                                }
                                else
                                {
                                    semester = listSemesters.Find(l => l.SemesterName == valueIndexs["NHHKNHAPHOC"].ToString());
                                    if (semester == null)
                                    {
                                        semester = objectSpace.FindObject <Semester>(new BinaryOperator("SemesterName", valueIndexs["NHHKNHAPHOC"].ToString()));
                                    }
                                    if (semester != null)
                                    {
                                        if (!listSemesters.Contains(semester))
                                        {
                                            listSemesters.Add(semester);
                                        }
                                    }
                                    else
                                    {
                                        semester = objectSpace.CreateObject <Semester>();
                                        semester.SemesterName = valueIndexs["NHHKNHAPHOC"].ToString();
                                        semester.Save();
                                        listSemesters.Add(semester);
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create new semester: \"{0}\" on {1:dd-mm-yy HH:MM:ss}",
                                                                              semester.SemesterName, DateTime.Now));
                                    }
                                }
                                Semester semesterGraduate;
                                if (valueIndexs["NHHKTOTNGHIEP"] == null)
                                {
                                    semesterGraduate = null;
                                }
                                else
                                {
                                    semesterGraduate = listSemesters.Find(l => l.SemesterName == valueIndexs["NHHKTOTNGHIEP"].ToString());

                                    if (semesterGraduate == null)
                                    {
                                        semesterGraduate = objectSpace.FindObject <Semester>(new BinaryOperator("SemesterName", valueIndexs["NHHKTOTNGHIEP"].ToString()));
                                    }
                                    if (semesterGraduate != null)
                                    {
                                        if (!listSemesters.Contains(semesterGraduate))
                                        {
                                            listSemesters.Add(semesterGraduate);
                                        }
                                    }
                                    else
                                    {
                                        semesterGraduate = objectSpace.CreateObject <Semester>();
                                        semesterGraduate.SemesterName = valueIndexs["NHHKTOTNGHIEP"].ToString();
                                        semesterGraduate.Save();
                                        listSemesters.Add(semesterGraduate);
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create new semester: \"{0}\" on {1:dd-mm-yy HH:MM:ss}",
                                                                              semesterGraduate.SemesterName, DateTime.Now));
                                    }
                                }
                                StudentClass studClass = listStudentClasses.Find(
                                    l => l.ClassCode == valueIndexs["LOP"].ToString());
                                if (studClass == null)
                                {
                                    studClass = objectSpace.FindObject <StudentClass>(
                                        new BinaryOperator("ClassCode", valueIndexs["LOP"].ToString()));
                                }
                                if (studClass != null)
                                {
                                    if (studClass.ClassName != valueIndexs["LOP"].ToString() ||
                                        studClass.Branch != branch ||
                                        studClass.EnrollSemester != semester ||
                                        studClass.GraduateSemester != semesterGraduate)
                                    {
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                string.Format("StudentClass: \"{0}\" has name [{1}] branch[{2}] enrollsemester [{3}] graduate semester [{4}] different to" +
                                                                              "[{5}]-[{6}]-[{7}]-[{8}] on {9:dd-mm-yy HH:MM:ss}",
                                                                              studClass.ClassCode, studClass.ClassName, studClass.Branch, studClass.EnrollSemester, studClass.GraduateSemester,
                                                                              valueIndexs["LOP"].ToString(), branch, semester, semesterGraduate,
                                                                              DateTime.Now));
                                    }
                                    if (!listStudentClasses.Contains(studClass))
                                    {
                                        listStudentClasses.Add(studClass);
                                    }
                                }
                                else
                                {
                                    studClass = objectSpace.CreateObject <StudentClass>();

                                    studClass.ClassCode        = valueIndexs["LOP"].ToString();
                                    studClass.ClassName        = valueIndexs["LOP"].ToString();
                                    studClass.Branch           = branch;
                                    studClass.EnrollSemester   = semester;
                                    studClass.GraduateSemester = semesterGraduate;
                                    studClass.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                            string.Format("Create new class: \"{0}\" on {1:dd-mm-yy HH:MM:ss}", valueIndexs["LOP"],
                                                                          DateTime.Now));
                                }

                                //tạo sinh viên
                                Student student = objectSpace.FindObject <Student>(new BinaryOperator("StudentCode", valueIndexs["MSSV"].ToString()));
                                if (student != null)
                                {
                                    student.ChangePasswordOnFirstLogon = true;
                                    student.UserName     = valueIndexs["MSSV"].ToString();
                                    student.StudentClass = studClass;
                                    student.FirstName    = valueIndexs["HO"] == null?null:valueIndexs["HO"].ToString();
                                    student.LastName     = valueIndexs["TEN"].ToString();
                                    try
                                    {
                                        DateTime d = new DateTime(1900, 1, 1).AddDays(
                                            Double.Parse(valueIndexs["NGAYSINH"].ToString()) - 2);
                                        student.BirthdayText = d.ToString("dd/MM/yyyy");
                                    }
                                    catch
                                    {
                                        student.BirthdayText = valueIndexs["NGAYSINH"] == null ? null : valueIndexs["NGAYSINH"].ToString();
                                    }
                                    student.BirthPlace = valueIndexs["NOISINH"] == null ? null : valueIndexs["NOISINH"].ToString();
                                    student.Ethnic     = valueIndexs["DANTOC"] == null ? null : valueIndexs["DANTOC"].ToString();
                                    if (valueIndexs["PHAI"] == null || valueIndexs["PHAI"].ToString().Trim() == "0" || valueIndexs["PHAI"].ToString().Trim() == "Nam")
                                    {
                                        student.IsFemale = false;
                                    }
                                    else if (valueIndexs["PHAI"].ToString().Trim() == "1" || valueIndexs["PHAI"].ToString().Trim() == "Nữ")
                                    {
                                        student.IsFemale = true;
                                    }
                                    else
                                    {
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                string.Format("PHAI value must be \"Nam\" or \"0\" or \"1\" or \"Nữ\", read value was \"{0}\" on {1:dd-mm-yy HH:MM:ss}",
                                                                              valueIndexs["PHAI"].ToString().Trim(), DateTime.Now));
                                    }
                                    student.Course = valueIndexs["KHOA"] == null ? null : valueIndexs["KHOA"].ToString();
                                    student.SetPassword(valueIndexs["MATKHAU"].ToString());

                                    Role studRole = objectSpace.FindObject <Role>(new BinaryOperator("Name", "Students"));
                                    student.Roles.Add(studRole);
                                    studRole = objectSpace.FindObject <Role>(new BinaryOperator("Name", "Users"));
                                    student.Roles.Add(studRole);
                                    student.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "UPDATE",
                                                            string.Format("Update student: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}", student.StudentCode, student.FullName, DateTime.Now));
                                }
                                else
                                {
                                    student = objectSpace.CreateObject <Student>();

                                    student.ChangePasswordOnFirstLogon = true;
                                    student.UserName     = valueIndexs["MSSV"].ToString();
                                    student.StudentClass = studClass;
                                    student.FirstName    = valueIndexs["HO"] == null ? null : valueIndexs["HO"].ToString();
                                    student.LastName     = valueIndexs["TEN"].ToString();
                                    student.BirthdayText = valueIndexs["NGAYSINH"] == null ? null : valueIndexs["NGAYSINH"].ToString();
                                    student.BirthPlace   = valueIndexs["NOISINH"] == null ? null : valueIndexs["NOISINH"].ToString();
                                    student.Ethnic       = valueIndexs["DANTOC"] == null ? null : valueIndexs["DANTOC"].ToString();
                                    if (valueIndexs["PHAI"] == null || valueIndexs["PHAI"].ToString() == "0")
                                    {
                                        student.IsFemale = false;
                                    }
                                    else if (valueIndexs["PHAI"].ToString() == "1")
                                    {
                                        student.IsFemale = true;
                                    }
                                    student.Course = valueIndexs["KHOA"] == null ? null : valueIndexs["KHOA"].ToString();
                                    student.SetPassword(valueIndexs["MATKHAU"].ToString());

                                    Role studRole = objectSpace.FindObject <Role>(new BinaryOperator("Name", "Students"));
                                    student.Roles.Add(studRole);
                                    studRole = objectSpace.FindObject <Role>(new BinaryOperator("Name", "Users"));
                                    student.Roles.Add(studRole);

                                    student.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                            string.Format("Create student: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}",
                                                                          student.StudentCode, student.FullName, DateTime.Now));
                                }
                                objectSpace.CommitChanges();
                                count++;
                            }
                            catch (Exception ex)
                            {
                                fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                        ex.Message + ex.StackTrace);
                            }
                        }
                        fileStreamlog.WriteLine("</table></body></html>");
                        fileStreamlog.Close();
                    }

                    View.ObjectSpace.SetModified(actFile);
                    actFile.IsImported = true;
                    actFile.ResultLink = "/tempFolder/" + templogname;

                    View.ObjectSpace.CommitChanges();
                }
            }
            PopUpMessage     ms;
            DialogController dc;

            ms         = objectSpace.CreateObject <PopUpMessage>();
            ms.Title   = "Kết quả import";
            ms.Message = string.Format("Đã thực hiện import {0} kết quả cho {1} dòng trong file\r\n Vui lòng xem link kết quả", count, iLine);
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(
                objectSpace, ms);
            e.ShowViewParameters.TargetWindow        = TargetWindow.NewModalWindow;
            e.ShowViewParameters.CreatedView.Caption = "Thông báo";
            dc = Application.CreateController <DialogController>();
            dc.AcceptAction.Active.SetItemValue("object", false);
            dc.CancelAction.Caption = "Đóng";
            dc.SaveOnAccept         = false;
            e.ShowViewParameters.Controllers.Add(dc);
        }
Esempio n. 11
0
        public void AutoreconcileBankStmtToCashFlow()
        {
            #region Arrange Forex objects
            // Currencies
            var ccyAUD = ObjectSpace.FindObject <Currency>(CriteriaOperator.Parse("Name = ?", "AUD"));
            var ccyUSD = ObjectSpace.FindObject <Currency>(CriteriaOperator.Parse("Name = ?", "USD"));

            // Forex Rates
            var rate = ObjectSpace.CreateObject <ForexRate>();
            rate.ConversionDate = new DateTime(2013, 11, 01);
            rate.FromCurrency   = ccyAUD;
            rate.ToCurrency     = ccyUSD;
            rate.ConversionRate = 0.9M;
            rate.Save();
            ObjectSpace.CommitChanges();

            // Constants
            decimal rate1 = 0.95M;
            decimal rate3 = 0.87M;
            decimal rate2 = 0.99M;

            #endregion

            #region Arrange Lookup Objects

            var priAccount = ObjectSpace.CreateObject <Account>();
            priAccount.Name     = "VHA ANZ 70086";
            priAccount.Currency = ccyAUD;

            var couAccount = ObjectSpace.CreateObject <Account>();
            couAccount.Name     = "VHA ANZ USD";
            couAccount.Currency = ccyUSD;

            var forexActivity = ObjectSpace.GetObjectByKey <Activity>(SetOfBooks.CachedInstance.ForexSettleActivity.Oid);

            var outActivity = ObjectSpace.CreateObject <Activity>();
            outActivity.Name = "AP Pymt";

            var outCounterparty = ObjectSpace.CreateObject <Counterparty>();
            outCounterparty.Name = "UNDEFINED";

            var inCounterparty = ObjectSpace.CreateObject <Counterparty>();
            inCounterparty.Name = "ANZ";

            var forexCounterparty = ObjectSpace.CreateObject <ForexCounterparty>();
            forexCounterparty.Name = "ANZ";
            forexCounterparty.CashFlowCounterparty = inCounterparty;
            #endregion

            #region Create Cash Flow Forex Trade Objects

            var cfCouForex1 = ObjectSpace.CreateObject <CashFlow>();
            cfCouForex1.CalculateEnabled = false;
            cfCouForex1.TranDate         = new DateTime(2013, 11, 16);
            cfCouForex1.Account          = couAccount;
            cfCouForex1.Activity         = forexActivity;
            cfCouForex1.Counterparty     = inCounterparty;
            cfCouForex1.AccountCcyAmt    = 100;
            cfCouForex1.FunctionalCcyAmt = 100 / rate1;
            cfCouForex1.CounterCcyAmt    = 100;
            cfCouForex1.CounterCcy       = ccyUSD;
            cfCouForex1.ForexSettleType  = CashFlowForexSettleType.In;
            cfCouForex1.Description      = "cfCouForex1";
            cfCouForex1.Save();

            var cfPriForex1 = ObjectSpace.CreateObject <CashFlow>();
            cfPriForex1.CalculateEnabled = false;
            cfPriForex1.TranDate         = new DateTime(2013, 11, 16);
            cfPriForex1.Account          = priAccount;
            cfPriForex1.Activity         = forexActivity;
            cfPriForex1.Counterparty     = inCounterparty;
            cfPriForex1.AccountCcyAmt    = -100 / rate1;
            cfPriForex1.FunctionalCcyAmt = -100 / rate1;
            cfPriForex1.CounterCcyAmt    = 100;
            cfPriForex1.CounterCcy       = ccyUSD;
            cfPriForex1.ForexSettleType  = CashFlowForexSettleType.In;
            cfPriForex1.Description      = "cfPriForex1";
            cfPriForex1.Save();

            var cfCouForex2 = ObjectSpace.CreateObject <CashFlow>();
            cfCouForex2.CalculateEnabled = false;
            cfCouForex2.TranDate         = new DateTime(2013, 11, 30);
            cfCouForex2.Account          = couAccount;
            cfCouForex2.Activity         = forexActivity;
            cfCouForex2.Counterparty     = inCounterparty;
            cfCouForex2.AccountCcyAmt    = 50;
            cfCouForex2.FunctionalCcyAmt = 50 / rate2;
            cfCouForex2.CounterCcyAmt    = 50;
            cfCouForex2.CounterCcy       = ccyUSD;
            cfCouForex2.ForexSettleType  = CashFlowForexSettleType.In;
            cfCouForex2.Description      = "cfCouForex2";
            cfCouForex2.Save();

            var cfPriForex2 = ObjectSpace.CreateObject <CashFlow>();
            cfPriForex2.CalculateEnabled = false;
            cfPriForex2.TranDate         = new DateTime(2013, 11, 30);
            cfPriForex2.Account          = priAccount;
            cfPriForex2.Activity         = forexActivity;
            cfPriForex2.Counterparty     = inCounterparty;
            cfPriForex2.AccountCcyAmt    = -50 / rate2;
            cfPriForex2.FunctionalCcyAmt = -50 / rate2;
            cfPriForex2.CounterCcyAmt    = -50;
            cfPriForex2.CounterCcy       = ccyUSD;
            cfPriForex2.ForexSettleType  = CashFlowForexSettleType.In;
            cfPriForex2.Description      = "cfPriForex2";
            cfPriForex2.Save();

            var cfCouForex3 = ObjectSpace.CreateObject <CashFlow>();
            cfCouForex3.CalculateEnabled = false;
            cfCouForex3.TranDate         = new DateTime(2013, 11, 30);
            cfCouForex3.Account          = couAccount;
            cfCouForex3.Activity         = forexActivity;
            cfCouForex3.Counterparty     = inCounterparty;
            cfCouForex3.AccountCcyAmt    = 30;
            cfCouForex3.FunctionalCcyAmt = 30 / rate3;
            cfCouForex3.CounterCcyAmt    = 30;
            cfCouForex3.CounterCcy       = ccyUSD;
            cfCouForex3.ForexSettleType  = CashFlowForexSettleType.In;
            cfCouForex3.Description      = "cfCouForex3";
            cfCouForex3.Save();

            var cfPriForex3 = ObjectSpace.CreateObject <CashFlow>();
            cfPriForex3.CalculateEnabled = false;
            cfPriForex3.TranDate         = new DateTime(2013, 11, 30);
            cfPriForex3.Account          = priAccount;
            cfPriForex3.Activity         = forexActivity;
            cfPriForex3.Counterparty     = inCounterparty;
            cfPriForex3.AccountCcyAmt    = -30 / rate3;
            cfPriForex3.FunctionalCcyAmt = -30 / rate3;
            cfPriForex3.CounterCcyAmt    = -30;
            cfPriForex3.CounterCcy       = ccyUSD;
            cfPriForex3.ForexSettleType  = CashFlowForexSettleType.In;
            cfPriForex3.Description      = "cfPriForex3";
            cfPriForex3.Save();

            #endregion

            #region Arrange Bank Stmt Forex Trade objects

            var bsCouForex1 = ObjectSpace.CreateObject <BankStmt>();
            bsCouForex1.TranDate           = new DateTime(2013, 11, 16);
            bsCouForex1.Account            = couAccount;
            bsCouForex1.Activity           = forexActivity;
            bsCouForex1.Counterparty       = outCounterparty;
            bsCouForex1.TranAmount         = 100;
            bsCouForex1.ForexSettleType    = CashFlowForexSettleType.In;
            bsCouForex1.SummaryDescription = "bsCouForex1";
            bsCouForex1.Save();

            var bsPriForex1 = ObjectSpace.CreateObject <BankStmt>();
            bsPriForex1.TranDate           = new DateTime(2013, 11, 16);
            bsPriForex1.Account            = priAccount;
            bsPriForex1.Activity           = forexActivity;
            bsPriForex1.Counterparty       = outCounterparty;
            bsPriForex1.TranAmount         = -100 / rate1;
            bsPriForex1.ForexSettleType    = CashFlowForexSettleType.In;
            bsPriForex1.SummaryDescription = "bsPriForex1";
            bsPriForex1.Save();

            var bsCouForex2 = ObjectSpace.CreateObject <BankStmt>();
            bsCouForex2.TranDate           = new DateTime(2013, 11, 30);
            bsCouForex2.Account            = couAccount;
            bsCouForex2.Activity           = forexActivity;
            bsCouForex2.Counterparty       = outCounterparty;
            bsCouForex2.TranAmount         = 50;
            bsCouForex2.ForexSettleType    = CashFlowForexSettleType.In;
            bsCouForex2.SummaryDescription = "bsCouForex2";
            bsCouForex2.Save();

            var bsPriForex2 = ObjectSpace.CreateObject <BankStmt>();
            bsPriForex2.TranDate           = new DateTime(2013, 11, 30);
            bsPriForex2.Account            = priAccount;
            bsPriForex2.Activity           = forexActivity;
            bsPriForex2.Counterparty       = outCounterparty;
            bsPriForex2.TranAmount         = -50 / rate2;
            bsPriForex2.ForexSettleType    = CashFlowForexSettleType.In;
            bsPriForex2.SummaryDescription = "bsPriForex2";
            bsPriForex2.Save();

            var bsCouForex3 = ObjectSpace.CreateObject <BankStmt>();
            bsCouForex3.TranDate           = new DateTime(2013, 11, 30);
            bsCouForex3.Account            = couAccount;
            bsCouForex3.Activity           = forexActivity;
            bsCouForex3.Counterparty       = outCounterparty;
            bsCouForex3.TranAmount         = 30;
            bsCouForex3.ForexSettleType    = CashFlowForexSettleType.In;
            bsCouForex3.SummaryDescription = "bsCouForex3";
            bsCouForex3.Save();

            var bsPriForex3 = ObjectSpace.CreateObject <BankStmt>();
            bsPriForex3.TranDate           = new DateTime(2013, 11, 30);
            bsPriForex3.Account            = priAccount;
            bsPriForex3.Activity           = forexActivity;
            bsPriForex3.Counterparty       = outCounterparty;
            bsPriForex3.TranAmount         = -30 / rate3;
            bsPriForex3.ForexSettleType    = CashFlowForexSettleType.In;
            bsPriForex3.SummaryDescription = "bsPriForex3";
            bsPriForex3.Save();

            #endregion

            #region Act Autoreconciliation

            ObjectSpace.CommitChanges();
            var bankStmts  = ObjectSpace.GetObjects <BankStmt>();
            var reconciler = new BankStmtForecastReconciler((XPObjectSpace)ObjectSpace);
            reconciler.AutoreconcileTransfers(bankStmts);

            #endregion

            #region Assert
            Assert.AreEqual(0, bankStmts.Sum(x => x.FunctionalCcyAmt));
            Assert.AreEqual(6, bankStmts.Where(x => x.Activity.Name == forexActivity.Name).Count());
            Assert.AreEqual(6, bankStmts.Where(x => x.Counterparty.Name == inCounterparty.Name).Count());
            #endregion
        }
Esempio n. 12
0
        public void ReconcileBankStmtToCashFlowSnapshot()
        {
            #region Arrange Forex objects
            // Currencies
            var ccyAUD = ObjectSpace.FindObject <Currency>(CriteriaOperator.Parse("Name = ?", "AUD"));
            var ccyUSD = ObjectSpace.FindObject <Currency>(CriteriaOperator.Parse("Name = ?", "USD"));

            // Forex Rates
            var rate = ObjectSpace.CreateObject <ForexRate>();
            rate.ConversionDate = new DateTime(2013, 11, 01);
            rate.FromCurrency   = ccyAUD;
            rate.ToCurrency     = ccyUSD;
            rate.ConversionRate = 0.9M;
            rate.Save();
            ObjectSpace.CommitChanges();

            // Constants
            decimal rate1 = 0.95M;
            #endregion

            #region Arrange Lookup Objects

            var priAccount = ObjectSpace.CreateObject <Account>();
            priAccount.Name     = "VHA ANZ 70086";
            priAccount.Currency = ccyAUD;

            var couAccount = ObjectSpace.CreateObject <Account>();
            couAccount.Name     = "VHA ANZ USD";
            couAccount.Currency = ccyUSD;

            var forexActivity = SetOfBooks.GetInstance(ObjectSpace).ForexSettleActivity;

            var outActivity = ObjectSpace.CreateObject <Activity>();
            outActivity.Name = "AP Pymt";

            var outCounterparty = ObjectSpace.CreateObject <Counterparty>();
            outCounterparty.Name = "UNDEFINED";

            var inCounterparty = ObjectSpace.CreateObject <Counterparty>();
            inCounterparty.Name = "ANZ";

            var forexCounterparty = ObjectSpace.CreateObject <ForexCounterparty>();
            forexCounterparty.Name = "ANZ";
            forexCounterparty.CashFlowCounterparty = inCounterparty;

            var snapshot1 = ObjectSpace.CreateObject <CashFlowSnapshot>();
            snapshot1.Name = "Snapshot 1";
            #endregion


            #region Create Cash Flow Forex Trade Objects

            var cfCouForex1 = ObjectSpace.CreateObject <CashFlow>();
            cfCouForex1.CalculateEnabled = false;
            cfCouForex1.TranDate         = new DateTime(2013, 11, 16);
            cfCouForex1.Account          = couAccount;
            cfCouForex1.Activity         = forexActivity;
            cfCouForex1.Counterparty     = inCounterparty;
            cfCouForex1.AccountCcyAmt    = 100;
            cfCouForex1.FunctionalCcyAmt = 100 / rate1;
            cfCouForex1.CounterCcyAmt    = 100;
            cfCouForex1.CounterCcy       = ccyUSD;
            cfCouForex1.ForexSettleType  = CashFlowForexSettleType.In;
            cfCouForex1.Description      = "cfCouForex1";
            cfCouForex1.Save();

            var cfPriForex1 = ObjectSpace.CreateObject <CashFlow>();
            cfPriForex1.CalculateEnabled = false;
            cfPriForex1.TranDate         = new DateTime(2013, 11, 16);
            cfPriForex1.Account          = priAccount;
            cfPriForex1.Activity         = forexActivity;
            cfPriForex1.Counterparty     = inCounterparty;
            cfPriForex1.AccountCcyAmt    = -100 / rate1;
            cfPriForex1.FunctionalCcyAmt = -100 / rate1;
            cfPriForex1.CounterCcyAmt    = 100;
            cfPriForex1.CounterCcy       = ccyUSD;
            cfPriForex1.ForexSettleType  = CashFlowForexSettleType.In;
            cfPriForex1.Description      = "cfPriForex1";
            cfPriForex1.Save();

            var cfCouForex1a = ObjectSpace.CreateObject <CashFlow>();
            cfCouForex1a.CalculateEnabled = false;
            cfCouForex1a.TranDate         = new DateTime(2013, 11, 16);
            cfCouForex1a.Account          = couAccount;
            cfCouForex1a.Activity         = forexActivity;
            cfCouForex1a.Counterparty     = inCounterparty;
            cfCouForex1a.AccountCcyAmt    = 100;
            cfCouForex1a.FunctionalCcyAmt = 100 / rate1;
            cfCouForex1a.CounterCcyAmt    = 100;
            cfCouForex1a.CounterCcy       = ccyUSD;
            cfCouForex1a.ForexSettleType  = CashFlowForexSettleType.In;
            cfCouForex1a.Description      = "cfCouForex1a";
            cfCouForex1a.Snapshot         = snapshot1;
            cfCouForex1a.Save();

            var cfPriForex1a = ObjectSpace.CreateObject <CashFlow>();
            cfPriForex1a.CalculateEnabled = false;
            cfPriForex1a.TranDate         = new DateTime(2013, 11, 16);
            cfPriForex1a.Account          = priAccount;
            cfPriForex1a.Activity         = forexActivity;
            cfPriForex1a.Counterparty     = inCounterparty;
            cfPriForex1a.AccountCcyAmt    = -100 / rate1;
            cfPriForex1a.FunctionalCcyAmt = -100 / rate1;
            cfPriForex1a.CounterCcyAmt    = 100;
            cfPriForex1a.CounterCcy       = ccyUSD;
            cfPriForex1a.ForexSettleType  = CashFlowForexSettleType.In;
            cfPriForex1a.Description      = "cfPriForex1a";
            cfPriForex1a.Snapshot         = snapshot1;
            cfPriForex1a.Save();

            #endregion

            #region Arrange Bank Stmt Forex Trade objects

            var bsCouForex1 = ObjectSpace.CreateObject <BankStmt>();
            bsCouForex1.TranDate           = new DateTime(2013, 11, 16);
            bsCouForex1.Account            = couAccount;
            bsCouForex1.Activity           = forexActivity;
            bsCouForex1.Counterparty       = outCounterparty;
            bsCouForex1.TranAmount         = 100;
            bsCouForex1.ForexSettleType    = CashFlowForexSettleType.In;
            bsCouForex1.SummaryDescription = "bsCouForex1";
            bsCouForex1.Save();

            var bsPriForex1 = ObjectSpace.CreateObject <BankStmt>();
            bsPriForex1.TranDate           = new DateTime(2013, 11, 16);
            bsPriForex1.Account            = priAccount;
            bsPriForex1.Activity           = forexActivity;
            bsPriForex1.Counterparty       = outCounterparty;
            bsPriForex1.TranAmount         = -100 / rate1;
            bsPriForex1.ForexSettleType    = CashFlowForexSettleType.In;
            bsPriForex1.SummaryDescription = "bsPriForex1";
            bsPriForex1.Save();

            #endregion

            #region Reconcile Bank Stmt

            ObjectSpace.CommitChanges();
            var bankStmts  = ObjectSpace.GetObjects <BankStmt>();
            var reconciler = new BankStmtForecastReconciler((XPObjectSpace)ObjectSpace);
            BankStmtCashFlowForecast bsCff = reconciler.ReconcileItem(bsCouForex1, cfCouForex1a);
            ObjectSpace.CommitChanges();
            #endregion

            #region Assert
            Assert.AreEqual("cfCouForex1a", bsCouForex1.SummaryDescription);
            #endregion
        }
Esempio n. 13
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
            //string name = "MyName";
            //DomainObject1 theObject = ObjectSpace.FindObject<DomainObject1>(CriteriaOperator.Parse("Name=?", name));
            //if(theObject == null) {
            //    theObject = ObjectSpace.CreateObject<DomainObject1>();
            //    theObject.Name = name;
            //}
            PermissionPolicyUser sampleUser = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "User"));

            if (sampleUser == null)
            {
                sampleUser          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                sampleUser.UserName = "******";
                sampleUser.SetPassword("");
            }
            PermissionPolicyRole defaultRole = CreateDefaultRole();

            sampleUser.Roles.Add(defaultRole);

            PermissionPolicyUser userAdmin = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "Admin"));

            if (userAdmin == null)
            {
                userAdmin          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                userAdmin.UserName = "******";
                // Set a password if the standard authentication type is used
                userAdmin.SetPassword("");
            }
            // If a role with the Administrators name doesn't exist in the database, create this role
            PermissionPolicyRole adminRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Administrators"));

            if (adminRole == null)
            {
                adminRole      = ObjectSpace.CreateObject <PermissionPolicyRole>();
                adminRole.Name = "Administrators";
            }
            adminRole.IsAdministrative = true;
            userAdmin.Roles.Add(adminRole);
            if (ObjectSpace.GetObjectsCount(typeof(Employee), null) == 0)
            {
                Employee Employee1 = ObjectSpace.CreateObject <Employee>();
                Employee1.EmployeeID = "001";
                Employee Employee2 = ObjectSpace.CreateObject <Employee>();
                Employee2.EmployeeID = "002";
            }

            if (ObjectSpace.GetObjectsCount(typeof(Product), null) == 0)
            {
                Product product = ObjectSpace.CreateObject <Product>();
                product.Name        = "Chai";
                product.Description = "is a tea beverage made by boiling black tea in milk and water with a mixture of aromatic herbs and spices[2]. Originating in India,[3] the beverage has gained worldwide popularity, becoming a feature in many coffee and tea houses. Although traditionally prepared as a decoction of green cardamom pods, cinnamon sticks, ground cloves, ground ginger, and black peppercorn together with black tea leaves, retail versions include tea bags for infusion, instant powdered mixtures, and concentrates.";
                for (int i = 0; i < 10; i++)
                {
                    Order order = ObjectSpace.CreateObject <Order>();
                    if (i % 2 == 0)
                    {
                        order.EmployeeID = "001";
                    }
                    else
                    {
                        order.EmployeeID = "002";
                    }
                    order.Product     = product;
                    order.Description = "Order " + i.ToString();
                }
                Order ExtraOrder = ObjectSpace.CreateObject <Order>();
                ExtraOrder.EmployeeID = "001";
                ExtraOrder.Product    = product;
            }
            if (ObjectSpace.GetObjectsCount(typeof(Person), null) == 0)
            {
                Person person = ObjectSpace.CreateObject <Person>();
                person.FirstName = "Jose";
                person.LastName  = "Ojeda";

                PhoneNumber RussianPhone = ObjectSpace.CreateObject <PhoneNumber>();
                RussianPhone.Number = "+7986532147";


                PhoneNumber SalvadoreanPhone = ObjectSpace.CreateObject <PhoneNumber>();
                SalvadoreanPhone.Number = "+5036532147";

                person.PhoneNumbers.Add(SalvadoreanPhone);
                person.PhoneNumbers.Add(RussianPhone);
            }



            ObjectSpace.CommitChanges(); //This line persists created object(s).
        }
Esempio n. 14
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
            //string name = "MyName";
            //DomainObject1 theObject = ObjectSpace.FindObject<DomainObject1>(CriteriaOperator.Parse("Name=?", name));
            //if(theObject == null) {
            //    theObject = ObjectSpace.CreateObject<DomainObject1>();
            //    theObject.Name = name;
            //}
            PermissionPolicyUser sampleUser = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "User"));

            if (sampleUser == null)
            {
                sampleUser          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                sampleUser.UserName = "******";
                sampleUser.SetPassword("");
            }
            PermissionPolicyRole defaultRole = CreateDefaultRole();

            sampleUser.Roles.Add(defaultRole);

            PermissionPolicyUser userAdmin = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "Admin"));

            if (userAdmin == null)
            {
                userAdmin          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                userAdmin.UserName = "******";
                // Set a password if the standard authentication type is used
                userAdmin.SetPassword("");
            }
            // If a role with the Administrators name doesn't exist in the database, create this role
            PermissionPolicyRole adminRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Administrators"));

            if (adminRole == null)
            {
                adminRole      = ObjectSpace.CreateObject <PermissionPolicyRole>();
                adminRole.Name = "Administrators";
            }
            adminRole.IsAdministrative = true;
            userAdmin.Roles.Add(adminRole);

            Company company = ObjectSpace.FindObject <Company>(new BinaryOperator("Name", "Demo"));

            if (company == null)
            {
                company      = ObjectSpace.CreateObject <Company>();
                company.Name = "Demo";
                company.Code = "Demo";
            }

            Series series = ObjectSpace.FindObject <Series>(new BinaryOperator("Name", "Order"));

            if (series == null)
            {
                series      = ObjectSpace.CreateObject <Series>();
                series.Name = "Order";
                series.Code = "Order";
            }

            series = ObjectSpace.FindObject <Series>(new BinaryOperator("Name", "Invoice"));
            if (series == null)
            {
                series      = ObjectSpace.CreateObject <Series>();
                series.Name = "Invoice";
                series.Code = "Invoice";
            }
            series = ObjectSpace.FindObject <Series>(new BinaryOperator("Name", "Delivery"));
            if (series == null)
            {
                series      = ObjectSpace.CreateObject <Series>();
                series.Name = "Delivery";
                series.Code = "Delivery";
            }

            ObjectSpace.CommitChanges(); //This line persists created object(s).
        }
Esempio n. 15
0
        private void PrzygotujDaneTestowe()
        {
            var stawki = ObjectSpace.GetObjectsQuery <StawkaVAT>().ToList();

            if (stawki.Count == 0)
            {
                stawki.Add(NowaStawka("23%", 23M));
                stawki.Add(NowaStawka("0%", 0M));
                stawki.Add(NowaStawka("7%", 7M));
                stawki.Add(NowaStawka("ZW", 0M));
            }

            var adrFaker = new Faker <AdresKlienta>("pl")
                           .CustomInstantiator(f => ObjectSpace.CreateObject <AdresKlienta>())
                           .RuleFor(o => o.Miejscowosc, f => f.Address.City())
                           .RuleFor(o => o.KodPocztowy, f => f.Address.ZipCode())
                           .RuleFor(o => o.Ulica, f => f.Address.StreetName());
            var adresses = adrFaker.Generate(200);

            ObjectSpace.CommitChanges();


            var cusFaker = new Faker <Klient>("pl")
                           .CustomInstantiator(f => ObjectSpace.CreateObject <Klient>())
                           .RuleFor(o => o.Telefon, f => f.Person.Phone)
                           .RuleFor(o => o.Skrot, f => f.Company.CompanyName())
                           .RuleFor(o => o.Nazwa, f => f.Company.CompanyName())
                           .RuleFor(o => o.Email, (f, u) => f.Internet.Email())
                           .RuleFor(o => o.AdresSiedziby, f => f.PickRandom(adresses))
                           .RuleFor(o => o.InnyAdresKorespondecyjny, true)
                           .RuleFor(o => o.AdresKorespondencyjny, f => f.PickRandom(adresses));


            var customers = cusFaker.Generate(100);

            ObjectSpace.CommitChanges();

            var conFaker = new Faker <Kontakt>("pl")
                           .CustomInstantiator(f => ObjectSpace.CreateObject <Kontakt>())
                           .RuleFor(o => o.Imie, f => f.Person.FirstName)
                           .RuleFor(o => o.Nazwisko, f => f.Person.LastName)
                           .RuleFor(o => o.Nazwisko, f => f.Person.LastName)
                           .RuleFor(o => o.Email, (f, u) => f.Internet.Email())
                           .RuleFor(o => o.Telefon, f => f.Person.Phone);

            var contacts = conFaker.Generate(10000);

            ObjectSpace.CommitChanges();



            var meetFaker = new Faker <Spotkanie>("pl")
                            .CustomInstantiator(f => ObjectSpace.CreateObject <Spotkanie>())
                            .RuleFor(o => o.Klient, f => f.PickRandom(customers))
                            .RuleFor(o => o.StartOn, f => f.Date.Soon(10));
            var meetings = meetFaker.Generate(1000);



            var prodFaker = new Faker <Produkt>("pl")
                            .CustomInstantiator(f => ObjectSpace.CreateObject <Produkt>())
                            .RuleFor(o => o.Nazwa, f => f.Commerce.ProductName())
                            .RuleFor(o => o.StawkaVAT, f => f.PickRandom(stawki))
                            .RuleFor(o => o.Cena, f => f.Random.Decimal(0.01M, 1000M));

            var products = prodFaker.Generate(100);

            WygenerujFaktury(1000, customers, products);
        }
Esempio n. 16
0
 public void OnCreated()
 {
     Person = ObjectSpace.CreateObject <Person>();
     Photo  = ObjectSpace.CreateObject <MediaDataObject>();
 }
Esempio n. 17
0
        public void UpdateSimpleHeaderCsv()
        {
            // arrange parameters

            var map1 = ObjectSpace.CreateObject <HeaderToFieldMap>();

            map1.SourceName = "Description";
            map1.TargetName = map1.SourceName;
            map1.IsKeyField = true;

            var map2 = ObjectSpace.CreateObject <HeaderToFieldMap>();

            map2.SourceName = "Amount";
            map2.TargetName = map2.SourceName;

            var param = ObjectSpace.CreateObject <ImportHeadersParam>();

            param.HeaderToFieldMaps.Add(map1);
            param.HeaderToFieldMaps.Add(map2);

            param.ObjectTypeName = "MockFactObject";

            // arrange XPO objects

            var obj1 = ObjectSpace.CreateObject <MockFactObject>();

            obj1.Description = "Hello 1";
            obj1.Amount      = 10;

            var obj2 = ObjectSpace.CreateObject <MockFactObject>();

            obj2.Description = "Hello 2";
            obj2.Amount      = 20;

            var obj3 = ObjectSpace.CreateObject <MockFactObject>();

            obj3.Description = "Hello 3";
            obj3.Amount      = 30;

            ObjectSpace.CommitChanges();

            // arrange loader

            string csvText = @"Description,Amount
Hello 1,100
Hello 2,200
Hello 3,300";

            var             csvStream      = ConvertToCsvStream(csvText);
            var             request        = ObjectSpace.CreateObject <ImportRequest>();
            var             logger         = new ImportLogger(request);
            var             xpoFieldMapper = new XpoFieldMapper();
            ICsvToXpoLoader loader         = new HeadCsvToXpoUpdater(param, csvStream, xpoFieldMapper, logger);

            // act

            loader.Execute();

            // assert
            var updated = new XPQuery <MockFactObject>(ObjectSpace.Session);

            Assert.AreEqual(3, updated.Count()); // returns 6 because it inserts instead of updates

            MockFactObject result = updated.Where(x => x.Description == "Hello 1").FirstOrDefault();

            Assert.AreEqual(100, result.Amount);

            result = updated.Where(x => x.Description == "Hello 2").FirstOrDefault();
            Assert.AreEqual(200, result.Amount);

            result = updated.Where(x => x.Description == "Hello 3").FirstOrDefault();
            Assert.AreEqual(300, result.Amount);
        }
Esempio n. 18
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
            UpdateAnalysisCriteriaColumn();

            // PermissionPolicyRole defaultRole = CreateDefaultRole();

            Position developerPosition = ObjectSpace.FindObject <Position>(CriteriaOperator.Parse("Title == 'Developer'"));

            if (developerPosition == null)
            {
                developerPosition       = ObjectSpace.CreateObject <Position>();
                developerPosition.Title = "Developer";
            }
            Position managerPosition = ObjectSpace.FindObject <Position>(CriteriaOperator.Parse("Title == 'Manager'"));

            if (managerPosition == null)
            {
                managerPosition       = ObjectSpace.CreateObject <Position>();
                managerPosition.Title = "Manager";
            }

            Department devDepartment = ObjectSpace.FindObject <Department>(CriteriaOperator.Parse("Title == 'Development Department'"));

            if (devDepartment == null)
            {
                devDepartment        = ObjectSpace.CreateObject <Department>();
                devDepartment.Title  = "Development Department";
                devDepartment.Office = "205";
                devDepartment.Positions.Add(developerPosition);
                devDepartment.Positions.Add(managerPosition);
            }
            Department seoDepartment = ObjectSpace.FindObject <Department>(CriteriaOperator.Parse("Title == 'SEO'"));

            if (seoDepartment == null)
            {
                seoDepartment        = ObjectSpace.CreateObject <Department>();
                seoDepartment.Title  = "SEO";
                seoDepartment.Office = "703";
                seoDepartment.Positions.Add(developerPosition);
                seoDepartment.Positions.Add(managerPosition);
            }
            ImageConverter imageConverter = new ImageConverter();
            Contact        contactMary    = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Mary' && LastName == 'Tellitson'"));

            if (contactMary == null)
            {
                contactMary            = ObjectSpace.CreateObject <Contact>();
                contactMary.FirstName  = "Mary";
                contactMary.LastName   = "Tellitson";
                contactMary.Email      = "*****@*****.**";
                contactMary.Birthday   = new DateTime(1980, 11, 27);
                contactMary.Department = devDepartment;
                contactMary.Notes      = "In duties included control software components";
                contactMary.Position   = managerPosition;
                contactMary.Photo      = (byte[])imageConverter.ConvertTo(ImageLoader.Instance.GetImageInfo("Tellitson_Mary_Photo").Image, typeof(byte[]));
            }
            if (LocationIsEmpty(contactMary))
            {
                if (contactMary.Location == null)
                {
                    contactMary.Location = ObjectSpace.CreateObject <Location>();
                }

                contactMary.Location.Contact   = contactMary;
                contactMary.Location.Latitude  = 40.620610;
                contactMary.Location.Longitude = -73.935242;
            }

            Contact contactJohn = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'John' && LastName == 'Nilsen'"));

            if (contactJohn == null)
            {
                contactJohn            = ObjectSpace.CreateObject <Contact>();
                contactJohn.FirstName  = "John";
                contactJohn.LastName   = "Nilsen";
                contactJohn.Email      = "*****@*****.**";
                contactJohn.Birthday   = new DateTime(1981, 10, 3);
                contactJohn.Department = devDepartment;
                contactJohn.Position   = developerPosition;
                contactJohn.Notes      = "In duties included development of software modules";
                contactJohn.Photo      = (byte[])imageConverter.ConvertTo(ImageLoader.Instance.GetImageInfo("Nilsen_John_Photo").Image, typeof(byte[]));
            }
            if (LocationIsEmpty(contactJohn))
            {
                if (contactJohn.Location == null)
                {
                    contactJohn.Location = ObjectSpace.CreateObject <Location>();
                }

                contactJohn.Location.Contact   = contactJohn;
                contactJohn.Location.Latitude  = 40.711510;
                contactJohn.Location.Longitude = -73.845252;
            }

            Contact contactJanete = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Janete' && LastName == 'Limeira'"));

            if (contactJanete == null)
            {
                contactJanete = ObjectSpace.CreateObject <Contact>();
                contactJanete.TitleOfCourtesy = TitleOfCourtesy.Miss;
                contactJanete.FirstName       = "Janete";
                contactJanete.LastName        = "Limeira";
                contactJanete.Email           = "*****@*****.**";
                contactJanete.Birthday        = new DateTime(1981, 12, 21);
                contactJanete.Department      = devDepartment;
                contactJanete.Position        = managerPosition;
                contactJanete.Notes           = "In duties included control software components";
                contactJanete.Photo           = (byte[])imageConverter.ConvertTo(ImageLoader.Instance.GetImageInfo("Limeira_Janete_Photo").Image, typeof(byte[]));
            }
            if (LocationIsEmpty(contactJanete))
            {
                if (contactJanete.Location == null)
                {
                    contactJanete.Location = ObjectSpace.CreateObject <Location>();
                }

                contactJanete.Location.Contact   = contactJanete;
                contactJanete.Location.Latitude  = 40.710410;
                contactJanete.Location.Longitude = -73.963262;
            }

            Contact contactKarl = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Karl' && LastName == 'Jablonski'"));

            if (contactKarl == null)
            {
                contactKarl            = ObjectSpace.CreateObject <Contact>();
                contactKarl.FirstName  = "Karl";
                contactKarl.LastName   = "Jablonski";
                contactKarl.Email      = " [email protected]";
                contactKarl.Birthday   = new DateTime(1975, 12, 19);
                contactKarl.Department = devDepartment;
                contactKarl.Position   = developerPosition;
                contactKarl.Manager    = contactJanete;
                contactKarl.Notes      = "In duties included  development of software modules";
                contactKarl.Photo      = (byte[])imageConverter.ConvertTo(ImageLoader.Instance.GetImageInfo("Jablonski_Karl_Photo").Image, typeof(byte[]));
            }
            if (LocationIsEmpty(contactKarl))
            {
                if (contactKarl.Location == null)
                {
                    contactKarl.Location = ObjectSpace.CreateObject <Location>();
                }

                contactKarl.Location.Contact   = contactKarl;
                contactKarl.Location.Latitude  = 40.792613;
                contactKarl.Location.Longitude = -73.925142;
            }

            Contact contactCatherine = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Catherine' && LastName == 'Dewey'"));

            if (contactCatherine == null)
            {
                contactCatherine = ObjectSpace.CreateObject <Contact>();
                contactCatherine.TitleOfCourtesy = TitleOfCourtesy.Miss;
                contactCatherine.FirstName       = "Catherine";
                contactCatherine.LastName        = "Dewey";
                contactCatherine.Email           = "catherine_ [email protected]";
                contactCatherine.Birthday        = new DateTime(1993, 7, 9);
                contactCatherine.Department      = seoDepartment;
                contactCatherine.Position        = managerPosition;
                contactCatherine.Notes           = "In duties included control software components";
                contactCatherine.Photo           = (byte[])imageConverter.ConvertTo(ImageLoader.Instance.GetImageInfo("Dewey_Catherine_Photo").Image, typeof(byte[]));
            }
            if (LocationIsEmpty(contactCatherine))
            {
                if (contactCatherine.Location == null)
                {
                    contactCatherine.Location = ObjectSpace.CreateObject <Location>();
                }

                contactCatherine.Location.Contact   = contactCatherine;
                contactCatherine.Location.Latitude  = 40.711510;
                contactCatherine.Location.Longitude = -73.967212;
            }

            Contact contactPaul = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Paul' && LastName == 'Henriot'"));

            if (contactPaul == null)
            {
                contactPaul = ObjectSpace.CreateObject <Contact>();
                contactPaul.TitleOfCourtesy = TitleOfCourtesy.Mr;
                contactPaul.FirstName       = "Paul";
                contactPaul.LastName        = "Henriot";
                contactPaul.Email           = "*****@*****.**";
                contactPaul.Birthday        = new DateTime(1958, 1, 30);
                contactPaul.Department      = seoDepartment;
                contactPaul.Position        = developerPosition;
                contactPaul.Notes           = "In duties included  development of software modules";
                contactPaul.Photo           = (byte[])imageConverter.ConvertTo(ImageLoader.Instance.GetImageInfo("Henriot_Paul_Photo").Image, typeof(byte[]));
            }
            if (LocationIsEmpty(contactPaul))
            {
                if (contactPaul.Location == null)
                {
                    contactPaul.Location = ObjectSpace.CreateObject <Location>();
                }

                contactPaul.Location.Contact   = contactPaul;
                contactPaul.Location.Latitude  = 40.759613;
                contactPaul.Location.Longitude = -73.914252;
            }

            Contact contactElizabeth = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Elizabeth' && LastName == 'Lincoln'"));

            if (contactElizabeth == null)
            {
                contactElizabeth = ObjectSpace.CreateObject <Contact>();
                contactElizabeth.TitleOfCourtesy = TitleOfCourtesy.Ms;
                contactElizabeth.FirstName       = "Elizabeth";
                contactElizabeth.LastName        = "Lincoln";
                contactElizabeth.Email           = "*****@*****.**";
                contactElizabeth.Birthday        = new DateTime(1988, 3, 14);
                contactElizabeth.Department      = seoDepartment;
                contactElizabeth.Position        = managerPosition;
                contactElizabeth.Manager         = contactCatherine;
                contactElizabeth.Notes           = "In duties included control software components";
                contactElizabeth.Photo           = (byte[])imageConverter.ConvertTo(ImageLoader.Instance.GetImageInfo("Lincoln_Elizabeth_Photo").Image, typeof(byte[]));
            }
            if (LocationIsEmpty(contactElizabeth))
            {
                if (contactElizabeth.Location == null)
                {
                    contactElizabeth.Location = ObjectSpace.CreateObject <Location>();
                }

                contactElizabeth.Location.Contact   = contactElizabeth;
                contactElizabeth.Location.Latitude  = 40.700600;
                contactElizabeth.Location.Longitude = -73.937210;
            }

            Contact contactDaniel = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Daniel' && LastName == 'Tonini'"));

            if (contactDaniel == null)
            {
                contactDaniel            = ObjectSpace.CreateObject <Contact>();
                contactDaniel.FirstName  = "Daniel";
                contactDaniel.LastName   = "Tonini";
                contactDaniel.Email      = "*****@*****.**";
                contactDaniel.Birthday   = new DateTime(1980, 12, 30);
                contactDaniel.Department = seoDepartment;
                contactDaniel.Notes      = "In duties included development of software modules";
                contactDaniel.Position   = developerPosition;
                contactDaniel.Manager    = contactElizabeth;
                contactDaniel.Photo      = (byte[])imageConverter.ConvertTo(ImageLoader.Instance.GetImageInfo("Tonini_Daniel_Photo").Image, typeof(byte[]));
            }
            if (LocationIsEmpty(contactDaniel))
            {
                if (contactDaniel.Location == null)
                {
                    contactDaniel.Location = ObjectSpace.CreateObject <Location>();
                }

                contactDaniel.Location.Contact   = contactDaniel;
                contactDaniel.Location.Latitude  = 40.711640;
                contactDaniel.Location.Longitude = -73.924246;
            }

            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Review reports'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Review reports";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("May 03, 2008");
                task.DueDate       = DateTime.Parse("September 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.InProgress;
                task.Priority      = Priority.High;
                task.EstimatedWork = 60;
                task.Description   = "Analyse the reports and assign new tasks to employees.";
            }

            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Fix breakfast'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Fix breakfast";
                task.AssignedTo    = contactMary;
                task.StartDate     = DateTime.Parse("May 03, 2008");
                task.DueDate       = DateTime.Parse("May 04, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.Low;
                task.EstimatedWork = 1;
                task.ActualWork    = 3;
                task.Description   = "The Development Department - by 9 a.m.\r\nThe R&QA Department - by 10 a.m.";
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task1'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Task1";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("June 03, 2008");
                task.DueDate       = DateTime.Parse("June 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.High;
                task.EstimatedWork = 10;
                task.ActualWork    = 15;
                task.Description   = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task2'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Task2";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("July 03, 2008");
                task.DueDate       = DateTime.Parse("July 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.Low;
                task.EstimatedWork = 8;
                task.ActualWork    = 16;
                task.Description   = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
            }
            UpdateStatus("CreateAnalysis", "", "Creating analysis reports in the database...");
            CreateDataToBeAnalysed();
            UpdateStatus("CreateSecurityData", "", "Creating users and roles in the database...");
            #region Create a User for the Simple Security Strategy
            //// If a simple user named 'Sam' doesn't exist in the database, create this simple user
            //SecuritySimpleUser adminUser = ObjectSpace.FindObject<SecuritySimpleUser>(new BinaryOperator("UserName", "Sam"));
            //if(adminUser == null) {
            //    adminUser = ObjectSpace.CreateObject<SecuritySimpleUser>();
            //    adminUser.UserName = "******";
            //}
            //// Make the user an administrator
            //adminUser.IsAdministrator = true;
            //// Set a password if the standard authentication type is used
            //adminUser.SetPassword("");
            #endregion

            #region Create Users for the Complex Security Strategy
            // If a user named 'Sam' doesn't exist in the database, create this user
            PermissionPolicyUser user1 = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "Sam"));
            if (user1 == null)
            {
                user1          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                user1.UserName = "******";
                // Set a password if the standard authentication type is used
                user1.SetPassword("");
            }
            // If a user named 'John' doesn't exist in the database, create this user
            PermissionPolicyUser user2 = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "John"));
            if (user2 == null)
            {
                user2          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                user2.UserName = "******";
                // Set a password if the standard authentication type is used
                user2.SetPassword("");
            }
            // If a role with the Administrators name doesn't exist in the database, create this role
            PermissionPolicyRole adminRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Administrators"));
            if (adminRole == null)
            {
                adminRole      = ObjectSpace.CreateObject <PermissionPolicyRole>();
                adminRole.Name = "Administrators";
            }
            adminRole.IsAdministrative = true;

            // If a role with the Users name doesn't exist in the database, create this role
            PermissionPolicyRole userRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Users"));
            if (userRole == null)
            {
                userRole                  = ObjectSpace.CreateObject <PermissionPolicyRole>();
                userRole.Name             = "Users";
                userRole.PermissionPolicy = SecurityPermissionPolicy.AllowAllByDefault;
                userRole.AddTypePermission <PermissionPolicyRole>(SecurityOperations.FullAccess, SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyUser>(SecurityOperations.FullAccess, SecurityPermissionState.Deny);
                userRole.AddObjectPermission <PermissionPolicyUser>(SecurityOperations.ReadOnlyAccess, "[Oid] = CurrentUserId()", SecurityPermissionState.Allow);
                userRole.AddMemberPermission <PermissionPolicyUser>(SecurityOperations.Write, "ChangePasswordOnFirstLogon", null, SecurityPermissionState.Allow);
                userRole.AddMemberPermission <PermissionPolicyUser>(SecurityOperations.Write, "StoredPassword", null, SecurityPermissionState.Allow);
                userRole.AddTypePermission <PermissionPolicyRole>(SecurityOperations.Read, SecurityPermissionState.Allow);
                userRole.AddTypePermission <PermissionPolicyTypePermissionObject>("Write;Delete;Navigate;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyMemberPermissionsObject>("Write;Delete;Navigate;Create", SecurityPermissionState.Deny);
                userRole.AddTypePermission <PermissionPolicyObjectPermissionsObject>("Write;Delete;Navigate;Create", SecurityPermissionState.Deny);
            }

            // Add the Administrators role to the user1
            user1.Roles.Add(adminRole);
            // Add the Users role to the user2
            user2.Roles.Add(userRole);
            #endregion

            ObjectSpace.CommitChanges();
        }
Esempio n. 19
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();

            #region Security
            PermissionPolicyUser sampleUser = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "User"));
            if (sampleUser == null)
            {
                sampleUser          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                sampleUser.UserName = "******";
                sampleUser.SetPassword("");
            }
            PermissionPolicyRole defaultRole = CreateDefaultRole();
            sampleUser.Roles.Add(defaultRole);

            PermissionPolicyUser userAdmin = ObjectSpace.FindObject <PermissionPolicyUser>(new BinaryOperator("UserName", "Admin"));
            if (userAdmin == null)
            {
                userAdmin          = ObjectSpace.CreateObject <PermissionPolicyUser>();
                userAdmin.UserName = "******";
                // Set a password if the standard authentication type is used
                userAdmin.SetPassword("");
            }
            // If a role with the Administrators name doesn't exist in the database, create this role
            PermissionPolicyRole adminRole = ObjectSpace.FindObject <PermissionPolicyRole>(new BinaryOperator("Name", "Administrators"));
            if (adminRole == null)
            {
                adminRole      = ObjectSpace.CreateObject <PermissionPolicyRole>();
                adminRole.Name = "Administrators";
            }
            adminRole.IsAdministrative = true;
            userAdmin.Roles.Add(adminRole);
            #endregion

            #region Location
            // Province
            using (StreamReader sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("MintaXAF.Module.DatabaseUpdate.Data.Province.json")))
            {
                dynamic lstProvince = JsonConvert.DeserializeObject(sr.ReadToEnd());
                foreach (var item in lstProvince.Province)
                {
                    Province province = ObjectSpace.FindObject <Province>(new BinaryOperator("Code", item.code.Value));
                    if (province == null)
                    {
                        province       = ObjectSpace.CreateObject <Province>();
                        province.Code  = item.code.Value;
                        province.Title = item.name_with_type.Value;
                        province.Save();
                    }
                }
            }
            // District
            using (StreamReader sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("MintaXAF.Module.DatabaseUpdate.Data.District.json")))
            {
                dynamic lstDistrict = JsonConvert.DeserializeObject(sr.ReadToEnd());
                foreach (var item in lstDistrict.District)
                {
                    District district = ObjectSpace.FindObject <District>(new BinaryOperator("Code", item.code.Value));
                    Province province = ObjectSpace.FindObject <Province>(new BinaryOperator("Code", item.parent_code.Value));
                    if (district == null && province != null)
                    {
                        district       = ObjectSpace.CreateObject <District>();
                        district.Code  = item.code.Value;
                        district.Title = item.name_with_type.Value;
                        province.Districts.Add(district);
                        district.Save();
                    }
                }
            }

            // Commune
            using (StreamReader sr = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("MintaXAF.Module.DatabaseUpdate.Data.Commune.json")))
            {
                dynamic lstCommune = JsonConvert.DeserializeObject(sr.ReadToEnd());
                foreach (var item in lstCommune.Commune)
                {
                    Commune  commune  = ObjectSpace.FindObject <Commune>(new BinaryOperator("Code", item.code.Value));
                    District district = ObjectSpace.FindObject <District>(new BinaryOperator("Code", item.parent_code.Value));
                    if (commune == null && district != null)
                    {
                        commune          = ObjectSpace.CreateObject <Commune>();
                        commune.Code     = item.code.Value;
                        commune.Title    = item.name_with_type.Value;
                        commune.Province = district.Province;
                        district.Communes.Add(commune);
                        commune.Save();
                    }
                }
            }
            #endregion

            ObjectSpace.CommitChanges(); //This line persists created object(s).
        }
Esempio n. 20
0
        private void DefaultRegister_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();

            dicStudentRegDetail = new Dictionary <string, List <string> >();
            Student currentStudent;
            Lesson  curLesson;
            Dictionary <string, List <string> > errorstudent           = new Dictionary <string, List <string> >();
            Dictionary <string, int>            dicLessonCurrentRegNum = new Dictionary <string, int>();
            int     numregok = 0;
            Vacancy vc;
            bool    isConflictTKB = false;

            using (XPCollection <Lesson> newCollectionSource = new XPCollection <Lesson>(objectSpace.Session))
            {
                objectSpace.Session.BeginTransaction();
                foreach (StudentClass studentClass in View.SelectedObjects)
                {
                    newCollectionSource.Criteria = CriteriaOperator.Parse(
                        "ClassIDs like ?", string.Format("%{0}%", studentClass.ClassCode));

                    foreach (Student student in studentClass.Students)
                    {
                        listVacancies  = new List <Vacancy>();
                        currentStudent = objectSpace.FindObject <Student>(
                            new BinaryOperator("StudentCode", student.StudentCode));

                        foreach (Lesson lesson in newCollectionSource)
                        {
                            isConflictTKB = false;
                            if (!dicLessonCurrentRegNum.ContainsKey(lesson.LessonName))
                            {
                                dicLessonCurrentRegNum[lesson.LessonName] = 0;
                            }
                            foreach (TkbSemester tkbsem in lesson.TKBSemesters)
                            {
                                vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
                                if (Utils.IsConfictTKB(listVacancies, vc))
                                {
                                    isConflictTKB = true;
                                    break;
                                }
                            }

                            if (isConflictTKB)
                            {
                                if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                {
                                    errorstudent.Add(currentStudent.StudentCode, new List <string>());
                                }
                                if (!errorstudent[currentStudent.StudentCode].Contains(lesson.Subject.SubjectCode))
                                {
                                    errorstudent[currentStudent.StudentCode].Add(lesson.Subject.SubjectCode + "{T}");
                                }
                            }
                            else
                            {
                                //si so chon chua vuot qua
                                if (lesson.NumExpectation > dicLessonCurrentRegNum[lesson.LessonName] + lesson.NumRegistration)
                                {
                                    curLesson = objectSpace.FindObject <Lesson>(
                                        new BinaryOperator("Oid", lesson.Oid));
                                    RegisterDetail regdetail = new RegisterDetail(objectSpace.Session)
                                    {
                                        Student       = currentStudent,
                                        Lesson        = curLesson,
                                        RegisterState = objectSpace.FindObject <RegisterState>(
                                            new BinaryOperator("Code", "SELECTED")),
                                        CheckState = objectSpace.FindObject <RegisterState>(
                                            new BinaryOperator("Code", "NOTCHECKED"))
                                    };
                                    RuleSet ruleSet = new RuleSet();

                                    RuleSetValidationResult result = ruleSet.ValidateTarget(regdetail, DefaultContexts.Save);
                                    if (ValidationState.Invalid ==
                                        result.GetResultItem("RegisterDetail.StudentRegLessonSemester").State)
                                    {
                                        if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                        {
                                            errorstudent.Add(currentStudent.StudentCode, new List <string>());
                                        }
                                        if (!errorstudent[currentStudent.StudentCode].Contains(curLesson.Subject.SubjectCode))
                                        {
                                            errorstudent[currentStudent.StudentCode].Add(curLesson.Subject.SubjectCode + "{D}");
                                        }
                                        regdetail.Delete();
                                        //regdetail.Reload();
                                    }
                                    else
                                    {
                                        numregok++;
                                        if (!dicStudentRegDetail.ContainsKey(student.StudentCode))
                                        {
                                            dicStudentRegDetail.Add(student.StudentCode, new List <string>());
                                        }
                                        dicStudentRegDetail[student.StudentCode].Add(curLesson.LessonName);

                                        dicLessonCurrentRegNum[lesson.LessonName]++;
                                        foreach (TkbSemester tkbsem in curLesson.TKBSemesters)
                                        {
                                            vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
                                            listVacancies.Add(vc);
                                        }
                                        regdetail.Save();
                                    }
                                }
                                else
                                {
                                    if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                    {
                                        errorstudent.Add(currentStudent.StudentCode, new List <string>());
                                    }
                                    if (!errorstudent[currentStudent.StudentCode].Contains(lesson.Subject.SubjectCode))
                                    {
                                        errorstudent[currentStudent.StudentCode].Add(lesson.Subject.SubjectCode + "{H}");
                                    }
                                }
                            }
                        }
                    }
                }
                objectSpace.Session.CommitTransaction();
                PopUpMessage ms = objectSpace.CreateObject <PopUpMessage>();
                if (errorstudent.Count > 0)
                {
                    ms.Title   = "Có lỗi khi chọn nhóm MH đăng ký!";
                    ms.Message = string.Format("Đã chọn được cho {0} sinh viên với {1} lượt nhóm MH\r\n", dicStudentRegDetail.Count, numregok);
                    string strmessage = "Không chọn được nhóm môn học do trùng môn đã đăng ký, trùng lịch hoặc hết chỗ: ";
                    foreach (KeyValuePair <string, List <string> > keypair in errorstudent)
                    {
                        strmessage += string.Format("Sinh viên:[{0}] - Môn:[", keypair.Key);
                        foreach (string str in keypair.Value)
                        {
                            strmessage += str + ",";
                        }
                        strmessage  = strmessage.TrimEnd(',');
                        strmessage += "]\r\n";
                    }
                    ms.Message += strmessage;
                }
                else
                {
                    ms.Title   = "Chọn nhóm MH thành công";
                    ms.Message = string.Format("Chọn nhóm MH thành công cho {0} sinh viên với {1} lượt nhóm MH\r\n", dicStudentRegDetail.Count, numregok);
                }
                ShowViewParameters svp = new ShowViewParameters();
                svp.CreatedView = Application.CreateDetailView(
                    objectSpace, ms);
                svp.TargetWindow        = TargetWindow.NewModalWindow;
                svp.CreatedView.Caption = "Thông báo";
                DialogController dc = Application.CreateController <DialogController>();
                svp.Controllers.Add(dc);

                dc.SaveOnAccept = false;
                Application.ShowViewStrategy.ShowView(svp, new ShowViewSource(null, null));
            }
        }
Esempio n. 21
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
            // Administrative role
            SecuritySystemRole adminRole = ObjectSpace.FindObject <SecuritySystemRole>(
                new BinaryOperator("Name", SecurityStrategy.AdministratorRoleName));

            if (adminRole == null)
            {
                adminRole                  = ObjectSpace.CreateObject <SecuritySystemRole>();
                adminRole.Name             = SecurityStrategy.AdministratorRoleName;
                adminRole.IsAdministrative = true;
            }
            // Administrator user
            SecuritySystemUser adminUser = ObjectSpace.FindObject <SecuritySystemUser>(
                new BinaryOperator("UserName", "Administrator"));

            if (adminUser == null)
            {
                adminUser          = ObjectSpace.CreateObject <SecuritySystemUser>();
                adminUser.UserName = "******";
                adminUser.SetPassword("");
                adminUser.Roles.Add(adminRole);
            }
            // A role whith type-level permissions
            SecuritySystemRole contactsManagerRole =
                ObjectSpace.FindObject <SecuritySystemRole>(
                    new BinaryOperator("Name", "Contacts Manager"));

            if (contactsManagerRole == null)
            {
                contactsManagerRole      = ObjectSpace.CreateObject <SecuritySystemRole>();
                contactsManagerRole.Name = "Contacts Manager";
                SecuritySystemTypePermissionObject contactTypePermission =
                    ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                contactTypePermission.TargetType    = typeof(Contact);
                contactTypePermission.AllowCreate   = true;
                contactTypePermission.AllowDelete   = true;
                contactTypePermission.AllowNavigate = true;
                contactTypePermission.AllowRead     = true;
                contactTypePermission.AllowWrite    = true;
                contactsManagerRole.TypePermissions.Add(contactTypePermission);
            }
            SecuritySystemUser userSam =
                ObjectSpace.FindObject <SecuritySystemUser>(
                    new BinaryOperator("UserName", "Sam"));

            if (userSam == null)
            {
                userSam          = ObjectSpace.CreateObject <SecuritySystemUser>();
                userSam.UserName = "******";
                userSam.SetPassword("");
                userSam.Roles.Add(contactsManagerRole);
            }
            // A role with object-level permissions
            SecuritySystemRole basicUserRole =
                ObjectSpace.FindObject <SecuritySystemRole>(
                    new BinaryOperator("Name", "Basic User"));

            if (basicUserRole == null)
            {
                basicUserRole      = ObjectSpace.CreateObject <SecuritySystemRole>();
                basicUserRole.Name = "Basic User";
                SecuritySystemTypePermissionObject userTypePermission =
                    ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                userTypePermission.TargetType = typeof(SecuritySystemUser);
                SecuritySystemObjectPermissionsObject currentUserObjectPermission =
                    ObjectSpace.CreateObject <SecuritySystemObjectPermissionsObject>();
                currentUserObjectPermission.Criteria      = "[Oid] = CurrentUserId()";
                currentUserObjectPermission.AllowNavigate = true;
                currentUserObjectPermission.AllowRead     = true;
                userTypePermission.ObjectPermissions.Add(currentUserObjectPermission);
                basicUserRole.TypePermissions.Add(userTypePermission);
            }
            SecuritySystemUser userJohn =
                ObjectSpace.FindObject <SecuritySystemUser>(
                    new BinaryOperator("UserName", "John"));

            if (userJohn == null)
            {
                userJohn          = ObjectSpace.CreateObject <SecuritySystemUser>();
                userJohn.UserName = "******";
                userJohn.SetPassword("");
                userJohn.Roles.Add(basicUserRole);
            }
            // A role with member-level permissions
            SecuritySystemRole contactViewerRole =
                ObjectSpace.FindObject <SecuritySystemRole>(
                    new BinaryOperator("Name", "Contact Viewer"));

            if (contactViewerRole == null)
            {
                contactViewerRole      = ObjectSpace.CreateObject <SecuritySystemRole>();
                contactViewerRole.Name = "Contact Viewer";
                SecuritySystemTypePermissionObject contactLimitedTypePermission =
                    ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                contactLimitedTypePermission.TargetType    = typeof(Contact);
                contactLimitedTypePermission.AllowNavigate = true;
                SecuritySystemMemberPermissionsObject contactMemberPermission =
                    ObjectSpace.CreateObject <SecuritySystemMemberPermissionsObject>();
                contactMemberPermission.Members   = "Name";
                contactMemberPermission.AllowRead = true;
                contactLimitedTypePermission.MemberPermissions.Add(contactMemberPermission);
                contactViewerRole.TypePermissions.Add(contactLimitedTypePermission);
            }
            SecuritySystemUser userBill =
                ObjectSpace.FindObject <SecuritySystemUser>(
                    new BinaryOperator("UserName", "Bill"));

            if (userBill == null)
            {
                userBill          = ObjectSpace.CreateObject <SecuritySystemUser>();
                userBill.UserName = "******";
                userBill.SetPassword("");
                userBill.Roles.Add(contactViewerRole);
            }
            // Contact objects are created for demo purposes
            Contact contactMary = ObjectSpace.FindObject <Contact>(
                new BinaryOperator("Name", "Mary Tellitson"));

            if (contactMary == null)
            {
                contactMary       = ObjectSpace.CreateObject <Contact>();
                contactMary.Name  = "Mary Tellitson";
                contactMary.Email = "*****@*****.**";
            }
            Contact contactJohn = ObjectSpace.FindObject <Contact>(
                new BinaryOperator("Name", "John Nilsen"));

            if (contactJohn == null)
            {
                contactJohn       = ObjectSpace.CreateObject <Contact>();
                contactJohn.Name  = "John Nilsen";
                contactJohn.Email = "*****@*****.**";
            }
        }
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();

            if (ObjectSpace.CreateCollection(typeof(Company)).Count == 0)
            {
                SecuritySystemRole adminRole = ObjectSpace.FindObject <SecuritySystemRole>(new BinaryOperator("Name", SecurityStrategy.AdministratorRoleName));
                if (adminRole == null)
                {
                    adminRole                  = ObjectSpace.CreateObject <SecuritySystemRole>();
                    adminRole.Name             = SecurityStrategy.AdministratorRoleName;
                    adminRole.IsAdministrative = true;
                }
                SecuritySystemRole userRole = ObjectSpace.FindObject <SecuritySystemRole>(new BinaryOperator("Name", "User"));
                if (userRole == null)
                {
                    userRole      = ObjectSpace.CreateObject <SecuritySystemRole>();
                    userRole.Name = "User";
                    SecuritySystemTypePermissionObject userTypePermission =
                        ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                    userTypePermission.TargetType = typeof(SecuritySystemUser);
                    SecuritySystemObjectPermissionsObject currentUserObjectPermission =
                        ObjectSpace.CreateObject <SecuritySystemObjectPermissionsObject>();
                    currentUserObjectPermission.Criteria      = "[Oid] = CurrentUserId()";
                    currentUserObjectPermission.AllowNavigate = true;
                    currentUserObjectPermission.AllowRead     = true;
                    userTypePermission.ObjectPermissions.Add(currentUserObjectPermission);
                    userRole.TypePermissions.Add(userTypePermission);

                    SecuritySystemTypePermissionObject validatedObjectTypePermission =
                        ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                    validatedObjectTypePermission.TargetType    = typeof(ValidatedObject);
                    validatedObjectTypePermission.AllowWrite    = true;
                    validatedObjectTypePermission.AllowNavigate = true;
                    validatedObjectTypePermission.AllowCreate   = true;
                    validatedObjectTypePermission.AllowDelete   = true;
                    validatedObjectTypePermission.AllowRead     = true;

                    userRole.TypePermissions.Add(validatedObjectTypePermission);

                    SecuritySystemTypePermissionObject companyTypePermission =
                        ObjectSpace.CreateObject <SecuritySystemTypePermissionObject>();
                    companyTypePermission.TargetType = typeof(Company);
                    companyTypePermission.AllowRead  = true;

                    userRole.TypePermissions.Add(companyTypePermission);
                }

                Employee admin = ObjectSpace.CreateObject <Employee>();
                admin.UserName = "******";
                admin.SetPassword("");
                admin.Roles.Add(adminRole);
                admin.Save();

                Company company1 = ObjectSpace.CreateObject <Company>();
                company1.Name = "Company 1";
                company1.Employees.Add(admin);
                company1.Save();

                Employee user = ObjectSpace.CreateObject <Employee>();
                user.UserName = "******";
                user.SetPassword("");
                user.Roles.Add(userRole);
                user.Save();

                Employee user2 = ObjectSpace.CreateObject <Employee>();
                user2.UserName = "******";
                user2.SetPassword("");
                user2.Roles.Add(userRole);
                user2.Save();

                Company company2 = ObjectSpace.CreateObject <Company>();
                company2.Name = "Company 2";
                company2.Employees.Add(user);
                company2.Employees.Add(user2);
                company2.Save();
            }
        }
Esempio n. 23
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();

            //Cập nhật Danh sách Department cấp trên: chỉ mở và cho chạy 1 lần

            /*
             * List<Department> allDepartment = ObjectSpace.GetObjects<Department>().ToList();
             * foreach(Department dep in allDepartment)
             * {
             *  if(dep != null)
             *  {
             *      dep.updateListManagerDepartmentOid();
             *      dep.Save();
             *  }
             * }
             * ObjectSpace.CommitChanges();
             * //*/

            #region EmployeeRole - Khoi tao Role/User cho EmployeeRole
            ///Phải có tài khoản Default (Default)
            EmployeeRole defaultEmployeeRole = ObjectSpace.FindObject <EmployeeRole>(
                new BinaryOperator("Name", "default"));
            if (defaultEmployeeRole == null)
            {
                defaultEmployeeRole                  = ObjectSpace.CreateObject <EmployeeRole>();
                defaultEmployeeRole.Name             = "Default";
                defaultEmployeeRole.IsAdministrative = false;
                defaultEmployeeRole.Save();
            }

            ///Phải có tài khoản Thủ quỷ (Cashier)
            EmployeeRole cashierEmployeeRole = ObjectSpace.FindObject <EmployeeRole>(
                new BinaryOperator("Name", "Cashier"));
            if (cashierEmployeeRole == null)
            {
                cashierEmployeeRole                  = ObjectSpace.CreateObject <EmployeeRole>();
                cashierEmployeeRole.Name             = "Cashier";
                cashierEmployeeRole.IsAdministrative = false;
                cashierEmployeeRole.Save();
            }
            ///Phải có tài khoản Giám đốc (Director)
            EmployeeRole directorEmployeeRole = ObjectSpace.FindObject <EmployeeRole>(
                new BinaryOperator("Name", "Director"));
            if (directorEmployeeRole == null)
            {
                directorEmployeeRole                  = ObjectSpace.CreateObject <EmployeeRole>();
                directorEmployeeRole.Name             = "Director";
                directorEmployeeRole.IsAdministrative = false;
                directorEmployeeRole.Save();
            }

            ///Phải có tài khoản Văn thư (Officer)
            EmployeeRole officerEmployeeRole = ObjectSpace.FindObject <EmployeeRole>(
                new BinaryOperator("Name", "Officer"));
            if (officerEmployeeRole == null)
            {
                officerEmployeeRole                  = ObjectSpace.CreateObject <EmployeeRole>();
                officerEmployeeRole.Name             = "Officer";
                officerEmployeeRole.IsAdministrative = false;
                officerEmployeeRole.Save();
            }


            EmployeeRole TaskerRole = ObjectSpace.FindObject <EmployeeRole>(
                new BinaryOperator("Name", "Tasker"));
            if (TaskerRole == null)
            {
                TaskerRole                  = ObjectSpace.CreateObject <EmployeeRole>();
                TaskerRole.Name             = "Tasker";
                TaskerRole.IsAdministrative = false;
                TaskerRole.Save();
            }

            ///Administrator
            EmployeeRole adminEmployeeRole = ObjectSpace.FindObject <EmployeeRole>(
                new BinaryOperator("Name", SecurityStrategy.AdministratorRoleName));
            if (adminEmployeeRole == null)
            {
                adminEmployeeRole                  = ObjectSpace.CreateObject <EmployeeRole>();
                adminEmployeeRole.Name             = SecurityStrategy.AdministratorRoleName;
                adminEmployeeRole.IsAdministrative = true;
                //SecuritySystemTypePermissionObject permissionObject = ObjectSpace.FindObject<SecuritySystemTypePermissionObject>(null);
                //permissionObject.MemberPermissions.Add(new SecuritySystemMemberPermissionsObject)
                //adminEmployeeRole.TypePermissions.Add(permissionObject);
                adminEmployeeRole.Save();
            }

            Employee adminEmployee = ObjectSpace.FindObject <Employee>(
                new BinaryOperator("UserName", "admin"));
            if (adminEmployee == null)
            {
                adminEmployee          = ObjectSpace.CreateObject <Employee>();
                adminEmployee.UserName = "******";
                adminEmployee.SetPassword("admin");
                adminEmployee.EmployeeRoles.Add(adminEmployeeRole);
            }
            #endregion

            #region DocType - Loại văn bản
            DocType doctype = ObjectSpace.FindObject <DocType>(new BinaryOperator("Code", "congvan"));
            if (doctype == null)
            {
                doctype       = ObjectSpace.CreateObject <DocType>();
                doctype.Code  = "congvan";
                doctype.Title = "Công văn";
                doctype.Save();
            }

            doctype = ObjectSpace.FindObject <DocType>(new BinaryOperator("Code", "quyetdinh"));
            if (doctype == null)
            {
                doctype       = ObjectSpace.CreateObject <DocType>();
                doctype.Code  = "quyetdinh";
                doctype.Title = "Quyết định";
                doctype.Save();
            }

            doctype = ObjectSpace.FindObject <DocType>(new BinaryOperator("Code", "totrinh"));
            if (doctype == null)
            {
                doctype       = ObjectSpace.CreateObject <DocType>();
                doctype.Code  = "totrinh";
                doctype.Title = "Tờ trình";
                doctype.Save();
            }

            doctype = ObjectSpace.FindObject <DocType>(new BinaryOperator("Code", "thongbao"));
            if (doctype == null)
            {
                doctype       = ObjectSpace.CreateObject <DocType>();
                doctype.Code  = "thongbao";
                doctype.Title = "Thông báo";
                doctype.Save();
            }

            doctype = ObjectSpace.FindObject <DocType>(new BinaryOperator("Code", "baocao"));
            if (doctype == null)
            {
                doctype       = ObjectSpace.CreateObject <DocType>();
                doctype.Code  = "baocao";
                doctype.Title = "Báo cáo";
                doctype.Save();
            }
            #endregion

            #region Position - Vị trí/chức vụ
            Position position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Chủ tịch hội đồng quản trị"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Chủ tịch hội đồng quản trị";
                position.PositionLevel = 900;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Ủy viên hội đồng quản trị"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Ủy viên hội đồng quản trị";
                position.PositionLevel = 800;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Tổng giám đốc"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Tổng giám đốc";
                position.PositionLevel = 500;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Phó tổng giám đốc"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Chủ tịch hội đồng quản trị văn";
                position.PositionLevel = 490;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Giám đốc"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Giám đốc";
                position.PositionLevel = 400;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Phó giám đốc"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Phó giám đốc";
                position.PositionLevel = 380;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Trưởng ban"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Trưởng ban";
                position.PositionLevel = 300;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Phó ban"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Phó ban";
                position.PositionLevel = 280;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Trưởng phòng"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Trưởng phòng";
                position.PositionLevel = 200;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Phó phòng"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Phó phòng";
                position.PositionLevel = 180;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Chuyên viên"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Chuyên viên";
                position.PositionLevel = 80;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Nhân viên"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Nhân viên";
                position.PositionLevel = 78;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Kế toán viên"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Kế toán viên";
                position.PositionLevel = 78;
                position.Save();
            }

            position = ObjectSpace.FindObject <Position>(new BinaryOperator("Title", "Công nhân"));
            if (doctype == null)
            {
                position               = ObjectSpace.CreateObject <Position>();
                position.Title         = "Công nhân";
                position.PositionLevel = 70;
                position.Save();
            }
            #endregion

            #region Configuration
            Global.Config = Configuration.GetInstance(ObjectSpace);
            #endregion

            ObjectSpace.CommitChanges(); //This line persists created object(s).
        }
Esempio n. 24
0
        public void ImportData()
        {
            DataTable dtExcel = new DataTable();

            LoadExcel(@"C:\Users\Xiameng\Desktop\import1.xlsx", "新生表", ref dtExcel);
            foreach (DataRow dataRow in dtExcel.Rows)
            {
                try
                {
                    if (string.IsNullOrWhiteSpace(dataRow["联系电话"]?.ToString()))
                    {
                        continue;
                    }

                    var studentInfo = ObjectSpace.CreateObject <StudentInfo>();
                    var arrayPhone  = dataRow["联系电话"].ToString().Split('/');
                    studentInfo.s_Phone = arrayPhone[0];
                    if (studentInfo.s_Phone.Length < 11)
                    {
                        studentInfo.s_Phone = studentInfo.s_Phone.PadLeft(11, '0');
                    }

                    if (arrayPhone.Length > 1)
                    {
                        studentInfo.s_Phone2 = arrayPhone[1];
                    }

                    studentInfo.s_Parent = dataRow["联系人"]?.ToString();
                    studentInfo.s_Name   = dataRow["姓名"]?.ToString();
                    studentInfo.s_Sex    = dataRow["性别"]?.ToString()?.Trim();
                    int.TryParse(dataRow["年龄"].ToString(), out var nAge);
                    studentInfo.dt_BirthDate = DateTime.Today.AddYears(0 - nAge);
                    studentInfo.s_Ability    = dataRow["基础"]?.ToString();
                    studentInfo.s_Character  = dataRow["性格"]?.ToString().Length > 10?string.Empty: dataRow["性格"]?.ToString();
                    studentInfo.s_Address    = dataRow["住址"]?.ToString();
                    studentInfo.s_School     = dataRow["幼儿园/小学"]?.ToString();
                    studentInfo.s_Train      = dataRow["兴趣班"]?.ToString();
                    studentInfo.s_Valid      = dataRow["有效"]?.ToString();

                    var consultRecord = studentInfo.ConsultRecords.Count > 0
                        ? studentInfo.ConsultRecords[0]
                        : ObjectSpace.CreateObject <ConsultRecord>();
                    consultRecord.StudentInfo = studentInfo;
                    consultRecord.s_Level     = dataRow["级别"]?.ToString();
                    studentInfo.s_Source      = dataRow["来源"]?.ToString();
                    consultRecord.s_Status    = dataRow["状态"]?.ToString();
                    consultRecord.s_Demand    = dataRow["需求"]?.ToString();
                    if (!string.IsNullOrWhiteSpace(dataRow["课程顾问"]?.ToString()))
                    {
                        consultRecord.Consultant = ObjectSpace.FindObject <SysUser>(
                            CriteriaOperator.Parse($"s_Name like '%{dataRow["课程顾问"]}%' or s_EName like '%{dataRow["课程顾问"]}%'"));
                    }

                    var contactRecord = studentInfo.ContactRecords.Count > 0
                        ? studentInfo.ContactRecords[0]
                        : ObjectSpace.CreateObject <ContactRecord>();

                    if (!string.IsNullOrWhiteSpace(dataRow["咨询日期"]?.ToString()))
                    {
                        consultRecord.dt_ConsultDate = Convert.ToDateTime(dataRow["咨询日期"].ToString().Replace("号", "日"));
                        contactRecord.dt_RecordDate  = consultRecord.dt_ConsultDate;
                    }

                    if (!string.IsNullOrWhiteSpace(dataRow["预计回访日期"]?.ToString()))
                    {
                        DateTime.TryParse(dataRow["预计回访日期"].ToString(), out var dtDate);
                        contactRecord.dt_NextDate = dtDate;
                        contactRecord.s_Content   = dataRow["上门日期"].ToString();
                    }
                    studentInfo.OwnerCC = consultRecord.Consultant;
                    ObjectSpace.CommitChanges();
                }
                catch (Exception e)
                {
                    ObjectSpace.Rollback();
                    Console.WriteLine(e);
                }
            }
        }
Esempio n. 25
0
        private Contact GetContact(DataRow employee)
        {
            string  email   = Convert.ToString(employee["EmailAddress"]);
            Contact contact = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("Email=?", email));

            if (contact == null)
            {
                contact           = ObjectSpace.CreateObject <Contact>();
                contact.Email     = email;
                contact.FirstName = Convert.ToString(employee["FirstName"]);
                contact.LastName  = Convert.ToString(employee["LastName"]);
                contact.Birthday  = Convert.ToDateTime(employee["BirthDate"]);
                contact.Photo     = Convert.FromBase64String(Convert.ToString(employee["ImageData"]));
                string titleOfCourtesyText = Convert.ToString(employee["Title"]).ToLower();
                if (!string.IsNullOrEmpty(titleOfCourtesyText))
                {
                    titleOfCourtesyText = titleOfCourtesyText.Replace(".", "");
                    TitleOfCourtesy titleOfCourtesy;
                    if (Enum.TryParse <TitleOfCourtesy>(titleOfCourtesyText, true, out titleOfCourtesy))
                    {
                        contact.TitleOfCourtesy = titleOfCourtesy;
                    }
                }
                PhoneNumber phoneNumber = ObjectSpace.CreateObject <PhoneNumber>();
                phoneNumber.Party     = contact;
                phoneNumber.Number    = Convert.ToString(employee["Phone"]);
                phoneNumber.PhoneType = "Work";

                Address address = ObjectSpace.CreateObject <Address>();
                contact.Address1      = address;
                address.ZipPostal     = Convert.ToString(employee["PostalCode"]);
                address.Street        = Convert.ToString(employee["AddressLine1"]);
                address.City          = Convert.ToString(employee["City"]);
                address.StateProvince = Convert.ToString(employee["StateProvinceName"]);
                string  countryName = Convert.ToString(employee["CountryRegionName"]);
                Country country     = ObjectSpace.FindObject <Country>(CriteriaOperator.Parse("Name=?", countryName), true);
                if (country == null)
                {
                    country      = ObjectSpace.CreateObject <Country>();
                    country.Name = countryName;
                }
                address.Country = country;

                string departmentTitle = Convert.ToString(employee["GroupName"]);
                contact.Department = FindDepartment(departmentTitle);

                string   positionTitle = Convert.ToString(employee["JobTitle"]);
                Position position      = FindPosition(positionTitle);
                if (position == null)
                {
                    position       = ObjectSpace.CreateObject <Position>();
                    position.Title = positionTitle;
                    if (contact.Department != null)
                    {
                        position.Departments.Add(contact.Department);
                        contact.Department.Positions.Add(position);
                    }
                }
                contact.Position = position;
            }
            return(contact);
        }
Esempio n. 26
0
        public void ProccesExcellRows(IEnumerable records, ObjectSpace objectSpace, DoWorkEventArgs e) {

            var i = 0;

            //for every row in excell sheet
            foreach (Row record in records) {
                ++i;
                if (i == 1) continue;
                if (_BgWorker.CancellationPending) { e.Cancel = true; break; }

                //var os = new ObjectSpace(objectSpace, XafTypesInfo.Instance);
                object newObj = null;

                //chech if row contains Oid

                //get key property name of the object type being imported
                var kp = objectSpace.GetKeyPropertyName(Type);
                //check if it exists in excel and is mapped ?
                var idMapping = ImportMap.Mappings.Where(p => p.MapedTo == kp).FirstOrDefault();
                if (idMapping != null && GetQString(record[idMapping.Column].Value) != string.Empty) {
                    try {
                        //find existing object
                        var val = record[idMapping.Column];
                        var gwid = new Guid(GetQString(val.Value));
                        newObj = objectSpace.FindObject(Type, new BinaryOperator(kp, gwid), true);
                    } catch {

                    }
                }
                if (newObj == null) //create a new instance
                    newObj = objectSpace.CreateObject(Type) as IXPSimpleObject;

                string message;
                if (newObj != null) {
                    var props = ((IXPSimpleObject)newObj).ClassInfo.PersistentProperties
                        .OfType<XPMemberInfo>();


                    foreach (var mapping in ImportMap.Mappings) {
                        if (_BgWorker.CancellationPending) { e.Cancel = true; break; }
                        Application.DoEvents();

                        var mapping1 = mapping;
                        var prop = props.Where(p => p.Name == mapping1.MapedTo).FirstOrDefault();

                        try {
                            var val = record[mapping.Column];
                            // continue;

                            if (val != null) {
                                //if simple property
                                if (prop.ReferenceType == null) {
                                    var isNullable = prop.MemberType.IsGenericType && prop.MemberType.GetGenericTypeDefinition() == typeof(Nullable<>);
                                    object convertedValue = null;

                                    if (prop.MemberType == null) return;

                                    if (isNullable) {
                                        if (prop.StorageType == typeof(int)) {
                                            int number;
                                            var rez = Int32.TryParse(val.Value, out number);
                                            if (rez) convertedValue = number;

                                        } else if (prop.StorageType == typeof(DateTime)) {
                                            if (val.Value != string.Empty) {
                                                //Include validate
                                                var dt = DateTime.FromOADate(Convert.ToDouble(val.Value));
                                                convertedValue = dt;
                                            }
                                        } else if (prop.StorageType == typeof(double)) {
                                            double number;
                                            var rez = Double.TryParse(val.Value, out number);
                                            if (rez) convertedValue = number;
                                        }
                                    } else {

                                        if (prop.MemberType == typeof(char))
                                            convertedValue = Convert.ChangeType(GetQString(val.Value), prop.MemberType);
                                        else if (prop.MemberType == typeof(Guid))
                                            convertedValue = new Guid(GetQString(val.Value));
                                        else if (prop.StorageType == typeof(DateTime)) {
                                            if (val.Value != string.Empty) {
                                                //Include validate
                                                var dt = DateTime.FromOADate(Convert.ToDouble(val.Value));
                                                convertedValue = dt;
                                            }
                                        } else if (prop.MemberType == typeof(double)) {
                                            double number;
                                            //  Application.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
                                            var rez = Double.TryParse(val.Value, NumberStyles.Number, new NumberFormatInfo { NumberDecimalSeparator = "." }, out number);
                                            if (rez) convertedValue = number;
                                        } else if (prop.MemberType == typeof(bool)) {
                                            if (val.Value != string.Empty && (val.Value.Length == 1 || val.Value.ToLower() == "true" || val.Value.ToLower() == "false")) {
                                                bool truefalse;
                                                if (val.Value.ToLower() == "true" || val.Value.ToLower() == "false")
                                                    truefalse = Convert.ToBoolean(val.Value);
                                                else
                                                    truefalse = Convert.ToBoolean(Convert.ToInt32(val.Value));
                                                convertedValue = truefalse;
                                            }
                                        } else
                                            convertedValue = Convert.ChangeType(val.Value, prop.MemberType);
                                    }

                                    if (convertedValue != null) {
                                        if (convertedValue.GetType() == typeof(double))
                                            convertedValue = Math.Round((double)convertedValue, 2, MidpointRounding.ToEven);

                                        prop.SetValue(newObj, convertedValue);
                                    }
                                }
                                //if referenced property
                                if (prop.ReferenceType != null) {

                                    //if other referenced type
                                    if (prop.MemberType.IsSubclassOf(typeof(XPBaseObject))) {
                                        var text = val.Value;
                                        var typ = prop.MemberType;
                                        var mval = ImportWizard.Helper.GetXpObjectByKeyValue(objectSpace, text, typ);
                                        prop.SetValue(newObj, objectSpace.GetObject(mval));
                                    }
                                }

                            }

                        } catch (Exception E) {
                            message = string.Format("Error processing record {0}. {1}", i, E);
                            _BgWorker.ReportProgress(0, message);
                        }

                        if (CurrentCollectionSource != null)
                            AddNewObjectToCollectionSource(CurrentCollectionSource, newObj, ObjectSpace);
                        ObjectSpace.Session.Save(newObj);
                    }
                }

                objectSpace.CommitChanges();
                message = string.Format("Importing record {0} succesfull.", i);
                _BgWorker.ReportProgress(1, message);
                Application.DoEvents();
            }
        }
Esempio n. 27
0
        void ImportSubjectAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace      objectSpace      = Application.CreateObjectSpace();
            CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(MyImportResult));
            int count = 0;
            int iLine = 0;

            if ((collectionSource.Collection as XPBaseCollection) != null)
            {
                ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
            }

            foreach (SubjectFile actFile in View.SelectedObjects)
            {
                if (actFile.Note == "")
                {
                    throw new UserFriendlyException("Vui lòng thêm thông tin Ghi chú trước khi import!!!");
                }

                string tempStudentFile;
                string tempStudentFolderPath;
                string tempStudentLogFile;
                string templogname = "";
                if (HttpContext.Current != null)
                {
                    tempStudentFolderPath = HttpContext.Current.Request.MapPath("~/tempFolder");
                    tempStudentFile       = HttpContext.Current.Request.MapPath("~/tempFolder/" + actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = HttpContext.Current.Request.MapPath("~/tempFolder/" + templogname);
                }
                else
                {
                    tempStudentFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder");
                    tempStudentFile       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", templogname);
                }

                if (!Directory.Exists(tempStudentFolderPath))
                {
                    Directory.CreateDirectory(tempStudentFolderPath);
                }

                using (System.IO.FileStream fileStream = new FileStream(tempStudentFile, FileMode.OpenOrCreate))
                {
                    Dictionary <string, int>    columnIndexs = new Dictionary <string, int>();
                    Dictionary <string, object> valueIndexs  = new Dictionary <string, object>();
                    valueIndexs.Add("MAMH", "");
                    valueIndexs.Add("TENMH", "");
                    valueIndexs.Add("SOTC", "");
                    valueIndexs.Add("MANGANH", "");
                    valueIndexs.Add("TENNGANH", "");

                    columnIndexs.Add("MAMH", -1);
                    columnIndexs.Add("TENMH", -1);
                    columnIndexs.Add("SOTC", -1);
                    columnIndexs.Add("MANGANH", -1);
                    columnIndexs.Add("TENNGANH", -1);


                    // open xls file
                    actFile.CsvFile.SaveToStream(fileStream);
                    fileStream.Close();
                    Workbook  book  = Workbook.Open(tempStudentFile);
                    Worksheet sheet = book.Worksheets[0];


                    bool foundHeader = false;

                    Row row;
                    //Tìm dòng chứa TEN cột
                    for (iLine = sheet.Cells.FirstRowIndex;
                         iLine <= sheet.Cells.LastRowIndex && !foundHeader; iLine++)
                    {
                        row = sheet.Cells.GetRow(iLine);
                        for (int colIndex = row.FirstColIndex;
                             colIndex <= row.LastColIndex; colIndex++)
                        {
                            Cell cell = row.GetCell(colIndex);
                            if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                            {
                                columnIndexs[cell.Value.ToString().ToUpper().Trim()] = colIndex; //Đã tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                            }
                        }
                        if (!columnIndexs.Values.Contains(-1))
                        {
                            foundHeader = true;
                        }
                        else
                        {
                            for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
                            {
                                Cell cell = row.GetCell(colIndex);
                                if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                                {
                                    columnIndexs[cell.Value.ToString().ToUpper().Trim()] = -1; //không tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                                }
                            }
                        }
                    }
                    if (!foundHeader)
                    {
                        throw new UserFriendlyException("Lỗi cấu trúc file");
                    }

                    using (System.IO.StreamWriter fileStreamlog = new System.IO.StreamWriter(tempStudentLogFile, true))
                    {
                        fileStreamlog.WriteLine("<html><header><title>" + actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log </title>	"+
                                                "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" +
                                                "</head><body>\r\n<table border=\"1px\"> <tr><Th>DÒNG</Th><th>TÌNH TRẠNG</th><th>THÔNG ĐIỆP</th></Tr>");
                        //Các dòng sau đó đều là dòng dữ liệu

                        List <Branch> listBranches = new List <Branch>();


                        for (; iLine <= sheet.Cells.LastRowIndex; iLine++)
                        {
                            row = sheet.Cells.GetRow(iLine);
                            try
                            {
                                foreach (var column in columnIndexs)
                                {
                                    Cell cell = row.GetCell(column.Value);
                                    valueIndexs[column.Key] = cell.Value;
                                }

                                if (valueIndexs["MAMH"] == null || valueIndexs["TENMH"] == null || valueIndexs["SOTC"] == null)
                                {
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                            string.Format("Can not import line with  [MAMH or TENMH or SOTINCHI] is NULL on {0:dd-mm-yy HH:MM:ss}", DateTime.Now));
                                    continue;
                                }
                                //tạo NGÀNH
                                Branch branch;
                                if (valueIndexs["MANGANH"] == null)
                                {
                                    branch = null;
                                }
                                else
                                {
                                    branch = listBranches.Find(l => l.BranchCode == valueIndexs["MANGANH"].ToString());
                                    if (branch == null)
                                    {
                                        objectSpace.FindObject <Branch>(new BinaryOperator("BranchCode", valueIndexs["MANGANH"].ToString()));
                                    }
                                    if (branch != null)
                                    {
                                        if (valueIndexs["TENNGANH"] == null || branch.BranchName != valueIndexs["TENNGANH"].ToString())
                                        {
                                            fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                    string.Format("Branch: \"{0}\" has name \"{1}\" different to \"{2}\" on {3:dd-mm-yy HH:MM:ss}",
                                                                                  branch.BranchCode, branch.BranchName, valueIndexs["TENNGANH"], DateTime.Now));
                                        }
                                        if (!listBranches.Contains(branch))
                                        {
                                            listBranches.Add(branch);
                                        }
                                    }
                                    else
                                    {
                                        branch = objectSpace.CreateObject <Branch>();

                                        branch.BranchCode = valueIndexs["MANGANH"].ToString();
                                        branch.BranchName = valueIndexs["TENNGANH"] == null ? null : valueIndexs["TENNGANH"].ToString();
                                        branch.Save();
                                        listBranches.Add(branch);
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create new branch: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}",
                                                                              branch.BranchCode, branch.BranchName, DateTime.Now));
                                    }
                                }

                                //tạo MÔN HỌC
                                Subject subject = objectSpace.FindObject <Subject>(new BinaryOperator("SubjectCode", valueIndexs["MAMH"].ToString()));
                                if (subject != null)
                                {
                                    //subject.SubjectCode = valueIndexs["MAMH"].ToString();
                                    subject.SubjectName = valueIndexs["TENMH"].ToString();
                                    subject.Credit      = (double)valueIndexs["SOTC"];
                                    subject.Branch      = branch;
                                    subject.Note        = actFile.Note;
                                    subject.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "UPDATE",
                                                            string.Format("Update subject: [{0}]-[{1}({2:#.#})] on {3:dd-mm-yy HH:MM:ss}",
                                                                          subject.SubjectCode, subject.SubjectName, subject.Credit, DateTime.Now));
                                }
                                else
                                {
                                    subject             = objectSpace.CreateObject <Subject>();
                                    subject.SubjectCode = valueIndexs["MAMH"].ToString();
                                    subject.SubjectName = valueIndexs["TENMH"].ToString();
                                    subject.Credit      = (double)valueIndexs["SOTC"];
                                    subject.Branch      = branch;
                                    subject.Note        = actFile.Note;
                                    subject.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                            string.Format("Create subject: [{0}]-[{1}({2:#.#})] on {3:dd-mm-yy HH:MM:ss}",
                                                                          subject.SubjectCode, subject.SubjectName, subject.Credit, DateTime.Now));
                                }
                                objectSpace.CommitChanges();
                                count++;
                            }
                            catch (Exception ex)
                            {
                                fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                        ex.Message + ex.StackTrace);
                            }
                        }
                        fileStreamlog.WriteLine("</table></body></html>");
                        fileStreamlog.Close();
                    }

                    View.ObjectSpace.SetModified(actFile);
                    actFile.IsImported = true;
                    actFile.ResultLink = "/tempFolder/" + templogname;

                    View.ObjectSpace.CommitChanges();
                }
            }
            PopUpMessage     ms;
            DialogController dc;

            ms         = objectSpace.CreateObject <PopUpMessage>();
            ms.Title   = "Kết quả import";
            ms.Message = string.Format("Đã thực hiện import {0} kết quả cho {1} dòng trong file\r\n Vui lòng xem link kết quả", count, iLine);
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(
                objectSpace, ms);
            e.ShowViewParameters.TargetWindow        = TargetWindow.NewModalWindow;
            e.ShowViewParameters.CreatedView.Caption = "Thông báo";
            dc = Application.CreateController <DialogController>();
            dc.AcceptAction.Active.SetItemValue("object", false);
            dc.CancelAction.Caption = "Đóng";
            dc.SaveOnAccept         = false;
            e.ShowViewParameters.Controllers.Add(dc);
        }
Esempio n. 28
0
        void Control_ValidatedDocEnl(object sender, EventArgs e)
        {
            if (View != null)
            {
                DocumenSal fac = View.CurrentObject as DocumenSal;
                PartSal    pit = null;

                if (!string.IsNullOrEmpty(fac.DocEnlace))
                {
                    string     aux     = fac.DocEnlace;
                    string[]   arrdocs = aux.Split(':');
                    DocumenSal docOrig = null;

                    foreach (string doc in arrdocs)
                    {
                        string cve = DocumenSal.ClaveFto(doc.Substring(1));

                        if (doc[0].ToString().ToUpper() == "C")
                        {
                            docOrig = fac.Session.FindObject <Cotizacion>(new BinaryOperator("Clave", cve));
                        }
                        else if (doc[0].ToString().ToUpper() == "P")
                        {
                            docOrig = fac.Session.FindObject <Pedido>(new BinaryOperator("Clave", cve));
                        }

                        if (fac != null && docOrig != null)
                        {
                            fac.Cliente = docOrig.Cliente;
                            fac.Vnddr   = docOrig.Vnddr;
                            foreach (PartSal cit in docOrig.LasPartidas())
                            {
                                if (cit.CantidadRemanente > 0)
                                {
                                    if (cit is CotizacionItem)
                                    {
                                        if (fac is Pedido)
                                        {
                                            pit = ObjectSpace.CreateObject <PedidoItem>();
                                        }
                                        else
                                        {
                                            pit = ObjectSpace.CreateObject <RemisionItem>();
                                        }
                                        pit.Antrr /*.Anterior*/ = cit as CotizacionItem;
                                    }
                                    else if (cit is PedidoItem)
                                    {
                                        pit = ObjectSpace.CreateObject <RemisionItem>();
                                        pit.Antrr /*.Anterior*/ = cit as PedidoItem;
                                    }
                                    pit.Item          = cit.Item;
                                    pit.Cantidad      = cit.Cantidad;
                                    pit.Producto      = cit.Producto;
                                    pit.MontoUnitario = cit.MontoUnitario;
                                    pit.Precio        = cit.Precio;
                                    pit.Costo         = cit.Costo;

                                    fac.LasPartidas().Add(pit);
                                }
                            }
                        }
                    }
                }
            }
        }
Esempio n. 29
0
        private void CreateSecurityDemoObjects()
        {
            FullAccessObject fullAccessObject = ObjectSpace.FindObject <FullAccessObject>(new BinaryOperator("Name", "Fully Accessible Object"));

            if (fullAccessObject == null)
            {
                fullAccessObject      = ObjectSpace.CreateObject <FullAccessObject>();
                fullAccessObject.Name = "Fully Accessible Object";
                fullAccessObject.Save();
            }
            ProtectedContentObject protectedContentObject = ObjectSpace.FindObject <ProtectedContentObject>(new BinaryOperator("Name", "Protected Object"));

            if (protectedContentObject == null)
            {
                protectedContentObject      = ObjectSpace.CreateObject <ProtectedContentObject>();
                protectedContentObject.Name = "Protected Object";
                protectedContentObject.Save();
            }
            ReadOnlyObject readOnlyObject = ObjectSpace.FindObject <ReadOnlyObject>(new BinaryOperator("Name", "Read-Only Object"));

            if (readOnlyObject == null)
            {
                readOnlyObject      = ObjectSpace.CreateObject <ReadOnlyObject>();
                readOnlyObject.Name = "Read-Only Object";
                readOnlyObject.Save();
            }

            IrremovableObject irremovableObject = ObjectSpace.FindObject <IrremovableObject>(new BinaryOperator("Name", "Protected Deletion Object"));

            if (irremovableObject == null)
            {
                irremovableObject      = ObjectSpace.CreateObject <IrremovableObject>();
                irremovableObject.Name = "Protected Deletion Object";
                irremovableObject.Save();
            }
            UncreatableObject uncreatableObject = ObjectSpace.FindObject <UncreatableObject>(new BinaryOperator("Name", "Protected Creation Object"));

            if (uncreatableObject == null)
            {
                uncreatableObject      = ObjectSpace.CreateObject <UncreatableObject>();
                uncreatableObject.Name = "Protected Creation Object";
                uncreatableObject.Save();
            }
            MemberLevelSecurityObject memberLevelSecurityObject = ObjectSpace.FindObject <MemberLevelSecurityObject>(new BinaryOperator("Name", "Member-Level Protected Object"));

            if (memberLevelSecurityObject == null)
            {
                memberLevelSecurityObject      = ObjectSpace.CreateObject <MemberLevelSecurityObject>();
                memberLevelSecurityObject.Name = "Member-Level Protected Object";
                memberLevelSecurityObject.ProtectedContentProperty = "Secure Property Value";
                memberLevelSecurityObject.ReadWriteProperty        = "Read Write Property Value";
                memberLevelSecurityObject.ReadOnlyProperty         = "Read Only Property Value";
                MemberLevelReferencedObject1 obj1 = ObjectSpace.CreateObject <MemberLevelReferencedObject1>();
                obj1.Name = "Referenced Object Type 1";
                obj1.Save();
                memberLevelSecurityObject.ProtectedContentCollection.Add(obj1);
                MemberLevelReferencedObject2 obj2 = ObjectSpace.CreateObject <MemberLevelReferencedObject2>();
                obj2.Name = "Referenced Object Type 2";
                obj2.Save();
                memberLevelSecurityObject.ReadOnlyCollection.Add(obj2);
                memberLevelSecurityObject.Save();
            }
            ObjectLevelSecurityObject fullAccessObjectObject = ObjectSpace.FindObject <ObjectLevelSecurityObject>(new BinaryOperator("Name", "Fully Accessible Object"));

            if (fullAccessObjectObject == null)
            {
                fullAccessObjectObject      = ObjectSpace.CreateObject <ObjectLevelSecurityObject>();
                fullAccessObjectObject.Name = "Fully Accessible Object";
                fullAccessObjectObject.Save();
            }
            ObjectLevelSecurityObject protectedContentObjectObject = ObjectSpace.FindObject <ObjectLevelSecurityObject>(new BinaryOperator("Name", "Protected Object"));

            if (protectedContentObjectObject == null)
            {
                protectedContentObjectObject      = ObjectSpace.CreateObject <ObjectLevelSecurityObject>();
                protectedContentObjectObject.Name = "Protected Object";
                protectedContentObjectObject.Save();
            }
            ObjectLevelSecurityObject readOnlyObjectObject = ObjectSpace.FindObject <ObjectLevelSecurityObject>(new BinaryOperator("Name", "Read-Only Object"));

            if (readOnlyObjectObject == null)
            {
                readOnlyObjectObject      = ObjectSpace.CreateObject <ObjectLevelSecurityObject>();
                readOnlyObjectObject.Name = "Read-Only Object";
                readOnlyObjectObject.Save();
            }
            ObjectLevelSecurityObject irremovableObjectObject = ObjectSpace.FindObject <ObjectLevelSecurityObject>(new BinaryOperator("Name", "Protected Deletion Object"));

            if (irremovableObjectObject == null)
            {
                irremovableObjectObject      = ObjectSpace.CreateObject <ObjectLevelSecurityObject>();
                irremovableObjectObject.Name = "Protected Deletion Object";
                irremovableObjectObject.Save();
            }
        }
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
#if EASYTEST
            var developerPosition = ObjectSpace.FindObject <Position>(CriteriaOperator.Parse("Title == 'Developer'"));
            if (developerPosition == null)
            {
                developerPosition       = ObjectSpace.CreateObject <Position>();
                developerPosition.Title = "Developer";
                developerPosition.Save();
            }
            var managerPosition = ObjectSpace.FindObject <Position>(CriteriaOperator.Parse("Title == 'Manager'"));
            if (managerPosition == null)
            {
                managerPosition       = ObjectSpace.CreateObject <Position>();
                managerPosition.Title = "Manager";
                managerPosition.Save();
            }
            var devDepartment = ObjectSpace.FindObject <Department>(CriteriaOperator.Parse("Title == 'Development Department'"));
            if (devDepartment == null)
            {
                devDepartment        = ObjectSpace.CreateObject <Department>();
                devDepartment.Title  = "Development Department";
                devDepartment.Office = "205";
                devDepartment.Positions.Add(developerPosition);
                devDepartment.Positions.Add(managerPosition);
                devDepartment.Save();
            }
            var contactMary = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Mary' && LastName == 'Tellitson'"));
            if (contactMary == null)
            {
                contactMary            = ObjectSpace.CreateObject <Contact>();
                contactMary.FirstName  = "Mary";
                contactMary.LastName   = "Tellitson";
                contactMary.Email      = "*****@*****.**";
                contactMary.Birthday   = new DateTime(1980, 11, 27);
                contactMary.Department = devDepartment;
                contactMary.Position   = managerPosition;
                contactMary.Save();
            }
            var contactJohn = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'John' && LastName == 'Nilsen'"));
            if (contactJohn == null)
            {
                contactJohn            = ObjectSpace.CreateObject <Contact>();
                contactJohn.FirstName  = "John";
                contactJohn.LastName   = "Nilsen";
                contactJohn.Email      = "*****@*****.**";
                contactJohn.Birthday   = new DateTime(1981, 10, 3);
                contactJohn.Department = devDepartment;
                contactJohn.Position   = developerPosition;
                contactJohn.Save();
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Review reports'")) == null)
            {
                var task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Review reports";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("May 03, 2008");
                task.DueDate       = DateTime.Parse("September 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.InProgress;
                task.Priority      = Priority.High;
                task.EstimatedWork = 60;
                task.Description   = "Analyse the reports and assign new tasks to employees.";
                task.Save();
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Fix breakfast'")) == null)
            {
                var task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Fix breakfast";
                task.AssignedTo    = contactMary;
                task.StartDate     = DateTime.Parse("May 03, 2008");
                task.DueDate       = DateTime.Parse("May 04, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.Low;
                task.EstimatedWork = 1;
                task.ActualWork    = 3;
                task.Description   = "The Development Department - by 9 a.m.\r\nThe R&QA Department - by 10 a.m.";
                task.Save();
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task1'")) == null)
            {
                var task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Task1";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("June 03, 2008");
                task.DueDate       = DateTime.Parse("June 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.High;
                task.EstimatedWork = 10;
                task.ActualWork    = 15;
                task.Description   = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
                task.Save();
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task2'")) == null)
            {
                var task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Task2";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("July 03, 2008");
                task.DueDate       = DateTime.Parse("July 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.Low;
                task.EstimatedWork = 8;
                task.ActualWork    = 16;
                task.Description   = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
                task.Save();
            }
            ObjectSpace.CommitChanges();
#endif
        }
Esempio n. 31
0
        private void CreatePlanningData()
        {
            Tracing.Tracer.LogText("Creating Persons");
            Person john = CreatePerson("Nilsen", "John", GetEmbeddedResourceByteArray("m01.jpg"), "*****@*****.**");
            Person sam  = CreatePerson("Peterson", "Sam", GetEmbeddedResourceByteArray("m03.jpg"), "*****@*****.**");
            Person mary = CreatePerson("Tellitson", "Mary", GetEmbeddedResourceByteArray("w02.jpg"), "*****@*****.**");
            Person lily = CreatePerson("Johnson", "Lily", GetEmbeddedResourceByteArray("w04.jpg"), "*****@*****.**");

            Tracing.Tracer.LogText("Creating 'General DevExpress XAF Evaluation' Project & Tasks");
            Project generalEvaluationProject = CreateProject("General DevExpress XAF Evaluation", mary);

            CreateProjectTask(generalEvaluationProject, "1. Check general product and company information, licensing and pricing", "http://www.devexpress.com/xaf", ProjectTaskStatus.Completed, mary);
            CreateProjectTask(generalEvaluationProject, "2. Check features of the DevExpress WinForms, ASP.NET WebForms & DevExtreme HTML5/JavaScript controls used in XAF", "http://www.devexpress.com/asp\r\nhttp://www.devexpress.com/winforms\r\nhttps://js.devexpress.com/", ProjectTaskStatus.NotStarted, mary);
            CreateProjectTask(generalEvaluationProject, "3. Download a free 30-day trial (free technical support included)", "http://www.devexpress.com/Home/Try.xml", ProjectTaskStatus.Completed, mary);
            CreateProjectTask(generalEvaluationProject, "4. Play with online demo applications on the web site and research local demos in the Demo Center from the installation", "SimpleProjectManager, MainDemo, XCRM, XVideoRental, FeatureCenter, SecurityDemo, WorkflowDemo, etc. at %public%\\Documents\\", ProjectTaskStatus.InProgress, mary);
            CreateProjectTask(generalEvaluationProject, "5. Analyze key characteristics (look & feel, features set, performance, usability, etc.)", "http://www.devexpress.com/xaf", ProjectTaskStatus.InProgress, mary);
            CreateProjectTask(generalEvaluationProject, "6. Try the Getting Started tutorials and build a few a prototypes", "https://documentation.devexpress.com/#eXpressAppFramework/CustomDocument113577", ProjectTaskStatus.InProgress, mary);
            CreateProjectTask(generalEvaluationProject, "7. Check support options and learning materials (documentation, examples, videos, blogs, webinars, etc.)", "http://www.devexpress.com/support/\r\n", ProjectTaskStatus.Completed, mary);
            CreateProjectTask(generalEvaluationProject, "8. Learn more about the Universal subscription features", "http://www.devexpress.com/Subscriptions/Universal.xml", ProjectTaskStatus.Completed, mary);
            CreateProjectTask(generalEvaluationProject, "9. Consider using a live chat on site or emailing at [email protected] if you have any pre-sales questions", "http://www.devexpress.com/Home/ContactUs.xml", ProjectTaskStatus.Deferred, mary);

            Tracing.Tracer.LogText("Creating 'DevExpress XAF Features Overview' Project & Tasks");
            Project featuresOverviewProject = CreateProject("DevExpress XAF Features Overview", sam);

            try {
                XDocument doc = XDocument.Load(GetEmbeddedResourceStream("ProjectTasks.xml"));
                foreach (XElement el in doc.Root.Elements())
                {
                    XAttribute subject = el.Attribute("Subject");
                    if (subject != null)
                    {
                        ProjectTask task = ObjectSpace.FindObject <ProjectTask>(new BinaryOperator("Subject", subject.Value));
                        if (task == null)
                        {
                            task         = ObjectSpace.CreateObject <ProjectTask>();
                            task.Subject = subject.Value;

                            XElement notes = el.Element(XName.Get("Notes"));
                            if (notes != null)
                            {
                                task.Notes = notes.Value.Replace("\n", Environment.NewLine);
                            }
                            task.AssignedTo = rnd.Next(5) % 2 == 0 ? (rnd.Next(6) % 2 == 0 ? sam : lily) : john;
                            task.Project    = featuresOverviewProject;
                            task.Status     = rnd.Next(7) % 2 == 0 ? (rnd.Next(8) % 2 == 0 ? ProjectTaskStatus.InProgress : ProjectTaskStatus.Completed) : (rnd.Next(9) % 2 == 0 ? ProjectTaskStatus.NotStarted : ProjectTaskStatus.Completed);
                            if (task.Status == ProjectTaskStatus.InProgress || task.Status == ProjectTaskStatus.Completed)
                            {
                                task.StartDate = DateTime.Now.AddDays(rnd.Next(1) * (-1));
                            }
                            if (task.Status == ProjectTaskStatus.Completed)
                            {
                                task.EndDate = DateTime.Now.AddDays(rnd.Next(2));
                            }
                        }
                    }
                    ObjectSpace.CommitChanges();
                }
            }
            catch (Exception ex) {
                Tracing.Tracer.LogError(ex);
            }
        }
Esempio n. 32
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
            UpdateAnalysisCriteriaColumn();

            SecuritySystemRole defaultRole = CreateDefaultRole();

            Position developerPosition = ObjectSpace.FindObject <Position>(CriteriaOperator.Parse("Title == 'Developer'"));

            if (developerPosition == null)
            {
                developerPosition       = ObjectSpace.CreateObject <Position>();
                developerPosition.Title = "Developer";
            }
            Position managerPosition = ObjectSpace.FindObject <Position>(CriteriaOperator.Parse("Title == 'Manager'"));

            if (managerPosition == null)
            {
                managerPosition       = ObjectSpace.CreateObject <Position>();
                managerPosition.Title = "Manager";
            }

            Department devDepartment = ObjectSpace.FindObject <Department>(CriteriaOperator.Parse("Title == 'Development Department'"));

            if (devDepartment == null)
            {
                devDepartment        = ObjectSpace.CreateObject <Department>();
                devDepartment.Title  = "Development Department";
                devDepartment.Office = "205";
                devDepartment.Positions.Add(developerPosition);
                devDepartment.Positions.Add(managerPosition);
            }

            Contact contactMary = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'Mary' && LastName == 'Tellitson'"));

            if (contactMary == null)
            {
                contactMary            = ObjectSpace.CreateObject <Contact>();
                contactMary.FirstName  = "Mary";
                contactMary.LastName   = "Tellitson";
                contactMary.Email      = "*****@*****.**";
                contactMary.Birthday   = new DateTime(1980, 11, 27);
                contactMary.Department = devDepartment;
                contactMary.Position   = managerPosition;
            }

            Contact contactJohn = ObjectSpace.FindObject <Contact>(CriteriaOperator.Parse("FirstName == 'John' && LastName == 'Nilsen'"));

            if (contactJohn == null)
            {
                contactJohn            = ObjectSpace.CreateObject <Contact>();
                contactJohn.FirstName  = "John";
                contactJohn.LastName   = "Nilsen";
                contactJohn.Email      = "*****@*****.**";
                contactJohn.Birthday   = new DateTime(1981, 10, 3);
                contactJohn.Department = devDepartment;
                contactJohn.Position   = developerPosition;
            }

            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Review reports'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Review reports";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("May 03, 2008");
                task.DueDate       = DateTime.Parse("September 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.InProgress;
                task.Priority      = Priority.High;
                task.EstimatedWork = 60;
                task.Description   = "Analyse the reports and assign new tasks to employees.";
            }

            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Fix breakfast'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Fix breakfast";
                task.AssignedTo    = contactMary;
                task.StartDate     = DateTime.Parse("May 03, 2008");
                task.DueDate       = DateTime.Parse("May 04, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.Low;
                task.EstimatedWork = 1;
                task.ActualWork    = 3;
                task.Description   = "The Development Department - by 9 a.m.\r\nThe R&QA Department - by 10 a.m.";
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task1'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Task1";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("June 03, 2008");
                task.DueDate       = DateTime.Parse("June 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.High;
                task.EstimatedWork = 10;
                task.ActualWork    = 15;
                task.Description   = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
            }
            if (ObjectSpace.FindObject <DemoTask>(CriteriaOperator.Parse("Subject == 'Task2'")) == null)
            {
                DemoTask task = ObjectSpace.CreateObject <DemoTask>();
                task.Subject       = "Task2";
                task.AssignedTo    = contactJohn;
                task.StartDate     = DateTime.Parse("July 03, 2008");
                task.DueDate       = DateTime.Parse("July 06, 2008");
                task.Status        = DevExpress.Persistent.Base.General.TaskStatus.Completed;
                task.Priority      = Priority.Low;
                task.EstimatedWork = 8;
                task.ActualWork    = 16;
                task.Description   = "A task designed specially to demonstrate the PivotChart module. Switch to the Reports navigation group to view the generated analysis.";
            }
            UpdateStatus("CreateAnalysis", "", "Creating analysis reports in the database...");
            CreateDataToBeAnalysed();
            UpdateStatus("CreateSecurityData", "", "Creating users and roles in the database...");
            #region Create a User for the Simple Security Strategy
            //// If a simple user named 'Sam' doesn't exist in the database, create this simple user
            //SecuritySimpleUser adminUser = ObjectSpace.FindObject<SecuritySimpleUser>(new BinaryOperator("UserName", "Sam"));
            //if(adminUser == null) {
            //    adminUser = ObjectSpace.CreateObject<SecuritySimpleUser>();
            //    adminUser.UserName = "******";
            //}
            //// Make the user an administrator
            //adminUser.IsAdministrator = true;
            //// Set a password if the standard authentication type is used
            //adminUser.SetPassword("");
            #endregion

            #region Create Users for the Complex Security Strategy
            // If a user named 'Sam' doesn't exist in the database, create this user
            SecuritySystemUser user1 = ObjectSpace.FindObject <SecuritySystemUser>(new BinaryOperator("UserName", "Sam"));
            if (user1 == null)
            {
                user1          = ObjectSpace.CreateObject <SecuritySystemUser>();
                user1.UserName = "******";
                // Set a password if the standard authentication type is used
                user1.SetPassword("");
            }
            // If a user named 'John' doesn't exist in the database, create this user
            SecuritySystemUser user2 = ObjectSpace.FindObject <SecuritySystemUser>(new BinaryOperator("UserName", "John"));
            if (user2 == null)
            {
                user2          = ObjectSpace.CreateObject <SecuritySystemUser>();
                user2.UserName = "******";
                // Set a password if the standard authentication type is used
                user2.SetPassword("");
            }
            // If a role with the Administrators name doesn't exist in the database, create this role
            SecuritySystemRole adminRole = ObjectSpace.FindObject <SecuritySystemRole>(new BinaryOperator("Name", "Administrators"));
            if (adminRole == null)
            {
                adminRole      = ObjectSpace.CreateObject <SecuritySystemRole>();
                adminRole.Name = "Administrators";
            }
            adminRole.IsAdministrative = true;

            // If a role with the Users name doesn't exist in the database, create this role
            SecuritySystemRole userRole = ObjectSpace.FindObject <SecuritySystemRole>(new BinaryOperator("Name", "Users"));
            if (userRole == null)
            {
                userRole      = ObjectSpace.CreateObject <SecuritySystemRole>();
                userRole.Name = "Users";
            }

            userRole.SetTypePermissionsRecursively <object>(SecurityOperations.FullAccess, SecuritySystemModifier.Allow);
            userRole.SetTypePermissionsRecursively <SecuritySystemUser>(SecurityOperations.FullAccess, SecuritySystemModifier.Deny);
            userRole.SetTypePermissionsRecursively <SecuritySystemRole>(SecurityOperations.FullAccess, SecuritySystemModifier.Deny);

            // Add the Administrators role to the user1
            user1.Roles.Add(adminRole);
            // Add the Users role to the user2
            user2.Roles.Add(userRole);
            user2.Roles.Add(defaultRole);
            #endregion

            ObjectSpace.CommitChanges();
        }
Esempio n. 33
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();

            /*
             * string[] lstTypen = new string[] { "Telefonnummer", "Zugangscode", "Schlüsseldepot" };
             *
             * for(int i=0;i<lstTypen.Count();i++)
             * {
             *  fiZugangsTyp curTyp = ObjectSpace.FindObject<fiZugangsTyp>(new BinaryOperator("Bezeichnung", lstTypen[i], BinaryOperatorType.Equal));
             *    if(curTyp == null)
             *  {
             *      curTyp = ObjectSpace.CreateObject<fiZugangsTyp>();
             *      curTyp.Bezeichnung = lstTypen[i];
             *      curTyp.Save();
             *  }
             * }
             */

            Hashtable lstFileTypes = new Hashtable();

            lstFileTypes.Add("xls", "Excel 2003");
            lstFileTypes.Add("xlsx", "Excel");
            lstFileTypes.Add("xlm", "Excel mit Makros");

            foreach (DictionaryEntry item in lstFileTypes)
            {
                importFileType curFileType = ObjectSpace.FindObject <importFileType>(new BinaryOperator("Name", item.Value, BinaryOperatorType.Equal));
                if (curFileType == null)
                {
                    curFileType           = ObjectSpace.CreateObject <importFileType>();
                    curFileType.Extension = item.Key.ToString();
                    curFileType.Name      = item.Value.ToString();
                    curFileType.Save();
                }
            }

            boGeraeteart curGeraeteart = ObjectSpace.FindObject <boGeraeteart>(new BinaryOperator("Bezeichnung", "Armatur", BinaryOperatorType.Equal));

            if (curGeraeteart == null)
            {
                curGeraeteart             = ObjectSpace.CreateObject <boGeraeteart>();
                curGeraeteart.Bezeichnung = "Armatur";
                curGeraeteart.Save();
            }

            //die Armaturarten auch gleich anlegen
            Hashtable lstArmaturarten = new Hashtable();

            lstArmaturarten.Add("EHM", "Einhebelmischer");
            lstArmaturarten.Add("ZGM", "Zweigriffarmatur");
            lstArmaturarten.Add("SA", "Sensorarmatur");
            lstArmaturarten.Add("THA", "Thermostatarmatur");
            lstArmaturarten.Add("KA", "Küchenarmatur");
            lstArmaturarten.Add("AZA", "Auszieharmatur");
            lstArmaturarten.Add("KFE", "Kessel Füll- und Entleerhahn");
            lstArmaturarten.Add("PV", "Probennahmeventil");
            lstArmaturarten.Add("VK", "Entleerventil/-hahn Kunststoff");
            lstArmaturarten.Add("VM", "Entleerventil/-hahn Messing");

            foreach (DictionaryEntry item in lstArmaturarten)
            {
                boGeraet curgeraet = ObjectSpace.FindObject <boGeraet>(new BinaryOperator("Bezeichnung", item.Value.ToString(), BinaryOperatorType.Equal));
                if (curgeraet == null)
                {
                    curgeraet             = ObjectSpace.CreateObject <boGeraet>();
                    curgeraet.Bezeichnung = item.Value.ToString();
                    curgeraet.Kuerzel     = item.Key.ToString();
                    curgeraet.Geraeteart  = ObjectSpace.FindObject <boGeraeteart>(new BinaryOperator("Bezeichnung", "Armatur", BinaryOperatorType.Equal));
                    curgeraet.Save();
                }

                AnPruefanschluss curAnschluss = ObjectSpace.FindObject <AnPruefanschluss>(new BinaryOperator("Bezeichnung", item.Value.ToString(), BinaryOperatorType.Equal));
                if (curAnschluss == null)
                {
                    curAnschluss             = ObjectSpace.CreateObject <AnPruefanschluss>();
                    curAnschluss.Bezeichnung = item.Value.ToString();
                    curAnschluss.Kuerzel     = item.Key.ToString();
                    curAnschluss.Save();
                }
            }

            Hashtable lstRisikoGruppe = new Hashtable();

            lstRisikoGruppe.Add("1a", "1a Verwaltungsgebäude, Öffentliche Gebäude, Büro oder Geschäfte");
            lstRisikoGruppe.Add("1b", "Wohnanlagen,private Gebäude");
            lstRisikoGruppe.Add("2", "Schulen, Kindergarten, Hotels, Kasernen, Sportanlagen");
            lstRisikoGruppe.Add("3", "Altenheime, Kuranstalten, Rehab, (Zahn- oder Facharzt)");
            lstRisikoGruppe.Add("4", "Krankenanstalten");

            foreach (DictionaryEntry item in lstRisikoGruppe)
            {
                fiRisikoGruppe curGruppe = ObjectSpace.FindObject <fiRisikoGruppe>(new BinaryOperator("Kuerzel", item.Key.ToString(), BinaryOperatorType.Equal));
                if (curGruppe == null)
                {
                    curGruppe             = ObjectSpace.CreateObject <fiRisikoGruppe>();
                    curGruppe.Bezeichnung = item.Value.ToString();
                    curGruppe.Kuerzel     = item.Key.ToString();
                    curGruppe.Save();
                }
            }

            //Prüfpunkttypen anlegen
            Hashtable lstPruefpunktTyp = new Hashtable();

            lstPruefpunktTyp.Add("SP", "Spüle");
            lstPruefpunktTyp.Add("WT", "Waschtisch");
            lstPruefpunktTyp.Add("SPUD", "Speucher unteres Drittel");
            lstPruefpunktTyp.Add("SPA", "Speicher Austritt");
            lstPruefpunktTyp.Add("AH", "Auslaufhahn");
            lstPruefpunktTyp.Add("BWS", "Badewanne mit Schlauch und DK");
            lstPruefpunktTyp.Add("BW", "Badewanne");
            lstPruefpunktTyp.Add("RDU", "Regenduschanlage");
            lstPruefpunktTyp.Add("DUMO", "Dusche mit Schlauch ohne DK");
            lstPruefpunktTyp.Add("DU", "Dusche ohne Schlauch und DK");
            lstPruefpunktTyp.Add("DUSK", "Dusche mit Schlauch und DK");
            lstPruefpunktTyp.Add("ZIRKS", "Zirkulationssammelleitung");
            lstPruefpunktTyp.Add("ZIRKE", "Zirkulationseinzelstrang");
            lstPruefpunktTyp.Add("WWE", "Warmwasser-Einzelstrang");
            lstPruefpunktTyp.Add("KWE", "Kaltwasser-Einzelstrang");
            lstPruefpunktTyp.Add("KWA", "Kaltwasser Allgemein");
            lstPruefpunktTyp.Add("WWA", "Warmwasser Allgemein");
            lstPruefpunktTyp.Add("KWSP", "Kaltwasser-Speicher");
            lstPruefpunktTyp.Add("KWH", "Kaltwasser-Hauseintritt");
            lstPruefpunktTyp.Add("KODU", "Überkopfdusche");

            foreach (DictionaryEntry item in lstPruefpunktTyp)
            {
                AnPruefPunktTyp curpTyp = ObjectSpace.FindObject <AnPruefPunktTyp>(new BinaryOperator("Bezeichnung", item.Value.ToString(), BinaryOperatorType.Equal));
                if (curpTyp == null)
                {
                    curpTyp             = ObjectSpace.CreateObject <AnPruefPunktTyp>();
                    curpTyp.Bezeichnung = item.Value.ToString();
                    curpTyp.Kuerzel     = item.Key.ToString();
                    curpTyp.Save();
                }
            }

            //die Ebebnenarten anlegen
            Hashtable lstEbnen = new Hashtable();

            lstEbnen.Add("UG", "Untergeschoss");
            lstEbnen.Add("EG", "Erdgeschoss");
            lstEbnen.Add("OG", "Obergeschoss");
            lstEbnen.Add("ZG", "Zwischengeschoss");
            lstEbnen.Add("DG", "Dachgeschoss");
            lstEbnen.Add("KG", "Kellergeschoss");
            foreach (DictionaryEntry item in lstEbnen)
            {
                fiEbenenart curEbenenart = ObjectSpace.FindObject <fiEbenenart>(new BinaryOperator("Bezeichnung", item.Value.ToString(), BinaryOperatorType.Equal));
                if (curEbenenart == null)
                {
                    curEbenenart             = ObjectSpace.CreateObject <fiEbenenart>();
                    curEbenenart.Kuerzel     = item.Key.ToString();
                    curEbenenart.Bezeichnung = item.Value.ToString();
                    curEbenenart.Save();
                }
            }
            //die Ruamarten anlegen
            Hashtable lstRaumarten = new Hashtable();

            lstRaumarten.Add("TR", "Technikraum");
            lstRaumarten.Add("WK", "Waschkücke");
            lstRaumarten.Add("K", "Küche");
            lstRaumarten.Add("WC", "Toilette");
            lstRaumarten.Add("HR", "Heizungsraum");

            foreach (DictionaryEntry item in lstRaumarten)
            {
                fiRaumart curRaumart = ObjectSpace.FindObject <fiRaumart>(new BinaryOperator("Bezeichnung", item.Value.ToString(), BinaryOperatorType.Equal));
                if (curRaumart == null)
                {
                    curRaumart             = ObjectSpace.CreateObject <fiRaumart>();
                    curRaumart.Kuerzel     = item.Key.ToString();
                    curRaumart.Bezeichnung = item.Value.ToString();
                    curRaumart.Save();
                }
            }

            //die Ruamarten anlegen
            Hashtable lstParameterTyp = new Hashtable();

            lstParameterTyp.Add("EP", "Einstellparameter");
            lstParameterTyp.Add("SP", "Sollparameter");
            lstParameterTyp.Add("PP", "Prüfparameter");


            foreach (DictionaryEntry item in lstParameterTyp)
            {
                parameterParameterTyp curParamTyp = ObjectSpace.FindObject <parameterParameterTyp>(new BinaryOperator("Code", item.Key.ToString(), BinaryOperatorType.Equal));
                if (curParamTyp == null)
                {
                    curParamTyp             = ObjectSpace.CreateObject <parameterParameterTyp>();
                    curParamTyp.Code        = item.Key.ToString();
                    curParamTyp.Bezeichnung = item.Value.ToString();
                    curParamTyp.Save();
                }
            }

            //Zugangskategorie
            Hashtable lstZugangsKategorie = new Hashtable();

            lstZugangsKategorie.Add("Hausverwaltung", "1");
            lstZugangsKategorie.Add("Hausbetreuung", "1");
            lstZugangsKategorie.Add("Schlüssel", "1");
            lstZugangsKategorie.Add("Kontakt", "0");
            lstZugangsKategorie.Add("Sonstiges", "0");
            foreach (DictionaryEntry item in lstZugangsKategorie)
            {
                fiZugangKategorie curKategorie = ObjectSpace.FindObject <fiZugangKategorie>(new BinaryOperator("Bezeichnung", item.Key.ToString(), BinaryOperatorType.Equal));
                Int32             value        = 0;
                if (curKategorie == null)
                {
                    curKategorie             = ObjectSpace.CreateObject <fiZugangKategorie>();
                    curKategorie.Bezeichnung = item.Key.ToString();
                    value = Int32.Parse(item.Value.ToString());
                    curKategorie.DefaultStatus = (EnumStore.enmStatusZugang)value;
                    curKategorie.Save();
                }
            }
        }
Esempio n. 34
0
        public void InsertMock()
        {
            #region Arrange

            var csvText = @"Description,Amount,MockLookupObject1,MockLookupObject2
Hello 1,10,Parent 1,Parent B1
Hello 2,11,Parent 2,Parent B2
Hello 3,12,Parent 3,Parent B3
Hello 4,13,Parent 4,Parent B4
";

            var map1 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map1.SourceName = "Description";
            map1.TargetName = map1.SourceName;

            var map2 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map2.SourceName = "Amount";
            map2.TargetName = map2.SourceName;

            var map3 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map3.SourceName   = "MockLookupObject1";
            map3.TargetName   = map3.SourceName;
            map3.CreateMember = true;
            map3.CacheObject  = true;

            var map4 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map4.SourceName   = "MockLookupObject2";
            map4.TargetName   = map4.SourceName;
            map4.CreateMember = true;
            map4.CacheObject  = true;

            var param = ObjectSpace.CreateObject <ImportHeadersParam>();

            param.HeaderToFieldMaps.Add(map1);
            param.HeaderToFieldMaps.Add(map2);
            param.HeaderToFieldMaps.Add(map3);
            param.HeaderToFieldMaps.Add(map4);

            param.ObjectTypeName = "MockFactObject";

            ObjectSpace.CommitChanges();

            #endregion

            #region Act

            var             csvStream = ConvertToCsvStream(csvText);
            var             xpoMapper = new XpoFieldMapper();
            ICsvToXpoLoader loader    = new HeadCsvToXpoInserter(param, csvStream, xpoMapper, null);
            loader.Execute();
            ObjectSpace.CommitChanges();

            #endregion

            #region Assert

            var inserted = new XPQuery <MockFactObject>(ObjectSpace.Session);
            Assert.AreEqual(4, inserted.Count());
            var obj1 = inserted.Where(x => x.Description == "Hello 1").FirstOrDefault();
            var obj2 = inserted.Where(x => x.Description == "Hello 2").FirstOrDefault();
            var obj3 = inserted.Where(x => x.Description == "Hello 3").FirstOrDefault();
            var obj4 = inserted.Where(x => x.Description == "Hello 4").FirstOrDefault();

            Assert.NotNull(obj1.MockLookupObject1);
            Assert.NotNull(obj1.MockLookupObject2);
            Assert.NotNull(obj2.MockLookupObject1);
            Assert.NotNull(obj2.MockLookupObject2);
            Assert.NotNull(obj3.MockLookupObject1);
            Assert.NotNull(obj3.MockLookupObject2);
            Assert.NotNull(obj4.MockLookupObject1);
            Assert.NotNull(obj4.MockLookupObject2);

            #endregion
        }
Esempio n. 35
0
        public static XPCollection<ClassTransactionTracking> CreateStudentClassTrackingData(ObjectSpace objectSpace, string semesterName)
        {
            string strParse = "";
            try
            {
                using (XPCollection<StudentClass> xpw = new XPCollection<StudentClass>(objectSpace.Session))
                {

                    foreach (StudentClass studentClass in xpw)
                    {
                        ClassTransactionTracking ct = objectSpace.FindObject<ClassTransactionTracking>
                            (CriteriaOperator.Parse("StudentClass.ClassCode = ? and Semester.SemesterName = ?",
                            studentClass.ClassCode, semesterName));
                        if (ct == null)
                        {
                            ct = objectSpace.CreateObject< ClassTransactionTracking>();
                            ct.Semester = objectSpace.FindObject<Semester>(CriteriaOperator.Parse("SemesterName=?", semesterName));
                            ct.StudentClass = objectSpace.FindObject<StudentClass>(CriteriaOperator.Parse("ClassCode=?", studentClass.ClassCode));
                            ct.Save();
                        }

                        strParse += (strParse == "" ? string.Format("StudentClass.ClassCode='{0}'", studentClass.ClassCode) :
                            string.Format(" or StudentClass.ClassCode='{0}'", studentClass.ClassCode));
                    }
                    objectSpace.CommitChanges();
                    strParse = string.Format("({0}) and Semester.SemesterName= '{1}'", strParse, semesterName);
                }
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException(string.Format("Lỗi thực hiện: {0}\r\n Strack trace:{1}", ex.Message, ex.StackTrace));
            }
            return new XPCollection<ClassTransactionTracking>(objectSpace.Session, CriteriaOperator.Parse(strParse));
        }
Esempio n. 36
0
        public void InsertCashFlow()
        {
            #region Arrange

            var csvText = @"TranDate,Account,Activity,Counterparty,CounterCcyAmt,CounterCcy,Description,Source
21/03/2016,VHA ANZ 70086,AP Pymt,APPLE PTY LTD,-10000,AUD,Test transaction,Chris Tso";

            var map1 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map1.SourceName = "TranDate";
            map1.TargetName = map1.SourceName;

            var map2 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map2.SourceName   = "Account";
            map2.TargetName   = map2.SourceName;
            map2.CreateMember = true;

            var map3 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map3.SourceName   = "Activity";
            map3.TargetName   = map3.SourceName;
            map3.CreateMember = true;
            map3.CacheObject  = true;

            var map4 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map4.SourceName   = "Counterparty";
            map4.TargetName   = map4.SourceName;
            map4.CreateMember = true;
            map4.CacheObject  = true;

            var map5 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map5.SourceName = "CounterCcyAmt";
            map5.TargetName = map5.SourceName;

            var map6 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map6.SourceName   = "CounterCcy";
            map6.TargetName   = map6.SourceName;
            map6.CreateMember = true;
            //map6.CacheObject = true;

            var map7 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map7.SourceName = "Description";
            map7.TargetName = map7.SourceName;

            var map8 = ObjectSpace.CreateObject <HeaderToFieldMap>();
            map8.SourceName   = "Source";
            map8.TargetName   = map8.SourceName;
            map8.CreateMember = true;
            map8.CacheObject  = true;

            var param = ObjectSpace.CreateObject <ImportHeadersParam>();

            param.HeaderToFieldMaps.Add(map1);
            param.HeaderToFieldMaps.Add(map2);
            param.HeaderToFieldMaps.Add(map3);
            param.HeaderToFieldMaps.Add(map4);
            param.HeaderToFieldMaps.Add(map5);
            param.HeaderToFieldMaps.Add(map6);
            param.HeaderToFieldMaps.Add(map7);
            param.HeaderToFieldMaps.Add(map8);

            param.ObjectTypeName = "CashFlow";

            ObjectSpace.CommitChanges();

            #endregion

            #region Act

            var             csvStream = ConvertToCsvStream(csvText);
            var             xpoMapper = new XpoFieldMapper();
            ICsvToXpoLoader loader    = new HeadCsvToXpoInserter(param, csvStream, xpoMapper, null);
            loader.Execute();
            ObjectSpace.CommitChanges();

            #endregion

            #region Assert

            var inserted = new XPQuery <CashFlow>(ObjectSpace.Session);
            Assert.AreEqual(1, inserted.Count());
            var obj1 = inserted.FirstOrDefault();
            Assert.NotNull(obj1.Account);
            Assert.NotNull(obj1.Activity);
            Assert.NotNull(obj1.Counterparty);
            Assert.NotNull(obj1.Source);
            Assert.NotNull(obj1.CounterCcy);

            #endregion
        }
Esempio n. 37
0
        public static XPCollection<WeekReportData> CreateClassroomTimetableData(ObjectSpace objectSpace, string classroomCode, string semesterName)
        {
            ConstrainstParameter cp = objectSpace.FindObject<ConstrainstParameter>(
               new BinaryOperator("Code", "AFTERNOONPERIODCOUNT"));
            int afternoonPeriodCount = Convert.ToInt32(cp.Value);

            cp = objectSpace.FindObject<ConstrainstParameter>(
               new BinaryOperator("Code", "MORNINGPERIODCOUNT"));
            int morningPeriodCount = Convert.ToInt32(cp.Value);

            try
            {
                using (XPCollection<WeekReportData> xpw = new XPCollection<WeekReportData>(objectSpace.Session,
                           new ContainsOperator("Classrooms", new BinaryOperator("ClassroomCode", classroomCode))))
                {

                    objectSpace.Delete(xpw);
                    objectSpace.CommitChanges();
                    using (XPCollection<TkbSemester> xpctkbSemester = new XPCollection<TkbSemester>(objectSpace.Session,
                        new GroupOperator(GroupOperatorType.And, new BinaryOperator("Lesson.Semester.SemesterName",
                            semesterName), new BinaryOperator("Classroom.ClassroomCode", classroomCode))))
                    {

                        Dictionary<string, WeekReportData> dicTimePeriodforWeekData = new Dictionary<string, WeekReportData>();
                        WeekReportData currentWeekData;

                        foreach (TkbSemester tkbSem in xpctkbSemester)
                        {
                            string[] strperiod = tkbSem.Period.Split(',');
                            List<string> periodTimeList = new List<string>();
                            foreach (string s in strperiod)
                            {
                                if (Convert.ToInt32(s) >= 1 && Convert.ToInt32(s) <= morningPeriodCount)
                                    if (!periodTimeList.Contains("Sáng"))
                                        periodTimeList.Add("Sáng");
                                if (Convert.ToInt32(s) > morningPeriodCount && Convert.ToInt32(s) <= (morningPeriodCount + afternoonPeriodCount))
                                    if (!periodTimeList.Contains("Chiều"))
                                        periodTimeList.Add("Chiều");
                                if (Convert.ToInt32(s) > (morningPeriodCount + afternoonPeriodCount))
                                    if (!periodTimeList.Contains("Tối"))
                                        periodTimeList.Add("Tối");
                            }

                            foreach (String period in periodTimeList)
                            {
                                if (!dicTimePeriodforWeekData.ContainsKey(period))
                                {
                                    currentWeekData = objectSpace.CreateObject<WeekReportData>();
                                    currentWeekData.Semester = objectSpace.FindObject<Semester>(
                                        CriteriaOperator.Parse("SemesterName = ?", semesterName));
                                    currentWeekData.Classrooms.Add(objectSpace.FindObject<Classroom>(
                                        CriteriaOperator.Parse("ClassroomCode=?", classroomCode)));
                                    currentWeekData.PeriodTime = period;
                                    dicTimePeriodforWeekData.Add(period, currentWeekData);
                                }

                                dicTimePeriodforWeekData[period][tkbSem.Day] += string.Format("Lớp:{0}\r\n Môn:{1}-{2}\r\nTiết:{3}\r\nTuần:{4}\r\n\r\n",
                                        tkbSem.Lesson.ClassIDs, tkbSem.Lesson.Subject.SubjectCode, tkbSem.Lesson.Subject.SubjectName,
                                        Utils.ShortStringPeriod(tkbSem.Period), Utils.ShortStringWeek(tkbSem.StringWeeks));
                            }

                        }
                        objectSpace.CommitChanges();
                    }

                }
            }

            catch (Exception ex)
            {
                throw new UserFriendlyException("Lỗi thực hiện: " + ex.Message);
            }

            return new XPCollection<WeekReportData>(objectSpace.Session,
                           new GroupOperator(GroupOperatorType.And, new BinaryOperator("Semester.SemesterName",
                            semesterName), new ContainsOperator("Classrooms", new BinaryOperator("ClassroomCode", classroomCode))));
        }
Esempio n. 38
0
 static XDocument ExportRecords(ObjectSpace objectSpace) {
     ISerializationConfiguration serializationConfiguration = objectSpace.CreateObject<SerializationConfiguration>();
     serializationConfiguration.TypeToSerialize = typeof(PEnumClass);
     serializationConfiguration.SerializationConfigurationGroup =
         objectSpace.CreateObject<SerializationConfigurationGroup>();
     new ClassInfoGraphNodeBuilder().Generate(serializationConfiguration);
     XDocument document = new ExportEngine().Export(new[] { _pEnumClass }, serializationConfiguration.SerializationConfigurationGroup);
     return document;
 }