Пример #1
0
    // Return the value of a given language from an XPath
    public static string GetValueI18n(string language,
				     XPathNodeIterator iterator)
    {
        string result = "";
        if ("en" == language)
          language = "";
        while (iterator.MoveNext ())
          {
        if (language == iterator.Current.XmlLang)
          {
        result = iterator.Current.Value;
        break;
          }
        // Fall back to English, if language is not available
        if ("" == result && "" == iterator.Current.XmlLang)
          result = iterator.Current.Value;
          }
        return result;
    }
Пример #2
0
        private void Parse()
        {
            try
            {
                PrintDataLogEvent("XML opening...");

                var            document  = new XPathDocument(Path);
                XPathNavigator navigator = document.CreateNavigator();

                XPathExpression   expression = navigator.Compile("/");
                XPathNodeIterator iterator   = navigator.Select(expression);

                if (iterator.MoveNext())
                {
                    XPathNavigator nav2 = iterator.Current.Clone();
                    PrintDataXMLEvent(nav2.OuterXml);
                }

                PrintDataLogEvent("");
            }
            catch (XmlException xExc)
            //Exception is thrown is there is an error in the Xml
            {
                PrintDataLogEvent(xExc.Message);
            }
            catch (Exception ex) //General exception
            {
                PrintDataLogEvent(ex.Message);
            }



            #region 2 вариант вывода
            // +  с памятью проблем нет.
            // -  проблема со временем: долго выводит на экран.

            // XmlTextReader reader = new XmlTextReader(Path);
            //
            // // ignore all white space nodes!!! IT'S FOR QUICKLY !
            // reader.WhitespaceHandling = WhitespaceHandling.None;
            //
            //
            // while (reader.Read())
            // {
            //     switch (reader.NodeType)
            //     {
            //         case XmlNodeType.Comment:
            //             PrintDataEvent(new string('\t', reader.Depth) + "Comment: " + reader.Name + " " + reader.Value + Environment.NewLine);
            //             break;
            //
            //         case XmlNodeType.Element:
            //             PrintDataEvent(new string('\t', reader.Depth) + reader.Name + ":" + Environment.NewLine);
            //
            //             if (reader.HasAttributes)
            //             {
            //                 while (reader.MoveToNextAttribute())
            //                 {
            //                     PrintDataEvent(new string('\t', reader.Depth) + "A: " + reader.Name + " " + reader.Value + Environment.NewLine);
            //                 }
            //             }
            //             break;
            //
            //         case XmlNodeType.Text:
            //             PrintDataEvent(new string('\t', reader.Depth) + reader.Value + Environment.NewLine);
            //             break;
            //
            //         default:
            //             break;
            //     }
            // }

            #endregion
        }
        private static PropertyDescriptorCollection GetComponentProperties(XPathNavigator schema, string component)
        {
            PropertyDescriptorCollection properties = new PropertyDescriptorCollection(new PropertyDescriptor[0]);

            XmlNamespaceManager namespaces = new XmlNamespaceManager(schema.NameTable);

            namespaces.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
            namespaces.AddNamespace("html", "http://www.w3.org/1999/xhtml");

            /* look for each attribute with the graph component */
            XPathNodeIterator componentElements = schema.Select(
                string.Format("/xsd:schema/xsd:complexType[@name='{0}']/xsd:attribute", component),
                namespaces);

            while (componentElements.MoveNext())
            {
                List <Attribute> descriptorAttributes = new List <Attribute>();
                string           name = componentElements.Current.GetAttribute("ref", string.Empty);

                /* add default attribute for any defaults */
                string descriptorDefault = componentElements.Current.GetAttribute("default", string.Empty);
                if (!string.IsNullOrEmpty(descriptorDefault))
                {
                    descriptorAttributes.Add(new DefaultValueAttribute(descriptorDefault));
                }

                /* add description attribute for any documentation (we'll need to preserve paragraph breaks though) */
                StringBuilder     description = new StringBuilder();
                XPathNodeIterator paragraphs  = schema.Select(
                    string.Format("/xsd:schema/xsd:attribute[@name='{0}']/xsd:annotation/xsd:documentation/html:p", name), namespaces);
                while (paragraphs.MoveNext())
                {
                    if (description.Length > 0)
                    {
                        description.Append("\r\n");
                    }
                    description.Append((string)paragraphs.Current.Evaluate("normalize-space(.)", namespaces));
                }
                if (description.Length > 0)
                {
                    descriptorAttributes.Add(new DescriptionAttribute(description.ToString()));
                }

                /* add standard values and type converter attribute for xsd:boolean or any enumerations */
                string type = (string)schema.Evaluate(
                    string.Format("string(/xsd:schema/xsd:attribute[@name='{0}']/@type)", name), namespaces);
                switch (type)
                {
                case "xsd:boolean":
                    descriptorAttributes.Add(new StandardValuesTypeConverter.Attribute(new string[] { "false", "true" }));
                    descriptorAttributes.Add(new TypeConverterAttribute(typeof(StandardValuesTypeConverter)));
                    break;

                default:
                    if (!type.StartsWith("xsd"))
                    {
                        XPathNodeIterator enumeration = schema.Select(
                            string.Format("/xsd:schema/xsd:simpleType[@name='{0}']/xsd:restriction/xsd:enumeration/@value", type),
                            namespaces);
                        if (enumeration.Count > 0)
                        {
                            List <string> standardValues = new List <string>();
                            while (enumeration.MoveNext())
                            {
                                standardValues.Add(enumeration.Current.Value);
                            }

                            descriptorAttributes.Add(new StandardValuesTypeConverter.Attribute(standardValues));
                            descriptorAttributes.Add(new TypeConverterAttribute(typeof(StandardValuesTypeConverter)));
                        }
                    }
                    break;
                }

                /* now create and add the property to the collection */
                properties.Add(new GraphPropertyDescriptor(component, name, descriptorAttributes.ToArray()));
            }
            return(properties);
        }
Пример #4
0
        private void WriteTypeReference(XPathNavigator reference, bool handle, SyntaxWriter writer)
        {
            switch (reference.LocalName)
            {
            case "arrayOf":
                XPathNavigator element = reference.SelectSingleNode(typeExpression);
                int            rank    = Convert.ToInt32(reference.GetAttribute("rank", String.Empty));
                writer.WriteKeyword("array");
                writer.WriteString("<");
                WriteTypeReference(element, writer);
                if (rank > 1)
                {
                    writer.WriteString(",");
                    writer.WriteString(rank.ToString());
                }
                writer.WriteString(">");
                if (handle)
                {
                    writer.WriteString("^");
                }
                break;

            case "pointerTo":
                XPathNavigator pointee = reference.SelectSingleNode(typeExpression);
                WriteTypeReference(pointee, writer);
                writer.WriteString("*");
                break;

            case "referenceTo":
                XPathNavigator referee = reference.SelectSingleNode(typeExpression);
                WriteTypeReference(referee, writer);
                writer.WriteString("%");
                break;

            case "type":
                string id    = reference.GetAttribute("api", String.Empty);
                bool   isRef = (reference.GetAttribute("ref", String.Empty) == "true");
                WriteNormalTypeReference(id, writer);
                XPathNodeIterator typeModifiers = reference.Select(typeModifiersExpression);
                while (typeModifiers.MoveNext())
                {
                    WriteTypeReference(typeModifiers.Current, writer);
                }
                if (handle && isRef)
                {
                    writer.WriteString("^");
                }

                break;

            case "template":
                string name = reference.GetAttribute("name", String.Empty);
                writer.WriteString(name);
                XPathNodeIterator modifiers = reference.Select(typeModifiersExpression);
                while (modifiers.MoveNext())
                {
                    WriteTypeReference(modifiers.Current, writer);
                }
                break;

            case "specialization":
                writer.WriteString("<");
                XPathNodeIterator arguments = reference.Select(specializationArgumentsExpression);
                while (arguments.MoveNext())
                {
                    if (arguments.CurrentPosition > 1)
                    {
                        writer.WriteString(", ");
                    }
                    WriteTypeReference(arguments.Current, writer);
                }
                writer.WriteString(">");
                break;
            }
        }
Пример #5
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="title">article to edit</param>
        /// <param name="text">new text to insert</param>
        /// <param name="summary">edit summary, or section title if section=ACTION_EDIT_SECTION_NEW</param>
        /// <param name="exists">What to do if the article exists.</param>
        /// <param name="minor">flag as a minor edit</param>
        /// <param name="bot">flag as a bot edit</param>
        /// <param name="location">Where to put the text</param>
        /// <param name="section">section to edit</param>
        public void edit(string title, string text, string summary, int exists, bool minor, bool bot, int location, int section)
        {
            EditToken t = EditToken.get(_wc, title);

            NameValueCollection vals = new NameValueCollection();

            if (section != ACTION_EDIT_SECTION_ALL)
            {
                vals.Add("section", section == ACTION_EDIT_SECTION_NEW ? "new" : section.ToString());
            }

            vals.Add("summary", summary);
            vals.Add("basetimestamp", t.lastEdit);
            switch (location)
            {
            case ACTION_EDIT_TEXT_APPEND:
                vals.Add("appendtext", text);
                break;

            case ACTION_EDIT_TEXT_PREPEND:
                vals.Add("prependtext", text);
                break;

            case ACTION_EDIT_TEXT_REPLACE:
                vals.Add("text", text);
                break;

            default:
                throw new ArgumentOutOfRangeException("location");
            }

            switch (exists)
            {
            case ACTION_EDIT_EXISTS_DOESEXIST:
                vals.Add("nocreate", "true");
                break;

            case ACTION_EDIT_EXISTS_NOCHECK:
                break;

            case ACTION_EDIT_EXISTS_NOTEXIST:
                vals.Add("createonly", "true");
                break;

            default:
                throw new ArgumentOutOfRangeException("exists");
            }

            vals.Add("starttimestamp", t.timestamp);
            vals.Add("token", t.token);

            Stream data = _wc.sendHttpPost(new WebHeaderCollection(), vals, "action=edit&assert=user&title=" + HttpUtility.UrlEncode(t.title) + (bot ? "&bot" : "") + "&token=" + t.token);
            XmlNamespaceManager ns;
            XPathNodeIterator   it = getIterator(data, "//error", out ns);

            if (it.Count != 0)
            {
                it.MoveNext();
                throw new MediaWikiException(it.Current.GetAttribute("info", ns.DefaultNamespace));
            }
            System.Threading.Thread.Sleep(1000 * 10);
        }
Пример #6
0
        /**
         * Parse the relationship part and add all relationship in this collection.
         *
         * @param relPart
         *            The package part to parse.
         * @throws InvalidFormatException
         *             Throws if the relationship part is invalid.
         */

        private void ParseRelationshipsPart(PackagePart relPart)
        {
            try
            {
                logger.Log(POILogger.DEBUG, "Parsing relationship: " + relPart.PartName);
                XPathDocument xmlRelationshipsDoc = DocumentHelper.ReadDocument(relPart.GetInputStream());

                // Check OPC compliance M4.1 rule
                bool fCorePropertiesRelationship = false;
                ///xmlRelationshipsDoc.ChildNodes.GetEnumerator();
                XPathNavigator      xpathnav = xmlRelationshipsDoc.CreateNavigator();
                XmlNamespaceManager nsMgr    = new XmlNamespaceManager(xpathnav.NameTable);
                nsMgr.AddNamespace("x", PackageNamespaces.RELATIONSHIPS);

                XPathNodeIterator iterator = xpathnav.Select("//x:" + PackageRelationship.RELATIONSHIP_TAG_NAME, nsMgr);

                while (iterator.MoveNext())
                {
                    // Relationship ID
                    String id = iterator.Current.GetAttribute(PackageRelationship.ID_ATTRIBUTE_NAME, xpathnav.NamespaceURI);
                    // Relationship type
                    String type = iterator.Current.GetAttribute(
                        PackageRelationship.TYPE_ATTRIBUTE_NAME, xpathnav.NamespaceURI);

                    /* Check OPC Compliance */
                    // Check Rule M4.1
                    if (type.Equals(PackageRelationshipTypes.CORE_PROPERTIES))
                    {
                        if (!fCorePropertiesRelationship)
                        {
                            fCorePropertiesRelationship = true;
                        }
                        else
                        {
                            throw new InvalidFormatException(
                                      "OPC Compliance error [M4.1]: there is more than one core properties relationship in the package !");
                        }
                    }

                    /* End OPC Compliance */

                    // TargetMode (default value "Internal")
                    string     targetModeAttr = iterator.Current.GetAttribute(PackageRelationship.TARGET_MODE_ATTRIBUTE_NAME, xpathnav.NamespaceURI);
                    TargetMode targetMode     = TargetMode.Internal;
                    if (targetModeAttr != string.Empty)
                    {
                        targetMode = targetModeAttr.ToLower()
                                     .Equals("internal") ? TargetMode.Internal
                                : TargetMode.External;
                    }

                    // Target converted in URI
                    Uri    target = PackagingUriHelper.ToUri("http://invalid.uri"); // dummy url
                    String value  = iterator.Current.GetAttribute(
                        PackageRelationship.TARGET_ATTRIBUTE_NAME, xpathnav.NamespaceURI);;
                    try
                    {
                        // when parsing of the given uri fails, we can either
                        // ignore this relationship, which leads to IllegalStateException
                        // later on, or use a dummy value and thus enable processing of the
                        // package
                        target = PackagingUriHelper.ToUri(value);
                    }
                    catch (UriFormatException e)
                    {
                        logger.Log(POILogger.ERROR, "Cannot convert " + value
                                   + " in a valid relationship URI-> dummy-URI used", e);
                    }
                    AddRelationship(target, targetMode, type, id);
                }
            }
            catch (Exception e)
            {
                logger.Log(POILogger.ERROR, e);
                throw new InvalidFormatException(e.Message);
            }
        }
Пример #7
0
        public bool Read()
        {
            if (_xpni == null)
            {
                return(false);
            }

            XPathNodeIterator ti = _xpni;

            Hashtable ht = new Hashtable(_Names.Length);

            // clear out previous values;  previous row might have values this row doesn't
            for (int i = 0; i < _Data.Length; i++)
            {
                _Data[i] = null;
            }

            XPathNodeIterator save_ti = ti.Clone();
            bool rc = false;

            while (ti.MoveNext())
            {
                if (ti.Current.Name != "key")
                {
                    continue;
                }
                string name = ti.Current.Value.Replace(' ', '_');
                // we only know we're on the next row when a column repeats
                if (ht.Contains(name))
                {
                    break;
                }
                ht.Add(name, name);

                int ix;
                try
                {
                    ix = this.GetOrdinal(name);
                    rc = true; // we know we got at least one column value
                }
                catch          // this isn't a know column; skip it
                {
                    ti.MoveNext();
                    save_ti = ti.Clone();
                    continue;                   // but keep trying
                }


                ti.MoveNext();
                save_ti = ti.Clone();
                try
                {
                    switch (ti.Current.Name)
                    {
                    case "integer":
                        if (_Names[ix] == "Play_Date")      // will overflow a long
                        {
                            _Data[ix] = ti.Current.ValueAsLong;
                        }
                        else
                        {
                            _Data[ix] = ti.Current.ValueAsInt;
                        }
                        break;

                    case "string":
                        _Data[ix] = ti.Current.Value;
                        break;

                    case "real":
                        _Data[ix] = ti.Current.ValueAsDouble;
                        break;

                    case "true":
                        _Data[ix] = true;
                        break;

                    case "false":
                        _Data[ix] = false;
                        break;

                    case "date":
                        _Data[ix] = ti.Current.ValueAsDateTime;
                        break;

                    default:
                        _Data[ix] = ti.Current.Value;
                        break;
                    }
                }
                catch { _Data[ix] = null; }
            }

            _xpni = save_ti;
            return(rc);
        }
Пример #8
0
        public static int LoadRecipes()
        {
            try
            {
                XPathNavigator    nav           = null;
                XPathDocument     docNav        = null;
                XPathNodeIterator NodeIter      = null;
                String            strExpression = null;

                // Open the XML.
                docNav = XMLHelper.LoadDocument(Environment.CurrentDirectory + "\\Config\\Recipes.xml", true);

                // Create a navigator to query with XPath.
                nav           = docNav.CreateNavigator();
                strExpression = "//Recipes/Recipe";
                NodeIter      = nav.Select(strExpression);

                int numLoaded = 0;

                //Iterate through the results showing the element value.
                while (NodeIter.MoveNext())
                {
                    Recipe r = new Recipe();
                    r.ID          = int.Parse(NodeIter.Current.SelectSingleNode("ID").Value);
                    r.Name        = NodeIter.Current.SelectSingleNode("Name").Value;
                    r.Description = NodeIter.Current.SelectSingleNode("Description").Value;
                    r.RecipeGroup = NodeIter.Current.SelectSingleNode("RecipeGroup").Value;
                    r.Description = NodeIter.Current.SelectSingleNode("Description").Value;

                    XPathNodeIterator ingIt     = NodeIter.Current.Select("./Ingredients/Ingredient");
                    GameEventType[]   listeners = new GameEventType[ingIt.Count];
                    while (ingIt.MoveNext())
                    {
                        Recipe.RecipeComponent ing = new Recipe.RecipeComponent();
                        string resourceType        = ingIt.Current.GetAttribute("resourceType", "");
                        if (resourceType.ToLower() == "item")
                        {
                            ing.ItemIngredient = ingIt.Current.GetAttribute("resource", "");
                        }
                        else
                        {
                            string statName = ingIt.Current.GetAttribute("resource", "");
                            Stat   s        = StatManager.Instance.AllStats.GetStat(statName);
                            ing.StatIngredient = s;
                        }

                        string amount = ingIt.Current.GetAttribute("amount", "");
                        if (amount.Length < 1)
                        {
                            amount = "1";
                        }
                        ing.Quantity = int.Parse(amount);
                        r.Ingredients.Add(ing);
                    }

                    ingIt = NodeIter.Current.Select("./Results/Result");
                    while (ingIt.MoveNext())
                    {
                        Recipe.RecipeComponent ing = new Recipe.RecipeComponent();
                        string resourceType        = ingIt.Current.GetAttribute("resourceType", "");
                        if (resourceType.ToLower() == "item")
                        {
                            ing.ItemIngredient = ingIt.Current.GetAttribute("resource", "");
                        }
                        else
                        {
                            string statName = ingIt.Current.GetAttribute("resource", "");
                            Stat   s        = StatManager.Instance.AllStats.GetStat(statName);
                            if (s != null)
                            {
                                ing.StatIngredient = s.Copy();
                            }
                        }

                        string amount = ingIt.Current.GetAttribute("amount", "");
                        if (amount.Length < 1)
                        {
                            amount = "1";
                        }

                        ing.Quantity = int.Parse(amount);
                        r.Results.Add(ing);
                    }

                    //Console.WriteLine("Loaded Recipe data for " + r.Name);
                    numLoaded++;
                    Recipes.Remove(r.ID);
                    Recipes.Add(r.ID, r);
                }

                return(numLoaded);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error loading Recipes: " + e.Message);
            }

            return(-1);
        }
Пример #9
0
        //Methode: Befüllen des PDF-Formlars mit Werten
        public void CreateRequirementPdf()
        {
            Dictionary <string, string> groupMapping = new Dictionary <string, string>();

            using (var sr = new StreamReader(pathToGroupMappingsFile))
            {
                string line = null;
                while ((line = sr.ReadLine()) != null)
                {
                    string oe    = line.Substring(0, line.IndexOf(','));
                    string group = line.Substring(line.LastIndexOf(',') + 1);
                    groupMapping.Add(oe, group);
                }
            }

            int   xDistance    = 34;
            int   yDistance    = 745;
            float rowMinHeight = 15f;
            float currentPos;

            //initialiseren eines MemoryStreams, welcher dem PDF-Stamper (siehe nächster Befehl) übergeben wird
            using (Document document = new Document(PageSize.A4))
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    //Folgende drei Initalisierungen werden in Kombination mit using(){} gemacht. Somit gelten die Initialisierungen nur innerhalb des using-Abschnitts.
                    //Das scheint C#-Best-Practice zu sein, da ansonsten u.a. das bearbeitete PDF für immer in einem "Die Datei wird schon verwendet"-Zustand bleibt und nicht verwendet werden kann.
                    //initialisieren des PDF-Readers von itextsharp (zum Lesen von PDFs); diesem wird die Vorlage des Auftragszettels als ByteArray übergeben
                    using (PdfReader pdfReader = new PdfReader(requirementTemplate))
                    {
                        //initialisieren des PDF-Stampers von itextsharp (zum Bearbeiten von PDFs)
                        using (PdfStamper pdfStamper = new PdfStamper(pdfReader, memoryStream, '\0', true))
                        {
                            PdfContentByte canvas = pdfStamper.GetOverContent(1);

                            ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("Bedarfsmeldung #" + requirementId), xDistance, yDistance, 0);

                            PdfPTable pdfInfoTable = new PdfPTable(2);
                            pdfInfoTable.SetTotalWidth(new float[] { 100, 400 });
                            AddPDFCell("Invest: ", 0, 2, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell(Invest, 0, 2, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell("Projektnummer: ", 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            string projectNumber = "";
                            if (root.SelectSingleNode(xIsMultipleProjects, nsmgr).ToString() != "false")
                            {
                                if (root.SelectSingleNode(xMultipleProjectsBookingType, nsmgr).Value == "percentage")
                                {
                                    xIteratorProjects = root.Select(xPercentageProject, nsmgr);
                                    while (xIteratorProjects.MoveNext())
                                    {
                                        projectNumber += xIteratorProjects.Current.SelectSingleNode(xPercentageProjectNumber, nsmgr).Value + " (" + xIteratorProjects.Current.SelectSingleNode(xPercentage, nsmgr).Value + "%)\n";
                                    }
                                }
                            }
                            else
                            {
                                projectNumber = root.SelectSingleNode(xProjectNumber, nsmgr).ToString();
                            }
                            AddPDFCell(projectNumber, 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell("Name Besteller:", 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell(listItemForm[collumnFormRequirementCustomer].ToString(), 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell("Durchwahl Besteller:", 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell(root.SelectSingleNode(xTelephone, nsmgr).ToString(), 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell("Projektleiter:", 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell(listItemForm[collumnFormRequirementProjectleader].ToString(), 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell("Gruppe/Abteilung:", 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell(groupMapping[root.SelectSingleNode(xGroup, nsmgr).ToString()], 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell("Laser:", 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell(laser, 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell("Gefahrstoff:", 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            AddPDFCell(danger, 0, 1, 0, 0, rowMinHeight, pdfInfoTable);
                            currentPos = pdfInfoTable.WriteSelectedRows(0, 2, 0, 8, xDistance, yDistance - 20, pdfStamper.GetOverContent(1));

                            PdfPTable pdfTablePositions = new PdfPTable(4);
                            pdfTablePositions.SetTotalWidth(new float[] { 28, 40, 330, 128 });
                            pdfTablePositions.DefaultCell.Border = Rectangle.NO_BORDER;
                            xIteratorPositions = root.Select("/my:myFields/my:positions/my:position", nsmgr);
                            AddPDFCell("Pos", 0, 2, 0, 0, 20f, pdfTablePositions);
                            AddPDFCell("Menge", PdfPCell.ALIGN_CENTER, 2, 4, 0, 20f, pdfTablePositions);
                            AddPDFCell("Warenbezeichnung", 0, 2, 4, 0, 20f, pdfTablePositions);
                            AddPDFCell("Geschätzter Auftragswert", PdfPCell.ALIGN_RIGHT, 2, 4, 0, 20f, pdfTablePositions);
                            pdfTablePositions.HeaderRows = 1;
                            while (xIteratorPositions.MoveNext())
                            {
                                AddPDFCell(xIteratorPositions.Current.SelectSingleNode(xPositionNumber, nsmgr).Value, 0, 0, 0, 0, rowMinHeight, pdfTablePositions);
                                AddPDFCell(xIteratorPositions.Current.SelectSingleNode(xPositionQuantity, nsmgr).Value, PdfPCell.ALIGN_CENTER, 4, 4, 0, rowMinHeight, pdfTablePositions);
                                string sonstiges = "";
                                if (xIteratorPositions.Current.SelectSingleNode(xPositionProjectNumber, nsmgr).Value != String.Empty)
                                {
                                    sonstiges = sonstiges + "\nProjekt-Nr.: " + xIteratorPositions.Current.SelectSingleNode(xPositionProjectNumber, nsmgr).Value;
                                }
                                AddPDFCell(xIteratorPositions.Current.SelectSingleNode(xPositionProductDescription, nsmgr).Value + sonstiges, 0, 4, 4, 0, rowMinHeight, pdfTablePositions);
                                if (xIteratorPositions.Current.SelectSingleNode(xPositionProductPrice, nsmgr).Value.ToString() != "")
                                {
                                    AddPDFCell(CurrencyToString(xIteratorPositions.Current.SelectSingleNode(xPositionProductPrice, nsmgr).ValueAsDouble), PdfPCell.ALIGN_RIGHT, 4, 4, 0, rowMinHeight, pdfTablePositions);
                                }
                            }
                            currentPos = pdfTablePositions.WriteSelectedRows(0, 4, 0, xIteratorPositions.Count + 1, xDistance, currentPos - 30, pdfStamper.GetOverContent(1));

                            PdfPTable pdfTableCompetitors = new PdfPTable(3);
                            pdfTableCompetitors.SetTotalWidth(new float[] { 306, 110, 110 });
                            pdfTableCompetitors.DefaultCell.Border = Rectangle.NO_BORDER;
                            AddPDFCell("Wettbewerber", 0, 2, 0, 0, 20f, pdfTableCompetitors);
                            AddPDFCell("Ort", 0, 2, 5, 0, 20f, pdfTableCompetitors);
                            AddPDFCell("Land", 0, 2, 5, 0, 20f, pdfTableCompetitors);
                            pdfTableCompetitors.HeaderRows = 1;
                            xIteratorCompetitors           = root.Select(xCompetitors, nsmgr);
                            while (xIteratorCompetitors.MoveNext())
                            {
                                AddPDFCell(xIteratorCompetitors.Current.SelectSingleNode(xCompetitorName, nsmgr).Value, 0, 0, 0, 0, rowMinHeight, pdfTableCompetitors);
                                AddPDFCell(xIteratorCompetitors.Current.SelectSingleNode(xCompetitorLocation, nsmgr).Value, 0, 4, 5, 0, rowMinHeight, pdfTableCompetitors);
                                AddPDFCell(xIteratorCompetitors.Current.SelectSingleNode(xCompetitorCountry, nsmgr).Value, 0, 4, 5, 0, rowMinHeight, pdfTableCompetitors);
                            }
                            currentPos = pdfTableCompetitors.WriteSelectedRows(0, 3, 0, xIteratorCompetitors.Count + 1, xDistance, currentPos - 30, pdfStamper.GetOverContent(1));

                            PdfPTable pdfTableCriteria = new PdfPTable(2);
                            pdfTableCriteria.SetTotalWidth(new float[] { 150, 45 });
                            pdfTableCriteria.DefaultCell.Border = Rectangle.NO_BORDER;
                            AddPDFCell("Kriterium", 0, 2, 0, 0, 20f, pdfTableCriteria);
                            AddPDFCell("%", 0, 2, 4, 0, 20f, pdfTableCriteria);
                            pdfTableCriteria.HeaderRows = 1;
                            xIteratorCriteria           = root.Select(xCriteria, nsmgr);
                            while (xIteratorCriteria.MoveNext())
                            {
                                AddPDFCell(xIteratorCriteria.Current.SelectSingleNode(xCriteriaName, nsmgr).Value, 0, 0, 0, 0, rowMinHeight, pdfTableCriteria);
                                AddPDFCell(xIteratorCriteria.Current.SelectSingleNode(xCriteriaImportance, nsmgr).Value, 0, 4, 4, 0, rowMinHeight, pdfTableCriteria);
                            }
                            currentPos = pdfTableCriteria.WriteSelectedRows(0, 2, 0, xIteratorCriteria.Count + 1, xDistance, currentPos - 30, pdfStamper.GetOverContent(1));

                            PdfPTable pdfTableInfo2 = new PdfPTable(2);
                            pdfTableInfo2.SetTotalWidth(new float[] { 140, 386 });
                            pdfTableInfo2.DefaultCell.Border = Rectangle.NO_BORDER;
                            AddPDFCell("Bedarfstermin: ", 0, 0, 0, 0, rowMinHeight, pdfTableInfo2);
                            if (root.SelectSingleNode(xDeliveryDate, nsmgr).Value != "")
                            {
                                var date = Convert.ToDateTime(root.SelectSingleNode(xDeliveryDate, nsmgr).Value);
                                AddPDFCell(date.ToString("dd.MM.yyyy"), 0, 0, 0, 0, rowMinHeight, pdfTableInfo2);
                            }
                            else
                            {
                                AddPDFCell("", 0, 0, 0, 0, rowMinHeight, pdfTableInfo2);
                            }
                            AddPDFCell("Anmerkung für den Einkauf: ", 0, 0, 0, 0, rowMinHeight, pdfTableInfo2);
                            AddPDFCell(root.SelectSingleNode(xNote, nsmgr).Value, 0, 0, 0, 0, rowMinHeight, pdfTableInfo2);
                            currentPos = pdfTableInfo2.WriteSelectedRows(0, 2, 0, 2, xDistance, currentPos - 30, pdfStamper.GetOverContent(1));
                            ColumnText.ShowTextAligned(canvas, Element.ALIGN_LEFT, new Phrase("Unterschrift Projektleiter"), xDistance, 80f, 0);
                        }
                    }
                    requirementPdf = memoryStream.ToArray();
                }
            }
        }
Пример #10
0
        static void Analyse_M3(string[] info_client, Logement l)
        {
            string nomDuDocXML = "M3.xml";

            //créer l'arborescence des chemins XPath du document
            //--------------------------------------------------
            XPathDocument  doc = new System.Xml.XPath.XPathDocument(nomDuDocXML);
            XPathNavigator nav = doc.CreateNavigator();

            //créer une requete XPath
            //-----------------------
            string          maRequeteXPath = "/Validation_sejour/*";
            XPathExpression expr           = nav.Compile(maRequeteXPath);

            //exécution de la requete
            //-----------------------
            XPathNodeIterator nodes = nav.Select(expr);// exécution de la requête XPath

            //parcourir le resultat
            //---------------------
            string[] nodeContent = { "", "" };
            while (nodes.MoveNext())
            {
                nodeContent[0] = nodes.Current.ToString(); //ID sejour
                nodes.MoveNext();
                nodeContent[1] = nodes.Current.ToString(); //information sejour valide
                break;
            }
            Console.WriteLine("Affichage du message de validation du client...\n");
            Console.WriteLine("ID sejour : " + nodeContent[0] + "\nInformation : " + nodeContent[1] + "\n\n");

            if (nodeContent[1] == "sejour valide")
            {
                //string connectionString = "SERVER=localhost; PORT =3306;DATABASE=BOS_MAXI;UID=root;PASSWORD=Maximedu33360;";
                string          connectionString = "SERVER=fboisson.ddns.net; PORT =3306;DATABASE=BOS_MAXI;UID=S6-BOS-MAXI;PASSWORD=12066;";
                MySqlConnection connection       = new MySqlConnection(connectionString);
                connection.Open();
                MySqlCommand command = connection.CreateCommand();
                command.CommandText =
                    "UPDATE sejour SET validation_sejour=@info WHERE num_sejour=@num;";    //actualise le sejour a sejour valide
                command.Parameters.AddWithValue("@info", nodeContent[1]);
                command.Parameters.AddWithValue("@num", nodeContent[0]);
                MySqlDataReader reader;
                reader = command.ExecuteReader();
                connection.Close();

                connection.Open();
                MySqlCommand command1 = connection.CreateCommand();
                command1.CommandText =
                    "SELECT immat FROM sejour WHERE num_sejour=@num;";    //selectionne immatriculation
                command1.Parameters.AddWithValue("@num", nodeContent[0]);

                MySqlDataReader reader1;
                reader1 = command1.ExecuteReader();
                reader1.Read();
                string immat = "";
                immat = reader1.GetString("immat");
                connection.Close();


                connection.Open();
                MySqlCommand command2 = connection.CreateCommand();
                command2.CommandText =
                    "UPDATE voiture SET disponibilite='en location' WHERE immat=@immatriculation;";    //actualise le statut du vehicule
                command2.Parameters.AddWithValue("@immatriculation", immat);
                MySqlDataReader reader2;
                reader2 = command2.ExecuteReader();
                connection.Close();

                Console.WriteLine("Enregistrement du sejour...\n");
                Console.WriteLine("num_sejour : A3\nID_client : " + info_client[4] + "\n" + "theme : " + info_client[3] + "\ndate : " + info_client[2] + "\nvalidation_sejour : sejour valide\nimmat " + info_client[5] + "\nprix du sejour " + l.Price + "\nnum_reservation " + l.Room_id + "\n");
            }

            else
            {
                Console.WriteLine("Annulation du sejour...");
            }
        }
Пример #11
0
        public string loadMsg(string XmlFilePath)
        {
            XmlDocument doc = new XmlDocument();

            doc.Load(XmlFilePath);


            ////Create XPathNavigator
            XPathNavigator xpathNav = null;

            xpathNav = doc.CreateNavigator();

            ////Compile the XPath expression
            XPathExpression xpathExpr = null;

            xpathExpr = xpathNav.Compile(Expression);

            ////Display the results depending on type of result
            string strOutput   = null;
            string strMsgValue = null;
            string strMsgName  = null;


            switch (xpathExpr.ReturnType)
            {
            case XPathResultType.String:
                strOutput = System.Convert.ToString(xpathNav.Evaluate(xpathExpr));

                break;

            case XPathResultType.NodeSet:
                XPathNodeIterator nodeIter = null;
                nodeIter = xpathNav.Select(xpathExpr);
                int nodecount = nodeIter.Count;
                while (nodeIter.MoveNext())
                {
                    if (nodeIter.Current.MoveToFirstChild())
                    {
                        int i = 0;
                        do
                        {
                            if (i == 0)
                            {
                                strMsgName = System.Convert.ToString(nodeIter.Current.Value);
                            }
                            else
                            {
                                strMsgValue = System.Convert.ToString(nodeIter.Current.Value);
                                switch (strMsgName)
                                {
                                case "Updated_SuccessFully":
                                    _Updated_SuccessFully = strMsgValue;
                                    break;

                                case "Update_SameAlreadyExists":
                                    _Update_SameAlreadyExists = strMsgValue;
                                    break;

                                case "Search_NoCriteria":
                                    _Search_NoCriteria = strMsgValue;
                                    break;

                                case "Insert_SameAlreadyExists":
                                    _Insert_SameAlreadyExists = strMsgValue;
                                    break;

                                case "Insert_UserAlreadyExists":
                                    _Insert_UserAlreadyExists = strMsgValue;
                                    break;

                                case "ErrorOccured":
                                    _ErrorOccured = strMsgValue;
                                    break;

                                case "Inserted_SuccessFully":
                                    _Inserted_SuccessFully = strMsgValue;
                                    break;

                                case "NoRecordExists":
                                    _NoRecordExists = strMsgValue;
                                    break;

                                case "Deleted_SuccessFully":
                                    _Deleted_SuccessFully = strMsgValue;
                                    break;

                                case "DeletedMultiple_SuccessFully":
                                    _DeletedMultiple_SuccessFully = strMsgValue;
                                    break;

                                case "Record_AlReady_Deleted":
                                    _Record_AlReady_Deleted = strMsgValue;
                                    break;

                                case "LoginFailed":
                                    _LoginFailed = strMsgValue;
                                    break;

                                case "PasswordRecovered":
                                    _PasswordRecovered = strMsgValue;
                                    break;

                                case "NoUserExists":
                                    _NoUserExists = strMsgValue;
                                    break;

                                case "ErrorOccured_ActionCancelled":
                                    _ErrorOccured_ActionCancelled = strMsgValue;
                                    break;

                                case "FromDate_Greater_Todate":
                                    _FromDate_Greater_Todate = strMsgValue;
                                    break;

                                case "Invalid_Date":
                                    _Invalid_Date = strMsgValue;
                                    break;

                                case "Password_Changed_Successfully":
                                    _Password_Changed_Successfully = strMsgValue;
                                    break;

                                case "PathNotFound":
                                    _PathNotFound = strMsgValue;
                                    break;

                                case "CannotDelete_ReferenceExists":
                                    _CannotDelete_ReferenceExists = strMsgValue;
                                    break;

                                case "Cart_Empty":
                                    _Cart_Empty = strMsgValue;
                                    break;

                                case "Please_Enter":
                                    _Please_Enter = strMsgValue;
                                    break;

                                case "Please_Select":
                                    _Please_Select = strMsgValue;
                                    break;

                                case "EmailNotFound":
                                    _EmailNotFound = strMsgValue;
                                    break;

                                case "EmailSent":
                                    _EmailSent = strMsgValue;
                                    break;

                                case "IncorrectPwd":
                                    _IncorrectPwd = strMsgValue;
                                    break;

                                case "Insert_EmailExists":
                                    _Insert_EmailExists = strMsgValue;
                                    break;

                                case "ConfirmPwd_Must_Match":
                                    _ConfirmPwd_Must_Match = strMsgValue;
                                    break;

                                case "Invalid_Email":
                                    _Invalid_Email = strMsgValue;
                                    break;

                                case "SqlInjectionMsg":
                                    _SqlInjectionMsg = strMsgValue;
                                    break;

                                case "SqlInjection_PwdLen":
                                    _SqlInjection_PwdLen = strMsgValue;
                                    break;

                                case "SqlInjection_ConfirmPwdLen":
                                    _SqlInjection_ConfirmPwdLen = strMsgValue;
                                    break;

                                case "AddEditUser_AccesRights":
                                    _AddEditUser_AccesRights = strMsgValue;
                                    break;

                                case "AddEditUser_LastSuperAdmin":
                                    _AddEditUser_LastSuperAdmin = strMsgValue;
                                    break;

                                case "Insert_UnitNoExists":
                                    _Insert_UnitNoExists = strMsgValue;
                                    break;

                                case "Not_LoggedIn":
                                    _Not_LoggedIn = strMsgValue;
                                    break;
                                }
                            }
                            i = i + 1;
                        } while (nodeIter.Current.MoveToNext());
                        nodeIter.Current.MoveToParent();
                    }
                }

                break;

            case XPathResultType.Error:
                strOutput = "Error ";

                break;
            }
            return(strOutput);
        }
Пример #12
0
        private int numberAny(Processor processor, ActionFrame frame)
        {
            int result = 0;
            // Our current point will be our end point in this search
            XPathNavigator endNode = frame.Node !;

            if (endNode.NodeType == XPathNodeType.Attribute || endNode.NodeType == XPathNodeType.Namespace)
            {
                endNode = endNode.Clone();
                endNode.MoveToParent();
            }
            XPathNavigator startNode = endNode.Clone();

            if (_fromKey != Compiler.InvalidQueryKey)
            {
                bool hitFrom = false;
                // First try to find start by traversing up. This gives the best candidate or we hit root
                do
                {
                    if (processor.Matches(startNode, _fromKey))
                    {
                        hitFrom = true;
                        break;
                    }
                } while (startNode.MoveToParent());

                Debug.Assert(
                    processor.Matches(startNode, _fromKey) ||   // we hit 'from' or
                    startNode.NodeType == XPathNodeType.Root    // we are at root
                    );

                // from this point (matched parent | root) create descendent quiery:
                // we have to reset 'result' on each 'from' node, because this point can' be not last from point;
                XPathNodeIterator sel = startNode.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ true);
                while (sel.MoveNext())
                {
                    if (processor.Matches(sel.Current, _fromKey))
                    {
                        hitFrom = true;
                        result  = 0;
                    }
                    else if (MatchCountKey(processor, frame.Node !, sel.Current !))
                    {
                        result++;
                    }
                    if (sel.Current !.IsSamePosition(endNode))
                    {
                        break;
                    }
                }
                if (!hitFrom)
                {
                    result = 0;
                }
            }
            else
            {
                // without 'from' we startting from the root
                startNode.MoveToRoot();
                XPathNodeIterator sel = startNode.SelectDescendants(XPathNodeType.All, /*matchSelf:*/ true);
                // and count root node by itself
                while (sel.MoveNext())
                {
                    if (MatchCountKey(processor, frame.Node !, sel.Current !))
                    {
                        result++;
                    }
                    if (sel.Current !.IsSamePosition(endNode))
                    {
                        break;
                    }
                }
            }
            return(result);
        }
Пример #13
0
        internal static CpArgument CreateArgument(CpAction parentAction, CpService parentService, XPathNavigator argumentNav,
                                                  IXmlNamespaceResolver nsmgr)
        {
            string          name = ParserHelper.SelectText(argumentNav, "s:name/text()", nsmgr);
            string          relatedStateVariableName = ParserHelper.SelectText(argumentNav, "s:relatedStateVariable/text()", nsmgr);
            CpStateVariable relatedStateVariable;

            if (!parentService.StateVariables.TryGetValue(relatedStateVariableName, out relatedStateVariable))
            {
                throw new ArgumentException("Related state variable '{0}' is not present in service", relatedStateVariableName);
            }
            string            direction = ParserHelper.SelectText(argumentNav, "s:direction/text()", nsmgr);
            XPathNodeIterator retValIt  = argumentNav.Select("s:retval", nsmgr);
            CpArgument        result    = new CpArgument(parentAction, name, relatedStateVariable, ParseArgumentDirection(direction), retValIt.MoveNext());

            return(result);
        }
        //============================================================
        //	PUBLIC METHODS
        //============================================================
        #region Load(XPathNavigator source)
        /// <summary>
        /// Loads this <see cref="FeedSynchronizationSharingInformation"/> using the supplied <see cref="XPathNavigator"/>.
        /// </summary>
        /// <param name="source">The <see cref="XPathNavigator"/> to extract information from.</param>
        /// <returns><b>true</b> if the <see cref="FeedSynchronizationSharingInformation"/> was initialized using the supplied <paramref name="source"/>, otherwise <b>false</b>.</returns>
        /// <remarks>
        ///     This method expects the supplied <paramref name="source"/> to be positioned on the XML element that represents a <see cref="FeedSynchronizationSharingInformation"/>.
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception>
        public bool Load(XPathNavigator source)
        {
            //------------------------------------------------------------
            //	Local members
            //------------------------------------------------------------
            bool wasLoaded = false;

            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(source, "source");

            //------------------------------------------------------------
            //	Create namespace manager to resolve prefixed elements
            //------------------------------------------------------------
            FeedSynchronizationSyndicationExtension extension = new FeedSynchronizationSyndicationExtension();
            XmlNamespaceManager manager = extension.CreateNamespaceManager(source);

            //------------------------------------------------------------
            //	Attempt to extract syndication information
            //------------------------------------------------------------
            if (source.HasAttributes)
            {
                string sinceAttribute   = source.GetAttribute("since", String.Empty);
                string untilAttribute   = source.GetAttribute("until", String.Empty);
                string expiresAttribute = source.GetAttribute("expires", String.Empty);

                if (!String.IsNullOrEmpty(sinceAttribute))
                {
                    this.Since = sinceAttribute;
                    wasLoaded  = true;
                }

                if (!String.IsNullOrEmpty(untilAttribute))
                {
                    this.Until = untilAttribute;
                    wasLoaded  = true;
                }

                if (!String.IsNullOrEmpty(expiresAttribute))
                {
                    DateTime expiresOn;
                    if (SyndicationDateTimeUtility.TryParseRfc3339DateTime(expiresAttribute, out expiresOn))
                    {
                        this.ExpiresOn = expiresOn;
                        wasLoaded      = true;
                    }
                }
            }

            if (source.HasChildren)
            {
                XPathNodeIterator relatedIterator = source.Select("sx:related", manager);

                if (relatedIterator != null && relatedIterator.Count > 0)
                {
                    while (relatedIterator.MoveNext())
                    {
                        FeedSynchronizationRelatedInformation relation = new FeedSynchronizationRelatedInformation();
                        if (relation.Load(relatedIterator.Current))
                        {
                            this.Relations.Add(relation);
                            wasLoaded = true;
                        }
                    }
                }
            }

            return(wasLoaded);
        }
Пример #15
0
        private string GetMap(XPathNodeIterator longitude, XPathNodeIterator latitude, decimal width, decimal height, string bingmapsKey, string culture, decimal?zoom, decimal?centreLongitude, decimal?centreLatitude, string pinType, ITracingService trace)
        {
            if (string.IsNullOrEmpty(pinType))
            {
                pinType = "46";
            }
            if (string.IsNullOrEmpty(width.ToString()))
            {
                width = 1010;
            }
            if (string.IsNullOrEmpty(height.ToString()))
            {
                height = 840;
            }

            // Add the long/latitudes for the map
            List <string> longitudes = new List <string>();
            List <string> latitudes  = new List <string>();

            while (longitude.MoveNext())
            {
                longitudes.Add(longitude.Current.Value);
            }

            while (latitude.MoveNext())
            {
                latitudes.Add(latitude.Current.Value);
            }

            // Check we have the same amount of both
            if (longitudes.Count != latitudes.Count)
            {
                throw new Exception("Longitude query returned different count to latitudes query");
            }

            // Create a list of pin points for the map request
            List <string> pinpoints = new List <string>();
            string        label     = @"";

            for (int i = 0; i < longitudes.Count; i++)
            {
                label = (longitudes.Count > 1) ? string.Format("{0}", (i + 1)) : @"";
                pinpoints.Add(string.Format("pp={1},{0};{2};{3}", longitudes[i].Replace(",", "."), latitudes[i].Replace(",", "."), pinType, label));
            }
            WebClient request = new WebClient();

            string data = string.Join("&", pinpoints);

            // If a zoom is specified then centre on the first pin and specify zoom
            string zoomData = string.Empty;

            decimal?zooming = MapHelper.CheckZooming(zoom, trace);

            /*(AZ) bug with center points*/
            if (zoom != null && (!centreLongitude.HasCorrectValue() || !centreLatitude.HasCorrectValue()))
            {
                // Centre on the pins because centre is not specified in the function call
                decimal minLon = decimal.Parse(longitudes[0]);
                decimal maxLon = minLon;
                decimal minLat = decimal.Parse(latitudes[0]);
                decimal maxLat = minLat;
                foreach (var x in longitudes)
                {
                    decimal value = decimal.Parse(x);
                    if (value < minLon)
                    {
                        minLon = value;
                    }
                    if (value > maxLon)
                    {
                        maxLon = value;
                    }
                }
                foreach (var y in latitudes)
                {
                    decimal value = decimal.Parse(y);
                    if (value < minLat)
                    {
                        minLat = value;
                    }
                    if (value > maxLat)
                    {
                        maxLat = value;
                    }
                }
                // Get centre of map
                var centreLon = 0m;
                var centreLat = 0m;

                // For list
                if (longitudes.Count > 2)
                {
                    List <decimal> Centre = MapHelper.CentralPoint(longitudes, latitudes, trace);
                    centreLon = Centre[1];
                    centreLat = Centre[0];
                }
                else
                {
                    centreLon = (maxLon + minLon) / 2;
                    centreLat = (maxLat + minLat) / 2;
                }
                zoomData = string.Format("/{1:N6},{0:N6}/{2:N0}", centreLon, centreLat, zooming);
            }
            else if (zooming != null && centreLongitude != null && centreLatitude != null)
            {
                // The centre coordinates are specified in the function call
                zoomData = string.Format("/{1:N6},{0:N6}/{2:N0}", centreLongitude, centreLatitude, zooming);
            }
            string mapUrl = string.Format(@"http://dev.virtualearth.net/REST/v1/Imagery/Map/Road{3}?mapSize={0},{1}&format=jpeg&c={4}&dcl=1&key={2}", width, height, bingmapsKey, zoomData, culture);

            byte[] imageData = new byte[0];

            imageData = request.UploadData(mapUrl, "POST", Encoding.UTF8.GetBytes(data));

            // Get the byte array and then base64 encode
            return(Convert.ToBase64String(imageData));
        }
Пример #16
0
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    lblLoad.Text = "Loading: ";
                    String fName  = ofd.FileName;
                    String sFName = ofd.FileName;
                    SBCFile   = new XPathDocument(fName);
                    nav       = SBCFile.CreateNavigator();
                    modListIt = nav.Select("//ModItem/PublishedFileId");

                    /*
                     * txtOutRAW.Clear();
                     *
                     * while (modListIt.MoveNext())
                     * {
                     *
                     *  txtOutRAW.AppendText(modListIt.Current.InnerXml + "\r\n");
                     *
                     *
                     * }
                     */



                    ModList.Clear();

                    while (modListIt.MoveNext())
                    {
                        ModInfo modInfo = new ModInfo();
                        modInfo.ID  = modListIt.Current.InnerXml;
                        modInfo.URL = "http://steamcommunity.com/sharedfiles/filedetails/?id=" + modInfo.ID;
                        int failcount = 0;
                        do
                        {
                            try
                            {
                                string workshopPage = web.DownloadString(modInfo.URL);
                                System.Threading.Thread.Sleep(500);
                                modInfo.title = Regex.Match(workshopPage, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups["Title"].Value;
                                modInfo.title = modInfo.title.Replace("Steam Workshop :: ", "");
                                if (failcount > 0)
                                {
                                    failcount = 0;
                                }
                            }
                            catch (Exception)
                            {
                                modInfo.title = "URL Timed Out";
                                failcount++;
                            }
                        }while(failcount > 0 && failcount < 4);
                        ModList.Add(modInfo);
                        lblLoad.Text += "|";
                        if (lblLoad.Text.TakeWhile(c => c == '|').Count() > 10)
                        {
                            lblLoad.Text = "Loading: ";
                        }

                        lblLoad.Refresh();
                        Application.DoEvents();
                        System.Threading.Thread.Sleep(500);
                    }

                    ModList = ModList.OrderBy(m => m.ID).ToList();

                    txtOutRAW.Clear();
                    txtOut.Clear();
                    foreach (ModInfo MI in ModList)
                    {
                        txtOutRAW.AppendText(MI.ID + "\r\n");
                        StringBuilder tOut = new StringBuilder();
                        tOut.Append("ModID: " + MI.ID + "       ");
                        tOut.Append("ModName: " + MI.title + "      ");
                        tOut.Append("Workshop URL: " + MI.URL + "\r\n");
                        txtOut.AppendText(tOut.ToString());
                    }
                    lblLoad.Text = "File Loaded";

                    //old code deprecated

                    /*
                     * while (modListIt.MoveNext())
                     * {
                     *  StringBuilder outputStr = new StringBuilder();
                     *  string ID = modListIt.Current.InnerXml;
                     *  outputStr.Append("ModID>>   " + ID);
                     *  string URL =  "http://steamcommunity.com/sharedfiles/filedetails/?id=" + ID;
                     *  try{
                     *      string workshopPage = web.DownloadString(URL);
                     *  string title = Regex.Match(workshopPage, @"\<title\b[^>]*\>\s*(?<Title>[\s\S]*?)\</title\>", RegexOptions.IgnoreCase).Groups["Title"].Value;
                     *  title = title.Replace("Steam Workshop :: ", "");
                     *  outputStr.Append("  >>NAME>>    " + title);
                     *  }
                     *  catch(Exception)
                     *  {
                     *      outputStr.Append("      >>NAME>>         BadURL");
                     *  }
                     *  outputStr.Append("  >>LINK>>    " + URL);
                     *  outputStr.Append("\r\n");
                     *  txtOut.AppendText(outputStr.ToString());
                     *
                     * }
                     *
                     */
                }

                else
                {
                    txtOutRAW.Text = "Unable To Read File";
                }
            }
            catch (Exception)
            {
                txtOutRAW.Text = "An Unknown Error Has Occurred";
            }
        }
Пример #17
0
 public void ReadSingleNode(String sNodePath)
 {
     // http://msdn2.microsoft.com/en-us/library/system.xml.xmlnode.selectsinglenode(VS.71).aspx
     // Select the node and place the results in an iterator.
     NodeIter = nav.Select(sNodePath);
     // Iterate through the results showing the element value.
     while (NodeIter.MoveNext())
         Console.WriteLine("Book Title: {0}", NodeIter.Current.Value);
 }
Пример #18
0
        /// <summary>
        /// Modifies the <see cref="AtomEntry"/> collection entities to match the supplied <see cref="XPathNavigator"/> data source.
        /// </summary>
        /// <param name="entry">The <see cref="AtomEntry"/> to be filled.</param>
        /// <param name="source">The <see cref="XPathNavigator"/> to extract information from.</param>
        /// <param name="manager">The <see cref="XmlNamespaceManager"/> used to resolve XML namespace prefixes.</param>
        /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> used to configure the fill operation.</param>
        /// <remarks>
        ///     This method expects the supplied <paramref name="source"/> to be positioned on the XML element that represents a <see cref="AtomEntry"/>.
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="entry"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="manager"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="settings"/> is a null reference (Nothing in Visual Basic).</exception>
        private static void FillEntryCollections(AtomEntry entry, XPathNavigator source, XmlNamespaceManager manager, SyndicationResourceLoadSettings settings)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(entry, "entry");
            Guard.ArgumentNotNull(source, "source");
            Guard.ArgumentNotNull(manager, "manager");
            Guard.ArgumentNotNull(settings, "settings");

            //------------------------------------------------------------
            //	Attempt to extract syndication information
            //------------------------------------------------------------
            XPathNodeIterator authorIterator      = source.Select("atom:author", manager);
            XPathNodeIterator categoryIterator    = source.Select("atom:category", manager);
            XPathNodeIterator contributorIterator = source.Select("atom:contributor", manager);
            XPathNodeIterator linkIterator        = source.Select("atom:link", manager);

            if (authorIterator != null && authorIterator.Count > 0)
            {
                while (authorIterator.MoveNext())
                {
                    AtomPersonConstruct author = new AtomPersonConstruct();
                    if (author.Load(authorIterator.Current, settings))
                    {
                        entry.Authors.Add(author);
                    }
                }
            }

            if (categoryIterator != null && categoryIterator.Count > 0)
            {
                while (categoryIterator.MoveNext())
                {
                    AtomCategory category = new AtomCategory();
                    if (category.Load(categoryIterator.Current, settings))
                    {
                        entry.Categories.Add(category);
                    }
                }
            }

            if (contributorIterator != null && contributorIterator.Count > 0)
            {
                while (contributorIterator.MoveNext())
                {
                    AtomPersonConstruct contributor = new AtomPersonConstruct();
                    if (contributor.Load(contributorIterator.Current, settings))
                    {
                        entry.Contributors.Add(contributor);
                    }
                }
            }

            if (linkIterator != null && linkIterator.Count > 0)
            {
                while (linkIterator.MoveNext())
                {
                    AtomLink link = new AtomLink();
                    if (link.Load(linkIterator.Current, settings))
                    {
                        entry.Links.Add(link);
                    }
                }
            }
        }
Пример #19
0
        /// <summary>
        /// Create a SOP Class instance using a raw xml file (that is generated by the ODD).
        /// </summary>
        /// <param name="path">The file path.</param>
        /// <returns>The created SopClass instance.</returns>
        public static SopClass Create(string path)
        {
            SopClass sopClass = new SopClass();

            try
            {
                XPathNodeIterator systemNodes   = null;
                XPathNodeIterator sopClassNodes = null;
                XPathNodeIterator dimseNodes    = null;

                sopClass.path = path;

                XPathDocument  document  = new XPathDocument(path);
                XPathNavigator navigator = document.CreateNavigator();


                //
                // Determine system name and system version.
                //

                systemNodes = navigator.Select("/System");
                if (systemNodes.MoveNext())
                {
                    sopClass.systemName    = systemNodes.Current.GetAttribute("Name", "");
                    sopClass.systemVersion = systemNodes.Current.GetAttribute("Version", "");

                    if ((sopClass.systemName.Length == 0) || (sopClass.systemVersion.Length == 0))
                    {
                        throw new Exception("System name and/or system version not found.");
                    }
                }
                else
                {
                    throw new Exception("/System node not found in \"" + path + "\"");
                }


                //
                // Determine name and UID.
                //

                if (sopClass != null)
                {
                    sopClassNodes = systemNodes.Current.Select("ApplicationEntity/SOPClass");
                    if (sopClassNodes.MoveNext())
                    {
                        sopClass.name = sopClassNodes.Current.GetAttribute("Name", "");
                        sopClass.uid  = sopClassNodes.Current.GetAttribute("UID", "");

                        if ((sopClass.name.Length == 0) || (sopClass.uid.Length == 0))
                        {
                            throw new Exception("Name and/or uid not found.");
                        }
                    }
                    else
                    {
                        throw new Exception("SOPClass node not found.");
                    }
                }


                //
                // Determine DimseDataSetPairs.
                //

                if (sopClass != null)
                {
                    dimseNodes = sopClassNodes.Current.Select("Dimse");

                    foreach (XPathNavigator dimseNode in dimseNodes)
                    {
                        string dimseName = dimseNode.GetAttribute("Name", "");

                        if (dimseName.Substring(dimseName.Length - 2, 2) == "RQ")
                        {
                            DimseDataSetPair dimseDataSetPair = DimseDataSetPair.Create(sopClass, dimseNode);
                            sopClass.DimseDataSetPairs.Add(dimseDataSetPair);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                throw new Exception("Exception occured while reading file \"" + path + "\".\n" + exception.Message);
            }

            return(sopClass);
        }
Пример #20
0
        /// <summary>
        /// Modifies the <see cref="AtomFeed"/> collection entities to match the supplied <see cref="XPathNavigator"/> data source.
        /// </summary>
        /// <param name="feed">The <see cref="AtomFeed"/> to be filled.</param>
        /// <param name="source">The <see cref="XPathNavigator"/> to extract information from.</param>
        /// <param name="manager">The <see cref="XmlNamespaceManager"/> used to resolve XML namespace prefixes.</param>
        /// <param name="settings">The <see cref="SyndicationResourceLoadSettings"/> used to configure the fill operation.</param>
        /// <remarks>
        ///     This method expects the supplied <paramref name="source"/> to be positioned on the XML element that represents a <see cref="AtomFeed"/>.
        /// </remarks>
        /// <exception cref="ArgumentNullException">The <paramref name="feed"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="source"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="manager"/> is a null reference (Nothing in Visual Basic).</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="settings"/> is a null reference (Nothing in Visual Basic).</exception>
        private static void FillFeedCollections(AtomFeed feed, XPathNavigator source, XmlNamespaceManager manager, SyndicationResourceLoadSettings settings)
        {
            //------------------------------------------------------------
            //	Validate parameter
            //------------------------------------------------------------
            Guard.ArgumentNotNull(feed, "feed");
            Guard.ArgumentNotNull(source, "source");
            Guard.ArgumentNotNull(manager, "manager");
            Guard.ArgumentNotNull(settings, "settings");

            //------------------------------------------------------------
            //	Attempt to extract syndication information
            //------------------------------------------------------------
            XPathNodeIterator authorIterator      = source.Select("atom:author", manager);
            XPathNodeIterator categoryIterator    = source.Select("atom:category", manager);
            XPathNodeIterator contributorIterator = source.Select("atom:contributor", manager);
            XPathNodeIterator linkIterator        = source.Select("atom:link", manager);
            XPathNodeIterator entryIterator       = source.Select("atom:entry", manager);

            if (authorIterator != null && authorIterator.Count > 0)
            {
                while (authorIterator.MoveNext())
                {
                    AtomPersonConstruct author = new AtomPersonConstruct();
                    if (author.Load(authorIterator.Current, settings))
                    {
                        feed.Authors.Add(author);
                    }
                }
            }

            if (categoryIterator != null && categoryIterator.Count > 0)
            {
                while (categoryIterator.MoveNext())
                {
                    AtomCategory category = new AtomCategory();
                    if (category.Load(categoryIterator.Current, settings))
                    {
                        feed.Categories.Add(category);
                    }
                }
            }

            if (contributorIterator != null && contributorIterator.Count > 0)
            {
                while (contributorIterator.MoveNext())
                {
                    AtomPersonConstruct contributor = new AtomPersonConstruct();
                    if (contributor.Load(contributorIterator.Current, settings))
                    {
                        feed.Contributors.Add(contributor);
                    }
                }
            }

            if (entryIterator != null && entryIterator.Count > 0)
            {
                int counter = 0;
                while (entryIterator.MoveNext())
                {
                    AtomEntry entry = new AtomEntry();
                    counter++;

                    Atom10SyndicationResourceAdapter.FillEntry(entry, entryIterator.Current, manager, settings);

                    if (settings.RetrievalLimit != 0 && counter > settings.RetrievalLimit)
                    {
                        break;
                    }

                    ((Collection <AtomEntry>)feed.Entries).Add(entry);
                }
            }

            if (linkIterator != null && linkIterator.Count > 0)
            {
                while (linkIterator.MoveNext())
                {
                    AtomLink link = new AtomLink();
                    if (link.Load(linkIterator.Current, settings))
                    {
                        feed.Links.Add(link);
                    }
                }
            }
        }
Пример #21
0
        public static List <Order> LoadXmlCore(XmlDocument doc, bool sortByPayingTime, bool extractOrderSubject)
        {
            if (null == doc)
            {
                return(null);
            }

            string          xpath = ".//o";
            XPathNavigator  nav   = doc.CreateNavigator();
            XPathExpression exp   = nav.Compile(xpath);

            exp.AddSort(sortByPayingTime ? "@pt" : "@dt", new DateTimeComparer());
            XPathNodeIterator iterator = nav.Select(exp);

            List <Order> orders = new List <Order>();

            //iterator.Current.att

            while (iterator.MoveNext())
            {
                DateTime dealTime = DateTime.Parse(iterator.Current.GetAttribute("dt", string.Empty));
                //TimeSpan ts = DateTime.Now - dealTime;
                //if (ts.TotalDays >= 30)
                //    break;

                string orderId       = iterator.Current.GetAttribute("oid", string.Empty);
                string buyerAccount  = iterator.Current.GetAttribute("ba", string.Empty);
                string alipayAccount = iterator.Current.GetAttribute("aa", string.Empty);
                //Trace.WriteLine(dealTime.ToString("yyyy-MM-dd HH:mm:ss"));
                Order order = new Order(orderId, buyerAccount, alipayAccount, dealTime);
                orders.Add(order);

                order._payingTime             = DateTime.Parse(iterator.Current.GetAttribute("pt", string.Empty));
                order._goodsMoney             = float.Parse(iterator.Current.GetAttribute("gm", string.Empty));
                order._freight                = float.Parse(iterator.Current.GetAttribute("f", string.Empty));
                order._totalMoney             = float.Parse(iterator.Current.GetAttribute("tm", string.Empty));
                order._realPayMoney           = float.Parse(iterator.Current.GetAttribute("pm", string.Empty));
                order._orderStatus            = (OrderStatus)Enum.Parse(typeof(OrderStatus), iterator.Current.GetAttribute("s", string.Empty));
                order._buyerRemark            = iterator.Current.GetAttribute("r", string.Empty);
                order._recipientName          = iterator.Current.GetAttribute("rn", string.Empty);
                order._recipientAddress       = iterator.Current.GetAttribute("ra", string.Empty);
                order._editedRecipientAddress = iterator.Current.GetAttribute("era", string.Empty);
                order._phoneNumber            = iterator.Current.GetAttribute("p", string.Empty);
                order._mobileNumber           = iterator.Current.GetAttribute("m", string.Empty);
                order._shipmentNumber         = iterator.Current.GetAttribute("sn", string.Empty);
                order._shipmentCompany        = iterator.Current.GetAttribute("sc", string.Empty);
                //order._itemSubject = iterator.Current.GetAttribute("i", string.Empty); // obsoleted. 2014/10/08.
                order._itemAmount    = int.Parse(iterator.Current.GetAttribute("ia", string.Empty));
                order._remark        = iterator.Current.GetAttribute("c", string.Empty);
                order._closingReason = iterator.Current.GetAttribute("cr", string.Empty);
                order._isPhoneOrder  = bool.Parse(iterator.Current.GetAttribute("po", string.Empty));

                if (null != iterator.Current.GetAttribute("pr", string.Empty))
                {
                    order._prepared = bool.Parse(iterator.Current.GetAttribute("pr", string.Empty));
                }

                order._items = iterator.Current.GetAttribute("is", string.Empty);
                if (extractOrderSubject)
                {
                    order.ExtractSubject(Egode.OrderItemSubjectInfo.SubjectInfos);
                }
            }

            return(orders);
        }
Пример #22
0
        /// <summary>
        /// Modifies the <see cref="ApmlDocument"/> to match the data source.
        /// </summary>
        /// <param name="resource">The <see cref="ApmlDocument"/> to be filled.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="resource"/> is a null reference (Nothing in Visual Basic).</exception>
        public void Fill(ApmlDocument resource)
        {
            Guard.ArgumentNotNull(resource, "resource");

            XmlNamespaceManager manager = ApmlUtility.CreateNamespaceManager(this.Navigator.NameTable);

            XPathNavigator headNavigator = this.Navigator.SelectSingleNode("apml:APML/apml:Head", manager);

            if (headNavigator != null)
            {
                resource.Head.Load(headNavigator, this.Settings);
            }

            XPathNavigator bodyNavigator = this.Navigator.SelectSingleNode("apml:APML/apml:Body", manager);

            if (bodyNavigator != null)
            {
                if (bodyNavigator.HasAttributes)
                {
                    string defaultProfileAttribute = bodyNavigator.GetAttribute("defaultprofile", String.Empty);
                    if (!String.IsNullOrEmpty(defaultProfileAttribute))
                    {
                        resource.DefaultProfileName = defaultProfileAttribute;
                    }
                }

                XPathNodeIterator profileIterator = bodyNavigator.Select("apml:Profile", manager);
                if (profileIterator != null && profileIterator.Count > 0)
                {
                    int counter = 0;
                    while (profileIterator.MoveNext())
                    {
                        ApmlProfile profile = new ApmlProfile();
                        counter++;

                        if (profile.Load(profileIterator.Current, this.Settings))
                        {
                            if (this.Settings.RetrievalLimit != 0 && counter > this.Settings.RetrievalLimit)
                            {
                                break;
                            }

                            ((Collection <ApmlProfile>)resource.Profiles).Add(profile);
                        }
                    }
                }

                XPathNodeIterator applicationIterator = bodyNavigator.Select("apml:Applications/apml:Application", manager);
                if (applicationIterator != null && applicationIterator.Count > 0)
                {
                    while (applicationIterator.MoveNext())
                    {
                        ApmlApplication application = new ApmlApplication();
                        if (application.Load(applicationIterator.Current, this.Settings))
                        {
                            resource.Applications.Add(application);
                        }
                    }
                }
            }

            SyndicationExtensionAdapter adapter = new SyndicationExtensionAdapter(this.Navigator.SelectSingleNode("apml:APML", manager), this.Settings);

            adapter.Fill(resource, manager);
        }
Пример #23
0
        /// <summary>
        /// Read the settings from Office 2003 SpreadsheetML XML file into a DataTable.
        /// </summary>
        /// <param name="inputFile"></param>
        /// <returns></returns>
        internal static DataTable ReadSettingsFromSpreadsheetMl(string inputFile)
        {
            // Read the SpreadsheetML XML file into a new XPathDocument.
            XPathDocument doc = new XPathDocument(inputFile);

            // Create a new, empty DataTable to hold the data. The resulting structure of the DataTable will
            // be identical to that produced with a binary XLS file.
            DataTable dt = null;

            XPathNavigator nav = doc.CreateNavigator();

            // Check the validity of the XML
            if (!IsValidSpreadsheetMl(nav))
            {
                throw new ArgumentException("The input file is not a valid SpreadsheetML file or it is an unsupported version.");
            }

            // Create a namespace manager and register the SpreadsheetML namespace and prefix
            XmlNamespaceManager nm = new XmlNamespaceManager(nav.NameTable);

            nm.AddNamespace("ss", "urn:schemas-microsoft-com:office:spreadsheet");

            // Locate the Settings worksheet
            XPathNavigator worksheetNav = nav.SelectSingleNode("//ss:Worksheet[@ss:Name='Settings']/ss:Table", nm);

            if (worksheetNav == null)
            {
                throw new ArgumentException("The input file does not contain a worksheet entitled Settings.");
            }

            dt = InitializeDataTable(worksheetNav, nm);

            // Select all of the rows in the worksheet
            XPathNodeIterator rowsIterator = worksheetNav.Select("//ss:Row", nm);

            // Loop through the rows
            while (rowsIterator.MoveNext())
            {
                // Select all of the cells in the row
                XPathNodeIterator cellsIterator = rowsIterator.Current.Select("ss:Cell", nm);

                int columnIndex = 0;

                // Create a new DataRow to hold the incoming values
                DataRow newRow = dt.NewRow();

                // Loop through the cells
                while (cellsIterator.MoveNext())
                {
                    // Select the comment value in the cell, if present
                    XPathNavigator commentNav = cellsIterator.Current.SelectSingleNode("ss:Comment/ss:Data", nm);

                    if (commentNav != null)
                    {
                        string commentValue = commentNav.Value;

                        if (!string.IsNullOrEmpty(commentValue))
                        {
                            newRow["Comment"] = commentNav.Value.Replace("\n", string.Empty);
                        }
                    }

                    // Check for Index attribute on Cell
                    if (cellsIterator.Current.HasAttributes)
                    {
                        XPathNavigator indexAttribute = cellsIterator.Current.SelectSingleNode("@ss:Index", nm);

                        if (indexAttribute != null)
                        {
                            // SpreadsheetML stores Index as 1 based, not zero based.
                            columnIndex = int.Parse(indexAttribute.Value) - 1;
                        }
                    }

                    // Select the data value in the cell, if present
                    XPathNavigator dataNav = cellsIterator.Current.SelectSingleNode("ss:Data", nm);

                    if (dataNav != null)
                    {
                        newRow[columnIndex] = dataNav.Value;
                    }

                    columnIndex++;
                }

                // Add the newly populated DataRow to the DataTable
                dt.Rows.Add(newRow);
            }

            return(dt);
        }
Пример #24
0
        public IEnumerable <EditorDataItem> GetEditorDataItems(int currentId, int parentId)
        {
            XmlDocument           xmlDocument;
            List <EditorDataItem> editorDataItems = new List <EditorDataItem>();

            switch (this.XmlData)
            {
            case "content":
                xmlDocument = uQuery.GetPublishedXml(uQuery.UmbracoObjectType.Document);
                break;

            case "media":
                xmlDocument = uQuery.GetPublishedXml(uQuery.UmbracoObjectType.Media);
                break;

            case "members":
                xmlDocument = uQuery.GetPublishedXml(uQuery.UmbracoObjectType.Member);
                break;

            case "url":
                xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(Helper.GetDataFromUrl(this.Url));
                break;

            default:
                xmlDocument = null;
                break;
            }

            if (xmlDocument != null)
            {
                // really the logic is self-or-parent-or-root
                int ancestorOrSelfId = currentId > 0 ? currentId : parentId > 0 ? parentId : -1;

                string xPath = this.XPath.Replace("$ancestorOrSelf", string.Concat("/descendant::*[@id='", ancestorOrSelfId, "']"));

                XPathNavigator    xPathNavigator    = xmlDocument.CreateNavigator();
                XPathNodeIterator xPathNodeIterator = xPathNavigator.Select(xPath);
                List <string>     keys = new List <string>(); // used to keep track of keys, so that duplicates aren't added

                string key;
                string label;

                while (xPathNodeIterator.MoveNext())
                {
                    // media xml is wrapped in a <Media id="-1" /> node to be valid, exclude this from any results
                    // member xml is wrapped in <Members id="-1" /> node to be valid, exclude this from any results
                    if (xPathNodeIterator.CurrentPosition > 1 ||
                        !(xPathNodeIterator.Current.GetAttribute("id", string.Empty) == "-1" &&
                          (xPathNodeIterator.Current.Name == "Media" || xPathNodeIterator.Current.Name == "Members")))
                    {
                        key = xPathNodeIterator.Current.SelectSingleNode(this.KeyXPath).Value;

                        // only add item if it has a unique key - failsafe
                        if (!string.IsNullOrWhiteSpace(key) && !keys.Any(x => x == key))
                        {
                            // TODO: ensure key doens't contain any commas (keys are converted saved as csv)
                            keys.Add(key); // add key so that it's not reused

                            // set default markup to use the configured label XPath
                            label = xPathNodeIterator.Current.SelectSingleNode(this.LabelXPath).Value;

                            editorDataItems.Add(new EditorDataItem()
                            {
                                Key   = key,
                                Label = label
                            });
                        }
                    }
                }
            }

            return(editorDataItems);
        }
Пример #25
0
        private void WriteValue(XPathNavigator parent, SyntaxWriter writer)
        {
            XPathNavigator type  = parent.SelectSingleNode(attributeTypeExpression);
            XPathNavigator value = parent.SelectSingleNode(valueExpression);

            if (value == null)
            {
                Console.WriteLine("null value");
            }

            switch (value.LocalName)
            {
            case "nullValue":
                writer.WriteKeyword("nullptr");
                break;

            case "typeValue":
                writer.WriteKeyword("typeof");
                writer.WriteString("(");
                WriteTypeReference(value.SelectSingleNode(typeExpression), false, writer);
                writer.WriteString(")");
                break;

            case "enumValue":
                XPathNodeIterator fields = value.SelectChildren(XPathNodeType.Element);
                while (fields.MoveNext())
                {
                    string name = fields.Current.GetAttribute("name", String.Empty);
                    if (fields.CurrentPosition > 1)
                    {
                        writer.WriteString("|");
                    }
                    WriteTypeReference(type, writer);
                    writer.WriteString("::");
                    writer.WriteString(name);
                }
                break;

            case "value":
                string text   = value.Value;
                string typeId = type.GetAttribute("api", String.Empty);
                switch (typeId)
                {
                case "T:System.String":
                    writer.WriteString("L\"");
                    writer.WriteString(text);
                    writer.WriteString("\"");
                    break;

                case "T:System.Boolean":
                    bool bool_value = Convert.ToBoolean(text);
                    if (bool_value)
                    {
                        writer.WriteKeyword("true");
                    }
                    else
                    {
                        writer.WriteKeyword("false");
                    }
                    break;

                case "T:System.Char":
                    writer.WriteString(@"L'");
                    writer.WriteString(text);
                    writer.WriteString(@"'");
                    break;
                }
                break;
            }
        }
Пример #26
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ArrayList arr = new ArrayList();

            string xmlText = Request["xml"];

            if (arr.Count > 0)
            {
                xmlText = (string)arr[0];
            }
            if (xmlText != null)
            {
                Log.WriteLine("", ">>>>>>>>>>>>>>>>  IN  >>>>>>>>>>>>>>>>");
                Log.WriteLine("", xmlText);
                Log.WriteLine("", ">>>>>>>>>>>>>>>>  IN  >>>>>>>>>>>>>>>>");

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(xmlText);
                XmlNodeReader     nodeReader         = new XmlNodeReader(doc);
                XPathDocument     xpathDoc           = new XPathDocument(nodeReader);
                XPathNavigator    xpathNav           = xpathDoc.CreateNavigator();
                XPathNodeIterator xpathParamNodeIter = xpathNav.Select(@"webmail/param");
                string            action             = "";
                while (xpathParamNodeIter.MoveNext())
                {
                    string name = xpathParamNodeIter.Current.GetAttribute("name", "");
                    string val  = xpathParamNodeIter.Current.GetAttribute("value", "");
                    if (string.IsNullOrEmpty(val))
                    {
                        val = Utils.DecodeHtml(xpathParamNodeIter.Current.Value);
                    }

                    switch (name.ToLower(CultureInfo.InvariantCulture))
                    {
                    case "request":
                        action = val;
                        break;
                    }
                }

                XPathNavigator textNode;
                switch (action)
                {
                case "spell":
                    textNode = xpathNav.SelectSingleNode(@"webmail/text");
                    string text = Utils.DecodeHtmlBody(textNode.Value);
                    doc = CreateServerXmlDocumentResponse(action, text);

                    break;

                case "suggest":
                    textNode = xpathNav.SelectSingleNode(@"webmail/word");
                    string suggestWord = Utils.DecodeHtml(textNode.Value);
                    doc = CreateServerXmlDocumentResponse(action, suggestWord);
                    break;
                }

                Response.Clear();
                Response.ContentType = @"text/xml";
                Log.WriteLine("", "<<<<<<<<<<<<<<<<<  OUT  <<<<<<<<<<<<<<<");
                Log.WriteLine("", doc.OuterXml);
                Log.WriteLine("", "<<<<<<<<<<<<<<<<<  OUT  <<<<<<<<<<<<<<<");
                Response.Write(doc.OuterXml);
                Response.End();
            }
        }
    private static string GetMenuHtml(XPathNavigator nav, string e = "ul", object attributes = null)
    {
        List <String> item = new List <String>();

        XPathNodeIterator nodes = nav.Select("items/item");

        TagBuilder holder = new TagBuilder(e);

        if (attributes != null)
        {
            IDictionary <string, object> htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(attributes);
            holder.MergeAttributes(htmlAttributes);
        }

        while (nodes.MoveNext())
        {
            TagBuilder a    = new TagBuilder("a");
            TagBuilder span = new TagBuilder("span");
            TagBuilder li   = new TagBuilder("li");

            string url   = nodes.Current.GetAttribute("link", string.Empty);
            string text  = nodes.Current.GetAttribute("text", string.Empty);
            string title = nodes.Current.GetAttribute("title", string.Empty);

            span.InnerHtml = text;

            a.MergeAttribute("href", url);

            if (!String.IsNullOrEmpty(title))
            {
                a.MergeAttribute("title", title);
            }

            a.InnerHtml = span.ToString();

            List <String> classes = new List <String>();

            if (url == HttpContext.Current.Request.Url.AbsolutePath)
            {
                classes.Add("active");
            }

            if (nodes.Count == nodes.CurrentPosition)
            {
                classes.Add("last");
            }
            else if (nodes.CurrentPosition == 1)
            {
                classes.Add("first");
            }

            if (nodes.Current.HasChildren)
            {
                li.InnerHtml = a.ToString() + GetMenuHtml(nodes.Current, e);

                if (li.InnerHtml.Contains("class=\"active"))
                {
                    classes.Add("active-trail");
                }

                classes.Add("leaf");
            }
            else
            {
                li.InnerHtml = a.ToString();
            }

            if (classes.Count > 0)
            {
                li.MergeAttribute("class", string.Join(" ", classes.ToArray()));
            }

            item.Add(li.ToString() + "\n");
        }

        holder.InnerHtml = string.Join("", item.ToArray());

        return(holder.ToString());
    }
Пример #28
0
    // For a list of platform targets, gather all the required folder names for the generated soundbanks. The goal is to know the list of required
    // folder names for a list of platforms. The size of the returned array is not guaranteed to be the safe size at the targets array since
    // a single platform is no guaranteed to output a single soundbank folder.
    public static bool GetWwiseSoundBankDestinationFoldersByUnityPlatform(BuildTarget target, string WwiseProjectPath, out string[] paths, out string[] platformNames)
    {
        paths         = null;
        platformNames = null;

        try
        {
            if (WwiseProjectPath.Length == 0)
            {
                return(false);
            }

            XmlDocument doc = new XmlDocument();
            doc.Load(WwiseProjectPath);
            XPathNavigator configNavigator = doc.CreateNavigator();

            List <string> pathsList         = new List <string>();
            List <string> platformNamesList = new List <string>();

            if (platformMapping.ContainsKey(target))
            {
                string[] referencePlatforms = platformMapping[target];

                // For each valid reference platform name for the provided Unity platform enum, list all the valid platform names
                // defined in the Wwise project XML, and for each of those accumulate the sound bank folders. In the end,
                // resultList will contain a list of soundbank folders that are generated for the provided unity platform enum.

                foreach (string reference in referencePlatforms)
                {
                    XPathExpression   expression = XPathExpression.Compile(string.Format("//Platforms/Platform[@ReferencePlatform='{0}']", reference));
                    XPathNodeIterator nodes      = configNavigator.Select(expression);

                    while (nodes.MoveNext())
                    {
                        string platform = nodes.Current.GetAttribute("Name", "");

                        // If the sound bank path information was located either in the user configuration or the project configuration, acquire the paths
                        // for the provided platform.
                        string sbPath = null;
                        if (s_ProjectBankPaths.TryGetValue(platform, out sbPath))
                        {
#if UNITY_EDITOR_OSX
                            sbPath = sbPath.Replace('\\', Path.DirectorySeparatorChar);
#endif
                            pathsList.Add(sbPath);
                            platformNamesList.Add(platform);
                        }
                    }
                }
            }

            if (pathsList.Count != 0)
            {
                paths         = pathsList.ToArray();
                platformNames = platformNamesList.ToArray();
                return(true);
            }
        }
        catch (Exception e)
        {
            Debug.LogException(e);
        }

        return(false);
    }
Пример #29
0
        void FillContent()
        {
            // Fill address in address text frame
            XPathNavigator item      = SelectItem("/invoice/to");
            Paragraph      paragraph = this.addressFrame.AddParagraph();

            paragraph.AddText(GetValue(item, "name/singleName"));
            paragraph.AddLineBreak();
            paragraph.AddText(GetValue(item, "address/line1"));
            paragraph.AddLineBreak();
            paragraph.AddText(GetValue(item, "address/postalCode") + " " + GetValue(item, "address/city"));

            // Iterate the invoice items
            double            totalExtendedPrice = 0;
            XPathNodeIterator iter = this.navigator.Select("/invoice/items/*");

            while (iter.MoveNext())
            {
                item = iter.Current;
                double quantity = GetValueAsDouble(item, "quantity");
                double price    = GetValueAsDouble(item, "price");
                double discount = GetValueAsDouble(item, "discount");

                // Each item fills two rows
                Row row1 = this.table.AddRow();
                Row row2 = this.table.AddRow();
                row1.TopPadding                 = 1.5;
                row1.Cells[0].Shading.Color     = Colors.Gray;
                row1.Cells[0].VerticalAlignment = VerticalAlignment.Center;
                row1.Cells[0].MergeDown         = 1;
                row1.Cells[1].Format.Alignment  = ParagraphAlignment.Left;
                row1.Cells[1].MergeRight        = 3;
                row1.Cells[5].Shading.Color     = Colors.Gray;
                row1.Cells[5].MergeDown         = 1;

                row1.Cells[0].AddParagraph(GetValue(item, "itemNumber"));
                paragraph = row1.Cells[1].AddParagraph();
                paragraph.AddFormattedText(GetValue(item, "title"), TextFormat.Bold);
                paragraph.AddFormattedText(" by ", TextFormat.Italic);
                paragraph.AddText(GetValue(item, "author"));
                row2.Cells[1].AddParagraph(GetValue(item, "quantity"));
                row2.Cells[2].AddParagraph(price.ToString("0.00") + " €");
                row2.Cells[3].AddParagraph(discount.ToString("0.0"));
                row2.Cells[4].AddParagraph();
                row2.Cells[5].AddParagraph(price.ToString("0.00"));
                double extendedPrice = quantity * price;
                extendedPrice = extendedPrice * (100 - discount) / 100;
                row1.Cells[5].AddParagraph(extendedPrice.ToString("0.00") + " €");
                row1.Cells[5].VerticalAlignment = VerticalAlignment.Bottom;
                totalExtendedPrice += extendedPrice;

                this.table.SetEdge(0, this.table.Rows.Count - 2, 6, 2, Edge.Box, BorderStyle.Single, 0.75);
            }

            // Add an invisible row as a space line to the table
            Row row = this.table.AddRow();

            row.Borders.Visible = false;

            // Add the total price row
            row = this.table.AddRow();
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].AddParagraph("Total Price");
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight       = 4;
            row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");

            // Add the VAT row
            row = this.table.AddRow();
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].AddParagraph("VAT (19%)");
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight       = 4;
            row.Cells[5].AddParagraph((0.19 * totalExtendedPrice).ToString("0.00") + " €");

            // Add the additional fee row
            row = this.table.AddRow();
            row.Cells[0].Borders.Visible = false;
            row.Cells[0].AddParagraph("Shipping and Handling");
            row.Cells[5].AddParagraph(0.ToString("0.00") + " €");
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight       = 4;

            // Add the total due row
            row = this.table.AddRow();
            row.Cells[0].AddParagraph("Total Due");
            row.Cells[0].Borders.Visible  = false;
            row.Cells[0].Format.Font.Bold = true;
            row.Cells[0].Format.Alignment = ParagraphAlignment.Right;
            row.Cells[0].MergeRight       = 4;
            totalExtendedPrice           += 0.19 * totalExtendedPrice;
            row.Cells[5].AddParagraph(totalExtendedPrice.ToString("0.00") + " €");

            // Set the borders of the specified cell range
            this.table.SetEdge(5, this.table.Rows.Count - 4, 1, 4, Edge.Box, BorderStyle.Single, 0.75);

            // Add the notes paragraph
            paragraph = this.document.LastSection.AddParagraph();
            paragraph.Format.SpaceBefore      = "1cm";
            paragraph.Format.Borders.Width    = 0.75;
            paragraph.Format.Borders.Distance = 3;
            paragraph.Format.Borders.Color    = Colors.Black;
            paragraph.Format.Shading.Color    = Colors.Gray;
            item = SelectItem("/invoice");
            paragraph.AddText(GetValue(item, "notes"));
        }
Пример #30
0
        private static void PerformXmlReplace(PwDatabase pd, XmlReplaceOptions opt,
                                              IStatusLogger sl)
        {
            if (opt.SelectNodesXPath.Length == 0)
            {
                return;
            }
            if (opt.Operation == XmlReplaceOp.None)
            {
                return;
            }

            bool bRemove    = (opt.Operation == XmlReplaceOp.RemoveNodes);
            bool bReplace   = (opt.Operation == XmlReplaceOp.ReplaceData);
            bool bMatchCase = ((opt.Flags & XmlReplaceFlags.CaseSensitive) != XmlReplaceFlags.None);
            bool bRegex     = ((opt.Flags & XmlReplaceFlags.Regex) != XmlReplaceFlags.None);

            Regex rxFind = null;

            if (bReplace && bRegex)
            {
                rxFind = new Regex(opt.FindText, (bMatchCase ? RegexOptions.None :
                                                  RegexOptions.IgnoreCase));
            }

            EnsureStandardFieldsExist(pd);

            KdbxFile     kdbxOrg = new KdbxFile(pd);
            MemoryStream msOrg   = new MemoryStream();

            kdbxOrg.Save(msOrg, null, KdbxFormat.PlainXml, sl);
            byte[] pbXml = msOrg.ToArray();
            msOrg.Close();
            string strXml = StrUtil.Utf8.GetString(pbXml);

            XmlDocument xd = XmlUtilEx.CreateXmlDocument();

            xd.LoadXml(strXml);

            XPathNavigator    xpNavRoot = xd.CreateNavigator();
            XPathNodeIterator xpIt      = xpNavRoot.Select(opt.SelectNodesXPath);

            // XPathNavigators must be cloned to make them independent
            List <XPathNavigator> lNodes = new List <XPathNavigator>();

            while (xpIt.MoveNext())
            {
                lNodes.Add(xpIt.Current.Clone());
            }

            if (lNodes.Count == 0)
            {
                return;
            }

            for (int i = lNodes.Count - 1; i >= 0; --i)
            {
                if ((sl != null) && !sl.ContinueWork())
                {
                    return;
                }

                XPathNavigator xpNav = lNodes[i];

                if (bRemove)
                {
                    xpNav.DeleteSelf();
                }
                else if (bReplace)
                {
                    ApplyReplace(xpNav, opt, rxFind);
                }
                else
                {
                    Debug.Assert(false);
                }                                             // Unknown action
            }

            MemoryStream msMod = new MemoryStream();

            using (XmlWriter xw = XmlUtilEx.CreateXmlWriter(msMod))
            {
                xd.Save(xw);
            }
            byte[] pbMod = msMod.ToArray();
            msMod.Close();

            PwDatabase pdMod = new PwDatabase();

            msMod = new MemoryStream(pbMod, false);
            try
            {
                KdbxFile kdbxMod = new KdbxFile(pdMod);
                kdbxMod.Load(msMod, KdbxFormat.PlainXml, sl);
            }
            catch (Exception)
            {
                throw new Exception(KPRes.XmlModInvalid + MessageService.NewParagraph +
                                    KPRes.OpAborted + MessageService.NewParagraph +
                                    KPRes.DbNoModBy.Replace(@"{PARAM}", @"'" + KPRes.XmlReplace + @"'"));
            }
            finally { msMod.Close(); }

            PrepareModDbForMerge(pdMod, pd);

            pd.Modified          = true;
            pd.UINeedsIconUpdate = true;
            pd.MergeIn(pdMod, PwMergeMethod.Synchronize, sl);
        }
Пример #31
0
        /// <summary>
        /// Wraps creation of translation controls.
        /// </summary>
        /// <param name="srcFile">The SRC file.</param>
        /// <param name="dstFile">The DST file.</param>
        private void PopulateTranslations([NotNull] string srcFile, [NotNull] string dstFile)
        {
            this.bUpdate = false;

            try
            {
                var docSrc = new XmlDocument();
                var docDst = new XmlDocument();

                docSrc.Load(srcFile);
                docDst.Load(dstFile);

                XPathNavigator navSrc = docSrc.DocumentElement.CreateNavigator();
                XPathNavigator navDst = docDst.DocumentElement.CreateNavigator();

                this.ResourcesNamespaces.Clear();
                if (navDst.MoveToFirstNamespace())
                {
                    do
                    {
                        this.ResourcesNamespaces.Add(navDst.Name, navDst.Value);
                    }while (navDst.MoveToNextNamespace());
                }

                navDst.MoveToRoot();
                navDst.MoveToFirstChild();

                this.ResourcesAttributes.Clear();
                if (navDst.MoveToFirstAttribute())
                {
                    do
                    {
                        this.ResourcesAttributes.Add(navDst.Name, navDst.Value);
                    }while (navDst.MoveToNextAttribute());
                }

                navDst.MoveToRoot();
                navDst.MoveToFirstChild();

                foreach (XPathNavigator pageItemNavigator in navSrc.Select("page"))
                {
                    // int pageResourceCount = 0;
                    string pageNameAttributeValue = pageItemNavigator.GetAttribute("name", string.Empty);

                    this.CreatePageResourceHeader(pageNameAttributeValue);

                    XPathNodeIterator resourceItemCollection = pageItemNavigator.Select("Resource");

                    foreach (XPathNavigator resourceItem in resourceItemCollection)
                    {
                        var resourceTagAttributeValue = resourceItem.GetAttribute("tag", string.Empty);

                        XPathNodeIterator iteratorSe =
                            navDst.Select(
                                "/Resources/page[@name=\"" + pageNameAttributeValue + "\"]/Resource[@tag=\""
                                + resourceTagAttributeValue + "\"]");

                        if (iteratorSe.Count <= 0)
                        {
                            // pageResourceCount++;

                            // Generate Missing Languages
                            this.CreatePageResourceControl(
                                pageNameAttributeValue,
                                resourceTagAttributeValue,
                                resourceItem.Value,
                                resourceItem.Value);

                            this.bUpdate = true;
                        }

                        while (iteratorSe.MoveNext())
                        {
                            // pageResourceCount++;
                            if (!iteratorSe.Current.Value.Equals(resourceItem.Value, StringComparison.OrdinalIgnoreCase))
                            {
                            }

                            this.CreatePageResourceControl(
                                pageNameAttributeValue,
                                resourceTagAttributeValue,
                                resourceItem.Value,
                                iteratorSe.Current.Value);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                this.Logger.Log(null, this, "Error loading files. {0}".FormatWith(exception.Message));
            }
        }
Пример #32
0
        private void LoadConfiguration(string configFilePath)
        {
            XPathNavigator navigator            = GetNavigator(configFilePath);
            string         overallTimeoutString = navigator.SelectSingleNode(OverallTimeoutValueXPath).Value;

            if (string.IsNullOrEmpty(overallTimeoutString) || (!int.TryParse(overallTimeoutString, out _overallTimeoutSeconds)))
            {
                LogUtils.WriteTrace(DateTime.UtcNow, "OverallTimeout value is not defined or is not a valid integer value. OverallTimeout = " +
                                    (string.IsNullOrEmpty(overallTimeoutString) ? "null" : overallTimeoutString));

                throw new InvalidOperationException(
                          "OverallTimeout value is not defined or is not a valid integer value. OverallTimeout = " +
                          (string.IsNullOrEmpty(overallTimeoutString) ? "null" : overallTimeoutString));
            }

            if (_overallTimeoutSeconds < 0)
            {
                LogUtils.WriteTrace(DateTime.UtcNow, "OverallTimeout value cannot be less than 0. OverallTimeout = " +
                                    overallTimeoutString);

                throw new InvalidOperationException(
                          "OverallTimeout value cannot be less than 0. OverallTimeout = " +
                          overallTimeoutString);
            }

            // Loop through all patches
            XPathNodeIterator nodeIterator = navigator.Select(PatchXPath);

            while (nodeIterator.MoveNext())
            {
                Patch patch = new Patch();

                // Read name
                if (nodeIterator.Current.SelectSingleNode("@name") == null)
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, "name attribute needed for Patch element");

                    throw new InvalidOperationException("name attribute needed for Patch element");
                }

                patch.Name = nodeIterator.Current.SelectSingleNode("@name").Value.Trim();
                if (string.IsNullOrEmpty(patch.Name))
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, "name attribute can't be empty for Patch element");

                    throw new InvalidOperationException("name attribute can't be empty for Patch element");
                }

                if (_patchMap.ContainsKey(patch.Name))
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, string.Format(CultureInfo.InvariantCulture, "Patch '{0}' is defined in multiple places.", patch.Name));

                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Patch '{0}' is defined in multiple places.", patch.Name));
                }

                // Read OS versions the patch applies to and check whether it is applicable to current OS version
                if (nodeIterator.Current.SelectSingleNode("@appliesToOsVersion") != null)
                {
                    string osVersionAppliesTo = string.Empty;

                    try
                    {
                        bool invalidVersionFormat = false;
                        osVersionAppliesTo = nodeIterator.Current.SelectSingleNode("@appliesToOsVersion").Value.Trim();

                        Version currentOsVersion = Environment.OSVersion.Version;

                        char[]   versionDelimiter           = new char[] { '.' };
                        string[] versionComponents          = osVersionAppliesTo.Split(versionDelimiter);
                        string[] currentOsVersionComponents = currentOsVersion.ToString().Split(versionDelimiter);

                        // OS version the patch applies to should have four components: major.minor.build.revision
                        if (versionComponents.Length != 4)
                        {
                            invalidVersionFormat = true;
                        }
                        else
                        {
                            // Each version component should be an integer or a wildcard character '*'
                            foreach (string t in versionComponents)
                            {
                                int versionComponent;
                                if (t.Equals("*", StringComparison.OrdinalIgnoreCase) || int.TryParse(t, out versionComponent))
                                {
                                    continue;
                                }
                                invalidVersionFormat = true;
                                break;
                            }
                        }

                        if (invalidVersionFormat)
                        {
                            LogUtils.WriteTrace(DateTime.UtcNow, string.Format(
                                                    @"PathUtil: Invalid version format for OS version patch {0} applies to : {1}; the patch will be installed",
                                                    patch.Name,
                                                    osVersionAppliesTo));
                        }
                        else
                        {
                            bool skipPatch = false;
                            for (int i = 0; i < Math.Min(versionComponents.Length, currentOsVersionComponents.Length); i++)
                            {
                                if (!versionComponents[i].Equals("*", StringComparison.OrdinalIgnoreCase) &&
                                    !versionComponents[i].Equals(currentOsVersionComponents[i], StringComparison.OrdinalIgnoreCase))
                                {
                                    skipPatch = true;
                                }
                            }

                            // If the patch is not applicable to current OS version, skip it
                            if (skipPatch)
                            {
                                LogUtils.WriteTrace(DateTime.UtcNow, string.Format(
                                                        @"PatchUtil: Patch {0} will be skipped since it is only applicable to OS version {1} while current OS version is {2}",
                                                        patch.Name,
                                                        osVersionAppliesTo,
                                                        currentOsVersion));

                                continue;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        LogUtils.WriteTrace(DateTime.UtcNow, string.Format(
                                                @"PathUtil: Exception occurred when checking whether patch {0} (applicable to OS version {1}) is applicable to current OS version, skip version checking and continue installing : {2}",
                                                patch.Name,
                                                osVersionAppliesTo,
                                                e));
                    }
                }

                // Read command line.
                if (nodeIterator.Current.SelectSingleNode(CommandLineXPath) == null)
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, string.Format(CultureInfo.InvariantCulture, "Command value attribute needed for Patch '{0}'.", patch.Name));

                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Command value attribute needed for Patch '{0}'.", patch.Name));
                }

                patch.CommandLine = nodeIterator.Current.SelectSingleNode(CommandLineXPath).Value.Trim();

                if (string.IsNullOrEmpty(patch.CommandLine))
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, string.Format(CultureInfo.InvariantCulture, "Command value can't be empty for Patch '{0}'.", patch.Name));

                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Command value can't be empty for Patch '{0}'.", patch.Name));
                }

                // Read log path (optional element).
                patch.LogFolderPath = null;
                if (nodeIterator.Current.SelectSingleNode(LogFolderPathXPath) != null)
                {
                    string logFolderPath = nodeIterator.Current.SelectSingleNode(LogFolderPathXPath).Value.Trim();

                    if (!string.IsNullOrEmpty(logFolderPath))
                    {
                        patch.LogFolderPath = logFolderPath;
                    }
                }

                // Read registry settings
                List <PatchRegistry> registrySettings = new List <PatchRegistry>();
                XPathNodeIterator    iterator         = nodeIterator.Current.Select(PatchRegistryXPath);
                while (iterator.MoveNext())
                {
                    string keyName       = ReadPatchRegistryAttribute(iterator, patch.Name, RegistryKeyNameAttribute, true);
                    string valueName     = ReadPatchRegistryAttribute(iterator, patch.Name, RegistryValueNameAttribute, true);
                    string expectedValue = ReadPatchRegistryAttribute(iterator, patch.Name, RegistryExpectedValueAttribute, false);

                    PatchRegistry registrySetting = new PatchRegistry
                    {
                        RegistryKeyName   = keyName,
                        RegistryValueName = valueName,
                        ExpectedValue     = expectedValue,
                    };
                    registrySettings.Add(registrySetting);
                }

                // We need at least one registry setting to confirm the patch is installed.
                if (!registrySettings.Any())
                {
                    LogUtils.WriteTrace(DateTime.UtcNow, string.Format(CultureInfo.InvariantCulture, "There is no registry setting found for Patch '{0}'", patch.Name));

                    throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "There is no registry setting found for Patch '{0}'", patch.Name));
                }

                patch.RegistrySettings = registrySettings;
                _patchMap.Add(patch.Name, patch);
            }
        }
Пример #33
0
 private List<string> get_all_(XPathNodeIterator iter)
 {
     var list = new List <string> ();
     while (iter.MoveNext())
         list.Add (iter.Current.Value);
     return list;
 }
Пример #34
0
    public String[] ReadAllNodes(String sNodePath, String sFieldPath)
    {
        NodeIter = nav.Select(sNodePath);
        ArrayList _DATA = new ArrayList(1024);

        // Iterate through the results showing the element value.

        while (NodeIter.MoveNext())
        {
            XPathNavigator here = NodeIter.Current;

            if (DEBUG)
            {
                try
                {
                    Type ResultType = here.GetType();
                    Console.WriteLine("Result type: {0}", ResultType);
                    foreach (PropertyInfo oProperty in ResultType.GetProperties())
                    {
                        string sProperty = oProperty.Name.ToString();
                        Console.WriteLine("{0} = {1}",
                                  sProperty,
                                  ResultType.GetProperty(sProperty).GetValue(here, new Object[] { })

                                          /* COM  way:
                                             ResultType.InvokeMember(sProperty,
                                                                     BindingFlags.Public |
                                                                     BindingFlags.Instance |
                                                                     BindingFlags.Static |
                                                                     BindingFlags.GetProperty,
                                                                     null,
                                                                     here,
                                                                     new Object[] {},
                                                                     new CultureInfo("en-US", false))
                                           */
                                  );
                    }
                    ;
                }
                catch (Exception e)
                {
                    // Fallback to system formatting
                    Console.WriteLine("Result:\n{0}", here.ToString());
                    Trace.Assert(e != null); // keep the compiler happy
                }
            } // DEBUG

            // collect the caller requested data
            NodeResult = null;

            try { NodeResult = here.Select(sFieldPath); }
            catch (Exception e)
            {
                // Fallback to system formatting
                Console.WriteLine(e.ToString());
                throw /* ??? */;
            }

            if (NodeResult != null)
            {
                while (NodeResult.MoveNext())
                    _DATA.Add(NodeResult.Current.Value);
            }
        }
        ;
        String[] res = (String[])_DATA.ToArray(typeof(string));
        if (DEBUG)
            Console.WriteLine(String.Join(";", res));
        return res;
    }