public static void AncestorsWithXNameBeforeAndAfter()
 {
     XText aText = new XText("a"), bText = new XText("b");
     XElement a = new XElement("A", aText), b = new XElement("B", bText);
     a.Add(b);
     IEnumerable<XElement> nodes = bText.Ancestors("B");
     Assert.Equal(1, nodes.Count());
     bText.Remove(); a.Add(bText);
     Assert.Equal(0, nodes.Count());
 }
        /// <summary> Preserves any <c> Keepers </c> - code that needs rescuing from the Link Zone. </summary>
        /// <param name="exclusionsList"> </param>
        internal void PreserveKeepersAndReport(List <string> exclusionsList)
        {
            string docString = DestProjXdoc.ToString().ToLower();

            if (Keepers?.Any() ?? false)
            {
                var newItemGroup = new XElement(Settings.MSBuild + "ItemGroup");
                newItemGroup?.Add(new XComment("Code Linker moved these here from inside the link zone because they were not re-linked"));
                newItemGroup?.Add(new XComment("You may wish to delete or un-comment these"));

                foreach (XElement keeper in Keepers)
                {
                    if (keeper?.FirstAttribute == null)
                    {
                        continue;
                    }

                    string keeperString = keeper.FirstAttribute.Value.ToLower();

                    string keeperCommentString = keeper.ToString().Replace("xmlns=\"" + Settings.MSBuild + "\"", "");

                    if (!docString.Contains(keeperString) && (exclusionsList == null || !exclusionsList.Any(e => e?.Contains(keeperString) ?? false)))
                    {
                        XAttribute attrib = keeper.Attribute("Include") ?? keeper.Attribute("Exclude");

                        if (attrib == null)
                        {
                            continue; // these are not the droids
                        }
                        string originalSourcePath = attrib.Value;

                        if (originalSourcePath.StartsWith("..", StringComparison.Ordinal)) // the file is outside the project tree, it is most likely an intruder
                        {
                            newItemGroup.Add(new XComment(keeperCommentString));
                            Log.WriteLine("[Warning] Rescued this from inside the link zone. Review it, you may want to uncomment it or delete it.  ", ConsoleColor.Red, ConsoleColor.DarkBlue);
                            Log.WriteLine(keeperCommentString, ConsoleColor.Red, ConsoleColor.DarkBlue);
                        }
                        else // the file is inside the project tree, it is most likely an keeper
                        {
                            newItemGroup.Add(keeper);
                            Log.WriteLine("[Warning] Rescued this from inside the link zone. Review it, you may want to delete it " + keeper.ToString().Replace("xmlns=\"" + Settings.MSBuild + "\"", ""), ConsoleColor.Red, ConsoleColor.DarkBlue);
                        }
                    }
                    else
                    {
                        Log.WriteLine("Skipped duplicating: " + keeper.FirstAttribute.Value, ConsoleColor.DarkGray);
                    }
                }
                // Log.WriteLine("DocString" +docString);
                EndPlaceHolder.AddAfterSelf(newItemGroup); // move the keepers out of the Link zone.
            }
        }
		public ThemaCompilerResultForQweb(ThemaCompilerContext context) {
			IsComplete = context.IsComplete;
			Errors = context.Errors.ToArray();
			if (!IsComplete) return;
			var r = new XElement("result");
			foreach (var t in context.Themas.Values.Where(t => null != t.Xml)) {
				r.Add(t.Xml);
			}
			if (null != context.ExtraData) {
				r.Add(context.ExtraData);
			}
			Result = new XmlToBxlConverter().Convert(r);
			Log = context.Project.GetLog();
		}
Exemple #4
0
        private static void Main()
        {
            helper.ConsoleMio.Setup();
            helper.ConsoleMio.PrintHeading("Extract Contact Information");

            string selctedFile = SelectFileToOpen();

            string saveLocation = SelectSaveLocation();

            var contactInfo = new XElement("person");
            
            using (var inputStream = new StreamReader(selctedFile))
            {
                string currentLine;
                while ((currentLine = inputStream.ReadLine()) != null)
                {
                    string[] args = currentLine.Split(' ');
                    string tag = args[0];
                    string content = string.Join(" ", args.Skip(1).ToArray());

                    contactInfo.Add(new XElement(tag, content));
                }
            }

            contactInfo.Save(saveLocation);

            helper.ConsoleMio.PrintColorText("Completed\n ", ConsoleColor.Green);
            
            helper.ConsoleMio.Restart(Main);
        }
Exemple #5
0
        /// <summary>
        /// Retrieves the musicXml that corresponds to this class and all that it encapsulates.
        /// </summary>
        /// <returns><see cref="XElement"/> containing the required musicXml.</returns>
        public XElement GetXml()
        {
            XElement dirnote   = SubRhythm.GetXml();
            XElement note      = dirnote.Element("note");
            XElement notations = note?.Element("notations");

            if (notations == null)
            {
                note?.Add(XElement.Parse("<notations><ornaments><tremolo type=\"single\">3</tremolo></ornaments></notations>"));
            }
            else
            {
                XElement orns = notations.Element("ornaments");
                if (orns == null)
                {
                    notations.Add(XElement.Parse("<ornaments><tremolo type=\"single\">3</tremolo></ornaments>"));
                }
                else
                {
                    XElement trem = orns.Element("tremolo");
                    if (trem == null)
                    {
                        orns.Add(XElement.Parse("<tremolo type=\"single\">3</tremolo>"));
                    }
                    else
                    {
                        if ((int)trem.Elements().First() != 3)
                        {
                            trem.ReplaceAll(3);
                        }
                    }
                }
            }
            return(dirnote);
        }
Exemple #6
0
        private XElement CreateElement(XElement child, XElement parent = null)
        {
            var key = ElementMap.Keys.FirstOrDefault(k => child.Name.LocalName.Contains(k));

            if (key == null)
            {
                return(null);
            }
            var element = new XElement(FormsNamespace + ElementMap[key]);

            parent?.Add(element);
            foreach (var attribute in child.Attributes())
            {
                Func <XElement, string, XAttribute> attributeResolver;

                if (!AttributeMap.TryGetValue(attribute.Name.LocalName, out attributeResolver))
                {
                    continue;
                }
                var resolvedAttribute = attributeResolver(child, attribute.Value);
                if (resolvedAttribute != null)
                {
                    element.Add(resolvedAttribute);
                }
            }
            ApplyPadding(element, child);
            ApplyMargin(element, child);
            ApplyBindings(element, child);
            return(element);
        }
        /// <summary>
        /// Retrieves the musicXml that corresponds to this class and all that it encapsulates.
        /// </summary>
        /// <returns><see cref="XElement"/> containing the required musicXml.</returns>
        public XElement GetXml()
        {
            XElement dirnote   = SubRhythm.GetXml();
            XElement note      = dirnote.Element("note");
            XElement notations = note?.Element("notations");

            if (notations == null)
            {
                note?.Add(XElement.Parse("<notations><articulations><strong-accent/></articulations></notations>"));
            }
            else
            {
                XElement artics = notations.Element("articulations");
                if (artics == null)
                {
                    notations.Add(XElement.Parse("<articulations><strong-accent/></articulations>"));
                }
                else
                {
                    if (artics.Element("strong-accent") == null)
                    {
                        artics.Add(XElement.Parse("<strong-accent/>"));
                    }
                }
            }
            return(dirnote);
        }
        /// <summary>
        /// Retrieves the musicXml that corresponds to this class and all that it encapsulates.
        /// </summary>
        /// <returns><see cref="XElement"/> containing the required musicXml.</returns>
        public XElement GetXml()
        {
            XElement dirnote = SubRhythm.GetXml();
            XElement note    = dirnote.Element("note");

            note?.Add(XElement.Parse("<rest/>"));
            return(dirnote);
        }
        /// <summary>
        /// Retrieves the musicXml that corresponds to this class and all that it encapsulates.
        /// </summary>
        /// <returns><see cref="XElement"/> containing the required musicXml.</returns>
        public XElement GetXml()
        {
            XElement dirnote = SubRhythm.GetXml();
            XElement note    = dirnote.Element("note");

            note?.Add(XElement.Parse("<beam number=\"" + number + "\">" + state + "</beam>"));
            return(dirnote);
        }
        private void AddEntryElements(IEnumerable <StructureEntity> batch)
        {
            foreach (StructureEntity structureEntity in batch
                     .Where(x => x.EntityId != _config.ChannelId && !x.IsChannelNode()))
            {
                Entity entity = _entityService.GetEntity(structureEntity.EntityId, LoadLevel.DataAndLinks);

                if (ShouldCreateSkus(structureEntity))
                {
                    List <XElement> skus = _catalogElementFactory.GenerateSkuItemElemetsFromItem(entity);
                    foreach (XElement sku in skus)
                    {
                        XElement codeElement = sku.Element("Code");

                        if (codeElement == null || _epiElementContainer.HasEntry(codeElement.Value))
                        {
                            continue;
                        }

                        _epiElementContainer.AddEntry(sku, codeElement.Value);
                        IntegrationLogger.Write(LogLevel.Debug, $"Added Item/SKU {sku.Name.LocalName} to Entries");
                    }
                }

                if ((!structureEntity.IsItem() || !_config.ItemsToSkus || !_config.UseThreeLevelsInCommerce) && ShouldCreateSkus(structureEntity))
                {
                    continue;
                }
                {
                    if (structureEntity.IsItem() && !_channelHelper.ItemHasParentInChannel(structureEntity))
                    {
                        continue;
                    }

                    XElement element = _catalogElementFactory.InRiverEntityToEpiEntry(entity);

                    XElement codeElement = element.Element("Code");
                    if (codeElement == null || _epiElementContainer.HasEntry(codeElement.Value))
                    {
                        continue;
                    }

                    XElement specificationField = GetSpecificationMetaField(entity);

                    if (specificationField != null)
                    {
                        XElement metaFieldsElement = element.Descendants().FirstOrDefault(f => f.Name == "MetaFields");
                        metaFieldsElement?.Add(specificationField);
                    }

                    _epiElementContainer.AddEntry(element, codeElement.Value);

                    IntegrationLogger.Write(LogLevel.Debug, $"Added Entity {entity.Id} to Entries");
                }
            }
        }
        public XDocument CreateUpdateDocument(Entity channelEntity, Entity updatedEntity)
        {
            var skus = new List <XElement>();

            if (_config.ItemsToSkus && updatedEntity.EntityType.Id == "Item")
            {
                skus = _catalogElementFactory.GenerateSkuItemElemetsFromItem(updatedEntity);
            }

            XElement updatedNode  = null;
            XElement updatedEntry = null;

            var shouldGetUpdatedEntry = !(updatedEntity.EntityType.Id == "Item" && !_config.UseThreeLevelsInCommerce && _config.ItemsToSkus);

            if (updatedEntity.EntityType.Id == "ChannelNode")
            {
                updatedNode = GetUpdatedNode(channelEntity, updatedEntity, updatedNode);
            }
            else if (shouldGetUpdatedEntry)
            {
                updatedEntry = _catalogElementFactory.InRiverEntityToEpiEntry(updatedEntity);
                Link specLink = updatedEntity.OutboundLinks.Find(l => l.Target.EntityType.Id == "Specification");
                if (specLink != null)
                {
                    XElement specificationField = new XElement("MetaField",
                                                               new XElement("Name", "SpecificationField"),
                                                               new XElement("Type", "LongHtmlString"));

                    foreach (var languageMap in _config.LanguageMapping)
                    {
                        var htmlData = RemoteManager.DataService.GetSpecificationAsHtml(specLink.Target.Id, updatedEntity.Id, languageMap.Value);
                        specificationField.Add(new XElement("Data",
                                                            new XAttribute("language", languageMap.Key.Name.ToLower()),
                                                            new XAttribute("value", htmlData)));
                    }

                    XElement element = updatedEntry.Descendants().FirstOrDefault(f => f.Name == "MetaFields");
                    element?.Add(specificationField);
                }
            }

            XElement catalogElement = _catalogElementFactory.CreateCatalogElement(channelEntity);
            var      updatedNodes   = new List <XElement> {
                updatedEntry
            };

            updatedNodes.AddRange(skus);

            var baseCatalogDocumentNodes = CreateBaseCatalogDocumentNodes(channelEntity, new List <XElement> {
                updatedNode
            }, updatedNodes, null, null);

            catalogElement.Add(baseCatalogDocumentNodes);

            return(CreateDocument(catalogElement, null, null));
        }
Exemple #12
0
 public static void ElementsAfterSelfWithXNameBeforeAndAfter()
 {
     XText aText = new XText("a"), bText = new XText("b");
     XElement a = new XElement("A", aText), b = new XElement("B", bText);
     a.Add(b);
     IEnumerable<XElement> nodes = aText.ElementsAfterSelf("B");
     Assert.Equal(1, nodes.Count());
     b.ReplaceWith(a);
     Assert.Equal(0, nodes.Count());
 }
Exemple #13
0
        public void CData(string value1, string value2, bool checkHashCode)
        {
            XCData t1 = new XCData(value1);
            XCData t2 = new XCData(value2);
            VerifyComparison(checkHashCode, t1, t2);

            XElement e2 = new XElement("p2p", t2);
            e2.Add(t1);
            VerifyComparison(checkHashCode, t1, t2);
        }
Exemple #14
0
        public bool AddGroupWithSudents()
        {
            if (Students.Count <= 0 || _groupDb.Root == null)
            {
                return(false);
            }
            if (!IsGroupIsExists(GroupName))
            {
                _groupDb.Root.Add(new XElement("group", new XElement(nameof(GroupName), GroupName)));
                _groupDb.Save(F1.FullName);
                _groupDb.Root?.Elements().Elements().FirstOrDefault(w => w.Value == GroupName)?.Parent?.Add(new XElement("students"));
                _groupDb.Save(F1.FullName);
                XElement studentElement = _groupDb.Root?.Elements().Elements().FirstOrDefault(f => f.Value == GroupName)?.Parent?.Element("students");

                foreach (Student s in Students)
                {
                    studentElement?.Add(new XElement(nameof(s.StudentName), s.StudentName));
                }

                _groupDb.Save(F1.FullName);
            }
            else
            {
                List <string> group = _groupDb.Root?.Elements().Elements().FirstOrDefault(f => f.Name == nameof(GroupName) && f.Value == GroupName)?.Parent?.Element("students")?.Elements().Select(s => s.Value).ToList();

                if (@group != null)
                {
                    List <string> both = Students.Select(s => s.StudentName).Intersect(@group).ToList();

                    if (both.Count == 0)
                    {
                        XElement studentElement = _groupDb.Root?.Elements().Elements().FirstOrDefault(f => f.Name == "students");
                        foreach (Student s in Students)
                        {
                            studentElement?.Add(new XElement(nameof(s.StudentName), s.StudentName));
                        }

                        _groupDb.Save(F1.FullName);
                    }
                    else
                    {
                        foreach (string s in both)
                        {
                            if (Students.Exists(e => e.StudentName == s))
                            {
                                Students.Remove(Students.ElementAt(Students.IndexOf(Students.FirstOrDefault(f => f.StudentName == s))));
                            }
                        }

                        return(AddGroupWithSudents());
                    }
                }
            }
            return(true);
        }
Exemple #15
0
        /// <summary>
        /// Retrieves the musicXml that corresponds to this class and all that it encapsulates.
        /// </summary>
        /// <returns><see cref="XElement"/> containing the required musicXml.</returns>
        public XElement GetXml()
        {
            XElement dirnote = SubRhythm.GetXml();
            XElement note    = dirnote.Element("note");
            XElement dot     = note?.Element("dot");

            if (dot == null)
            {
                note?.Add(XElement.Parse("<dot/>"));
            }
            return(dirnote);
        }
Exemple #16
0
        public Playlist Add(Playlist entity)
        {
            if (!ItCanBeAdded(entity))
            {
                throw new InvalidOperationException("No se puede tener una lista de reproducción con el nombre de otra ya existente");
            }

            entity.Id = ComputeNextId();
            XElement playlist = null;

            using (var storage = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null))
            {
                // Playlists (parent node).
                playlist = _document.Descendants(rootNode)?.FirstOrDefault();

                // Playlist element (child node)
                var playlistElement = new XElement(
                    name: playlistNode,
                    content: new[] {
                    new XAttribute("Id", entity.Id),
                    new XAttribute("Name", entity.Name),
                    new XAttribute("Logo", entity.Logo),
                }
                    );

                // Adding piece IDs to Playlist element..
                var pieces = entity.PieceList.Select <Piece, XElement>(p =>
                {
                    var element = new XElement("PieceId");
                    element.Add(p.Id);
                    return(element);
                });

                foreach (var p in pieces)
                {
                    playlistElement.Add(p);
                }

                // If exists, add the new piece to descendatants
                playlist?.Add(playlistElement);

                using (Stream stream = storage.CreateFile(isolatedFilePath))
                {
                    _document.Save(stream);
                }
            }

            this.count++;

            return(entity);
        }
        public void CreateUser(long userId)
        {
            CheckDoc();
            XDocument xDoc    = XDocument.Load("users.xml");
            XElement  xRoot   = xDoc.Element("users");
            XElement  newUser = new XElement("user",
                                             new XAttribute("id", userId),
                                             new XElement("university", ""),
                                             new XElement("faculty", ""),
                                             new XElement("course", ""),
                                             new XElement("group", ""));

            xRoot?.Add(newUser);
            xDoc.Save("users.xml");
        }
        /// <summary>
        /// Converts a given <see cref="Account"/> into an <see cref="T:XElement"/>.
        /// </summary>
        /// <param name="account">The <see cref="Account"/> to convert.</param>
        /// <returns>The newly created <see cref="T:XElement"/>.</returns>
        public XElement ToXElement(Account account)
        {
            XElement element = new XElement(account.AccountType.ToString());
            element.Add(new XElement("AccountID", account.AccountID));
            element.Add(new XElement("CreatedByUsername", account.CreatedByUsername));
            element.Add(new XElement("CreatedDate", account.CreatedDate));
            element.Add(new XElement("Description", account.Description));
            element.Add(new XElement("Name", account.Name));
            element.Add(new XElement("UpdatedByUsername", account.UpdatedByUsername));
            element.Add(new XElement("UpdatedDate", account.UpdatedDate));

            // Append the change history
            ChangeSetHistoryXElementAdapter adapter = new ChangeSetHistoryXElementAdapter();
            element.Add(adapter.ToXElement(account.ChangeSetHistory));

            return element;
        }
        /// <summary>
        /// Retrieves the musicXml that corresponds to this class and all that it encapsulates.
        /// </summary>
        /// <returns><see cref="XElement"/> containing the required musicXml.</returns>
        public XElement GetXml()
        {
            XElement dirnote = SubRhythm.GetXml();
            XElement note    = dirnote.Element("note");
            XElement head    = note?.Element("notehead");

            if (head == null)
            {
                note?.Add(XElement.Parse("<notehead font-weight=\"bold\">cross</notehead>"));
            }
            else
            {
                head.ReplaceAll("cross");
            }
            return(dirnote);
        }
 /// <summary>
 /// Converts a given <see cref="ChangeSetHistory"/> into an <see cref="T:XElement"/>.
 /// </summary>
 /// <param name="changeSetHistory">The <see cref="ChangeSetHistory"/> to convert.</param>
 /// <returns>The newly created <see cref="T:XElement"/>.</returns>
 public XElement ToXElement(ChangeSetHistory changeSetHistory)
 {
     XElement historyElement = new XElement("ChangeSetHistory");
     foreach (ChangeSet changeSet in changeSetHistory) {
         XElement changeSetElement = new XElement("ChangeSet",
             new XElement("Applied", changeSet.Applied),
             new XElement("Username", changeSet.Username));
         foreach (Change change in changeSet.Changes) {
             XElement changeElement = new XElement("Change",
                 new XElement("PropertyName", change.PropertyName),
                 new XElement("OldValue", change.OldValue),
                 new XElement("NewValue", change.NewValue));
             changeSetElement.Add(changeElement);
         }
         historyElement.Add(changeSetElement);
     }
     return historyElement;
 }
 public XElement GetLog() 
 {
     int id = GetIdFromHeaders();
     PTEntities ctx = this.CurrentDataSource;
     TestOperation t = ctx.TestOperations.Include("LogEntries.LogEntryHeaders").FirstOrDefault(to => (to.Id == id));
     if (t == null) return null;
     XElement retVal = new XElement("TestOperation", new XAttribute("id", id), new XAttribute("desc", t.Name));
     foreach (var le in t.LogEntries) 
     {
         XElement xle = new XElement(le.Verb, new XAttribute("Uri", le.URI));
         retVal.Add(xle);
         foreach (var leh in le.LogEntryHeaders) 
         {
             xle.Add(new XElement("Header", new XAttribute("key", leh.Header), new XAttribute("value", leh.Value)));
         }
     }
     return retVal;
 }
        /// <summary>
        /// Retrieves the musicXml that corresponds to this class and all that it encapsulates.
        /// </summary>
        /// <returns><see cref="XElement"/> containing the required musicXml.</returns>
        public XElement GetXml()
        {
            XElement dirnote = SubRhythm.GetXml();
            XElement note    = dirnote.Element("note");
            XElement head    = note?.Element("notehead");

            if (head == null)
            {
                note?.Add(XElement.Parse("<notehead>ti</notehead>"));
            }
            else
            {
                head.ReplaceAll("ti");
            }
            XElement pitch = note?.Element("unpitched");
            XElement step  = pitch?.Element("display-step");

            step?.ReplaceAll("D");
            return(dirnote);
        }
        public void TestEditInherited()
        {
            SetUp();

            var site     = Path.Combine("Website1", "web.config");
            var expected = "expected_remove.site.config";
            var document = XDocument.Load(site);
            var node     = document.Root?.XPathSelectElement("/configuration/system.webServer");
            var security = new XElement("security");
            var request  = new XElement("requestFiltering");
            var file     = new XElement("filteringRules");
            var remove   = new XElement("remove");

            remove.SetAttributeValue("name", "test");
            file?.Add(remove);
            var add = new XElement("filteringRule");

            add.SetAttributeValue("name", "test");
            add.SetAttributeValue("scanQueryString", "true");
            node?.Add(security);
            security.Add(request);
            request.Add(file);
            file.Add(add);
            document.Save(expected);

            _feature.SelectedItem = _feature.Items[0];
            Assert.False(_feature.SelectedItem.ScanQueryString);
            var item = _feature.SelectedItem;

            item.ScanQueryString = true;
            _feature.EditItem(item);
            Assert.NotNull(_feature.SelectedItem);
            Assert.True(_feature.SelectedItem.ScanQueryString);

            const string Original     = @"original.config";
            const string OriginalMono = @"original.mono.config";

            XmlAssert.Equal(Helper.IsRunningOnMono() ? OriginalMono : Original, Current);
            XmlAssert.Equal(expected, site);
        }
Exemple #24
0
 /// <summary>
 /// 添加元素
 /// </summary>
 /// <param name="parentElement"></param>
 /// <param name="childElement">new XElement("节点名称", new XAttribute("节点属性", 节点属性),  new XElement("子节点", new XAttribute("节点属性", 节点属性)),无限添加子节点   );</param>
 public static void Add(ref XElement parentElement, XElement childElement)
 {
     parentElement?.Add(childElement);
 }
Exemple #25
0
        private void FillElements(List <StructureEntity> structureEntitiesBatch, Configuration config, List <string> addedEntities, List <string> addedNodes, List <string> addedRelations, Dictionary <string, List <XElement> > epiElements)
        {
            int logCounter          = 0;
            var channelPrefixHelper = new ChannelPrefixHelper(_context);


            Dictionary <string, LinkType> linkTypes = new Dictionary <string, LinkType>();

            foreach (LinkType linkType in config.LinkTypes)
            {
                if (!linkTypes.ContainsKey(linkType.Id))
                {
                    linkTypes.Add(linkType.Id, linkType);
                }
            }

            foreach (StructureEntity structureEntity in structureEntitiesBatch)
            {
                try
                {
                    if (structureEntity.EntityId == config.ChannelId)
                    {
                        continue;
                    }

                    logCounter++;

                    if (logCounter == 1000)
                    {
                        logCounter = 0;
                        _context.Log(LogLevel.Debug, "Generating catalog xml.");
                    }

                    int id = structureEntity.EntityId;

                    if (structureEntity.LinkEntityId.HasValue)
                    {
                        // Add the link entity

                        Entity linkEntity = null;

                        if (config.ChannelEntities.ContainsKey(structureEntity.LinkEntityId.Value))
                        {
                            linkEntity = config.ChannelEntities[structureEntity.LinkEntityId.Value];
                        }

                        if (linkEntity == null)
                        {
                            _context.Log(
                                LogLevel.Warning,
                                string.Format(
                                    "Link Entity with id {0} does not exist in system or ChannelStructure table is not in sync.",
                                    (int)structureEntity.LinkEntityId));
                            continue;
                        }

                        XElement entryElement = _epiElement.InRiverEntityToEpiEntry(linkEntity, config);

                        XElement codeElement = entryElement.Element("Code");
                        if (codeElement != null && !addedEntities.Contains(codeElement.Value))
                        {
                            epiElements["Entries"].Add(entryElement);
                            addedEntities.Add(codeElement.Value);

                            _context.Log(LogLevel.Debug, string.Format("Added Entity {0} to Entries", linkEntity.DisplayName));
                        }

                        if (!addedRelations.Contains(channelPrefixHelper.GetEPiCodeWithChannelPrefix(linkEntity.Id, config) + "_" + channelPrefixHelper.GetEPiCodeWithChannelPrefix("_inRiverAssociations", config)))
                        {
                            epiElements["Relations"].Add(
                                _epiElement.CreateNodeEntryRelationElement(
                                    "_inRiverAssociations",
                                    linkEntity.Id.ToString(CultureInfo.InvariantCulture),
                                    0,
                                    config));
                            addedRelations.Add(
                                channelPrefixHelper.GetEPiCodeWithChannelPrefix(linkEntity.Id, config) + "_"
                                + channelPrefixHelper.GetEPiCodeWithChannelPrefix("_inRiverAssociations", config));


                            _context.Log(LogLevel.Debug, string.Format("Added Relation for EntryCode {0}", channelPrefixHelper.GetEPiCodeWithChannelPrefix(linkEntity.Id, config)));
                        }
                    }

                    if (structureEntity.Type == "Resource")
                    {
                        continue;
                    }

                    Entity entity;

                    if (config.ChannelEntities.ContainsKey(id))
                    {
                        entity = config.ChannelEntities[id];
                    }
                    else
                    {
                        entity = _context.ExtensionManager.DataService.GetEntity(id, LoadLevel.DataOnly);

                        config.ChannelEntities.Add(id, entity);
                    }

                    if (entity == null)
                    {
                        //missmatch with entity data and ChannelStructure.

                        config.ChannelEntities.Remove(id);
                        continue;
                    }

                    if (structureEntity.Type == "ChannelNode")
                    {
                        string parentId = structureEntity.ParentId.ToString(CultureInfo.InvariantCulture);

                        if (config.ChannelId.Equals(structureEntity.ParentId))
                        {
                            _epiApi.CheckAndMoveNodeIfNeeded(id.ToString(CultureInfo.InvariantCulture), config);
                        }

                        _context.Log(LogLevel.Debug, string.Format("Trying to add channelNode {0} to Nodes", id));

                        XElement nodeElement = epiElements["Nodes"].Find(e =>
                        {
                            XElement xElement = e.Element("Code");
                            return(xElement != null && xElement.Value.Equals(channelPrefixHelper.GetEPiCodeWithChannelPrefix(entity.Id, config)));
                        });

                        int linkIndex = structureEntity.SortOrder;

                        if (nodeElement == null)
                        {
                            epiElements["Nodes"].Add(_epiElement.CreateNodeElement(entity, parentId, linkIndex, config));
                            addedNodes.Add(channelPrefixHelper.GetEPiCodeWithChannelPrefix(entity.Id, config));

                            _context.Log(LogLevel.Debug, string.Format("Added channelNode {0} to Nodes", id));
                        }
                        else
                        {
                            XElement parentNode = nodeElement.Element("ParentNode");
                            if (parentNode != null && (parentNode.Value != config.ChannelId.ToString(CultureInfo.InvariantCulture) && parentId == config.ChannelId.ToString(CultureInfo.InvariantCulture)))
                            {
                                string oldParent = parentNode.Value;
                                parentNode.Value = config.ChannelId.ToString(CultureInfo.InvariantCulture);
                                parentId         = oldParent;

                                XElement sortOrderElement = nodeElement.Element("SortOrder");
                                if (sortOrderElement != null)
                                {
                                    string oldSortOrder = sortOrderElement.Value;
                                    sortOrderElement.Value = linkIndex.ToString(CultureInfo.InvariantCulture);
                                    linkIndex = int.Parse(oldSortOrder);
                                }
                            }

                            if (!addedRelations.Contains(channelPrefixHelper.GetEPiCodeWithChannelPrefix(
                                                             id.ToString(CultureInfo.InvariantCulture),
                                                             config) + "_" + channelPrefixHelper.GetEPiCodeWithChannelPrefix(parentId, config)))
                            {
                                // add relation
                                epiElements["Relations"].Add(
                                    _epiElement.CreateNodeRelationElement(
                                        parentId,
                                        id.ToString(CultureInfo.InvariantCulture),
                                        linkIndex,
                                        config));

                                addedRelations.Add(
                                    channelPrefixHelper.GetEPiCodeWithChannelPrefix(
                                        id.ToString(CultureInfo.InvariantCulture),
                                        config) + "_" + channelPrefixHelper.GetEPiCodeWithChannelPrefix(parentId, config));

                                _context.Log(LogLevel.Debug, string.Format("Adding relation to channelNode {0}", id));
                            }
                        }

                        continue;
                    }

                    if (structureEntity.Type == "Item" && config.ItemsToSkus)
                    {
                        List <XElement> skus = _epiElement.GenerateSkuItemElemetsFromItem(entity, config);
                        foreach (XElement sku in skus)
                        {
                            XElement codeElement = sku.Element("Code");
                            if (codeElement != null && !addedEntities.Contains(codeElement.Value))
                            {
                                epiElements["Entries"].Add(sku);
                                addedEntities.Add(codeElement.Value);

                                _context.Log(LogLevel.Debug, string.Format("Added Item/SKU {0} to Entries", sku.Name.LocalName));
                            }
                        }
                    }

                    if ((structureEntity.Type == "Item" && config.ItemsToSkus && config.UseThreeLevelsInCommerce) ||
                        !(structureEntity.Type == "Item" && config.ItemsToSkus))
                    {
                        XElement element = _epiElement.InRiverEntityToEpiEntry(entity, config);

                        StructureEntity specificationStructureEntity =
                            config.ChannelStructureEntities.FirstOrDefault(
                                s => s.ParentId.Equals(id) && s.Type.Equals("Specification"));

                        if (specificationStructureEntity != null)
                        {
                            XElement metaField = new XElement(
                                "MetaField",
                                new XElement("Name", "SpecificationField"),
                                new XElement("Type", "LongHtmlString"));
                            foreach (KeyValuePair <CultureInfo, CultureInfo> culturePair in config.LanguageMapping)
                            {
                                string htmlData =
                                    _context.ExtensionManager.DataService.GetSpecificationAsHtml(
                                        specificationStructureEntity.EntityId,
                                        entity.Id,
                                        culturePair.Value);
                                metaField.Add(
                                    new XElement(
                                        "Data",
                                        new XAttribute("language", culturePair.Key.Name.ToLower()),
                                        new XAttribute("value", htmlData)));
                            }

                            XElement metaFieldsElement = element.Descendants().FirstOrDefault(f => f.Name == "MetaFields");
                            metaFieldsElement?.Add(metaField);
                        }

                        XElement codeElement = element.Element("Code");
                        if (codeElement != null && !addedEntities.Contains(codeElement.Value))
                        {
                            epiElements["Entries"].Add(element);
                            addedEntities.Add(codeElement.Value);

                            _context.Log(LogLevel.Debug, string.Format("Added Entity {0} to Entries", id));
                        }
                    }

                    List <StructureEntity> existingStructureEntities =
                        config.ChannelStructureEntities.FindAll(i => i.EntityId.Equals(id));

                    List <StructureEntity> filteredStructureEntities = new List <StructureEntity>();

                    foreach (StructureEntity se in existingStructureEntities)
                    {
                        if (!filteredStructureEntities.Exists(i => i.EntityId == se.EntityId && i.ParentId == se.ParentId))
                        {
                            filteredStructureEntities.Add(se);
                        }
                        else
                        {
                            if (se.LinkEntityId.HasValue)
                            {
                                if (!filteredStructureEntities.Exists(
                                        i =>
                                        i.EntityId == se.EntityId && i.ParentId == se.ParentId &&
                                        (i.LinkEntityId != null && i.LinkEntityId == se.LinkEntityId)))
                                {
                                    filteredStructureEntities.Add(se);
                                }
                            }
                        }
                    }

                    foreach (StructureEntity existingStructureEntity in filteredStructureEntities)
                    {
                        //Parent.
                        LinkType linkType = null;

                        if (linkTypes.ContainsKey(existingStructureEntity.LinkTypeIdFromParent))
                        {
                            linkType = linkTypes[existingStructureEntity.LinkTypeIdFromParent];
                        }

                        if (linkType == null)
                        {
                            continue;
                        }

                        if (linkType.SourceEntityTypeId == "ChannelNode")
                        {
                            if (!addedRelations.Contains(channelPrefixHelper.GetEPiCodeWithChannelPrefix(id.ToString(CultureInfo.InvariantCulture), config) + "_" + channelPrefixHelper.GetEPiCodeWithChannelPrefix(existingStructureEntity.ParentId.ToString(CultureInfo.InvariantCulture), config)))
                            {
                                epiElements["Relations"].Add(_epiElement.CreateNodeEntryRelationElement(existingStructureEntity.ParentId.ToString(), existingStructureEntity.EntityId.ToString(), existingStructureEntity.SortOrder, config));

                                addedRelations.Add(channelPrefixHelper.GetEPiCodeWithChannelPrefix(id, config) + "_" + channelPrefixHelper.GetEPiCodeWithChannelPrefix(existingStructureEntity.ParentId, config));

                                _context.Log(LogLevel.Debug, string.Format("Added Relation for Source {0} and Target {1} for LinkTypeId {2}", existingStructureEntity.ParentId, existingStructureEntity.EntityId, linkType.Id));
                            }

                            continue;
                        }

                        List <string> skus = new List <string> {
                            id.ToString(CultureInfo.InvariantCulture)
                        };
                        string parent = null;

                        if (structureEntity.Type.Equals("Item") && config.ItemsToSkus)
                        {
                            skus = _epiElement.SkuItemIds(entity, config);
                            for (int i = 0; i < skus.Count; i++)
                            {
                                skus[i] = channelPrefixHelper.GetEPiCodeWithChannelPrefix(skus[i], config);
                            }

                            if (config.UseThreeLevelsInCommerce)
                            {
                                parent = structureEntity.EntityId.ToString(CultureInfo.InvariantCulture);
                                skus.Add(parent);
                            }
                        }

                        Entity linkEntity = null;

                        if (existingStructureEntity.LinkEntityId != null)
                        {
                            if (config.ChannelEntities.ContainsKey(existingStructureEntity.LinkEntityId.Value))
                            {
                                linkEntity = config.ChannelEntities[existingStructureEntity.LinkEntityId.Value];
                            }
                            else
                            {
                                linkEntity = _context.ExtensionManager.DataService.GetEntity(
                                    existingStructureEntity.LinkEntityId.Value,
                                    LoadLevel.DataOnly);

                                config.ChannelEntities.Add(linkEntity.Id, linkEntity);
                            }
                        }

                        foreach (string skuId in skus)
                        {
                            string channelPrefixAndSkuId = channelPrefixHelper.GetEPiCodeWithChannelPrefix(skuId, config);

                            // prod -> item link, bundle, package or dynamic package => Relation
                            if (_epiMappingHelper.IsRelation(linkType.SourceEntityTypeId, linkType.TargetEntityTypeId, linkType.Index, config))
                            {
                                int parentNodeId = _channelHelper.GetParentChannelNode(structureEntity, config);
                                if (parentNodeId == 0)
                                {
                                    continue;
                                }

                                string channelPrefixAndParentNodeId = channelPrefixHelper.GetEPiCodeWithChannelPrefix(parentNodeId, config);

                                if (!addedRelations.Contains(channelPrefixAndSkuId + "_" + channelPrefixAndParentNodeId))
                                {
                                    epiElements["Relations"].Add(
                                        _epiElement.CreateNodeEntryRelationElement(
                                            parentNodeId.ToString(CultureInfo.InvariantCulture),
                                            skuId,
                                            existingStructureEntity.SortOrder,
                                            config));
                                    addedRelations.Add(channelPrefixAndSkuId + "_" + channelPrefixAndParentNodeId);

                                    _context.Log(
                                        LogLevel.Debug,
                                        string.Format("Added Relation for EntryCode {0}", channelPrefixAndSkuId));
                                }

                                string channelPrefixAndParentStructureEntityId =
                                    channelPrefixHelper.GetEPiCodeWithChannelPrefix(
                                        existingStructureEntity.ParentId.ToString(CultureInfo.InvariantCulture),
                                        config);

                                if (parent != null && skuId != parent)
                                {
                                    string channelPrefixAndParent = channelPrefixHelper.GetEPiCodeWithChannelPrefix(parent, config);

                                    if (!addedRelations.Contains(channelPrefixAndSkuId + "_" + channelPrefixAndParent))
                                    {
                                        epiElements["Relations"].Add(_epiElement.CreateEntryRelationElement(parent, linkType.SourceEntityTypeId, skuId, existingStructureEntity.SortOrder, config));
                                        addedRelations.Add(channelPrefixAndSkuId + "_" + channelPrefixAndParent);

                                        _context.Log(
                                            LogLevel.Debug,
                                            string.Format("Added Relation for ChildEntryCode {0}", channelPrefixAndSkuId));
                                    }
                                }
                                else if (!addedRelations.Contains(string.Format("{0}_{1}", channelPrefixAndSkuId, channelPrefixAndParentStructureEntityId)))
                                {
                                    epiElements["Relations"].Add(_epiElement.CreateEntryRelationElement(existingStructureEntity.ParentId.ToString(CultureInfo.InvariantCulture), linkType.SourceEntityTypeId, skuId, existingStructureEntity.SortOrder, config));
                                    addedRelations.Add(string.Format("{0}_{1}", channelPrefixAndSkuId, channelPrefixAndParentStructureEntityId));

                                    _context.Log(
                                        LogLevel.Debug,
                                        string.Format("Added Relation for ChildEntryCode {0}", channelPrefixAndSkuId));
                                }
                            }
                            else
                            {
                                if (!addedRelations.Contains(string.Format("{0}_{1}", channelPrefixAndSkuId, channelPrefixHelper.GetEPiCodeWithChannelPrefix("_inRiverAssociations", config))))
                                {
                                    epiElements["Relations"].Add(_epiElement.CreateNodeEntryRelationElement("_inRiverAssociations", skuId, existingStructureEntity.SortOrder, config));
                                    addedRelations.Add(string.Format("{0}_{1}", channelPrefixAndSkuId, channelPrefixHelper.GetEPiCodeWithChannelPrefix("_inRiverAssociations", config)));

                                    _context.Log(LogLevel.Debug, string.Format("Added Relation for EntryCode {0}", channelPrefixAndSkuId));
                                }

                                if (!config.UseThreeLevelsInCommerce && config.ItemsToSkus && structureEntity.Type == "Item")
                                {
                                    string channelPrefixAndLinkEntityId = channelPrefixHelper.GetEPiCodeWithChannelPrefix(existingStructureEntity.LinkEntityId, config);
                                    string associationName = _epiMappingHelper.GetAssociationName(existingStructureEntity, linkEntity, config);

                                    Entity source;

                                    if (config.ChannelEntities.ContainsKey(existingStructureEntity.ParentId))
                                    {
                                        source = config.ChannelEntities[existingStructureEntity.ParentId];
                                    }
                                    else
                                    {
                                        source = _context.ExtensionManager.DataService.GetEntity(
                                            existingStructureEntity.ParentId,
                                            LoadLevel.DataOnly);
                                        config.ChannelEntities.Add(source.Id, source);
                                    }

                                    List <string> sourceSkuIds = _epiElement.SkuItemIds(source, config);
                                    for (int i = 0; i < sourceSkuIds.Count; i++)
                                    {
                                        sourceSkuIds[i] = channelPrefixHelper.GetEPiCodeWithChannelPrefix(
                                            sourceSkuIds[i],
                                            config);
                                    }

                                    foreach (string sourceSkuId in sourceSkuIds)
                                    {
                                        bool exists;
                                        if (existingStructureEntity.LinkEntityId != null)
                                        {
                                            exists = epiElements["Associations"].Any(
                                                e =>
                                            {
                                                XElement entryCode   = e.Element("EntryCode");
                                                XElement description = e.Element("Description");
                                                return(description != null && entryCode != null && entryCode.Value.Equals(sourceSkuId) && e.Elements("Association").Any(
                                                           e2 =>
                                                {
                                                    XElement associatedEntryCode =
                                                        e2.Element("EntryCode");
                                                    return associatedEntryCode != null &&
                                                    associatedEntryCode.Value
                                                    .Equals(sourceSkuId);
                                                }) && description.Value.Equals(channelPrefixAndLinkEntityId));
                                            });
                                        }
                                        else
                                        {
                                            exists = epiElements["Associations"].Any(
                                                e =>
                                            {
                                                XElement entryCode = e.Element("EntryCode");
                                                return(entryCode != null && entryCode.Value.Equals(sourceSkuId) && e.Elements("Association").Any(
                                                           e2 =>
                                                {
                                                    XElement associatedEntryCode = e2.Element("EntryCode");
                                                    return associatedEntryCode != null && associatedEntryCode.Value.Equals(sourceSkuId);
                                                }) && e.Elements("Association").Any(
                                                           e3 =>
                                                {
                                                    XElement typeElement = e3.Element("Type");
                                                    return typeElement != null && typeElement.Value.Equals(linkType.Id);
                                                }));
                                            });
                                        }

                                        if (!exists)
                                        {
                                            XElement existingAssociation;

                                            if (existingStructureEntity.LinkEntityId != null)
                                            {
                                                existingAssociation = epiElements["Associations"].FirstOrDefault(
                                                    a =>
                                                {
                                                    XElement nameElement        = a.Element("Name");
                                                    XElement entryCodeElement   = a.Element("EntryCode");
                                                    XElement descriptionElement = a.Element("Description");
                                                    return(descriptionElement != null && entryCodeElement != null && nameElement != null && nameElement.Value.Equals(
                                                               associationName) && entryCodeElement.Value.Equals(sourceSkuId) && descriptionElement.Value.Equals(channelPrefixAndLinkEntityId));
                                                });
                                            }
                                            else
                                            {
                                                existingAssociation = epiElements["Associations"].FirstOrDefault(
                                                    a =>
                                                {
                                                    XElement nameElement      = a.Element("Name");
                                                    XElement entryCodeElement = a.Element("EntryCode");
                                                    return(entryCodeElement != null && nameElement != null && nameElement.Value.Equals(
                                                               associationName) && entryCodeElement.Value.Equals(sourceSkuId));
                                                });
                                            }

                                            XElement associationElement = new XElement(
                                                "Association",
                                                new XElement("EntryCode", skuId),
                                                new XElement("SortOrder", existingStructureEntity.SortOrder),
                                                new XElement("Type", linkType.Id));

                                            if (existingAssociation != null)
                                            {
                                                if (!existingAssociation.Descendants().Any(e => e.Name.LocalName == "EntryCode" && e.Value == skuId))
                                                {
                                                    existingAssociation.Add(associationElement);
                                                }
                                            }
                                            else
                                            {
                                                string description = existingStructureEntity.LinkEntityId == null
                                                                         ? linkType.Id
                                                                         : channelPrefixAndLinkEntityId;
                                                description = description ?? string.Empty;

                                                XElement catalogAssociation = new XElement(
                                                    "CatalogAssociation",
                                                    new XElement("Name", associationName),
                                                    new XElement("Description", description),
                                                    new XElement("SortOrder", existingStructureEntity.SortOrder),
                                                    new XElement("EntryCode", sourceSkuId),
                                                    associationElement);

                                                epiElements["Associations"].Add(catalogAssociation);
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    string channelPrefixAndEntityId       = channelPrefixHelper.GetEPiCodeWithChannelPrefix(existingStructureEntity.EntityId.ToString(CultureInfo.InvariantCulture), config);
                                    string channelPrefixAndParentEntityId = channelPrefixHelper.GetEPiCodeWithChannelPrefix(existingStructureEntity.ParentId.ToString(CultureInfo.InvariantCulture), config);

                                    string channelPrefixAndLinkEntityId = string.Empty;

                                    if (existingStructureEntity.LinkEntityId != null)
                                    {
                                        channelPrefixAndLinkEntityId = channelPrefixHelper.GetEPiCodeWithChannelPrefix(existingStructureEntity.LinkEntityId, config);
                                    }

                                    string associationName = _epiMappingHelper.GetAssociationName(existingStructureEntity, linkEntity, config);

                                    bool exists;
                                    if (existingStructureEntity.LinkEntityId != null)
                                    {
                                        exists = epiElements["Associations"].Any(
                                            e =>
                                        {
                                            XElement entryCodeElement   = e.Element("EntryCode");
                                            XElement descriptionElement = e.Element("Description");
                                            return(descriptionElement != null && entryCodeElement != null && entryCodeElement.Value.Equals(channelPrefixAndParentEntityId) && e.Elements("Association").Any(
                                                       e2 =>
                                            {
                                                XElement associatedEntryCode = e2.Element("EntryCode");
                                                return associatedEntryCode != null && associatedEntryCode.Value.Equals(channelPrefixAndEntityId);
                                            }) && descriptionElement.Value.Equals(channelPrefixAndLinkEntityId));
                                        });
                                    }
                                    else
                                    {
                                        exists = epiElements["Associations"].Any(
                                            e =>
                                        {
                                            XElement entryCodeElement = e.Element("EntryCode");
                                            return(entryCodeElement != null && entryCodeElement.Value.Equals(channelPrefixAndParentEntityId) && e.Elements("Association").Any(
                                                       e2 =>
                                            {
                                                XElement associatedEntryCode = e2.Element("EntryCode");
                                                return associatedEntryCode != null && associatedEntryCode.Value.Equals(channelPrefixAndEntityId);
                                            }) && e.Elements("Association").Any(
                                                       e3 =>
                                            {
                                                XElement typeElement = e3.Element("Type");
                                                return typeElement != null && typeElement.Value.Equals(linkType.Id);
                                            }));
                                        });
                                    }

                                    if (!exists)
                                    {
                                        XElement existingAssociation;

                                        if (existingStructureEntity.LinkEntityId != null)
                                        {
                                            existingAssociation = epiElements["Associations"].FirstOrDefault(
                                                a =>
                                            {
                                                XElement nameElement        = a.Element("Name");
                                                XElement entryCodeElement   = a.Element("EntryCode");
                                                XElement descriptionElement = a.Element("Description");
                                                return(descriptionElement != null && entryCodeElement != null && nameElement != null && nameElement.Value.Equals(associationName) && entryCodeElement.Value.Equals(
                                                           channelPrefixAndParentEntityId) && descriptionElement.Value.Equals(channelPrefixAndLinkEntityId));
                                            });
                                        }
                                        else
                                        {
                                            existingAssociation = epiElements["Associations"].FirstOrDefault(
                                                a =>
                                            {
                                                XElement nameElement      = a.Element("Name");
                                                XElement entryCodeElement = a.Element("EntryCode");
                                                return(entryCodeElement != null && nameElement != null && nameElement.Value.Equals(associationName) && entryCodeElement.Value.Equals(channelPrefixAndParentEntityId));
                                            });
                                        }

                                        if (existingAssociation != null)
                                        {
                                            XElement newElement = _epiElement.CreateAssociationElement(existingStructureEntity, config);

                                            if (!existingAssociation.Descendants().Any(
                                                    e =>
                                                    e.Name.LocalName == "EntryCode" &&
                                                    e.Value == channelPrefixAndEntityId))
                                            {
                                                existingAssociation.Add(newElement);
                                            }
                                        }
                                        else
                                        {
                                            epiElements["Associations"].Add(
                                                _epiElement.CreateCatalogAssociationElement(
                                                    existingStructureEntity,
                                                    linkEntity,
                                                    config));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _context.Log(LogLevel.Error, ex.Message, ex);
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// Informs the screen manager to serialize its state to disk.
        /// </summary>
        public void Deactivate()
        {
            #if !WINDOWS_PHONE
            return;
            #else
            // Open up isolated storage
            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                // Create an XML document to hold the list of screen types currently in the stack
                XDocument doc = new XDocument();
                XElement root = new XElement("ScreenManager");
                doc.Add(root);

                // Make a copy of the master screen list, to avoid confusion if
                // the process of deactivating one screen adds or removes others.
                tempScreensList.Clear();
                foreach (GameScreen screen in screens)
                    tempScreensList.Add(screen);

                // Iterate the screens to store in our XML file and deactivate them
                foreach (GameScreen screen in tempScreensList)
                {
                    // Only add the screen to our XML if it is serializable
                    if (screen.IsSerializable)
                    {
                        // We store the screen's controlling player so we can rehydrate that value
                        string playerValue = screen.ControllingPlayer.HasValue
                            ? screen.ControllingPlayer.Value.ToString()
                            : "";

                        root.Add(new XElement(
                            "GameScreen",
                            new XAttribute("Type", screen.GetType().AssemblyQualifiedName),
                            new XAttribute("ControllingPlayer", playerValue)));
                    }

                    // Deactivate the screen regardless of whether we serialized it
                    screen.Deactivate();
                }

                // Save the document
                using (IsolatedStorageFileStream stream = storage.CreateFile(StateFilename))
                {
                    doc.Save(stream);
                }
            }
            #endif
        }
        public override Task Execute(AddCapability command, CancellationToken cancellationToken = default)
        {
            if (this.Manifest.Root == null)
            {
                throw new InvalidOperationException("The root element cannot be empty.");
            }

            var capabilities = this.Manifest.Root.XPathSelectElement("//*[local-name()='Capabilities']");

            if (capabilities == null)
            {
                var(_, rootNamespace) = this.EnsureNamespace();
                capabilities          = new XElement(rootNamespace + "Capabilities");
                this.Manifest.Root.Add(capabilities);
            }

            string     nodeName;
            XNamespace ns;
            bool       isRestricted;

            switch (command.Name)
            {
            // Restricted capabilities in RESCAP namespace
            case "cellularDeviceIdentity":
            case "deviceUnlock":
            case "networkingVpnProvider":
            case "inputSuppression":
            case "accessoryManager":
            case "appLicensing":
            case "cellularMessaging":
            case "userDataAccountsProvider":
            case "storeLicenseManagement":
            case "userPrincipalName":
            case "packageManagement":
            case "packagedServices":
            case "uiAutomation":
            case "confirmAppClose":
            case "cortanaPermissions":
            case "teamEditionView":
            case "customInstallActions":
            case "localSystemServices":
            case "teamEditionDeviceCredential":
            case "packagePolicySystem":
            case "modifiableApp":
            case "backgroundSpatialPerception":
            case "phoneLineTransportManagement":
            case "developmentModeNetwork":
            case "unvirtualizedResources":
            case "backgroundVoIP":
            case "gameMonitor":
            case "packageWriteRedirectionCompatibilityShim":
            case "cameraProcessingExtension":
            case "runFullTrust":
            case "allowElevation":
            case "smbios":
            case "appDiagnostics":
            case "devicePortalProvider":
            case "networkDataUsageManagement":
            case "gameBarServices":
            case "broadFileSystemAccess":
            case "backgroundMediaRecording":
            case "oneProcessVoIP":
            case "deviceManagementWapSecurityPolicies":
            case "previewInkWorkspace":
            case "teamEditionExperience":
            case "enterpriseCloudSSO":
            case "appCaptureServices":
            case "startScreenManagement":
            case "email":
            case "expandedResources":
            case "protectedApp":
            case "oemPublicDirectory":
            case "allAppMods":
            case "previewPenWorkspace":
            case "inputForegroundObservation":
            case "userSystemId":
            case "audioDeviceConfiguration":
            case "appBroadcastServices":
            case "targetedContent":
            case "interopServices":
            case "locationSystem":
            case "secondaryAuthenticationFactor":
            case "gameList":
            case "previewStore":
            case "xboxAccessoryManagement":
            case "oemDeployment":
            case "extendedBackgroundTaskTime":
            case "deviceManagementDmAccount":
            case "deviceManagementFoundation":
            case "cortanaSpeechAccessory":
            case "deviceManagementEmailAccount":
            case "extendedExecutionCritical":
            case "extendedExecutionBackgroundAudio":
            case "firstSignInSettings":
            case "extendedExecutionUnconstrained":
            case "appointmentsSystem":
            case "emailSystem":
            case "networkDataPlanProvisioning":
            case "phoneCallHistory":
            case "networkConnectionManagerProvisioning":
            case "chatSystem":
            case "remotePassportAuthentication":
            case "previewUiComposition":
            case "userDataSystem":
            case "slapiQueryLicenseValue":
            case "packageQuery":
            case "walletSystem":
            case "secureAssessment":
            case "smsSend":
            case "inputObservation":
            case "locationHistory":
            case "phoneCallHistorySystem":
            case "dualSimTiles":
            case "cellularDeviceControl":
            case "inputInjectionBrokered":
            case "contactsSystem":
            case "enterpriseDeviceLockdown":
            case "enterpriseDataPolicy":
                // restricted capabilities
                nodeName     = "Capability";
                (_, ns)      = EnsureNamespace(Namespaces.RestrictedCapabilities);
                isRestricted = true;
                break;

            // Restricted capabilities in UAP namespace
            case "documentsLibrary":
            case "sharedUserCertificates":
            case "enterpriseAuthentication":
                // general capabilities
                nodeName     = "Capability";
                (_, ns)      = EnsureNamespace(Namespaces.Uap);
                isRestricted = true;
                break;

            // General capabilities in UAP or UAP# namespaces
            case "videosLibrary":
            case "appointments":
            case "contacts":
            case "removableStorage":
            case "phoneCall":
            case "userAccountInformation":
            case "voipCall":
            case "objects3D":
            case "blockedChatMessages":
            case "chat":
            case "picturesLibrary":
            case "musicLibrary":
                isRestricted = false;
                nodeName     = "Capability";
                (_, ns)      = EnsureNamespace(Namespaces.Uap);
                break;

            case "recordedCallsFolder":
                isRestricted = false;
                nodeName     = "Capability";
                (_, ns)      = EnsureNamespace(Namespaces.Mobile);
                break;

            case "graphicsCaptureWithoutBorder":
            case "graphicsCaptureProgrammatic":
                isRestricted = false;
                nodeName     = "Capability";
                (_, ns)      = EnsureNamespace(Namespaces.Uap, 11);
                break;

            case "graphicsCapture":
                isRestricted = false;
                nodeName     = "Capability";
                (_, ns)      = EnsureNamespace(Namespaces.Uap, 6);
                break;

            case "globalMediaControl":
                isRestricted = false;
                nodeName     = "Capability";
                (_, ns)      = EnsureNamespace(Namespaces.Uap, 7);
                break;

            // General capabilities in IOT namespace
            case "lowLevelDevices":
            case "systemManagement":
                isRestricted = false;
                nodeName     = "Capability";
                (_, ns)      = EnsureNamespace(Namespaces.Iot);
                break;

            // Device capabilities
            case "bluetooth":
            case "location":
            case "microphone":
            case "gazeInput":
            case "radios":
            case "optical":
            case "lowLevel":
            case "wiFiControl":
            case "proximity":
            case "usb":
            case "serialcommunication":
            case "activity":
            case "humaninterfacedevice":
            case "pointOfService":
            case "webcam":
                isRestricted = false;
                nodeName     = "DeviceCapability";
                (_, ns)      = EnsureNamespace(Namespaces.Uap);
                break;

            // Custom capability
            default:
                if (command.Name.Length < 15)
                {
                    throw new InvalidOperationException($"The name of a custom capability must be longer than 15 characters. Capability '{command.Name}' has only {command.Name.Length} characters.");
                }

                isRestricted = false;
                nodeName     = "CustomCapability";
                (_, ns)      = EnsureNamespace(Namespaces.Uap, 4);
                break;
            }

            var element = new XElement(ns + nodeName);

            element.Add(new XAttribute("Name", command.Name));

            var find = capabilities.Elements().FirstOrDefault(e => e.Name.Namespace == ns && e.Name.LocalName == nodeName && e.Attribute("Name")?.Value == command.Name);

            if (find != null)
            {
                Logger.Warn($"The capability '{command.Name}' already exists and will not be added again.");
                return(Task.CompletedTask);
            }

            if (isRestricted)
            {
                capabilities.AddFirst(element);
            }
            else
            {
                capabilities.Add(element);
            }

            this.CapabilityAdded?.Invoke(this, new CapabilityChange(command.Name, isRestricted, nodeName == "CustomCapability"));
            return(Task.CompletedTask);
        }
Exemple #28
0
 /// <summary>
 /// Runs test for valid cases
 /// </summary>
 /// <param name="nodeType">XElement/XAttribute</param>
 /// <param name="name">name to be tested</param>
 public void RunValidTests(string nodeType, string name)
 {
     XDocument xDocument = new XDocument();
     XElement element = null;
     switch (nodeType)
     {
         case "XElement":
             element = new XElement(name, name);
             xDocument.Add(element);
             IEnumerable<XNode> nodeList = xDocument.Nodes();
             Assert.True(nodeList.Count() == 1, "Failed to create element { " + name + " }");
             xDocument.RemoveNodes();
             break;
         case "XAttribute":
             element = new XElement(name, name);
             XAttribute attribute = new XAttribute(name, name);
             element.Add(attribute);
             xDocument.Add(element);
             XAttribute x = element.Attribute(name);
             Assert.Equal(name, x.Name.LocalName);
             xDocument.RemoveNodes();
             break;
         case "XName":
             XName xName = XName.Get(name, name);
             Assert.Equal(name, xName.LocalName);
             Assert.Equal(name, xName.NamespaceName);
             Assert.Equal(name, xName.Namespace.NamespaceName);
             break;
         default:
             break;
     }
 }
Exemple #29
0
        public void Element6(int param)
        {
            XElement e1 = new XElement("A", "datata");
            XElement e2 = new XElement("A", "datata");
            switch (param)
            {
                case 1:
                    XComment c = new XComment("hele");
                    e2.Add(c);
                    c.Remove();
                    break;
                case 2:
                    break;
            }

            VerifyComparison(true, e1, e2);
        }
Exemple #30
0
        public string GenerateReport(CoverageResult coverageResult)
        {
            var lineCoverage   = coverageResult.GetLineSummary();
            var branchCoverage = coverageResult.GetBranchSummary();

            XDocument xml      = new XDocument();
            XElement  coverage = new XElement("coverage");

            coverage.Add(new XAttribute("line-rate", (lineCoverage.Percentage / 100).ToString(CultureInfo.InvariantCulture)));
            coverage.Add(new XAttribute("branch-rate", (branchCoverage.Percentage / 100).ToString(CultureInfo.InvariantCulture)));
            coverage.Add(new XAttribute("version", "1.9"));
            coverage.Add(new XAttribute("timestamp", (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds));

            XElement sources       = new XElement("sources");
            var      absolutePaths = coverageResult.GetSources().ToList();

            absolutePaths.ForEach(x => sources.Add(new XElement("source", x)));

            XElement packages = new XElement("packages");

            foreach (var module in coverageResult.Assemblies)
            {
                var asmLineSummary   = module.GetLineSummary();
                var asmBranchSummary = module.GetBranchSummary();

                XElement package = new XElement("package");
                package.Add(new XAttribute("name", module.Name));
                package.Add(new XAttribute("line-rate", (asmLineSummary.Percentage / 100).ToString(CultureInfo.InvariantCulture)));
                package.Add(new XAttribute("branch-rate", (asmBranchSummary.Percentage / 100).ToString(CultureInfo.InvariantCulture)));
                package.Add(new XAttribute("complexity", module.CalculateCyclomaticComplexity()));

                XElement classes = new XElement("classes");
                foreach (var document in module.GetDocumentToTypesMap())
                {
                    foreach (var cls in document.Value)
                    {
                        var clsLineSummary   = cls.GetLineSummary();
                        var clsBranchSummary = cls.GetBranchSummary();

                        XElement @class = new XElement("class");
                        @class.Add(new XAttribute("name", cls.FullName));
                        @class.Add(new XAttribute("filename", document.Key));
                        @class.Add(new XAttribute("line-rate", (clsLineSummary.Percentage / 100).ToString(CultureInfo.InvariantCulture)));
                        @class.Add(new XAttribute("branch-rate", (clsBranchSummary.Percentage / 100).ToString(CultureInfo.InvariantCulture)));
                        @class.Add(new XAttribute("complexity", cls.CalculateCyclomaticComplexity()));

                        XElement classLines = new XElement("lines");
                        XElement methods    = new XElement("methods");

                        foreach (var meth in cls.Methods)
                        {
                            if (meth.LinesCount == 0)
                            {
                                continue;
                            }

                            var methLineSummary   = meth.GetLineSummary();
                            var methBranchSummary = meth.GetBranchSummary();

                            XElement method = new XElement("method");
                            method.Add(new XAttribute("name", meth.FullName.Split(':').Last().Split('(').First()));
                            method.Add(new XAttribute("signature", "(" + meth.FullName.Split(':').Last().Split('(').Last()));
                            method.Add(new XAttribute("line-rate", (methLineSummary.Percentage / 100).ToString(CultureInfo.InvariantCulture)));
                            method.Add(new XAttribute("branch-rate", (branchCoverage.Percentage / 100).ToString(CultureInfo.InvariantCulture)));

                            XElement lines = new XElement("lines");
                            // Add only one line
                            const bool isBranchPoint = false; // TODO: Check if it's really branch point
                            XElement   line          = new XElement("line");
                            line.Add(new XAttribute("number", meth.StartLine));
                            line.Add(new XAttribute("hits", meth.VisitCount));
                            line.Add(new XAttribute("branch", isBranchPoint.ToString()));

                            lines.Add(line);
                            classLines.Add(line);


                            method.Add(lines);
                            methods.Add(method);
                        }

                        @class.Add(methods);
                        @class.Add(classLines);
                        classes.Add(@class);
                    }
                }

                package.Add(classes);
                packages.Add(package);
            }

            coverage.Add(new XAttribute("lines-covered", lineCoverage.Covered.ToString(CultureInfo.InvariantCulture)));
            coverage.Add(new XAttribute("lines-valid", lineCoverage.Total.ToString(CultureInfo.InvariantCulture)));
            coverage.Add(new XAttribute("branches-covered", branchCoverage.Covered.ToString(CultureInfo.InvariantCulture)));
            coverage.Add(new XAttribute("branches-valid", branchCoverage.Total.ToString(CultureInfo.InvariantCulture)));

            coverage.Add(sources);
            coverage.Add(packages);
            xml.Add(coverage);

            var stream = new MemoryStream();

            xml.Save(stream);

            return(Encoding.UTF8.GetString(stream.ToArray()));
        }
    public void OnPreprocessBuild(BuildTarget target, string path)
#endif
    {
        string manifestPath = Path.Combine(
            Application.dataPath, "Plugins/Android/GoogleMobileAdsPlugin/AndroidManifest.xml");

        XDocument manifest = null;

        try
        {
            manifest = XDocument.Load(manifestPath);
        }
        #pragma warning disable 0168
        catch (IOException e)
        #pragma warning restore 0168
        {
            StopBuildWithMessage("AndroidManifest.xml is missing. Try re-importing the plugin.");
        }

        XElement elemManifest = manifest.Element("manifest");
        if (elemManifest == null)
        {
            StopBuildWithMessage("AndroidManifest.xml is not valid. Try re-importing the plugin.");
        }

        XElement elemApplication = elemManifest.Element("application");
        if (elemApplication == null)
        {
            StopBuildWithMessage("AndroidManifest.xml is not valid. Try re-importing the plugin.");
        }

        bool IsAdManagerEnabled = GoogleMobileAdsSettings.Instance.IsAdManagerEnabled;

        if (!GoogleMobileAdsSettings.Instance.IsAdManagerEnabled && !GoogleMobileAdsSettings.Instance.IsAdMobEnabled)
        {
            GoogleMobileAdsSettingsEditor.OpenInspector();
            StopBuildWithMessage("Neither AdManager nor AdMob is enabled yet.");
        }

        IEnumerable <XElement> metas = elemApplication.Descendants()
                                       .Where(elem => elem.Name.LocalName.Equals("meta-data"));

        XElement elemAdManagerEnabled = GetMetaElement(metas, META_AD_MANAGER_APP);
        if (GoogleMobileAdsSettings.Instance.IsAdManagerEnabled)
        {
            if (elemAdManagerEnabled == null)
            {
                elemApplication.Add(CreateMetaElement(META_AD_MANAGER_APP, true));
            }
            else
            {
                elemAdManagerEnabled.SetAttributeValue(ns + "value", true);
            }
        }
        else
        {
            if (elemAdManagerEnabled != null)
            {
                elemAdManagerEnabled.Remove();
            }
        }

        XElement elemAdMobEnabled = GetMetaElement(metas, META_APPLICATION_ID);
        if (GoogleMobileAdsSettings.Instance.IsAdMobEnabled)
        {
            string appId = GoogleMobileAdsSettings.Instance.AdMobAndroidAppId;

            if (appId.Length == 0)
            {
                StopBuildWithMessage(
                    "Android AdMob app ID is empty. Please enter a valid app ID to run ads properly.");
            }

            if (elemAdMobEnabled == null)
            {
                elemApplication.Add(CreateMetaElement(META_APPLICATION_ID, appId));
            }
            else
            {
                elemAdMobEnabled.SetAttributeValue(ns + "value", appId);
            }
        }
        else
        {
            if (elemAdMobEnabled != null)
            {
                elemAdMobEnabled.Remove();
            }
        }

        XElement elemDelayAppMeasurementInit =
            GetMetaElement(metas, META_DELAY_APP_MEASUREMENT_INIT);
        if (GoogleMobileAdsSettings.Instance.DelayAppMeasurementInit)
        {
            if (elemDelayAppMeasurementInit == null)
            {
                elemApplication.Add(CreateMetaElement(META_DELAY_APP_MEASUREMENT_INIT, true));
            }
            else
            {
                elemDelayAppMeasurementInit.SetAttributeValue(ns + "value", true);
            }
        }
        else
        {
            if (elemDelayAppMeasurementInit != null)
            {
                elemDelayAppMeasurementInit.Remove();
            }
        }

        elemManifest.Save(manifestPath);
    }
        //  Creates an <code>xs:element</code> element to represent a value field in a class.
        //
        //  The returned element should be appended to <code>xs:sequence</code> element of the
        //  xs:element representing the type of the owning object.

        public XElement CreateXsElementForNofValue(XElement parentXsElementElement, XElement xmlValueElement)
        {
            // gather details from XML element

            XAttribute datatype  = xmlValueElement.Attribute(NofMetaModel.Nof + "datatype");
            string     fieldName = xmlValueElement.Name.LocalName;

            // <xs:element name="%owning object%">
            //		<xs:complexType>
            //			<xs:sequence>
            //				<xs:element name="%%field object%%">
            //					<xs:complexType>
            //						<xs:sequence>
            //				            <xs:element name="nof-extensions">
            //					            <xs:complexType>
            //						            <xs:sequence>
            //                                      <xs:element name="%extensionClassShortName%" default="%extensionObjString" minOccurs="0"/>
            //                                      <xs:element name="%extensionClassShortName%" default="%extensionObjString" minOccurs="0"/>
            //                                      ...
            //                                      <xs:element name="%extensionClassShortName%" default="%extensionObjString" minOccurs="0"/>
            //						            </xs:sequence>
            //					            </xs:complexType>
            //				            </xs:element>
            //						</xs:sequence>
            //						<xs:attribute ref="nof:feature" fixed="value"/>
            //						<xs:attribute ref="nof:datatype" fixed="nof:%datatype%"/>
            //						<xs:attribute ref="nof:isEmpty"/>
            //			            <xs:attribute ref="nof:annotation"/>
            //					</xs:complexType>
            //				</xs:element>
            //			</xs:sequence>
            //		</xs:complexType>
            //	</xs:element>

            // xs:element/xs:complexType/xs:sequence
            XElement parentXsComplexTypeElement = XsMetaModel.ComplexTypeFor(parentXsElementElement);
            XElement parentXsSequenceElement    = XsMetaModel.SequenceFor(parentXsComplexTypeElement);

            // xs:element/xs:complexType/xs:sequence/xs:element name="%%field object%"
            XElement xsFieldElementElement = XsMetaModel.CreateXsElementElement(Helper.DocFor(parentXsSequenceElement), fieldName);

            parentXsSequenceElement.Add(xsFieldElementElement);

            // xs:element/xs:complexType/xs:sequence/xs:element/xs:complexType
            XElement xsFieldComplexTypeElement = XsMetaModel.ComplexTypeFor(xsFieldElementElement);

            // NEW CODE TO SUPPORT EXTENSIONS;
            // uses a complexType/sequence

            // xs:element/xs:complexType/xs:sequence/xs:element/xs:complexType/xs:sequence
            //XElement xsFieldSequenceElement = XsMetaModel.SequenceFor(xsFieldComplexTypeElement);

            // xs:element/xs:complexType/xs:sequence/xs:element/xs:complexType/xs:sequence/xs:element name="nof-extensions"
            // xs:element/xs:complexType/xs:sequence/xs:element/xs:complexType/xs:sequence/xs:element/xs:complexType/xs:sequence
            //addXsElementForAppExtensions(xsFieldSequenceElement, extensions);

            XsMetaModel.AddXsNofFeatureAttributeElements(xsFieldComplexTypeElement, "value");
            XsMetaModel.AddXsNofAttribute(xsFieldComplexTypeElement, "datatype", datatype == null ? "" : datatype.Value);
            XsMetaModel.AddXsNofAttribute(xsFieldComplexTypeElement, "isEmpty");
            XsMetaModel.AddXsNofAttribute(xsFieldComplexTypeElement, "annotation");

            // ORIGINAL CODE THAT DIDN'T EXPORT EXTENSIONS
            // uses a simpleContent
            // (I've left this code in in case there is a need to regenerate schemas the "old way").

            // <xs:element name="%owning object%">
            //		<xs:complexType>
            //			<xs:sequence>
            //				<xs:element name="%%field object%%">
            //					<xs:complexType>
            //						<xs:simpleContent>
            //							<xs:extension base="xs:string">
            //								<xs:attribute ref="nof:feature" fixed="value"/>
            //								<xs:attribute ref="nof:datatype" fixed="nof:%datatype%"/>
            //								<xs:attribute ref="nof:isEmpty"/>
            //			                    <xs:attribute ref="nof:annotation"/>
            //							</xs:extension>
            //						</xs:simpleContent>
            //					</xs:complexType>
            //				</xs:element>
            //			</xs:sequence>
            //		</xs:complexType>
            //	</xs:element>

            // xs:element/xs:complexType/xs:sequence/xs:element/xs:complexType/xs:simpleContent/xs:extension
            //		XElement xsFieldSimpleContentElement = XsMetaModel.simpleContentFor(xsFieldComplexTypeElement);
            //		XElement xsFieldExtensionElement = XsMetaModel.extensionFor(xsFieldSimpleContentElement, "string");
            //		XsMetaModel.addXsNofFeatureAttributeElements(xsFieldExtensionElement, "value");
            //		XsMetaModel.addXsNofAttribute(xsFieldExtensionElement, "datatype", datatype);
            //		XsMetaModel.addXsNofAttribute(xsFieldExtensionElement, "isEmpty");
            //		XsMetaModel.addXsNofAttribute(xsFieldExtensionElement, "annotation");

            return(xsFieldElementElement);
        }
Exemple #33
0
        public void Deactivate()
        {
            #if !WINDOWS_PHONE
            return;
            #else

            using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
            {

                XDocument doc = new XDocument();
                XElement root = new XElement("ScreenManager");
                doc.Add(root);

                tempScreensList.Clear();
                foreach (GameScreen screen in screens)
                    tempScreensList.Add(screen);

                foreach (GameScreen screen in tempScreensList)
                {

                    if (screen.IsSerializable)
                    {

                        string playerValue = screen.ControllingPlayer.HasValue
                            ? screen.ControllingPlayer.Value.ToString()
                            : "";

                        root.Add(new XElement(
                            "GameScreen",
                            new XAttribute("Type", screen.GetType().AssemblyQualifiedName),
                            new XAttribute("ControllingPlayer", playerValue)));
                    }

                    screen.Deactivate();
                }

                using (IsolatedStorageFileStream stream = storage.CreateFile(StateFilename))
                {
                    doc.Save(stream);
                }
            }
            #endif
        }
Exemple #34
0
        public void CreatingXElementsFromNewDev10Types(object t, Type type)
        {
            XElement e = new XElement("e1", new XElement("e2"), "text1", new XElement("e3"), t);
            e.Add(t);
            e.FirstNode.ReplaceWith(t);

            XNode n = e.FirstNode.NextNode;
            n.AddBeforeSelf(t);
            n.AddAnnotation(t);
            n.ReplaceWith(t);

            e.FirstNode.AddAfterSelf(t);
            e.AddFirst(t);
            e.Annotation(type);
            e.Annotations(type);
            e.RemoveAnnotations(type);
            e.ReplaceAll(t);
            e.ReplaceAttributes(t);
            e.ReplaceNodes(t);
            e.SetAttributeValue("a", t);
            e.SetElementValue("e2", t);
            e.SetValue(t);

            XAttribute a = new XAttribute("a", t);
            XStreamingElement se = new XStreamingElement("se", t);
            se.Add(t);

            Assert.Throws<ArgumentException>(() => new XDocument(t));
            Assert.Throws<ArgumentException>(() => new XDocument(t));
        }
        //  Creates an &lt;xs:element&gt; element defining the presence of the named element
        //  representing a reference to a class; appended to xs:sequence element

        public XElement CreateXsElementForNofReference(XElement parentXsElementElement, XElement xmlReferenceElement, string referencedClassName)
        {
            // gather details from XML element
            string fieldName = xmlReferenceElement.Name.LocalName;

            // <xs:element name="%owning object%">
            //		<xs:complexType>
            //			<xs:sequence>
            //				<xs:element name="%%field object%%">
            //					<xs:complexType>
            //						<xs:sequence>
            //							<xs:element ref="nof:title" minOccurs="0"/>
            //				            <xs:element name="nof-extensions">
            //					            <xs:complexType>
            //						            <xs:sequence>
            //				                        <xs:element name="app:%extension class short name%" minOccurs="0" maxOccurs="1" default="%value%"/>
            //				                        <xs:element name="app:%extension class short name%" minOccurs="0" maxOccurs="1" default="%value%"/>
            //				                        ...
            //				                        <xs:element name="app:%extension class short name%" minOccurs="0" maxOccurs="1" default="%value%"/>
            //						            </xs:sequence>
            //					            </xs:complexType>
            //				            </xs:element>
            //							<xs:sequence minOccurs="0" maxOccurs="1"/>
            //						</xs:sequence>
            //						<xs:attribute ref="nof:feature" fixed="reference"/>
            //						<xs:attribute ref="nof:type" default="%%appX%%:%%type%%"/>
            //						<xs:attribute ref="nof:isEmpty"/>
            //						<xs:attribute ref="nof:annotation"/>
            //					</xs:complexType>
            //				</xs:element>
            //			</xs:sequence>
            //		</xs:complexType>
            //	</xs:element>

            // xs:element/xs:complexType/xs:sequence
            XElement parentXsComplexTypeElement = XsMetaModel.ComplexTypeFor(parentXsElementElement);
            XElement parentXsSequenceElement    = XsMetaModel.SequenceFor(parentXsComplexTypeElement);

            // xs:element/xs:complexType/xs:sequence/xs:element name="%%field object%"
            XElement xsFieldElementElement = XsMetaModel.CreateXsElementElement(Helper.DocFor(parentXsSequenceElement), fieldName);

            parentXsSequenceElement.Add(xsFieldElementElement);

            // xs:element/xs:complexType/xs:sequence/xs:element/xs:complexType/xs:sequence
            XElement xsFieldComplexTypeElement = XsMetaModel.ComplexTypeFor(xsFieldElementElement);
            XElement xsFieldSequenceElement    = XsMetaModel.SequenceFor(xsFieldComplexTypeElement);

            // xs:element/xs:complexType/xs:sequence/xs:element/xs:complexType/xs:sequence/xs:element ref="nof:title"
            XElement xsFieldTitleElement = XsMetaModel.CreateXsElement(Helper.DocFor(xsFieldSequenceElement), "element");

            xsFieldTitleElement.SetAttributeValue("ref", NofMetaModel.NofMetamodelNsPrefix + ":" + "title");
            xsFieldSequenceElement.Add(xsFieldTitleElement);
            XsMetaModel.SetXsCardinality(xsFieldTitleElement, 0, 1);

            // xs:element/xs:complexType/xs:sequence/xs:element/xs:complexType/xs:sequence/xs:element name="nof-extensions"
            //addXsElementForAppExtensions(xsFieldSequenceElement, extensions);

            // xs:element/xs:complexType/xs:sequence/xs:element/xs:complexType/xs:sequence/xs:sequence   // placeholder
            XElement xsReferencedElementSequenceElement = XsMetaModel.SequenceFor(xsFieldSequenceElement);

            XsMetaModel.SetXsCardinality(xsReferencedElementSequenceElement, 0, 1);

            XsMetaModel.AddXsNofFeatureAttributeElements(xsFieldComplexTypeElement, "reference");
            XsMetaModel.AddXsNofAttribute(xsFieldComplexTypeElement, "type", "app:" + referencedClassName, false);
            XsMetaModel.AddXsNofAttribute(xsFieldComplexTypeElement, "isEmpty");
            XsMetaModel.AddXsNofAttribute(xsFieldComplexTypeElement, "annotation");
            return(xsFieldElementElement);
        }
Exemple #36
0
 public static void DescendantsOnXDocBeforeAndAfter()
 {
     XElement a = new XElement("A", "a"), b = new XElement("B", "b");
     a.Add(b);
     XDocument xDoc = new XDocument(a);
     IEnumerable<XElement> nodes = xDoc.Descendants("B");
     Assert.Equal(1, nodes.Count());
     b.Remove();
     Assert.Equal(0, nodes.Count());
 }
Exemple #37
0
        public void Text(string value1, string value2, bool checkHashCode)
        {
            XText t1 = new XText(value1);
            XText t2 = new XText(value2);
            VerifyComparison(checkHashCode, t1, t2);

            XElement e2 = new XElement("p2p", t2);
            e2.Add(t1);
            VerifyComparison(checkHashCode, t1, t2);
        }
Exemple #38
0
 public static void ElementsWithXNameOnXElementBeforeAndAfter()
 {
     XElement a = new XElement("A", "a"), b = new XElement("B", "b");
     IEnumerable<XElement> nodes = a.Elements("B");
     Assert.Equal(0, nodes.Count());
     a.Add(b, b, b, b);
     Assert.Equal(4, nodes.Count());
 }
Exemple #39
0
        public XDocument GetDocument()
        {
            XElement?node = null;

            var document = new XDocument(new XDeclaration("1.0", GetEncodingString(_encoding), "no"));

            foreach (var rawNode in this)
            {
                switch (rawNode.Type)
                {
                case NodeType.FileEnd when node == null:
                    throw new NullReferenceException("Attempt to add a node that doesn't exist.");

                case NodeType.NodeEnd when node == null:
                    throw new NullReferenceException("Attempt to end node that hasn't started.");

                case NodeType.Attribute when node == null:
                    throw new NullReferenceException("Attempt to add an attribute to a node that hasn't started.");

                case NodeType.NodeStart: {
                    var newNode = new XElement(rawNode.Name);
                    node?.Add(newNode);
                    node = newNode;
                    break;
                }

                case NodeType.FileEnd: {
                    document.Add(node);
                    return(document);
                }

                case NodeType.NodeEnd: {
                    node = node.Parent ?? node;
                    break;
                }

                case NodeType.Attribute: {
                    node.Add(new XAttribute(rawNode.Name, DataStream.ReadString(_encoding)));
                    break;
                }

                case NodeType.String: {
                    var newNode = new XElement(rawNode.Name);
                    node?.Add(newNode);
                    node = newNode;
                    node.Add(new XAttribute("__type", rawNode.TypeName));


                    node.Add(DataStream.ReadString(_encoding));

                    break;
                }

                case NodeType.Binary: {
                    var newNode = new XElement(rawNode.Name);
                    node?.Add(newNode);
                    node = newNode;
                    node.Add(new XAttribute("__type", rawNode.TypeName));


                    var length = DataStream.ReadUInt32(Endianness.BigEndian);
                    var data   = DataStream.Read((int)length);
                    DataStream.Realign();

                    node.Add(string.Join("", data.Select(x => x.ToString("X2"))));

                    break;
                }

                default: {
                    var newNode = new XElement(rawNode.Name);
                    node?.Add(newNode);
                    node = newNode;
                    node.Add(new XAttribute("__type", rawNode.TypeName));

                    if (DataTypeHandlers.ToStringMap.TryGetValue(rawNode.Type, out var toString))
                    {
                        if (rawNode.IsArray)
                        {
                            var arraySize = DataStream.ReadUInt32(Endianness.BigEndian);
                            var count     = arraySize / (toString.Attribute.Size * toString.Attribute.Count);
                            var data      = toString.Method(DataStream, (int)count);

                            node.Add(string.Join(" ", data));
                            node.Add(new XAttribute("__count", count));
                        }
                        else
                        {
                            node.Add(toString.Method(DataStream, 1));
                        }

                        DataStream.Realign();
                    }
                    else
                    {
                        throw new Exception($"Data type {rawNode.Type} handler not found.");
                    }

                    break;
                }
                }
            }

            return(document);
        }
Exemple #40
0
 public static void DescendantNodesAndSelfBeforeAndAfter()
 {
     XElement a = new XElement("A", "a"), b = new XElement("B", "b");
     a.Add(b);
     IEnumerable<XNode> nodes = a.DescendantNodesAndSelf();
     Assert.Equal(4, nodes.Count());
     a.Add("New Text Node");
     Assert.Equal(5, nodes.Count());
 }
Exemple #41
0
        /// <summary>
        /// Runs test for InValid cases
        /// </summary>
        /// <param name="nodeType">XElement/XAttribute</param>
        /// <param name="name">name to be tested</param>
        public void RunInValidTests(string nodeType, string name)
        {
            XDocument xDocument = new XDocument();
            XElement element = null;
            try
            {
                switch (nodeType)
                {
                    case "XElement":
                        element = new XElement(name, name);
                        xDocument.Add(element);
                        IEnumerable<XNode> nodeList = xDocument.Nodes();
                        break;
                    case "XAttribute":
                        element = new XElement(name, name);
                        XAttribute attribute = new XAttribute(name, name);
                        element.Add(attribute);
                        xDocument.Add(element);
                        XAttribute x = element.Attribute(name);
                        break;
                    case "XName":
                        XName xName = XName.Get(name, name);
                        break;
                    default:
                        break;
                }
            }
            catch (XmlException)
            {
                return;
            }
            catch (ArgumentException)
            {
                return;
            }

            Assert.True(false, "Expected exception not thrown");
        }
Exemple #42
0
 public static void AncestorsAndSelfWithXNameBeforeAndAfter()
 {
     XElement a = new XElement("A", "a"), b = new XElement("B", "b");
     a.Add(b);
     IEnumerable<XElement> nodes = b.AncestorsAndSelf("A");
     Assert.Equal(1, nodes.Count());
     XElement c = new XElement("A", "a", a);
     Assert.Equal(2, nodes.Count());
 }
        private void WriteSong(string _artist, string _title, string _extra, string cover = null,
                               bool forceUpdate = false, string _trackId = null, string _trackUrl = null)
        {
            _currentId = _trackId;

            if (_artist.Contains("Various Artists, "))
            {
                _artist = _artist.Replace("Various Artists, ", "");
                _artist = _artist.Trim();
            }

            // get the songPath which is default the directory where the exe is, else get the user set directory
            _root = string.IsNullOrEmpty(Settings.Directory)
                ? Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location)
                : Settings.Directory;

            _songPath  = _root + "/Songify.txt";
            _coverTemp = _root + "/tmp.png";
            _coverPath = _root + "/cover.png";

            if (_firstRun)
            {
                File.WriteAllText(_songPath, "");
            }

            // if all those are empty we expect the player to be paused
            if (string.IsNullOrEmpty(_artist) && string.IsNullOrEmpty(_title) && string.IsNullOrEmpty(_extra))
            {
                // read the text file
                if (!File.Exists(_songPath))
                {
                    File.Create(_songPath).Close();
                }

                File.WriteAllText(_songPath, Settings.CustomPauseText);

                if (Settings.SplitOutput)
                {
                    WriteSplitOutput(Settings.CustomPauseText, _title, _extra);
                }

                DownloadCover(null);

                TxtblockLiveoutput.Dispatcher.Invoke(
                    DispatcherPriority.Normal,
                    new Action(() => { TxtblockLiveoutput.Text = Settings.CustomPauseText; }));
                return;
            }

            // get the output string
            CurrSong = Settings.OutputString;

            if (_selectedSource == PlayerType.SpotifyWeb)
            {
                // this only is used for Spotify because here the artist and title are split
                // replace parameters with actual info
                CurrSong = CurrSong.Format(
                    artist => _artist,
                    title => _title,
                    extra => _extra,
                    uri => _trackId
                    ).Format();

                if (ReqList.Count > 0)
                {
                    RequestObject rq = ReqList.Find(x => x.TrackID == _currentId);
                    if (rq != null)
                    {
                        CurrSong = CurrSong.Replace("{{", "");
                        CurrSong = CurrSong.Replace("}}", "");
                        CurrSong = CurrSong.Replace("{req}", rq.Requester);
                    }
                    else
                    {
                        int start = CurrSong.IndexOf("{{", StringComparison.Ordinal);
                        int end   = CurrSong.LastIndexOf("}}", StringComparison.Ordinal) + 2;
                        if (start >= 0)
                        {
                            CurrSong = CurrSong.Remove(start, end - start);
                        }
                    }
                }
                else
                {
                    try
                    {
                        int start = CurrSong.IndexOf("{{", StringComparison.Ordinal);
                        int end   = CurrSong.LastIndexOf("}}", StringComparison.Ordinal) + 2;
                        if (start >= 0)
                        {
                            CurrSong = CurrSong.Remove(start, end - start);
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.LogExc(ex);
                    }
                }
            }
            else
            {
                // used for Youtube and Nightbot
                // replace parameters with actual info

                // get the first occurance of "}" to get the seperator from the custom output ({artist} - {title})
                // and replace it
                //int pFrom = CurrSong.IndexOf("}", StringComparison.Ordinal);
                //string result = CurrSong.Substring(pFrom + 2, 1);
                //CurrSong = CurrSong.Replace(result, "");

                // artist is set to be artist and title in this case, {title} and {extra} are empty strings
                CurrSong = CurrSong.Format(
                    artist => _artist,
                    title => _title,
                    extra => _extra,
                    uri => _trackId
                    ).Format();

                try
                {
                    int start = CurrSong.IndexOf("{{", StringComparison.Ordinal);
                    int end   = CurrSong.LastIndexOf("}}", StringComparison.Ordinal) + 2;
                    if (start >= 0)
                    {
                        CurrSong = CurrSong.Remove(start, end - start);
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogExc(ex);
                }
            }

            // Cleanup the string (remove double spaces, trim and add trailing spaces for scroll)
            CurrSong     = CleanFormatString(CurrSong);
            this._title  = _title;
            this._artist = _artist;

            // read the text file
            if (!File.Exists(_songPath))
            {
                File.Create(_songPath).Close();
                File.WriteAllText(_songPath, CurrSong);
            }

            if (new FileInfo(_songPath).Length == 0)
            {
                File.WriteAllText(_songPath, CurrSong);
            }

            string[] temp = File.ReadAllLines(_songPath);

            // if the text file is different to _currSong (fetched song) or update is forced
            if (temp[0].Trim() != CurrSong.Trim() || forceUpdate || _firstRun)
            {
                // write song to the text file
                File.WriteAllText(_songPath, CurrSong);

                try
                {
                    ReqList.Remove(ReqList.Find(x => x.TrackID == _prevId));
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        foreach (Window window in Application.Current.Windows)
                        {
                            if (window.GetType() != typeof(Window_Queue))
                            {
                                continue;
                            }
                            //(qw as Window_Queue).dgv_Queue.ItemsSource.
                            (window as Window_Queue)?.dgv_Queue.Items.Refresh();
                        }
                    });
                }
                catch (Exception)
                {
                    // ignored
                }

                if (Settings.SplitOutput)
                {
                    WriteSplitOutput(_artist, _title, _extra);
                }

                // if upload is enabled
                if (Settings.Upload)
                {
                    UploadSong(CurrSong.Trim(), cover);
                }

                if (_firstRun)
                {
                    _prevSong = CurrSong.Trim();
                    _firstRun = false;
                }
                else
                {
                    if (_prevSong == CurrSong.Trim())
                    {
                        return;
                    }
                }

                //Write History
                if (Settings.SaveHistory && !string.IsNullOrEmpty(CurrSong.Trim()) &&
                    CurrSong.Trim() != Settings.CustomPauseText)
                {
                    _prevSong = CurrSong.Trim();

                    int unixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                    //save the history file
                    string historyPath = Path.GetDirectoryName(Assembly.GetEntryAssembly()?.Location) + "/" +
                                         "history.shr";
                    XDocument doc;
                    if (!File.Exists(historyPath))
                    {
                        doc = new XDocument(new XElement("History",
                                                         new XElement("d_" + DateTime.Now.ToString("dd.MM.yyyy"))));
                        doc.Save(historyPath);
                    }

                    doc = XDocument.Load(historyPath);
                    if (!doc.Descendants("d_" + DateTime.Now.ToString("dd.MM.yyyy")).Any())
                    {
                        doc.Descendants("History").FirstOrDefault()
                        ?.Add(new XElement("d_" + DateTime.Now.ToString("dd.MM.yyyy")));
                    }

                    XElement elem = new XElement("Song", CurrSong.Trim());
                    elem.Add(new XAttribute("Time", unixTimestamp));
                    XElement x = doc.Descendants("d_" + DateTime.Now.ToString("dd.MM.yyyy")).FirstOrDefault();
                    x?.Add(elem);
                    doc.Save(historyPath);
                }

                //Upload History
                if (Settings.UploadHistory && !string.IsNullOrEmpty(CurrSong.Trim()) &&
                    CurrSong.Trim() != Settings.CustomPauseText)
                {
                    _prevSong = CurrSong.Trim();

                    int unixTimestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

                    // Upload Song
                    try
                    {
                        string extras = Settings.Uuid + "&tst=" + unixTimestamp + "&song=" +
                                        HttpUtility.UrlEncode(CurrSong.Trim(), Encoding.UTF8);
                        string url = "https://songify.rocks/song_history.php/?id=" + extras;
                        // Create a new 'HttpWebRequest' object to the mentioned URL.
                        HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                        myHttpWebRequest.UserAgent = Settings.Webua;

                        // Assign the response object of 'HttpWebRequest' to a 'HttpWebResponse' variable.
                        HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                        if (myHttpWebResponse.StatusCode != HttpStatusCode.OK)
                        {
                            Logger.LogStr("MAIN: Upload Song:" + myHttpWebResponse.StatusCode);
                        }

                        myHttpWebResponse.Close();
                    }
                    catch (Exception ex)
                    {
                        Logger.LogExc(ex);
                        // Writing to the statusstrip label
                        LblStatus.Dispatcher.Invoke(
                            DispatcherPriority.Normal,
                            new Action(() => { LblStatus.Content = "Error uploading Songinformation"; }));
                    }
                }

                // Update Song Queue, Track has been player. All parameters are optional except track id, playerd and o. o has to be the value "u"
                if (_trackId != null)
                {
                    WebHelper.UpdateWebQueue(_trackId, "", "", "", "", "1", "u");
                }

                // Send Message to Twitch if checked
                if (Settings.AnnounceInChat && TwitchHandler.Client.IsConnected)
                {
                    TwitchHandler.SendCurrSong("Now playing: " + CurrSong.Trim());
                }

                _prevId = _currentId;

                //Save Album Cover
                if (Settings.DownloadCover)
                {
                    DownloadCover(cover);
                }



                if (File.Exists(_coverPath) && new FileInfo(_coverPath).Length > 0)
                {
                    img_cover.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                     new Action(() =>
                    {
                        BitmapImage image = new BitmapImage();
                        image.BeginInit();
                        image.CacheOption   = BitmapCacheOption.OnLoad;
                        image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                        image.UriSource     = new Uri(_coverPath);
                        image.EndInit();
                        img_cover.Source = image;
                    }));
                }
            }

            // write song to the output label
            TxtblockLiveoutput.Dispatcher.Invoke(
                DispatcherPriority.Normal,
                new Action(() => { TxtblockLiveoutput.Text = CurrSong.Trim(); }));
        }
Exemple #44
0
        public XElement GetXDPCustomFormData(string customFormData, string xdpFileName)
        {
            // NOTE:  The namespace of the <template> element can vary by what the target version of the XDP is set to.
            //        So for example the namespace of the <template> can  be something like th following:
            //        http://www.xfa.org/schema/xfa-template/X.Y/ where X.Y can be 2.5, 2.6, 2.8, 3.3 etc.
            //
            //        So we will find the <template> element using the LocalName (element name sans namespace) and get the
            //        default namespace for use in XPath queries


            XElement customFormDataElement = new XElement(customFormData, new XAttribute("xdpFileName", SecurityElement.Escape(xdpFileName)), new XAttribute("datetime", DateTime.UtcNow.ToString("O")));
            XElement xdpElement            = XElement.Load(xdpFileName);
            XElement template = xdpElement.Descendants().First(d => d.Name.LocalName.Equals("template"));

            XmlNamespaceManager nsManager = new XmlNamespaceManager(new NameTable());

            nsManager.AddNamespace("xdp", "http://ns.adobe.com/xdp/");
            nsManager.AddNamespace("ns", template.GetDefaultNamespace().ToString());

            foreach (var field in xdpElement.Descendants().Where(e => e.Name.LocalName.Equals("field")))
            {
                foreach (var bind in field.Descendants().Where(d => d.Name.LocalName.Equals("bind") && d.Attributes().Any(a => a.Name.LocalName.Equals("ref"))))
                {
                    bool   requiredField        = false;
                    string requiredFieldMessage = String.Empty;
                    string defaultValueText     = String.Empty;

                    // Get the name of the containing field of the <bind> element
                    var fieldElementName = (field.Attributes().Any(a => a.Name.LocalName == "name")) ? (field.Attribute("name").Value) : ("");

                    // Get the first child of the <ui> element, this will be the actual control seen by the user
                    /* <barcode>, <button>, <checkButton>, <choiceList>, <dateTimeEdit>, <defaultUi>, <imageEdit>, <numericEdit>, <passwordEdit>, <signature>, <textEdit> */
                    var uiControlType = field.Descendants().First(d => d.Name.LocalName.Equals("ui")).Elements().First();

                    // The <assist> element can have <speak> and/or <tooTip> child elements
                    var assist = field.Descendants().FirstOrDefault(d => d.Name.LocalName.Equals("assist"));

                    // See if the field is required and grab the validation message
                    var validate = field.XPathSelectElement("ns:validate[@nullTest='error']", nsManager);

                    if (validate != null)
                    {
                        // If the nullTest attribute is set to 'error' then the field is required
                        requiredField = true;

                        // There may also be a message to display for the missing required field
                        var validateMessage = validate.XPathSelectElement("ns:message/ns:text[@name='nullTest']", nsManager);

                        if (validateMessage != null)
                        {
                            requiredFieldMessage = validateMessage.Value;
                        }
                    }

                    // See if the field has a default value
                    var defaultValue = field.XPathSelectElement("ns:value/ns:text", nsManager);

                    if (defaultValue != null)
                    {
                        defaultValueText = SecurityElement.Escape(defaultValue.Value);
                    }

                    // This will be the path in the form's XML that this control is bound to
                    string refAttr = bind.Attribute("ref").Value;

                    // Split the binding path into tokens
                    string[] tokens = refAttr.Split("$.".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                    // Find the CustomFormData or FormFillInData element in the binding path
                    int i = Array.IndexOf(tokens, customFormData);

                    // Create a destination array with the path tokens to the right of the CustomFormData or FormFillInData element
                    string[] elements = tokens.Skip(i + 1).ToArray();

                    // Create the XML from the reconstructed path
                    MakeXPath(customFormDataElement, String.Join("/", (String[])elements));

                    // Get the leaf in the path
                    XElement leaf = customFormDataElement.XPathSelectElement($"//{elements[elements.Length - 1]}");

                    // Add attributes to the leaf
                    if (leaf != null)
                    {
                        leaf.Add(new XAttribute("name", fieldElementName));
                        leaf.Add(new XAttribute("datatype", uiControlType.Name.LocalName));

                        // This will add all other attributes like multiline="1" to the <textEdit>
                        foreach (var a in uiControlType.Attributes())
                        {
                            leaf.Add(new XAttribute(a.Name.LocalName, a.Value));
                        }

                        if (requiredField)
                        {
                            leaf.Add(new XAttribute("required", true));

                            if (!String.IsNullOrEmpty(requiredFieldMessage))
                            {
                                leaf.Add(new XAttribute("requiredFieldMessage", requiredFieldMessage));
                            }
                        }

                        #region Assist Values

                        // We are using the <assist> and it's possible child elements to provide
                        // an unobtrusive way to specify alternative labels for fields on the
                        // dynamically generated forms

                        // If we have and <assist> element
                        if (assist != null)
                        {
                            // See if there is a <speak> element
                            XElement speak = assist.XPathSelectElement("ns:speak", nsManager);

                            // Add these values as attributes
                            if (speak != null)
                            {
                                leaf.Add(new XAttribute("speak", SecurityElement.Escape(speak.Value)));
                            }

                            // See if there is a <tooTip> element
                            XElement toolTip = assist.XPathSelectElement("ns:toolTip", nsManager);

                            if (toolTip != null)
                            {
                                leaf.Add(new XAttribute("toolTip", SecurityElement.Escape(toolTip.Value)));
                            }
                        }

                        #endregion

                        #region Default Values

                        if (!String.IsNullOrEmpty(defaultValueText))
                        {
                            leaf.Add(new XAttribute("default", defaultValueText));
                        }

                        #endregion
                    }
                }
            }

            return(customFormDataElement);
        }
Exemple #45
0
        public void PohraniBazu(Baza azuriranaBaza)
        {
            XDocument doc = XDocument.Load(path);

            azuriranaBaza.odjelniLijecnici.Sort();
            XElement bazaOdjelnihLijecnika = doc.Descendants("odjelnilijecnici").First();

            bazaOdjelnihLijecnika.Elements().Remove();
            foreach (string lijecnik in azuriranaBaza.odjelniLijecnici)
            {
                bazaOdjelnihLijecnika.Add(new XElement("lijecnik", lijecnik));
            }

            azuriranaBaza.imena.Sort();
            XElement bazaImena = doc.Descendants("imena").First();

            bazaImena.Elements().Remove();
            foreach (string ime in azuriranaBaza.imena)
            {
                bazaImena.Add(new XElement("ime", ime));
            }

            azuriranaBaza.prezimena.Sort();
            XElement bazaPrezimena = doc.Descendants("prezimena").First();

            bazaPrezimena.Elements().Remove();
            foreach (string prezime in azuriranaBaza.prezimena)
            {
                bazaPrezimena.Add(new XElement("prezime", prezime));
            }

            azuriranaBaza.gradovi.Sort();
            XElement bazaGradova = doc.Descendants("gradovi").First();

            bazaGradova.Elements().Remove();
            foreach (string grad in azuriranaBaza.gradovi)
            {
                bazaGradova.Add(new XElement("grad", grad));
            }

            azuriranaBaza.ulice.Sort();
            XElement bazaUlica = doc.Descendants("ulice").First();

            bazaUlica.Elements().Remove();
            foreach (string ulica in azuriranaBaza.ulice)
            {
                bazaUlica.Add(new XElement("ulica", ulica));
            }

            azuriranaBaza.dijagnoze.Sort();
            XElement bazaDijagnoza = doc.Descendants("dijagnoze").First();

            bazaDijagnoza.Elements().Remove();
            foreach (string dijagnoza in azuriranaBaza.dijagnoze)
            {
                bazaDijagnoza.Add(new XElement("dijagnoza", dijagnoza));
            }

            azuriranaBaza.zahvati.Sort();
            XElement bazaZahvata = doc.Descendants("zahvati").First();

            bazaZahvata.Elements().Remove();
            foreach (string zahvat in azuriranaBaza.zahvati)
            {
                bazaZahvata.Add(new XElement("zahvat", zahvat));
            }

            doc.Save(path);
        }
        private void SaveTransactions(List<Transaction> transactions)
        {
            Uri accountUri = new Uri("/Accounts/Transactions/Transactions.xml", UriKind.Relative);

            using (Package package = ZipPackage.Open(this.FilePath, System.IO.FileMode.OpenOrCreate)) {
                // Either get the existing PackagePart or create a new one
                PackagePart accountPart = null;
                if (package.PartExists(accountUri)) {
                    accountPart = package.GetPart(accountUri);
                } else {
                    accountPart = package.CreatePart(accountUri, "text/xml");
                }

                XElement resultingXElement = new XElement("Transactions");

                TransactionXElementAdapter adapter = new TransactionXElementAdapter();
                foreach (Transaction transaction in transactions) {
                    resultingXElement.Add(adapter.ToXElement(transaction));
                }

                using (StreamWriter sw = new StreamWriter(accountPart.GetStream())) {
                    sw.Write(resultingXElement.ToString());
                }
            }
        }
Exemple #47
0
 public static void NodesOnXElementBeforeAndAfter()
 {
     XElement a = new XElement("A", "a"), b = new XElement("B", "b");
     a.Add(b);
     IEnumerable<XNode> nodes = a.Nodes();
     Assert.Equal(2, nodes.Count());
     b.Remove();
     Assert.Equal(1, nodes.Count());
 }
Exemple #48
0
        protected override void RenderAttributes(XElement element, FoRenderOptions options)
        {
            base.RenderAttributes(element, options);

            if (DisplayAlign != FoDisplayAlign.Inherit)
            {
                element.Add(new XAttribute("display-align", ToKebabCase(DisplayAlign)));
            }
            if (!string.IsNullOrEmpty(FontFamily))
            {
                element.Add(new XAttribute("font-family", FontFamily));
            }
            if (!string.IsNullOrEmpty(FontSize))
            {
                element.Add(new XAttribute("font-size", FontSize));
            }
            if (FontWeight != FoFontWeight.Inherit)
            {
                element.Add(new XAttribute("font-weight", ToKebabCase(FontWeight)));
            }
            if (FontStyle != FoFontStyle.Inherit)
            {
                element.Add(new XAttribute("font-style", ToKebabCase(FontStyle)));
            }
            if (TextAlign != FoTextAlign.Inherit)
            {
                element.Add(new XAttribute("text-align", ToKebabCase(TextAlign)));
            }
            if (TextDecoration != FoTextDecoration.Inherit)
            {
                element.Add(new XAttribute("text-decoration", ToKebabCase(TextDecoration)));
            }
            if (!string.IsNullOrEmpty(Color))
            {
                element.Add(new XAttribute("color", Color));
            }
            if (!string.IsNullOrEmpty(PageBreakBefore))
            {
                element.Add(new XAttribute("page-break-before", PageBreakBefore));
            }
            if (!string.IsNullOrEmpty(Background))
            {
                element.Add(new XAttribute("background", Background));
            }
            if (!string.IsNullOrEmpty(BackgroundImage))
            {
                element.Add(new XAttribute("background-image", BackgroundImage));
            }
            if (!string.IsNullOrEmpty(BackgroundRepeat))
            {
                element.Add(new XAttribute("background-repeat", BackgroundRepeat));
            }
            if (KeepTogether != FoKeepTogether.Inherit)
            {
                element.Add(new XAttribute("keep-together", ToKebabCase(KeepTogether)));
            }
            if (!string.IsNullOrEmpty(LineHeight))
            {
                element.Add(new XAttribute("line-height", LineHeight));
            }
            if (!string.IsNullOrEmpty(Width))
            {
                element.Add(new XAttribute("width", Width));
            }
            if (!string.IsNullOrEmpty(Height))
            {
                element.Add(new XAttribute("height", Height));
            }
            if (!string.IsNullOrEmpty(Margin))
            {
                element.Add(new XAttribute("margin", Margin));
            }
            if (!string.IsNullOrEmpty(MarginTop))
            {
                element.Add(new XAttribute("margin-top", MarginTop));
            }
            if (!string.IsNullOrEmpty(MarginRight))
            {
                element.Add(new XAttribute("margin-right", MarginRight));
            }
            if (!string.IsNullOrEmpty(MarginBottom))
            {
                element.Add(new XAttribute("margin-bottom", MarginBottom));
            }
            if (!string.IsNullOrEmpty(MarginLeft))
            {
                element.Add(new XAttribute("margin-left", MarginLeft));
            }
            if (!string.IsNullOrEmpty(Padding))
            {
                element.Add(new XAttribute("padding", Padding));
            }
            if (!string.IsNullOrEmpty(PaddingTop))
            {
                element.Add(new XAttribute("padding-top", PaddingTop));
            }
            if (!string.IsNullOrEmpty(PaddingRight))
            {
                element.Add(new XAttribute("padding-right", PaddingRight));
            }
            if (!string.IsNullOrEmpty(PaddingBottom))
            {
                element.Add(new XAttribute("padding-bottom", PaddingBottom));
            }
            if (!string.IsNullOrEmpty(PaddingLeft))
            {
                element.Add(new XAttribute("padding-left", PaddingLeft));
            }
            if (!string.IsNullOrEmpty(Border))
            {
                element.Add(new XAttribute("border", Border));
            }
            if (!string.IsNullOrEmpty(BorderTop))
            {
                element.Add(new XAttribute("border-top", BorderTop));
            }
            if (!string.IsNullOrEmpty(BorderRight))
            {
                element.Add(new XAttribute("border-right", BorderRight));
            }
            if (!string.IsNullOrEmpty(BorderBottom))
            {
                element.Add(new XAttribute("border-bottom", BorderBottom));
            }
            if (!string.IsNullOrEmpty(BorderLeft))
            {
                element.Add(new XAttribute("border-left", BorderLeft));
            }

            #endregion
        }
Exemple #49
0
 public static void DescendantsWithXNameOnXElementBeforeAndAfter()
 {
     XElement a = new XElement("A", "a"), b = new XElement("B", "b");
     a.Add(b);
     IEnumerable<XElement> nodes = a.Descendants("B");
     Assert.Equal(1, nodes.Count());
     b.Remove();
     Assert.Equal(0, nodes.Count());
 }
Exemple #50
0
        private bool UpdateOrInsertValue(XDocument xdoc, string id, string language, string value)
        {
            //var ii = xdoc.Descendants().Where(x => x.Name.ToString().ToLowerInvariant() == "key" && (string)x.Attribute("ID") == id);


            //var ii = from xel in  xdoc.Descendants()
            //         where xel.Name.ToString().ToLowerInvariant() == "key" && (string)xel.Attribute("ID") == id
            //         select xel.Descendants(language).ToList();

            bool changed = false;

            //get keys
            List <XElement> keys = (from xel in xdoc.Descendants() where xel.Name.ToString().ToLowerInvariant() == KEY_NAME.ToLowerInvariant() select xel).ToList();

            XElement parent;

            if (keys.Any())
            {
                parent = keys.FirstOrDefault().Parent;
            }
            else
            {
                parent = (from xel in xdoc.Descendants() where xel.Name.ToString().ToLowerInvariant() == PACKAGE_NAME.ToLowerInvariant() select xel).FirstOrDefault();
            }

            //get ids
            XElement xID = (from xel in keys where xel.Attributes().Any(x => x.Value.ToString().ToLowerInvariant() == id.ToLowerInvariant()) select xel).FirstOrDefault();

            //get language


            if (xID == null)
            {
                //new create
                //Too tired to make that in 1 single block :D
                var xelKeyNew = new XElement(KEY_NAME);
                xelKeyNew.Add(new XAttribute(ID_NAME, id));

                parent.Add(xelKeyNew);
                xID = xelKeyNew;
            }


            XElement xLanguage = (from xel in xID.Descendants() where xel.Name.ToString().ToLowerInvariant() == language.ToLowerInvariant() select xel).FirstOrDefault();


            if (xLanguage != null)
            {
                //exist -> update (or delete)
                if (xLanguage.Value != value)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        xLanguage.Remove();
                    }
                    else
                    {
                        xLanguage.Value = value;
                    }

                    changed = true;
                }
            }
            else
            {
                // don't add a new language if the value is empty
                if (!string.IsNullOrEmpty(value))
                {
                    xID.Add(new XElement(language, value));

                    changed = true;
                }
            }

            return(changed);
        }
Exemple #51
0
 public static void DescendantsAndSelfWithXNameBeforeAndAfter()
 {
     XElement a = new XElement("A", "a"), b = new XElement("B", "b");
     a.Add(b);
     IEnumerable<XElement> nodes = a.DescendantsAndSelf("A");
     Assert.Equal(1, nodes.Count());
     b.ReplaceWith(a);
     Assert.Equal(2, nodes.Count());
 }
        //Name:GenerateXmlRequest
        //Description:Generate the xml file for the PayOrder Request
        //
        private string GenerateXmlRequest(string returnUrlApproved, string returnUrlDeclined)
        {
            #region "create Skeleton"

            // Create Skeleton
            var xmlToSend    = new XDocument();
            var xDeclaration = new XDeclaration("1.0", "UTF-8", "no");
            xmlToSend.Declaration = xDeclaration;
            var xmlRoot = new XElement("payOrder");
            xmlToSend.Add(xmlRoot);
            var order_data    = new XElement("order_data");
            var behavior_data = new XElement("behavior_data");
            var payment_data  = new XElement("payment_data");

            xmlRoot.Add(order_data);
            xmlRoot.Add(behavior_data);
            xmlRoot.Add(payment_data);

            #endregion

            #region "order data section"

            //Fill order data section
            order_data.Add(new XElement("merch_ref", OrderNumber));
            order_data.Add(new XElement("origin", "E-commerce"));
            order_data.Add(new XElement("currency", "BRL"));
            order_data.Add(new XElement("tax_boarding", 0));
            order_data.Add(new XElement("tax_freight", 0));
            order_data.Add(new XElement("tax_others", 0));
            order_data.Add(new XElement("discount_plus", 0));
            order_data.Add(new XElement("order_subtotal",
                                        (string.Format(getPriceFormat(_orderAmount), _orderAmount).Replace(".", ""))
                                        .Replace(",", "")));
            // Only positive values are accepted.Value without formatting.Two last digits are cents. Eg. 1234 = 12.34.
            order_data.Add(new XElement("interests_value", 0));
            order_data.Add(new XElement("order_total",
                                        (string.Format(getPriceFormat(_orderAmount), _orderAmount).Replace(".", ""))
                                        .Replace(",", "")));
            var order_items = new XElement("order_items");
            order_data.Add(order_items);

            #endregion

            #region "order items section"

            order_items.Add(new XElement("order_item", new XElement("code", "Grand Total"),
                                         new XElement("description", "Grand Total"),
                                         new XElement("units", 1),
                                         new XElement("unit_value",
                                                      (string.Format(getPriceFormat(_orderAmount), _orderAmount)
                                                       .Replace(".", "")).Replace(",", ""))));

            #endregion

            #region "behavior_data section"

            //Fill behavior_data section
            behavior_data.Add(new XElement("language", "ptbr"));
            behavior_data.Add(new XElement("url_post_bell",
                                           (string.Format("{0}?Agency=itauboldcron&Bell=bell&merch_ref={1}",
                                                          returnUrlApproved, OrderNumber))));
            behavior_data.Add(new XElement("url_redirect_success",
                                           (string.Format("{0}?Agency=itauboldcron&merchant=herbalife&merch_ref={1}",
                                                          returnUrlApproved, OrderNumber))));
            behavior_data.Add(new XElement("url_redirect_error",
                                           (string.Format("{0}?Agency=itauboldcron", returnUrlDeclined))));

            #endregion

            #region "payment_data section"

            //Fill payment_data section

            payment_data.Add(new XElement("payment", new XElement("payment_method", "itau")));

            #endregion

            //   xmlToSend.Save("C:\\XMLRequest Files\\bradesco.xml");
            String xmlReadyToSend;
            xmlReadyToSend = xmlToSend.Declaration + xmlToSend.Root.ToString();
            return(xmlReadyToSend);
        }
Exemple #53
0
 public static void AttributeWithXNameBeforeAndAfter()
 {
     XElement a = new XElement("A", "a");
     IEnumerable<XAttribute> nodes = a.Attributes("name");
     Assert.Equal(0, nodes.Count());
     a.Add(new XAttribute("name", "a"), new XAttribute("type", "alphabet"));
     Assert.Equal(1, nodes.Count());
 }
Exemple #54
0
 /// <summary>
 /// 批量添加子级元素
 /// </summary>
 /// <param name="parentElement"></param>
 /// <param name="childElements">new XElement("节点名称", new XAttribute("节点属性", 节点属性),  new XElement("子节点", new XAttribute("节点属性", 节点属性)),无限添加子节点   );</param>
 public static void Add(ref XElement parentElement, IEnumerable <XElement> childElements)
 {
     parentElement?.Add(childElements);
 }
        /// <summary>
        /// Converts a given <see cref="Transaction"/> into an <see cref="T:XElement"/>.
        /// </summary>
        /// <param name="transaction">The <see cref="Transaction"/> to convert.</param>
        /// <returns>The newly created <see cref="T:XElement"/>.</returns>
        public XElement ToXElement(Transaction transaction)
        {
            XElement element = new XElement("Transaction");
            element.Add(new XElement("DebitAccountID", transaction.DebitAccount.AccountID));
            element.Add(new XElement("CreditAccountID", transaction.CreditAccount.AccountID));
            element.Add(new XElement("CreatedByUsername", transaction.CreatedByUsername));
            element.Add(new XElement("CreatedDate", transaction.CreatedDate));
            element.Add(new XElement("Date", transaction.Date));
            element.Add(new XElement("Particulars", transaction.Particulars));
            element.Add(new XElement("TransactionID", transaction.TransactionID));
            element.Add(new XElement("Value", transaction.Value));
            element.Add(new XElement("UpdatedByUsername", transaction.UpdatedByUsername));
            element.Add(new XElement("UpdatedDate", transaction.UpdatedDate));

            // Append the change history
            ChangeSetHistoryXElementAdapter adapter = new ChangeSetHistoryXElementAdapter();
            element.Add(adapter.ToXElement(transaction.ChangeSetHistory));

            return element;
        }
        /// <summary>
        /// Initializes the xml descriptor for this effect.
        /// </summary>
        private void InitializeXml()
        {
            xml = new XDocument();
            var effect = new XElement("Effect");
            xml.Add(effect);

            var customEffectTypeInfo = customEffectType.GetTypeInfo();

            // Add 
            var customEffectAttribute = Utilities.GetCustomAttribute<CustomEffectAttribute>(customEffectTypeInfo, true);
            effect.Add(CreateXmlProperty("DisplayName", "string", customEffectAttribute != null ? customEffectAttribute.DisplayName : customEffectTypeInfo.Name));
            effect.Add(CreateXmlProperty("Author", "string", customEffectAttribute != null ? customEffectAttribute.Author : string.Empty));
            effect.Add(CreateXmlProperty("Category", "string", customEffectAttribute != null ? customEffectAttribute.Category : string.Empty));
            effect.Add(CreateXmlProperty("Description", "string", customEffectAttribute != null ? customEffectAttribute.Description : string.Empty));

            var inputs = new XElement("Inputs");
            var inputAttributes = Utilities.GetCustomAttributes<CustomEffectInputAttribute>(customEffectTypeInfo, true);
            foreach(var inputAttribute in inputAttributes) {
                var inputXml = new XElement("Input");
                inputXml.SetAttributeValue("name", inputAttribute.Input);
                inputs.Add(inputXml);
            }
            effect.Add(inputs);

            // Add custom properties
            foreach(var binding in Bindings) {
                var property = CreateXmlProperty(binding.PropertyName,  binding.TypeName);

                property.Add(CreateXmlProperty("DisplayName", "string", binding.PropertyName));
                property.Add(CreateXmlProperty("Min", binding.TypeName, binding.Attribute.Min != null ? binding.Attribute.Min.ToString() : string.Empty));
                property.Add(CreateXmlProperty("Max", binding.TypeName, binding.Attribute.Max != null ? binding.Attribute.Max.ToString() : string.Empty));
                property.Add(CreateXmlProperty("Default", binding.TypeName, binding.Attribute.Default != null ? binding.Attribute.Default.ToString() : string.Empty));

                effect.Add(property);
            }
        }