public void SilentlyRemoveNonExistentAlias()
        {
            string id = null;
            string dn = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";
            User   e  = new User
            {
                PrimaryEmail = dn,
                Password     = Guid.NewGuid().ToString(),
                Name         = new UserName
                {
                    GivenName  = "gn",
                    FamilyName = "sn"
                }
            };

            e  = UnitTestControl.TestParameters.UsersService.Add(e);
            id = e.Id;

            string alias1 = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";
            string alias2 = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";

            UnitTestControl.TestParameters.UsersService.AddAlias(id, alias1);
            UnitTestControl.TestParameters.UsersService.AddAlias(id, alias2);

            CSEntryChange cs = CSEntryChange.Create();

            cs.ObjectModificationType = ObjectModificationType.Update;
            cs.DN         = dn;
            cs.ObjectType = SchemaConstants.User;
            cs.AnchorAttributes.Add(AnchorAttribute.Create("id", id));

            cs.AttributeChanges.Add(AttributeChange.CreateAttributeUpdate("aliases", new List <ValueChange>
            {
                new ValueChange($"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}", ValueModificationType.Delete)
            }));

            try
            {
                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.User], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                System.Threading.Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);

                e = UnitTestControl.TestParameters.UsersService.Get(id);

                CollectionAssert.AreEquivalent(new string[] { alias1, alias2 }, e.Aliases);
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.UsersService.Delete(id);
                }
            }
        }
        public void UpdateDescription()
        {
            Group e = null;

            try
            {
                e = UnitTestControl.CreateGroup();

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Update;
                cs.DN         = e.Email;
                cs.ObjectType = SchemaConstants.Group;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", e.Id));
                cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("description"));

                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Group], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail($"{result.ErrorName}\n{result.ErrorDetail}");
                }

                e = UnitTestControl.TestParameters.GroupsService.Get(e.Id);
                Assert.AreEqual(cs.DN, e.Email);
                Assert.AreEqual(true, e.AdminCreated);
                Assert.AreEqual(string.Empty, e.Description);
            }
            finally
            {
                UnitTestControl.Cleanup(e);
            }
        }
Exemple #3
0
        public InstallScript ConvertManifestXml(XmlDocument doc, string name)
        {
            ExportProcessor.EnsureSystemData(_conn, ref _itemTypes);

            foreach (var elem in doc.ElementsByXPath("//Item[@action='add']").ToList())
            {
                elem.SetAttribute("action", "merge");
            }
            ItemType itemType;

            foreach (var elem in doc.ElementsByXPath("//Item[@type and @id]").ToList())
            {
                if (_itemTypes.TryGetValue(elem.Attribute("type", "").ToLowerInvariant(), out itemType) && itemType.IsVersionable)
                {
                    elem.SetAttribute(XmlFlags.Attr_ConfigId, elem.Attribute("id"));
                    elem.SetAttribute("where", string.Format("[{0}].[config_id] = '{1}'", itemType.Name.Replace(' ', '_'), elem.Attribute("id")));
                    elem.RemoveAttribute("id");
                }
            }

            var result = new InstallScript();

            result.Title = name;
            _exportTools.Export(result, doc);
            return(result);
        }
Exemple #4
0
        public void Delete()
        {
            string id = null;

            User owner = null;

            try
            {
                owner = UserTests.CreateUser();

                Course e = new Course
                {
                    Name    = "name",
                    OwnerId = owner.Id
                };

                e  = UnitTestControl.TestParameters.ClassroomService.Add(e);
                id = e.Id;

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Delete;
                cs.DN         = id;
                cs.ObjectType = SchemaConstants.Course;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", id));
                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Course], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                try
                {
                    System.Threading.Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);
                    e = UnitTestControl.TestParameters.ClassroomService.GetCourse(id);
                    Assert.Fail("The object did not get deleted");
                }
                catch (GoogleApiException ex)
                {
                    if (ex.HttpStatusCode == HttpStatusCode.NotFound)
                    {
                        id = null;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            finally
            {
                UnitTestControl.Cleanup(owner);

                if (id != null)
                {
                    UnitTestControl.TestParameters.ClassroomService.Delete(id);
                }
            }
        }
        public void Delete()
        {
            string id = null;

            try
            {
                string dn = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";
                User   e  = new User
                {
                    PrimaryEmail = dn,
                    Password     = Guid.NewGuid().ToString(),
                    Name         =
                    {
                        GivenName  = "test",
                        FamilyName = "test"
                    }
                };

                e  = UnitTestControl.TestParameters.UsersService.Add(e);
                id = e.Id;

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Delete;
                cs.DN         = dn;
                cs.ObjectType = SchemaConstants.User;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", id));
                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.User], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                try
                {
                    System.Threading.Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);
                    e = UnitTestControl.TestParameters.UsersService.Get(id);
                    Assert.Fail("The object did not get deleted");
                }
                catch (GoogleApiException ex)
                {
                    if (ex.HttpStatusCode == HttpStatusCode.NotFound)
                    {
                        id = null;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.UsersService.Delete(id);
                }
            }
        }
Exemple #6
0
        public void UpdateBuildingClearValues()
        {
            Building building = new Building();

            building.BuildingId   = "test-building";
            building.BuildingName = "My building";
            building.Description  = "some description";
            building.FloorNames   = new List <string>()
            {
                "B1", "B2", "G"
            };
            building.Coordinates = new BuildingCoordinates()
            {
                Latitude = -66, Longitude = 44
            };


            UnitTestControl.TestParameters.ResourcesService.AddBuilding(UnitTestControl.TestParameters.CustomerID, building);

            CSEntryChange cs = CSEntryChange.Create();

            cs.ObjectModificationType = ObjectModificationType.Update;
            cs.DN         = $"{building.BuildingId}{ApiInterfaceBuilding.DNSuffix}";
            cs.ObjectType = SchemaConstants.Building;
            cs.AnchorAttributes.Add(AnchorAttribute.Create("id", building.BuildingId));

            cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("description"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("coordinates_latitude"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("coordinates_longitude"));

            string id = building.BuildingId;

            try
            {
                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Building], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);

                Building c = UnitTestControl.TestParameters.ResourcesService.GetBuilding(UnitTestControl.TestParameters.CustomerID, id);
                Assert.AreEqual("test-building", c.BuildingId);
                Assert.IsTrue(string.IsNullOrEmpty(c.Description));
                Assert.IsNull(c.Coordinates?.Longitude);
                Assert.IsNull(c.Coordinates?.Latitude);
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.ResourcesService.DeleteBuilding(UnitTestControl.TestParameters.CustomerID, id);
                }
            }
        }
Exemple #7
0
        private void ExportAllFolder_bg(string outputPath, bool IncludeSubFolder, RhoFile file)
        {
            IPackedObject[]         ipos  = RhoPackedFilesInfoDecoder.GetRhoPackedFileInfos(file.GetStreamData(0xFFFFFFFF), file.HeaderKey, 0xFFFFFFFF);
            Stack <ExportProcessor> Stack = new Stack <ExportProcessor>();

            if (!Directory.Exists(outputPath))
            {
                throw new Exception("");
            }
            string StartPath = "";

            Stack.Push(new ExportProcessor
            {
                Path = StartPath,
                ipos = ipos
            });
            while (Stack.Count > 0 && !Canceled)
            {
                ExportProcessor ep      = Stack.Pop();
                string          outPath = outputPath + (StartPath == "" ? ep.Path : ep.Path.Replace(StartPath, ""));
                foreach (IPackedObject ipo in ep.ipos)
                {
                    if (ipo.Type == ObjectType.Folder && IncludeSubFolder)
                    {
                        RhoPackedFolderInfo jpfi = (RhoPackedFolderInfo)ipo;
                        ExportProcessor     nep  = new ExportProcessor
                        {
                            Path = ep.Path + $"\\{jpfi.FolderName}",
                            ipos = RhoPackedFilesInfoDecoder.GetRhoPackedFileInfos(file.GetStreamData(jpfi.Index), file.HeaderKey, jpfi.Index)
                        };
                        Stack.Push(nep);
                        if (!Directory.Exists($"{outPath}\\{((RhoPackedFolderInfo)ipo).FolderName}"))
                        {
                            Directory.CreateDirectory($"{outPath}\\{((RhoPackedFolderInfo)ipo).FolderName}");
                        }
                        continue;
                    }
                    if (ipo.Type == ObjectType.File)
                    {
                        RhoPackedFileInfo jfi = (RhoPackedFileInfo)ipo;
                        ChangeText(label5, $"Outputing: {ep.Path}\\{jfi.FileName}.{jfi.Extension}");
                        FileStream fs   = new FileStream($"{outPath}\\{jfi.FileName}.{jfi.Extension}", FileMode.Create);
                        byte[]     data = file.GetPackedFile(jfi);
                        fs.Write(data, 0, data.Length);
                        fs.Close();
                        data = null;
                    }
                    if (Canceled)
                    {
                        break;
                    }
                }
            }
            CloseWindow();
        }
Exemple #8
0
        public void CreateCalendar()
        {
            CSEntryChange cs = CSEntryChange.Create();

            cs.ObjectModificationType = ObjectModificationType.Add;
            cs.DN         = Guid.NewGuid().ToString();
            cs.ObjectType = SchemaConstants.Calendar;

            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("name", "test-name"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("buildingId", "testbuilding1"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("capacity", 33L));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("floorName", "G"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("floorSection", "33B"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("resourceCategory", "CONFERENCE_ROOM"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("resourceDescription", "internal description"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("userVisibleDescription", "user description"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("features", new List <object> {
                "Test1", "Test2"
            }));

            string id = null;

            try
            {
                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Calendar], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                id = result.AnchorAttributes["id"].GetValueAdd <string>();

                Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);

                CalendarResource c = UnitTestControl.TestParameters.ResourcesService.GetCalendar(UnitTestControl.TestParameters.CustomerID, id);
                Assert.AreEqual("test-name", c.ResourceName);
                Assert.IsNotNull(c.ResourceEmail);
                Assert.AreEqual("testbuilding1", c.BuildingId);
                Assert.AreEqual(33, c.Capacity);
                Assert.AreEqual("G", c.FloorName);
                Assert.AreEqual("33B", c.FloorSection);
                Assert.AreEqual("CONFERENCE_ROOM", c.ResourceCategory);
                Assert.AreEqual("internal description", c.ResourceDescription);
                Assert.AreEqual("user description", c.UserVisibleDescription);
                CollectionAssert.AreEquivalent(new string[] { "Test1", "Test2" }, ApiInterfaceCalendar.GetFeatureNames(c).ToList());
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.ResourcesService.DeleteCalendar(UnitTestControl.TestParameters.CustomerID, id);
                }
            }
        }
        public void Rename()
        {
            string id = null;

            try
            {
                string dn = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";
                User   e  = new User
                {
                    PrimaryEmail = dn,
                    Password     = Guid.NewGuid().ToString(),
                    Name         =
                    {
                        GivenName  = "test",
                        FamilyName = "test"
                    }
                };

                e  = UnitTestControl.TestParameters.UsersService.Add(e);
                id = e.Id;
                System.Threading.Thread.Sleep(2000);

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Update;
                cs.DN         = dn;
                cs.ObjectType = SchemaConstants.User;

                string newDN = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";

                cs.AttributeChanges.Add(AttributeChange.CreateAttributeUpdate("DN", new List <ValueChange>()
                {
                    ValueChange.CreateValueAdd(newDN), ValueChange.CreateValueDelete(dn)
                }));

                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", id));
                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.User], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                System.Threading.Thread.Sleep(2000);
                e = UnitTestControl.TestParameters.UsersService.Get(id);
                Assert.AreEqual(newDN, e.PrimaryEmail);
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.UsersService.Delete(id);
                }
            }
        }
Exemple #10
0
        public void ContactDelete()
        {
            string id = null;

            try
            {
                string       dn = Guid.NewGuid().ToString();
                ContactEntry e  = new ContactEntry
                {
                    BillingInformation = "test"
                };

                e.ExtendedProperties.Add(new ExtendedProperty(dn, ApiInterfaceContact.DNAttributeName));

                e  = UnitTestControl.TestParameters.ContactsService.Add(e, UnitTestControl.TestParameters.Domain);
                id = e.SelfUri.Content;

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Delete;
                cs.DN         = dn;
                cs.ObjectType = SchemaConstants.Contact;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", id));
                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Contact], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                try
                {
                    System.Threading.Thread.Sleep(5000);
                    e = UnitTestControl.TestParameters.ContactsService.GetContact(id);
                    Assert.Fail("The object did not get deleted");
                }
                catch (GDataRequestException ex)
                {
                    if (((HttpWebResponse)ex.Response).StatusCode == HttpStatusCode.NotFound)
                    {
                        id = null;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.ContactsService.Delete(id);
                }
            }
        }
        public void ReplaceMembers()
        {
            Group e       = null;
            Group member1 = null;
            Group member2 = null;
            Group member3 = null;
            Group member4 = null;

            try
            {
                e = UnitTestControl.CreateGroup();

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Update;
                cs.DN         = e.Email;
                cs.ObjectType = SchemaConstants.Group;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", e.Id));

                member1 = UnitTestControl.CreateGroup();
                member2 = UnitTestControl.CreateGroup();
                member3 = UnitTestControl.CreateGroup();
                member4 = UnitTestControl.CreateGroup();
                UnitTestControl.TestParameters.GroupsService.MemberFactory.AddMember(e.Email, new Member()
                {
                    Email = member1.Email
                });
                UnitTestControl.TestParameters.GroupsService.MemberFactory.AddMember(e.Email, new Member()
                {
                    Email = member2.Email
                });

                Thread.Sleep(1000);

                cs.AttributeChanges.Add(AttributeChange.CreateAttributeReplace("member", new List <object>()
                {
                    member3.Email, member4.Email
                }));

                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Group], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                Thread.Sleep(10000);

                CollectionAssert.AreEquivalent(new string[] { member3.Email, member4.Email }, UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(cs.DN).Members.ToArray());
            }
            finally
            {
                UnitTestControl.Cleanup(e, member1, member2, member3, member4);
            }
        }
 public async Task Initialize(InstallScript script)
 {
     _log.Length = 0;
     _script     = script;
     _lines      = (_script.DependencySorted
 ? (_script.Lines ?? Enumerable.Empty <InstallItem>())
 : (await ExportProcessor.SortByDependencies(script.Lines, _conn).ConfigureAwait(false))
                    .Where(l => l.Type != InstallType.DependencyCheck)
                    ).Where(l => l.Script != null && l.Type != InstallType.Warning).ToList();
     _currLine = -1;
 }
        public void RemoveMembers()
        {
            Group e       = null;
            Group member1 = null;
            Group member2 = null;

            try
            {
                e       = UnitTestControl.CreateGroup();
                member1 = UnitTestControl.CreateGroup();
                member2 = UnitTestControl.CreateGroup();

                UnitTestControl.TestParameters.GroupsService.MemberFactory.AddMember(e.Email, new Member()
                {
                    Email = member1.Email
                });
                UnitTestControl.TestParameters.GroupsService.MemberFactory.AddMember(e.Email, new Member()
                {
                    Email = member2.Email
                });

                Thread.Sleep(1000);

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Update;
                cs.DN         = e.Email;
                cs.ObjectType = SchemaConstants.Group;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", e.Id));

                cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("member"));

                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Group], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                Thread.Sleep(1000);

                Assert.AreEqual(0, UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(cs.DN).Members.Count);
                Assert.AreEqual(0, UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(cs.DN).ExternalMembers.Count);
                Assert.AreEqual(0, UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(cs.DN).Managers.Count);
                Assert.AreEqual(0, UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(cs.DN).ExternalManagers.Count);
                Assert.AreEqual(0, UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(cs.DN).Owners.Count);
                Assert.AreEqual(0, UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(cs.DN).ExternalOwners.Count);
            }
            finally
            {
                UnitTestControl.Cleanup(e, member1, member2);
            }
        }
Exemple #14
0
        public void DowngradeManagersToMembers()
        {
            Group e       = null;
            User  member1 = null;
            User  member2 = null;
            User  member3 = null;
            User  member4 = null;

            try
            {
                e = UnitTestControl.CreateGroup();

                member1 = UserTests.CreateUser();
                member2 = UserTests.CreateUser();
                member3 = UserTests.CreateUser();
                member4 = UserTests.CreateUser();

                UnitTestControl.TestParameters.GroupsService.MemberFactory.AddMember(e.Email, member1.PrimaryEmail, "MANAGER");
                UnitTestControl.TestParameters.GroupsService.MemberFactory.AddMember(e.Email, member2.PrimaryEmail, "MANAGER");
                UnitTestControl.TestParameters.GroupsService.MemberFactory.AddMember(e.Email, member3.PrimaryEmail, "MEMBER");
                UnitTestControl.TestParameters.GroupsService.MemberFactory.AddMember(e.Email, member4.PrimaryEmail, "MEMBER");
                Thread.Sleep(1000);

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Update;
                cs.DN         = e.Email;
                cs.ObjectType = SchemaConstants.Group;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", e.Email));

                cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("manager"));

                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Group], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                Thread.Sleep(1000);
                GroupMembership membership = UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(cs.DN);

                Assert.AreEqual(0, membership.ExternalManagers.Count);
                Assert.AreEqual(0, membership.Managers.Count);
                Assert.AreEqual(0, membership.ExternalMembers.Count);
                CollectionAssert.AreEquivalent(new string[] { member1.PrimaryEmail, member2.PrimaryEmail, member3.PrimaryEmail, member4.PrimaryEmail }, membership.Members.ToArray());
            }
            finally
            {
                UnitTestControl.Cleanup(e, member1, member2, member3, member4);
            }
        }
Exemple #15
0
        public void ContactRename()
        {
            string id = null;

            try
            {
                string       dn = Guid.NewGuid().ToString();
                ContactEntry e  = new ContactEntry();

                e.Emails.Add(new EMail()
                {
                    Address = "*****@*****.**", Label = "work"
                });

                e.ExtendedProperties.Add(new ExtendedProperty(dn, ApiInterfaceContact.DNAttributeName));

                e  = UnitTestControl.TestParameters.ContactsService.Add(e, UnitTestControl.TestParameters.Domain);
                id = e.SelfUri.Content;

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Update;
                cs.DN         = dn;
                cs.ObjectType = SchemaConstants.Contact;

                string newDN = Guid.NewGuid().ToString();

                cs.AttributeChanges.Add(AttributeChange.CreateAttributeUpdate("DN", new List <ValueChange>()
                {
                    ValueChange.CreateValueAdd(newDN), ValueChange.CreateValueDelete(dn)
                }));

                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", id));
                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Contact], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                System.Threading.Thread.Sleep(5000);
                e = UnitTestControl.TestParameters.ContactsService.GetContact(id);
                Assert.AreEqual(newDN, e.ExtendedProperties.Single(t => t.Name == ApiInterfaceContact.DNAttributeName).Value);
                var x = CSEntryChangeQueue.Take();
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.ContactsService.Delete(id);
                }
            }
        }
Exemple #16
0
        public void CreateCalendarWithAcls()
        {
            CSEntryChange cs = CSEntryChange.Create();

            cs.ObjectModificationType = ObjectModificationType.Add;
            cs.DN         = Guid.NewGuid().ToString();
            cs.ObjectType = SchemaConstants.Calendar;

            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("name", "test-name"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("buildingId", "testbuilding1"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("capacity", 33L));

            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("owner", new List <object> {
                this.CreateAddress("owner1"), this.CreateAddress("owner2")
            }));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("reader", this.CreateAddress("reader")));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("writer", this.CreateAddress("writer")));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("freeBusyReader", this.CreateAddress("freebusyreader")));

            string id = null;

            try
            {
                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Calendar], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                id = result.AnchorAttributes["id"].GetValueAdd <string>();

                Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);

                CalendarResource c = UnitTestControl.TestParameters.ResourcesService.GetCalendar(UnitTestControl.TestParameters.CustomerID, id);

                List <AclRule> acls = UnitTestControl.TestParameters.ResourcesService.GetCalendarAclRules(UnitTestControl.TestParameters.CustomerID, c.ResourceEmail).ToList();

                Assert.IsNotNull(acls.FirstOrDefault(t => t.Role == "owner" && t.Scope.Value == this.CreateAddress("owner1")));
                Assert.IsNotNull(acls.FirstOrDefault(t => t.Role == "owner" && t.Scope.Value == this.CreateAddress("owner2")));
                Assert.IsNotNull(acls.FirstOrDefault(t => t.Role == "reader" && t.Scope.Value == this.CreateAddress("reader")));
                Assert.IsNotNull(acls.FirstOrDefault(t => t.Role == "writer" && t.Scope.Value == this.CreateAddress("writer")));
                Assert.IsNotNull(acls.FirstOrDefault(t => t.Role == "freeBusyReader" && t.Scope.Value == this.CreateAddress("freebusyreader")));
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.ResourcesService.DeleteCalendar(UnitTestControl.TestParameters.CustomerID, id);
                }
            }
        }
        public void MakeAdmin()
        {
            string id = null;
            string dn = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";
            User   e  = new User
            {
                PrimaryEmail = dn,
                Password     = Guid.NewGuid().ToString(),
                Name         = new UserName
                {
                    GivenName  = "gn",
                    FamilyName = "sn"
                }
            };

            e  = UnitTestControl.TestParameters.UsersService.Add(e);
            id = e.Id;

            CSEntryChange cs = CSEntryChange.Create();

            cs.ObjectModificationType = ObjectModificationType.Update;
            cs.DN         = dn;
            cs.ObjectType = SchemaConstants.User;
            cs.AnchorAttributes.Add(AnchorAttribute.Create("id", id));

            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("isAdmin", true));

            try
            {
                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.User], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                System.Threading.Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);

                e = UnitTestControl.TestParameters.UsersService.Get(id);

                Assert.AreEqual(true, e.IsAdmin);
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.UsersService.Delete(id);
                }
            }
        }
Exemple #18
0
        public void Update()
        {
            User   owner = null;
            string id    = null;

            try
            {
                owner = UserTests.CreateUser();

                Course e = new Course
                {
                    Name    = "name",
                    OwnerId = owner.Id
                };

                e  = UnitTestControl.TestParameters.ClassroomService.Add(e);
                id = e.Id;

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Update;
                cs.DN         = id;
                cs.ObjectType = SchemaConstants.Course;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", id));

                cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("name", "name2"));


                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Course], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                System.Threading.Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);

                e = UnitTestControl.TestParameters.ClassroomService.GetCourse(id);
                Assert.AreEqual("name2", e.Name);
            }
            finally
            {
                UnitTestControl.Cleanup(owner);

                if (id != null)
                {
                    UnitTestControl.TestParameters.ClassroomService.Delete(id);
                }
            }
        }
        public InstallScript Merge(IDiffDirectory baseDir, IDiffDirectory compareDir)
        {
            var docs     = new List <Tuple <XmlDocument, string> >();
            var metadata = baseDir.WriteAmlMergeScripts(compareDir, (path, prog) =>
            {
                ProgressChanged?.Invoke(this, new ProgressChangedEventArgs("Reading files", prog / 2));
                var doc = new XmlDocument();
                docs.Add(Tuple.Create(doc, path));
                return(new XmlNodeWriter(doc));
            });

            ProgressChanged?.Invoke(this, new ProgressChangedEventArgs("Performing cleanup", 50));

            var allItems = docs
                           .Where(d => d.Item1.DocumentElement != null)
                           .SelectMany(d => d.Item1.DocumentElement
                                       .DescendantsAndSelf(el => el.LocalName == "Item"))
                           .ToArray();

            RemoveDeletesForItemsWithMultipleScripts(allItems);
            RemoveChangesToSystemProperties(allItems);

            var installScripts = docs
                                 .Where(d => d.Item1.DocumentElement != null)
                                 .SelectMany(d => XmlUtils.RootItems(d.Item1.DocumentElement)
                                             .Select(i => InstallItem.FromScript(i, d.Item2)))
                                 .ToArray();

            ProgressChanged?.Invoke(this, new ProgressChangedEventArgs("Processing dependencies", 75));

            var lines = (SortDependencies
        ? ExportProcessor.SortByDependencies(installScripts, metadata)
        : installScripts).ToList();

            lines.RemoveWhere(i => i.Type == InstallType.DependencyCheck);

            var script = new InstallScript()
            {
                Created = DateTime.Now,
                Creator = Environment.UserName,
                Title   = "MergeScript",
                Lines   = lines
            };

            lines.InsertRange(0, FillInNullsOnRequiredProperties(allItems, metadata));

            ProgressChanged?.Invoke(this, new ProgressChangedEventArgs("Processing dependencies", 80));

            return(script);
        }
Exemple #20
0
        public void DowngradeOwnerToManager()
        {
            Group e = null;

            try
            {
                e = UnitTestControl.CreateGroup();

                string member2 = "*****@*****.**";
                Thread.Sleep(1000);

                UnitTestControl.TestParameters.GroupsService.MemberFactory.AddMember(e.Email, member2, "OWNER");

                Thread.Sleep(1000);

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Update;
                cs.DN         = e.Email;
                cs.ObjectType = SchemaConstants.Group;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", e.Id));

                cs.AttributeChanges.Add(AttributeChange.CreateAttributeUpdate("externalOwner", new List <ValueChange>()
                {
                    new ValueChange(member2, ValueModificationType.Delete)
                }));

                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Group], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                Thread.Sleep(1000);
                GroupMembership membership = UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(cs.DN);

                Assert.AreEqual(0, membership.ExternalOwners.Count);
                Assert.AreEqual(0, membership.Owners.Count);
                Assert.AreEqual(0, membership.Managers.Count);
                Assert.AreEqual(0, membership.Members.Count);
                CollectionAssert.AreEquivalent(new string[] { member2 }, membership.ExternalManagers.ToArray());
            }
            finally
            {
                UnitTestControl.Cleanup(e);
            }
        }
        public void AddGroupWithMembers()
        {
            Group member1 = null;
            Group member2 = null;
            User  member3 = null;

            try
            {
                string dn = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Add;
                cs.DN         = dn;
                cs.ObjectType = SchemaConstants.Group;
                cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("name", Guid.NewGuid().ToString()));

                member1 = UnitTestControl.CreateGroup();
                member2 = UnitTestControl.CreateGroup();
                member3 = UserTests.CreateUser();

                cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("member", new List <object>()
                {
                    member1.Email, member2.Email
                }));
                cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("owner", new List <object>()
                {
                    member3.PrimaryEmail
                }));

                CSEntryChangeResult result = null;

                result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Group], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                Thread.Sleep(5000);

                CollectionAssert.AreEquivalent(new string[] { member1.Email, member2.Email }, UnitTestControl.TestParameters.GroupsService.MemberFactory.GetMembership(cs.DN).Members.ToArray());
            }
            finally
            {
                UnitTestControl.Cleanup(member1, member2, member3);
            }
        }
        public void ReplaceAliases()
        {
            Group e = null;

            try
            {
                e = UnitTestControl.CreateGroup();

                string alias1 = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";
                string alias2 = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";
                string alias3 = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";
                string alias4 = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";

                UnitTestControl.TestParameters.GroupsService.AddAlias(e.Id, alias1);
                UnitTestControl.TestParameters.GroupsService.AddAlias(e.Id, alias2);

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Update;
                cs.DN         = e.Email;
                cs.ObjectType = SchemaConstants.Group;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", e.Id));

                cs.AttributeChanges.Add(AttributeChange.CreateAttributeReplace("aliases", new List <object>
                {
                    alias3, alias4
                }));

                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Group], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                System.Threading.Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);

                e = UnitTestControl.TestParameters.GroupsService.Get(e.Id);

                CollectionAssert.AreEquivalent(new string[] { alias3, alias4 }, e.Aliases.ToArray());
            }
            finally
            {
                UnitTestControl.Cleanup(e);
            }
        }
Exemple #23
0
        public void CreateBuilding()
        {
            CSEntryChange cs = CSEntryChange.Create();

            cs.ObjectModificationType = ObjectModificationType.Add;
            cs.DN         = "*****@*****.**";
            cs.ObjectType = SchemaConstants.Building;

            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("buildingName", "My building"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("description", "my description"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("coordinates_latitude", "1"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("coordinates_longitude", "-99"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("floorNames", "B2,B1,G,1,2,3,4,5"));

            string id = null;

            try
            {
                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Building], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                id = result.AnchorAttributes["id"].GetValueAdd <string>();

                Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);

                Building c = UnitTestControl.TestParameters.ResourcesService.GetBuilding(UnitTestControl.TestParameters.CustomerID, id);
                Assert.AreEqual("new-building", c.BuildingId);
                Assert.AreEqual("My building", c.BuildingName);
                Assert.AreEqual("my description", c.Description);
                Assert.AreEqual(1D, c.Coordinates?.Latitude);
                Assert.AreEqual(-99D, c.Coordinates?.Longitude);
                CollectionAssert.AreEqual(new string[] { "B2", "B1", "G", "1", "2", "3", "4", "5" }, c.FloorNames.ToArray());
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.ResourcesService.DeleteBuilding(UnitTestControl.TestParameters.CustomerID, id);
                }
            }
        }
        public void Delete()
        {
            Group e = null;

            try
            {
                e = UnitTestControl.CreateGroup();

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Delete;
                cs.DN         = e.Email;
                cs.ObjectType = SchemaConstants.Group;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", e.Id));
                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Group], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                try
                {
                    System.Threading.Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);
                    e = UnitTestControl.TestParameters.GroupsService.Get(e.Id);
                    Assert.Fail("The object did not get deleted");
                }
                catch (GoogleApiException ex)
                {
                    if (ex.HttpStatusCode == HttpStatusCode.NotFound)
                    {
                        e = null;
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            finally
            {
                UnitTestControl.Cleanup(e);
            }
        }
        public void TakeAdmin()
        {
            User e = UserTests.CreateUser();

            try
            {
                UnitTestControl.TestParameters.UsersService.MakeAdmin(true, e.Id);

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Update;
                cs.DN         = e.PrimaryEmail;
                cs.ObjectType = SchemaConstants.User;
                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", e.Id));

                cs.AttributeChanges.Add(AttributeChange.CreateAttributeReplace("isAdmin", false));

                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.User], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                System.Threading.Thread.Sleep(5000);

                e = UnitTestControl.TestParameters.UsersService.Get(e.Id);

                Assert.AreEqual(false, e.IsAdmin);
            }
            finally
            {
                if (e.Id != null)
                {
                    UnitTestControl.TestParameters.UsersService.Delete(e.Id);
                }
            }
        }
        public void CreateFeature()
        {
            Guid g = Guid.NewGuid();

            CSEntryChange cs = CSEntryChange.Create();

            cs.ObjectModificationType = ObjectModificationType.Add;
            cs.DN         = $"my-feature{g:N}{ApiInterfaceFeature.DNSuffix}";
            cs.ObjectType = SchemaConstants.Feature;

            cs.AttributeChanges.Add(AttributeChange.CreateAttributeAdd("name", "My feature 2"));

            string id = null;

            try
            {
                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Feature], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                id = result.AnchorAttributes["id"].GetValueAdd <string>();

                Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);

                Feature c = UnitTestControl.TestParameters.ResourcesService.GetFeature(UnitTestControl.TestParameters.CustomerID, id);
                Assert.AreEqual($"my-feature{g:N}", c.Name);
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.ResourcesService.DeleteFeature(UnitTestControl.TestParameters.CustomerID, id);
                }
            }
        }
        public void Rename()
        {
            Group e = null;

            try
            {
                e = UnitTestControl.CreateGroup();

                CSEntryChange cs = CSEntryChange.Create();
                cs.ObjectModificationType = ObjectModificationType.Update;
                cs.ObjectType             = SchemaConstants.Group;
                cs.DN = e.Email;

                string newDN = $"{Guid.NewGuid()}@{UnitTestControl.TestParameters.Domain}";

                cs.AttributeChanges.Add(AttributeChange.CreateAttributeUpdate("DN", new List <ValueChange>()
                {
                    ValueChange.CreateValueAdd(newDN), ValueChange.CreateValueDelete(e.Email)
                }));

                cs.AnchorAttributes.Add(AnchorAttribute.Create("id", e.Id));
                CSEntryChangeResult result =
                    ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Group], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                System.Threading.Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);
                e = UnitTestControl.TestParameters.GroupsService.Get(e.Id);
                Assert.AreEqual(newDN, e.Email);
            }
            finally
            {
                UnitTestControl.Cleanup(e);
            }
        }
Exemple #28
0
        public void UpdateCalendarClearValues()
        {
            CalendarResource calendar = new CalendarResource();

            calendar.ResourceId             = Guid.NewGuid().ToString("n");
            calendar.ResourceName           = "test-name";
            calendar.BuildingId             = "testbuilding2";
            calendar.Capacity               = 9;
            calendar.FloorName              = "G";
            calendar.FloorSection           = "39b";
            calendar.ResourceCategory       = "OTHER";
            calendar.ResourceDescription    = "internal description 1";
            calendar.UserVisibleDescription = "my description 2";
            calendar.FeatureInstances       = new List <FeatureInstance>()
            {
                new FeatureInstance()
                {
                    Feature = new Feature()
                    {
                        Name = "Test1"
                    }
                },
                new FeatureInstance()
                {
                    Feature = new Feature()
                    {
                        Name = "Test2"
                    }
                },
            };

            UnitTestControl.TestParameters.ResourcesService.AddCalendar(UnitTestControl.TestParameters.CustomerID, calendar);

            CSEntryChange cs = CSEntryChange.Create();

            cs.ObjectModificationType = ObjectModificationType.Update;
            cs.DN         = "*****@*****.**";
            cs.ObjectType = SchemaConstants.Calendar;
            cs.AnchorAttributes.Add(AnchorAttribute.Create("id", calendar.ResourceId));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("buildingId"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("capacity"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("floorName"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("floorSection"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("resourceDescription"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("userVisibleDescription"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeDelete("features"));

            string id = calendar.ResourceId;

            try
            {
                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Calendar], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);

                CalendarResource c = UnitTestControl.TestParameters.ResourcesService.GetCalendar(UnitTestControl.TestParameters.CustomerID, id);
                Assert.IsNull(c.BuildingId);
                Assert.IsNull(c.Capacity);
                Assert.IsNull(c.FloorName);
                Assert.IsNull(c.FloorSection);
                Assert.IsNull(c.ResourceDescription);
                Assert.IsNull(c.UserVisibleDescription);
                Assert.IsNull(c.FeatureInstances);
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.ResourcesService.DeleteCalendar(UnitTestControl.TestParameters.CustomerID, id);
                }
            }
        }
Exemple #29
0
        public void UpdateCalendar()
        {
            CalendarResource calendar = new CalendarResource();

            calendar.ResourceId             = Guid.NewGuid().ToString("n");
            calendar.ResourceName           = "test-name";
            calendar.BuildingId             = "testbuilding2";
            calendar.Capacity               = 9;
            calendar.FloorName              = "G";
            calendar.FloorSection           = "39b";
            calendar.ResourceCategory       = "OTHER";
            calendar.ResourceDescription    = "internal description 1";
            calendar.UserVisibleDescription = "my description 2";
            calendar.FeatureInstances       = new List <FeatureInstance>()
            {
                new FeatureInstance()
                {
                    Feature = new Feature()
                    {
                        Name = "Test1"
                    }
                },
                new FeatureInstance()
                {
                    Feature = new Feature()
                    {
                        Name = "Test2"
                    }
                },
            };

            UnitTestControl.TestParameters.ResourcesService.AddCalendar(UnitTestControl.TestParameters.CustomerID, calendar);

            CSEntryChange cs = CSEntryChange.Create();

            cs.ObjectModificationType = ObjectModificationType.Update;
            cs.DN         = "*****@*****.**";
            cs.ObjectType = SchemaConstants.Calendar;
            cs.AnchorAttributes.Add(AnchorAttribute.Create("id", calendar.ResourceId));

            cs.AttributeChanges.Add(AttributeChange.CreateAttributeUpdate("buildingId", new List <ValueChange>()
            {
                ValueChange.CreateValueAdd("testbuilding1")
            }));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeReplace("capacity", 33L));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeReplace("floorName", "G"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeReplace("floorSection", "33B"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeReplace("resourceCategory", "CONFERENCE_ROOM"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeReplace("resourceDescription", "internal description"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeReplace("userVisibleDescription", "user description"));
            cs.AttributeChanges.Add(AttributeChange.CreateAttributeUpdate("features", new List <ValueChange>()
            {
                ValueChange.CreateValueAdd("Test3"),
                ValueChange.CreateValueDelete("Test1"),
            }));

            string id = calendar.ResourceId;

            try
            {
                CSEntryChangeResult result = ExportProcessor.PutCSEntryChange(cs, UnitTestControl.Schema.GetSchema().Types[SchemaConstants.Calendar], UnitTestControl.TestParameters);

                if (result.ErrorCode != MAExportError.Success)
                {
                    Assert.Fail(result.ErrorName);
                }

                Thread.Sleep(UnitTestControl.PostGoogleOperationSleepInterval);

                CalendarResource c = UnitTestControl.TestParameters.ResourcesService.GetCalendar(UnitTestControl.TestParameters.CustomerID, id);
                Assert.AreEqual(cs.DN, "*****@*****.**");
                Assert.AreEqual("test-name", c.ResourceName);
                Assert.AreEqual("testbuilding1", c.BuildingId);
                Assert.AreEqual(33, c.Capacity);
                Assert.AreEqual("G", c.FloorName);
                Assert.AreEqual("33B", c.FloorSection);
                Assert.AreEqual("CONFERENCE_ROOM", c.ResourceCategory);
                Assert.AreEqual("internal description", c.ResourceDescription);
                Assert.AreEqual("user description", c.UserVisibleDescription);
                CollectionAssert.AreEquivalent(new string[] { "Test2", "Test3" }, ApiInterfaceCalendar.GetFeatureNames(c).ToList());
            }
            finally
            {
                if (id != null)
                {
                    UnitTestControl.TestParameters.ResourcesService.DeleteCalendar(UnitTestControl.TestParameters.CustomerID, id);
                }
            }
        }
        public IEnumerable <IEditorScript> GetScripts()
        {
            var items = (Items ?? Enumerable.Empty <IItemData>())
                        .Where(i => !string.IsNullOrEmpty(i.Id) && !string.IsNullOrEmpty(i.Type))
                        .ToArray();

            if (!items.Any())
            {
                yield break;
            }

            if (items.Skip(1).Any()) // There is more than one
            {
                if (items.OfType <DataRowItemData>().Any())
                {
                    yield return(new EditorScriptExecute()
                    {
                        Name = "Delete",
                        Execute = () =>
                        {
                            foreach (var row in items.OfType <DataRowItemData>())
                            {
                                row.Delete();
                            }
                            return Task.FromResult(true);
                        }
                    });
                }
                else
                {
                    var builder = new StringBuilder("<AML>");
                    foreach (var item in items)
                    {
                        builder.AppendLine().AppendFormat("  <Item type='{0}' {1} action='delete'></Item>", item.Type, GetCriteria(item.Id));
                    }
                    builder.AppendLine().Append("</AML>");
                    yield return(new EditorScript()
                    {
                        Name = "Delete",
                        Action = "ApplyAML",
                        Script = builder.ToString()
                    });
                }

                var dataRows = items.OfType <DataRowItemData>()
                               .OrderBy(r => r.Property("generation")).ThenBy(r => r.Id)
                               .ToArray();
                if (dataRows.Length == 2) // There are exactly two items
                {
                    yield return(new EditorScript()
                    {
                        Name = "------"
                    });

                    yield return(new EditorScriptExecute()
                    {
                        Name = "Compare",
                        Execute = async() =>
                        {
                            try
                            {
                                await Settings.Current.PerformDiff(dataRows[0].Id, dataRows[0].ToAml
                                                                   , dataRows[1].Id, dataRows[1].ToAml);
                            }
                            catch (Exception ex)
                            {
                                Utils.HandleError(ex);
                            }
                        }
                    });
                }
                yield return(new EditorScript()
                {
                    Name = "------"
                });

                yield return(new EditorScriptExecute()
                {
                    Name = "Export",
                    Execute = () =>
                    {
                        var refs = items.OfType <ItemRefData>().Select(i => i.Ref);
                        if (!refs.Any())
                        {
                            refs = items.Select(i => new ItemReference(i.Type, i.Id));
                        }
                        StartExport(refs);
                        return Task.FromResult(true);
                    }
                });
            }
            else
            {
                var item    = items.Single();
                var rowItem = item as DataRowItemData;

                ArasMetadataProvider metadata = null;
                ItemType             itemType = null;
                if (Conn != null)
                {
                    metadata = ArasMetadataProvider.Cached(Conn);
                    if (!metadata.ItemTypeByName(item.Type, out itemType))
                    {
                        metadata = null;
                    }
                }

                if (Conn != null)
                {
                    yield return(ArasEditorProxy.ItemTypeAddScript(Conn, itemType));
                }

                if (item is EditorItemData data)
                {
                    yield return(new EditorScript()
                    {
                        Name = "Clone as New",
                        Action = "ApplyItem",
                        ScriptGetter = () =>
                        {
                            var aml = data.ToItem(Conn.AmlContext).CloneAsNew().ToAml();
                            return Task.FromResult(XElement.Parse(aml).ToString());
                        }
                    });
                }

                yield return(new EditorScript()
                {
                    Name = "------"
                });

                if (rowItem == null)
                {
                    var script = string.Format("<Item type='{0}' {1} action='edit'></Item>", item.Type, GetCriteria(item.Id));
                    if (item.Property("config_id") != null && itemType != null && itemType.IsVersionable)
                    {
                        script = string.Format("<Item type='{0}' where=\"[{1}].[config_id] = '{2}'\" action='edit'></Item>"
                                               , item.Type, item.Type.Replace(' ', '_'), item.Property("config_id"));
                    }

                    yield return(new EditorScript()
                    {
                        Name = "Edit",
                        Action = "ApplyItem",
                        Script = script
                    });
                }
                else
                {
                    if (!string.IsNullOrEmpty(Column))
                    {
                        var prop = metadata.GetProperty(itemType, Column.Split('/')[0]).Wait();
                        switch (prop.Type)
                        {
                        case PropertyType.item:
                            yield return(new EditorScriptExecute()
                            {
                                Name = "Edit Value",
                                Execute = () =>
                                {
                                    var query = string.Format("<Item type='{0}' action='get'><keyed_name condition='like'>**</keyed_name></Item>", prop.Restrictions.First());
                                    var values = EditorWindow.GetItems(Conn, query, query.Length - 21);
                                    var results = values.Where(i => prop.Restrictions.Contains(i.Type)).ToArray();
                                    if (results.Length == 1)
                                    {
                                        rowItem.SetProperty(prop.Name, results[0].Unique);
                                        rowItem.SetProperty(prop.Name + "/keyed_name", results[0].KeyedName);
                                        rowItem.SetProperty(prop.Name + "/type", results[0].Type);
                                    }
                                    return Task.FromResult(true);
                                }
                            });

                            break;
                        }
                    }
                }
                if (metadata != null)
                {
                    yield return(new EditorScript()
                    {
                        Name = "View \"" + (itemType.Label ?? itemType.Name) + "\"",
                        Action = "ApplyItem",
                        Script = string.Format("<Item type='{0}' {1} action='get' levels='1'></Item>", item.Type, GetCriteria(item.Id)),
                        AutoRun = true,
                        PreferredOutput = OutputType.Table
                    });

                    if (item.Property("related_id") != null && itemType.Related != null)
                    {
                        yield return(new EditorScript()
                        {
                            Name = "View \"" + (itemType.Related.Label ?? itemType.Related.Name) + "\"",
                            Action = "ApplyItem",
                            Script = string.Format("<Item type='{0}' id='{1}' action='get' levels='1'></Item>", itemType.Related.Name, item.Property("related_id")),
                            AutoRun = true,
                            PreferredOutput = OutputType.Table
                        });
                    }
                }
                yield return(new EditorScript()
                {
                    Name = "------"
                });

                if (rowItem == null)
                {
                    yield return(new EditorScript()
                    {
                        Name = "Delete",
                        Action = "ApplyItem",
                        Script = string.Format("<Item type='{0}' {1} action='delete'></Item>", item.Type, GetCriteria(item.Id))
                    });
                }
                else
                {
                    yield return(new EditorScriptExecute()
                    {
                        Name = "Delete",
                        Execute = () =>
                        {
                            rowItem.Delete();
                            return Task.FromResult(true);
                        }
                    });
                }
                if (item.Id.IsGuid())
                {
                    yield return(new EditorScript()
                    {
                        Name = "Replace Item",
                        Action = "ApplySql",
                        ScriptGetter = async() =>
                        {
                            var aml = string.Format("<Item type='{0}' action='get'><keyed_name condition='like'>**</keyed_name></Item>", item.Type);
                            var replace = EditorWindow.GetItems(Conn, aml, aml.Length - 21);
                            if (replace.Count() == 1)
                            {
                                var sqlItem = Conn.AmlContext.FromXml(_whereUsedSqlAml).AssertItem();
                                var export = new ExportProcessor(Conn);
                                var script = new InstallScript();
                                var itemRef = ItemReference.FromFullItem(sqlItem, true);
                                await export.Export(script, new[] { itemRef });

                                var existing = script.Lines.FirstOrDefault(i => i.Reference.Equals(itemRef));
                                var needsSql = true;
                                if (existing != null)
                                {
                                    var merge = AmlDiff.GetMergeScript(XmlReader.Create(new StringReader(_whereUsedSqlAml)), new XmlNodeReader(existing.Script));
                                    needsSql = merge.Elements().Any();
                                }

                                if (needsSql)
                                {
                                    if (Dialog.MessageDialog.Show("To run this action, InnovatorAdmin needs to install the SQL WhereUsed_General into the database.  Do you want to install this?", "Install SQL", "Install", "Cancel") == System.Windows.Forms.DialogResult.OK)
                                    {
                                        await Conn.ApplyAsync(_whereUsedSqlAml, true, false).ToTask();
                                    }
                                    else
                                    {
                                        return null;
                                    }
                                }

                                var result = await Conn.ApplyAsync(@"<AML>
                                   <Item type='SQL' action='SQL PROCESS'>
                                     <name>WhereUsed_General</name>
                                     <PROCESS>CALL</PROCESS>
                                     <ARG1>@0</ARG1>
                                     <ARG2>@1</ARG2>
                                   </Item>
                                 </AML>", true, false, item.Type, item.Id).ToTask();

                                var sql = new StringBuilder("<sql>");
                                var whereUsed = result.Items().Where(i => !i.Property("type").HasValue() || i.Property("type").Value == i.Property("parent_type").Value);
                                var replaceId = replace.First().Unique;
                                sql.AppendLine();
                                foreach (var i in whereUsed)
                                {
                                    var props = (from p in i.Elements().OfType <IReadOnlyProperty>()
                                                 where p.Name.Length == 2 && p.Name[0] == 'p' && char.IsNumber(p.Name[1])
                                                 select p.Value).GroupConcat(" = '" + replaceId + "',");
                                    sql.Append("update innovator.[").Append(i.Property("main_type").Value.Replace(' ', '_')).Append("] set ");
                                    sql.Append(props).Append(" = '").Append(replaceId).Append("'");
                                    sql.Append(" where id ='").Append(i.Property("main_id").Value).Append("';");
                                    sql.AppendLine();
                                }
                                sql.Append("</sql>");

                                return sql.ToString();
                            }

                            return null;
                        }
                    });
                }
                yield return(new EditorScript()
                {
                    Name = "------"
                });

                yield return(new EditorScriptExecute()
                {
                    Name = "Export",
                    Execute = () =>
                    {
                        var refs = new[] { new ItemReference(item.Type, item.Id) };
                        StartExport(refs);
                        return Task.FromResult(true);
                    }
                });

                yield return(new EditorScript()
                {
                    Name = "------"
                });

                yield return(new EditorScript()
                {
                    Name = "Lock",
                    Action = "ApplyItem",
                    Script = string.Format("<Item type='{0}' {1} action='lock'></Item>", item.Type, GetCriteria(item.Id))
                });

                yield return(new EditorScript()
                {
                    Name = "------"
                });

                if (itemType != null && itemType.IsVersionable)
                {
                    var whereClause = "id='" + item.Id + "'";
                    if (!item.Id.IsGuid())
                    {
                        whereClause = item.Id;
                    }

                    yield return(new EditorScript()
                    {
                        Name = "Revisions",
                        AutoRun = true,
                        Action = "ApplyItem",
                        PreferredOutput = OutputType.Table,
                        Script = string.Format(@"<Item type='{0}' action='get' orderBy='generation'>
<config_id condition='in'>(select config_id from innovator.[{1}] where {2})</config_id>
<generation condition='gt'>0</generation>
</Item>", item.Type, item.Type.Replace(' ', '_'), whereClause)
                    });

                    yield return(new EditorScript()
                    {
                        Name = "------"
                    });
                }
                yield return(new EditorScript()
                {
                    Name = "Promote",
                    Action = "ApplyItem",
                    Script = string.Format("<Item type='{0}' {1} action='promoteItem'></Item>", item.Type, GetCriteria(item.Id))
                });

                yield return(new EditorScript()
                {
                    Name = "------"
                });

                yield return(new EditorScript()
                {
                    Name = "Where Used",
                    AutoRun = true,
                    Action = "ApplyItem",
                    Script = string.Format("<Item type='{0}' {1} action='getItemWhereUsed'></Item>", item.Type, GetCriteria(item.Id))
                });

                yield return(new EditorScript()
                {
                    Name = "Structure Browser",
                    Action = "ApplyItem",
                    AutoRun = true,
                    Script = string.Format(@"<Item type='Method' action='GetItemsForStructureBrowser'>
  <Item type='{0}' {1} action='GetItemsForStructureBrowser' levels='2' />
</Item>", item.Type, GetCriteria(item.Id))
                });

                yield return(new EditorScript()
                {
                    Name = "------"
                });

                if (metadata != null)
                {
                    var actions = new EditorScript()
                    {
                        Name = "Actions"
                    };

                    var serverActions = metadata.ServerItemActions(item.Type)
                                        .OrderBy(l => l.Label ?? l.Value, StringComparer.CurrentCultureIgnoreCase)
                                        .ToArray();
                    foreach (var action in serverActions)
                    {
                        actions.Add(new EditorScript()
                        {
                            Name    = (action.Label ?? action.Value),
                            Action  = "ApplyItem",
                            Script  = string.Format("<Item type='{0}' {1} action='{2}'></Item>", item.Type, GetCriteria(item.Id), action.Value),
                            AutoRun = true
                        });
                    }

                    if (serverActions.Any())
                    {
                        yield return(actions);
                    }

                    var reports = new EditorScript()
                    {
                        Name = "Reports"
                    };

                    var serverReports = metadata.ServerReports(item.Type)
                                        .OrderBy(l => l.Label ?? l.Value, StringComparer.CurrentCultureIgnoreCase)
                                        .ToArray();
                    foreach (var report in serverReports)
                    {
                        reports.Add(new EditorScript()
                        {
                            Name    = (report.Label ?? report.Value),
                            Action  = "ApplyItem",
                            Script  = @"<Item type='Method' action='Run Report'>
  <report_name>" + report.Value + @"</report_name>
  <AML>
    <Item type='" + itemType.Name + "' typeId='" + itemType.Id + "' " + GetCriteria(item.Id) + @" />
  </AML>
</Item>",
                            AutoRun = true
                        });
                    }

                    if (serverReports.Any())
                    {
                        yield return(reports);
                    }
                }
                if (item.Id.IsGuid())
                {
                    yield return(new EditorScriptExecute()
                    {
                        Name = "Copy ID",
                        Execute = () =>
                        {
                            System.Windows.Clipboard.SetText(item.Id);
                            return Task.FromResult(true);
                        }
                    });
                }
            }
        }
    public IEnumerable<IEditorScript> GetScripts()
    {
      var items = (Items ?? Enumerable.Empty<IItemData>())
        .Where(i => !string.IsNullOrEmpty(i.Id) && !string.IsNullOrEmpty(i.Type))
        .ToArray();
      if (!items.Any())
        yield break;

      if (items.Skip(1).Any()) // There is more than one
      {
        if (items.OfType<DataRowItemData>().Any())
        {
          yield return new EditorScriptExecute()
          {
            Name = "Delete",
            Execute = () =>
            {
              foreach (var row in items.OfType<DataRowItemData>())
              {
                row.Delete();
              }
              return Task.FromResult(true);
            }
          };
        }
        else
        {
          var builder = new StringBuilder("<AML>");
          foreach (var item in items)
          {
            builder.AppendLine().AppendFormat("  <Item type='{0}' {1} action='delete'></Item>", item.Type, GetCriteria(item.Id));
          }
          builder.AppendLine().Append("</AML>");
          yield return new EditorScript()
          {
            Name = "Delete",
            Action = "ApplyAML",
            Script = builder.ToString()
          };
        }

        var dataRows = items.OfType<DataRowItemData>()
          .OrderBy(r => r.Property("generation")).ThenBy(r => r.Id)
          .ToArray();
        if (dataRows.Length == 2) // There are exactly two items
        {
          yield return new EditorScript()
          {
            Name = "------"
          };
          yield return new EditorScriptExecute()
          {
            Name = "Compare",
            Execute = async () =>
            {
              try
              {
                await Settings.Current.PerformDiff(dataRows[0].Id, dataRows[0].ToAml
                  , dataRows[1].Id, dataRows[1].ToAml);
              }
              catch (Exception ex)
              {
                Utils.HandleError(ex);
              }
            }
          };
        }
        yield return new EditorScript()
        {
          Name = "------"
        };
        yield return new EditorScriptExecute()
        {
          Name = "Export",
          Execute = () =>
          {
            var refs = items.OfType<ItemRefData>().Select(i => i.Ref);
            if (!refs.Any())
              refs = items.Select(i => new ItemReference(i.Type, i.Id));
            StartExport(refs);
            return Task.FromResult(true);
          }
        };
      }
      else
      {
        var item = items.Single();
        var rowItem = item as DataRowItemData;

        ArasMetadataProvider metadata = null;
        ItemType itemType = null;
        if (Conn != null)
        {
          metadata = ArasMetadataProvider.Cached(Conn);
          if (!metadata.ItemTypeByName(item.Type, out itemType))
            metadata = null;
        }

        if (Conn != null)
        {
          yield return ArasEditorProxy.ItemTypeAddScript(Conn, itemType);
        }
        yield return new EditorScript()
        {
          Name = "------"
        };
        if (rowItem == null)
        {
          var script = string.Format("<Item type='{0}' {1} action='edit'></Item>", item.Type, GetCriteria(item.Id));
          if (item.Property("config_id") != null && itemType != null && itemType.IsVersionable)
          {
            script = string.Format("<Item type='{0}' where=\"[{1}].[config_id] = '{2}'\" action='edit'></Item>"
              , item.Type, item.Type.Replace(' ', '_'), item.Property("config_id"));
          }

          yield return new EditorScript()
          {
            Name = "Edit",
            Action = "ApplyItem",
            Script = script
          };
        }
        else
        {
          if (!string.IsNullOrEmpty(Column))
          {
            var prop = metadata.GetProperty(itemType, Column.Split('/')[0]).Wait();
            switch (prop.Type)
            {
              case PropertyType.item:
                yield return new EditorScriptExecute()
                {
                  Name = "Edit Value",
                  Execute = () =>
                  {
                    var query = string.Format("<Item type='{0}' action='get'><keyed_name condition='like'>**</keyed_name></Item>", prop.Restrictions.First());
                    var values = EditorWindow.GetItems(Conn, query, query.Length - 21);
                    var results = values.Where(i => prop.Restrictions.Contains(i.Type)).ToArray();
                    if (results.Length == 1)
                    {
                      rowItem.SetProperty(prop.Name, results[0].Unique);
                      rowItem.SetProperty(prop.Name + "/keyed_name", results[0].KeyedName);
                      rowItem.SetProperty(prop.Name + "/type", results[0].Type);
                    }
                    return Task.FromResult(true);
                  }
                };
                break;
            }
          }
        }
        if (metadata != null)
        {
          yield return new EditorScript()
          {
            Name = "View \"" + (itemType.Label ?? itemType.Name) + "\"",
            Action = "ApplyItem",
            Script = string.Format("<Item type='{0}' {1} action='get' levels='1'></Item>", item.Type, GetCriteria(item.Id)),
            AutoRun = true,
            PreferredOutput = OutputType.Table
          };
          if (item.Property("related_id") != null && itemType.Related != null)
          {
            yield return new EditorScript()
            {
              Name = "View \"" + (itemType.Related.Label ?? itemType.Related.Name) + "\"",
              Action = "ApplyItem",
              Script = string.Format("<Item type='{0}' id='{1}' action='get' levels='1'></Item>", itemType.Related.Name, item.Property("related_id")),
              AutoRun = true,
              PreferredOutput = OutputType.Table
            };
          }
        }
        yield return new EditorScript()
        {
          Name = "------"
        };
        if (rowItem == null)
        {
          yield return new EditorScript()
          {
            Name = "Delete",
            Action = "ApplyItem",
            Script = string.Format("<Item type='{0}' {1} action='delete'></Item>", item.Type, GetCriteria(item.Id))
          };
        }
        else
        {
          yield return new EditorScriptExecute()
          {
            Name = "Delete",
            Execute = () =>
            {
              rowItem.Delete();
              return Task.FromResult(true);
            }
          };
        }
        if (item.Id.IsGuid())
        {
          yield return new EditorScript()
          {
            Name = "Replace Item",
            Action = "ApplySql",
            ScriptGetter = async () =>
            {
              var aml = string.Format("<Item type='{0}' action='get'><keyed_name condition='like'>**</keyed_name></Item>", item.Type);
              var replace = EditorWindow.GetItems(Conn, aml, aml.Length - 21);
              if (replace.Count() == 1)
              {
                var sqlItem = Conn.AmlContext.FromXml(_whereUsedSqlAml).AssertItem();
                var export = new ExportProcessor(Conn);
                var script = new InstallScript();
                var itemRef = ItemReference.FromFullItem(sqlItem, true);
                await export.Export(script, new[] { itemRef });
                var existing = script.Lines.FirstOrDefault(i => i.Reference.Equals(itemRef));
                var needsSql = true;
                if (existing != null)
                {
                  var merge = AmlDiff.GetMergeScript(XmlReader.Create(new StringReader(_whereUsedSqlAml)), new XmlNodeReader(existing.Script));
                  needsSql = merge.Elements().Any();
                }

                if (needsSql)
                {
                  if (Dialog.MessageDialog.Show("To run this action, InnovatorAdmin needs to install the SQL WhereUsed_General into the database.  Do you want to install this?", "Install SQL", "Install", "Cancel") == System.Windows.Forms.DialogResult.OK)
                  {
                    await Conn.ApplyAsync(_whereUsedSqlAml, true, false).ToTask();
                  }
                  else
                  {
                    return null;
                  }
                }

                var result = await Conn.ApplyAsync(@"<AML>
                                   <Item type='SQL' action='SQL PROCESS'>
                                     <name>WhereUsed_General</name>
                                     <PROCESS>CALL</PROCESS>
                                     <ARG1>@0</ARG1>
                                     <ARG2>@1</ARG2>
                                   </Item>
                                 </AML>", true, false, item.Type, item.Id).ToTask();
                var sql = new StringBuilder("<sql>");
                var whereUsed = result.Items().Where(i => !i.Property("type").HasValue() || i.Property("type").Value == i.Property("parent_type").Value);
                var replaceId = replace.First().Unique;
                sql.AppendLine();
                foreach (var i in whereUsed)
                {
                  var props = (from p in i.Elements().OfType<IReadOnlyProperty>()
                               where p.Name.Length == 2 && p.Name[0] == 'p' && char.IsNumber(p.Name[1])
                               select p.Value).GroupConcat(" = '" + replaceId + "',");
                  sql.Append("update innovator.[").Append(i.Property("main_type").Value.Replace(' ', '_')).Append("] set ");
                  sql.Append(props).Append(" = '").Append(replaceId).Append("'");
                  sql.Append(" where id ='").Append(i.Property("main_id").Value).Append("';");
                  sql.AppendLine();
                }
                sql.Append("</sql>");

                return sql.ToString();
              }

              return null;
            }
          };
        }
        yield return new EditorScript()
        {
          Name = "------"
        };
        yield return new EditorScriptExecute()
        {
          Name = "Export",
          Execute = () =>
          {
            var refs = new[] { new ItemReference(item.Type, item.Id) };
            StartExport(refs);
            return Task.FromResult(true);
          }
        };
        yield return new EditorScript()
        {
          Name = "------"
        };
        yield return new EditorScript()
        {
          Name = "Lock",
          Action = "ApplyItem",
          Script = string.Format("<Item type='{0}' {1} action='lock'></Item>", item.Type, GetCriteria(item.Id))
        };
        yield return new EditorScript()
        {
          Name = "------"
        };
        if (itemType != null && itemType.IsVersionable)
        {
          var whereClause = "id='" + item.Id + "'";
          if (!item.Id.IsGuid())
            whereClause = item.Id;

          yield return new EditorScript()
          {
            Name = "Revisions",
            AutoRun = true,
            Action = "ApplyItem",
            PreferredOutput = OutputType.Table,
            Script = string.Format(@"<Item type='{0}' action='get' orderBy='generation'>
<config_id condition='in'>(select config_id from innovator.[{1}] where {2})</config_id>
<generation condition='gt'>0</generation>
</Item>", item.Type, item.Type.Replace(' ', '_'), whereClause)
          };
          yield return new EditorScript()
          {
            Name = "------"
          };
        }
        yield return new EditorScript()
        {
          Name = "Promote",
          Action = "ApplyItem",
          Script = string.Format("<Item type='{0}' {1} action='promoteItem'></Item>", item.Type, GetCriteria(item.Id))
        };
        yield return new EditorScript()
        {
          Name = "------"
        };
        yield return new EditorScript()
        {
          Name = "Where Used",
          AutoRun = true,
          Action = "ApplyItem",
          Script = string.Format("<Item type='{0}' {1} action='getItemWhereUsed'></Item>", item.Type, GetCriteria(item.Id))
        };
        yield return new EditorScript()
        {
          Name = "Structure Browser",
          Action = "ApplyItem",
          AutoRun = true,
          Script = string.Format(@"<Item type='Method' action='GetItemsForStructureBrowser'>
  <Item type='{0}' {1} action='GetItemsForStructureBrowser' levels='2' />
</Item>", item.Type, GetCriteria(item.Id))
        };
        yield return new EditorScript()
        {
          Name = "------"
        };
        if (metadata != null)
        {
          var actions = new EditorScript()
          {
            Name = "Actions"
          };

          var serverActions = metadata.ServerItemActions(item.Type)
            .OrderBy(l => l.Label ?? l.Value, StringComparer.CurrentCultureIgnoreCase)
            .ToArray();
          foreach (var action in serverActions)
          {
            actions.Add(new EditorScript()
            {
              Name = (action.Label ?? action.Value),
              Action = "ApplyItem",
              Script = string.Format("<Item type='{0}' {1} action='{2}'></Item>", item.Type, GetCriteria(item.Id), action.Value),
              AutoRun = true
            });
          }

          if (serverActions.Any())
            yield return actions;

          var reports = new EditorScript()
          {
            Name = "Reports"
          };

          var serverReports = metadata.ServerReports(item.Type)
            .OrderBy(l => l.Label ?? l.Value, StringComparer.CurrentCultureIgnoreCase)
            .ToArray();
          foreach (var report in serverReports)
          {
            reports.Add(new EditorScript()
            {
              Name = (report.Label ?? report.Value),
              Action = "ApplyItem",
              Script = @"<Item type='Method' action='Run Report'>
  <report_name>" + report.Value + @"</report_name>
  <AML>
    <Item type='" + itemType.Name + "' typeId='" + itemType.Id + "' " + GetCriteria(item.Id) + @" />
  </AML>
</Item>",
              AutoRun = true
            });
          }

          if (serverReports.Any())
            yield return reports;
        }
        if (item.Id.IsGuid())
        {
          yield return new EditorScriptExecute()
          {
            Name = "Copy ID",
            Execute = () =>
            {
              System.Windows.Clipboard.SetText(item.Id);
              return Task.FromResult(true);
            }
          };
        }
      }
    }