Example #1
0
	public static void Main(string[] arg) {
		if (arg.Length < 1) throw new ArgumentException("Must pass one or two command line arguments.");
	
		StringWriter sw = new StringWriter();
		string s;
		while ((s = Console.ReadLine()) != null) {
			sw.WriteLine(s);
		}
		
		XmlDocument d = new XmlDocument();
		d.LoadXml(sw.ToString());
		
		object ret;
		
		if (arg.Length == 1) {
			ret = d.CreateNavigator().Evaluate(arg[0]);
		} else if (arg.Length == 2 && arg[0] == "-expr") {
			ret = d.CreateNavigator().Evaluate(arg[1]);
		} else if (arg.Length == 2 && arg[0] == "-node") {
			ret = d.SelectSingleNode(arg[1]);
		} else {
			throw new ArgumentException("Bad command line arguments.");
		}
		
		if (ret is XPathNodeIterator) {
			XPathNodeIterator iter = (XPathNodeIterator)ret;
			while (iter.MoveNext()) {
				Console.WriteLine(iter.Current);
			}
		} else if (ret is XmlNode) {
			Console.WriteLine(((XmlNode)ret).InnerXml);
		} else {
			Console.WriteLine(ret);
		}
	}
Example #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Load document
        string booksFile = Server.MapPath("books.xml");

        XmlDocument document = new XmlDocument();
        document.Load(booksFile);
        XPathNavigator nav = document.CreateNavigator();

        //Add a namespace prefix that can be used in the XPath expression
        XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(nav.NameTable);
        namespaceMgr.AddNamespace("b", "http://example.books.com");

        //All books whose price is not greater than 10.00
        foreach (XPathNavigator node in
            nav.Select("//b:book[not(b:price[. > 10.00])]/b:price",
            namespaceMgr))
        {
            Decimal price = (decimal)node.ValueAs(typeof(decimal));
            node.SetTypedValue(price * 1.2M);
            Response.Write(String.Format("Price raised from {0} to {1}<BR/>",
                price,
                node.ValueAs(typeof(decimal))));
        }
    }
    //public void saveState(string deviceName, string[] state, DateTime[] stateDate, int iPacketSize)
    //{
    //    saveState(deviceName, ArraytoString(state, stateDate, iPacketSize) );
    //}
    public void saveState(string deviceName, string deviceState)
    {
        if (_sname != String.Empty)
        {
            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                XPathNavigator xpn = xmlDoc.CreateNavigator();

                if (!File.Exists(_fname))
                {
                    CreateXmlDoc(xmlDoc, xpn, deviceName);
                }
                else
                {
                    xmlDoc.Load(_fname);
                }
                string xpath = String.Format("/{0}/device[@name='{1}']/currentState", _sname, deviceName);
                XPathNavigator currentStateNode = xpn.SelectSingleNode(xpath);

                if (currentStateNode == null)
                {
                    AddDeviceToXmlDoc(xmlDoc, xpn, deviceName);
                    currentStateNode = xpn.SelectSingleNode(xpath);
                }
                currentStateNode.SetValue(deviceState);
                xmlDoc.Save(_fname);
            }
            catch { }
        }
    }
Example #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
		string xmlFile = Server.MapPath("DvdList.xml");

		// Load the XML file in an XmlDocument.
		XmlDocument doc = new XmlDocument();
		doc.Load(xmlFile);

		// Create the navigator.
		XPathNavigator xnav = doc.CreateNavigator();

		XmlText.Text = GetXNavDescr(xnav, 0);
    }
Example #5
0
    public static string CTypeToManagedType(string ctype, XmlDocument api_doc)
    {
        switch (ctype) {
          case "GObject":
        return "GLib.Object";
          case "gchararray":
        return "string";
          case "gboolean":
        return "bool";
          case "guint":
        return "uint";
          case "gint":
        return "int";
          case "gulong":
          case "guint64":
        return "ulong";
          case "glong":
          case "gint64":
        return "long";
          case "gfloat":
        return "float";
          case "gdouble":
        return "double";
          case "GValueArray":
        return "GLib.ValueArray";
        }

        XPathNavigator api_nav = api_doc.CreateNavigator ();
        XPathNodeIterator type_iter = api_nav.Select ("/api/namespace/*[@cname='" + ctype + "']");
        while (type_iter.MoveNext ()) {
          string ret = type_iter.Current.GetAttribute ("name", "");
          if (ret != null && ret != String.Empty) {
        XPathNavigator parent = type_iter.Current.Clone ();
        parent.MoveToParent ();
        ret = parent.GetAttribute ("name", "") + "." + ret;
        return ret;
          }
        }

        return null;
    }
Example #6
0
 protected void Page_Load(object sender, EventArgs e)
 {
     string connStr = "database=Northwind;Data Source=.\\SQLEXPRESS;User id=wrox;pwd=wrox1*c";
     XmlDocument x = new XmlDocument();
     XPathNavigator xpathnav = x.CreateNavigator();
     using (SqlConnection conn = new SqlConnection(connStr))
     {
         conn.Open();
         SqlCommand command = new SqlCommand(
             "select * from Customers as Customer for XML AUTO, ELEMENTS", conn);
         using (XmlWriter xw = xpathnav.PrependChild())
         {
             xw.WriteStartElement("Customers");
             using (XmlReader xr = command.ExecuteXmlReader())
             {
                 xw.WriteNode(xr, true);
             }
             xw.WriteEndElement();
         }
     }
     Response.ContentType = "text/xml";
     x.Save(Response.Output);
 }
    public string getSavedState(string deviceName)
    {
        string retval = string.Empty;

        try
        {
            XmlDocument x = new XmlDocument();
            XPathNavigator xpn = x.CreateNavigator();

            if (File.Exists(_fname) & (_sname != String.Empty))
            {
                x.Load(_fname);
                string xpath = String.Format("/{0}/device[@name='{1}']/currentState", _sname, deviceName);
                XPathNavigator currentStateNode = xpn.SelectSingleNode(xpath);
                if (currentStateNode != null)
                {
                    retval = currentStateNode.InnerXml;
                }
            }
        }
        catch { }

        return retval;
    }
Example #8
0
        /// <summary>
        /// This method is used to execute the plug-in during the build process
        /// </summary>
        /// <param name="context">The current execution context</param>
        public void Execute(Utils.PlugIn.ExecutionContext context)
        {
            Encoding        enc = Encoding.Default;
            Thread          browserThread;
            XmlDocument     sharedContent;
            XPathNavigator  navContent, item;
            XmlCommentsFile comments;
            string          sharedContentFilename, workingPath, content;

            // Copy any XML comments files from the project to the working
            // folder.  Solutions, projects, and assemblies are ignored as
            // they won't be used with this build type.
            if (context.BuildStep == BuildStep.ValidatingDocumentationSources)
            {
                builder.ExecuteBeforeStepPlugIns();

                foreach (DocumentationSource ds in
                         builder.CurrentProject.DocumentationSources)
                {
                    foreach (string commentsName in
                             DocumentationSource.CommentsFiles(ds.SourceFile,
                                                               ds.IncludeSubFolders))
                    {
                        workingPath = builder.WorkingFolder +
                                      Path.GetFileName(commentsName);

                        // Warn if there is a duplicate and copy the comments
                        // file to a unique name to preserve its content.
                        if (File.Exists(workingPath))
                        {
                            workingPath = builder.WorkingFolder +
                                          Guid.NewGuid().ToString("B");

                            builder.ReportWarning("BE0063", "'{0}' matches " +
                                                  "a previously copied comments filename.  The " +
                                                  "duplicate will be copied to a unique name " +
                                                  "to preserve the comments it contains.",
                                                  commentsName);
                        }

                        File.Copy(commentsName, workingPath, true);
                        File.SetAttributes(workingPath, FileAttributes.Normal);

                        // Add the file to the XML comments file collection
                        comments = new XmlCommentsFile(workingPath);

                        // Fixup comments for CPP comments files?
                        if (builder.CurrentProject.CppCommentsFixup)
                        {
                            comments.FixupComments();
                        }

                        builder.CommentsFiles.Add(comments);
                        builder.ReportProgress("    {0} -> {1}", commentsName,
                                               workingPath);
                    }
                }

                builder.ExecuteAfterStepPlugIns();
                return;
            }

            // Remove the version information items from the shared content
            // file as the AjaxDoc reflection file doesn't contain version
            // information.
            if (context.BuildStep == BuildStep.GenerateSharedContent)
            {
                builder.ReportProgress("Removing version information items " +
                                       "from shared content file");

                sharedContentFilename = builder.WorkingFolder +
                                        "SharedBuilderContent.xml";

                sharedContent = new XmlDocument();
                sharedContent.Load(sharedContentFilename);
                navContent = sharedContent.CreateNavigator();

                item = navContent.SelectSingleNode("content/item[@id='" +
                                                   "locationInformation']");

                if (item != null)
                {
                    item.DeleteSelf();
                }

                item = navContent.SelectSingleNode("content/item[@id='" +
                                                   "assemblyNameAndModule']");

                if (item != null)
                {
                    item.DeleteSelf();
                }

                sharedContent.Save(sharedContentFilename);
                return;
            }

            builder.ReportProgress("Using project '{0}'", projectName);

            if (regenerateFiles)
            {
                // Regenerate the files first.  This is done by starting a
                // thread to invoke the AjaxDoc application via a web browser
                // control.  This is necessary as the brower control needs to
                // run in a thread with a single-threaded apartment state.
                // We can't just request the page as AjaxDoc has to post back
                // to itself in order to store the generated information.
                builder.ReportProgress("Generating XML comments and " +
                                       "reflection information via AjaxDoc");

                browserThread = new Thread(RunBrowser);
                browserThread.SetApartmentState(ApartmentState.STA);

                navCount = 0;
                browserThread.Start();

                if (!browserThread.Join(11000))
                {
                    browserThread.Abort();
                }

                if (!String.IsNullOrEmpty(errorText))
                {
                    throw new BuilderException("ADP0003", "AjaxDoc encountered " +
                                               "a scripting error: " + errorText);
                }

                if (commentsFile == null || reflectionFile == null)
                {
                    throw new BuilderException("ADP0004", "Unable to produce " +
                                               "comments file and/or reflection file");
                }

                builder.ReportProgress("Generated comments file '{0}' " +
                                       "and reflection file '{1}'", commentsFile, reflectionFile);
            }
            else
            {
                // Use the existing files
                commentsFile   = "Output/" + projectName + ".xml";
                reflectionFile = "Output/" + projectName + ".org";

                builder.ReportProgress("Using existing XML comments file " +
                                       "'{0}' and reflection information file '{1}'",
                                       commentsFile, reflectionFile);
            }

            // Allow Before step plug-ins to run
            builder.ExecuteBeforeStepPlugIns();

            // Download the files
            using (WebClient webClient = new WebClient())
            {
                webClient.UseDefaultCredentials = userCreds.UseDefaultCredentials;
                if (!userCreds.UseDefaultCredentials)
                {
                    webClient.Credentials = new NetworkCredential(
                        userCreds.UserName, userCreds.Password);
                }

                webClient.CachePolicy = new RequestCachePolicy(
                    RequestCacheLevel.NoCacheNoStore);

                if (proxyCreds.UseProxyServer)
                {
                    webClient.Proxy = new WebProxy(proxyCreds.ProxyServer, true);

                    if (!proxyCreds.Credentials.UseDefaultCredentials)
                    {
                        webClient.Proxy.Credentials = new NetworkCredential(
                            proxyCreds.Credentials.UserName,
                            proxyCreds.Credentials.Password);
                    }
                }

                // Since there are only two, download them synchronously
                workingPath = builder.WorkingFolder + projectName + ".xml";
                builder.ReportProgress("Downloading {0}", commentsFile);
                webClient.DownloadFile(ajaxDocUrl + commentsFile, workingPath);
                builder.CommentsFiles.Add(new XmlCommentsFile(workingPath));

                builder.ReportProgress("Downloading {0}", reflectionFile);
                webClient.DownloadFile(ajaxDocUrl + reflectionFile,
                                       builder.ReflectionInfoFilename);

                builder.ReportProgress("Downloads completed successfully");
            }

            // AjaxDoc 1.1 prefixes all member names with "J#" which causes
            // BuildAssembler's ResolveReferenceLinksComponent2 component in
            // the Sept 2007 CTP to crash.  As such, we'll strip it out.  I
            // can't see a need for it anyway.
            content = BuildProcess.ReadWithEncoding(workingPath, ref enc);
            content = content.Replace(":J#", ":");

            using (StreamWriter sw = new StreamWriter(workingPath, false, enc))
            {
                sw.Write(content);
            }

            content = BuildProcess.ReadWithEncoding(
                builder.ReflectionInfoFilename, ref enc);
            content = content.Replace(":J#", ":");

            using (StreamWriter sw = new StreamWriter(
                       builder.ReflectionInfoFilename, false, enc))
            {
                sw.Write(content);
            }

            // Don't apply the filter in a partial build
            if (!builder.IsPartialBuild && builder.BuildApiFilter.Count != 0)
            {
                builder.ReportProgress("Applying API filter manually");
                builder.ApplyManualApiFilter(builder.BuildApiFilter,
                                             builder.ReflectionInfoFilename);
            }

            // Allow After step plug-ins to run
            builder.ExecuteAfterStepPlugIns();
        }
Example #9
0
    public static bool CalculateShippingCost(CartLocation ship_to, string ship_type, double weight, double min_cost, out double cost)
    {
        string url = "https://wwwcie.ups.com/ups.app/xml/Rate";
        //string url = "https://www.ups.com/ups.app/xml/Rate";
        double originalw = weight;
        if (weight < 1)
        {
            weight = 1;
        }

        #region Template XML
        string template = "<?xml version=\"1.0\"?>" +
        "<AccessRequest xml:lang=\"en-US\">" +
        @" 	<AccessLicenseNumber>{license}</AccessLicenseNumber>
            <UserId>{user_id}</UserId>
            <Password>{user_password}</Password>
        </AccessRequest>" +
        "<?xml version=\"1.0\"?>" +
        "<RatingServiceSelectionRequest xml:lang=\"en-US\">" +
        @"<Request>
            <TransactionReference>
              <CustomerContext>Rating and Service</CustomerContext>
              <XpciVersion>1.0</XpciVersion>
            </TransactionReference>
            <RequestAction>Rate</RequestAction>
            <RequestOption>Rate</RequestOption>
          </Request>
            <PickupType>
          	            <Code>07</Code>
          	            <Description>Rate</Description>
            </PickupType>
          <Shipment>
            <Description>Rate Description</Description>
            <Shipper>
              <Name>{shipper_name}</Name>
              <PhoneNumber>{shipper_phone}</PhoneNumber>
              <ShipperNumber>{shipper_number}</ShipperNumber>
              <Address>
                <AddressLine1>{shipper_address}</AddressLine1>
                <City>{shipper_city}</City>
                <StateProvinceCode>{shipper_state}</StateProvinceCode>
                <PostalCode>{shipper_postal}</PostalCode>
                <CountryCode>{shipper_country}</CountryCode>
              </Address>
            </Shipper>
            <ShipTo>
              <CompanyName>{shipto_company}</CompanyName>
              <PhoneNumber>{shipto_phone}</PhoneNumber>
              <Address>
                <AddressLine1>{shipto_address1}</AddressLine1>
                <AddressLine2>{shipto_address2}</AddressLine2>
                <City>{shipto_city}</City>
                <PostalCode>{shipto_postal}</PostalCode>
                <CountryCode>{shipto_country}</CountryCode>
              </Address>
            </ShipTo>
          	        <Service>
                <Code>{ship_type}</Code>
          	        </Service>
          	        <Package>
                <PackagingType>
                    <Code>02</Code>
                    <Description>Customer Supplied</Description>
                </PackagingType>
                <Description>Rate</Description>
                <PackageWeight>
                    <UnitOfMeasurement>
                      <Code>LBS</Code>
                    </UnitOfMeasurement>
                    <Weight>{pounds}</Weight>
                </PackageWeight>
           	        </Package>
          </Shipment>
        </RatingServiceSelectionRequest>";
        #endregion

        template = template.Replace("{user_id}", "jdesario");
        template = template.Replace("{user_password}", "edship15");
        template = template.Replace("{license}", "2C44986E2F8FE20C");

        template = template.Replace("{ship_type}", ship_type);

        template = template.Replace("{shipper_name}", "Educational Resources, Inc.");
        template = template.Replace("{shipper_phone}", "847-888-8300");
        template = template.Replace("{shipper_number}", "");
        template = template.Replace("{shipper_address}", "1550 Executive Drive");
        template = template.Replace("{shipper_city}", "Elgin");
        template = template.Replace("{shipper_state}", "IL");
        template = template.Replace("{shipper_postal}", "60123");
        template = template.Replace("{shipper_country}", "US");

        template = template.Replace("{shipto_company}", ship_to.BusinessName);
        template = template.Replace("{shipto_phone}", ship_to.Phone);
        template = template.Replace("{shipto_address1}", ship_to.Address1);
        template = template.Replace("{shipto_address2}", ship_to.Address2);
        template = template.Replace("{shipto_city}", ship_to.City);
        template = template.Replace("{shipto_state}", ship_to.StateCode);
        template = template.Replace("{shipto_postal}", ship_to.PostalCode);
        template = template.Replace("{shipto_country}", ship_to.CountryCode);

        template = template.Replace("{pounds}", weight.ToString());

        byte[] buffer = Encoding.ASCII.GetBytes(template);

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
        req.ContentLength = buffer.Length;
        req.ContentType = "text/xml";
        req.Method = "POST";

        Stream s = req.GetRequestStream();
        s.Write(buffer, 0, buffer.Length);
        s.Close();

        HttpWebResponse resp = null;
        try
        {
            resp = (HttpWebResponse)req.GetResponse();
        }
        catch (System.Net.WebException ex)
        {
            throw new UPSException(String.Format("There was an error ({0}) getting shipping data", ex.Status));
        }

        if (resp != null && resp.StatusCode == HttpStatusCode.OK)
        {
            StreamReader sr = new StreamReader(resp.GetResponseStream());
            string response = sr.ReadToEnd();

            XmlDocument doc = new XmlDocument();
            doc.LoadXml(response);

            XPathNavigator nav = doc.CreateNavigator();
            XPathExpression status = nav.Compile("//ResponseStatusCode");
            int status_code = nav.SelectSingleNode(status).ValueAsInt;
            if (status_code != 1) throw new UPSException(String.Format("There was an error ({0})", status_code, template));

            XPathExpression exp = nav.Compile("//RatedShipment/TotalCharges/MonetaryValue");
            XPathNodeIterator iter = nav.Select(exp);

            while (iter.MoveNext())
            {
                cost = iter.Current.ValueAsDouble;
                if (cost < min_cost) cost = min_cost;
        if (originalw < 1) { cost = min_cost; }
                return true;
            }
        }

        cost = min_cost;
        return false;
    }
Example #10
0
        /// <summary>
        /// Update the Mod's information based on the Mod selected and current Rating.
        /// </summary>
        private void UpdateGearInfo()
        {
            if (_blnSkipUpdate)
            {
                return;
            }
            _blnSkipUpdate = true;
            if (!string.IsNullOrEmpty(lstMod.Text))
            {
                // Retireve the information for the selected Mod.
                // Filtering is also done on the Category in case there are non-unique names across categories.
                XmlNode objXmlMod = _objXmlDocument.SelectSingleNode("/chummer/mods/mod[id = \"" + lstMod.SelectedValue + "\"]");

                // Extract the Avil and Cost values from the Gear info since these may contain formulas and/or be based off of the Rating.
                // This is done using XPathExpression.
                XPathNavigator nav = _objXmlDocument.CreateNavigator();

                int intMinRating = 1;
                if (objXmlMod["minrating"]?.InnerText.Length > 0)
                {
                    string          strMinRating = ReplaceStrings(objXmlMod["minrating"]?.InnerText);
                    XPathExpression xprRating    = nav.Compile(strMinRating);
                    intMinRating = Convert.ToInt32(nav.Evaluate(xprRating).ToString());
                }
                // If the rating is "qty", we're looking at Tires instead of actual Rating, so update the fields appropriately.
                if (objXmlMod["rating"].InnerText == "qty")
                {
                    nudRating.Enabled   = true;
                    nudRating.Maximum   = 20;
                    nudRating.Minimum   = intMinRating;
                    lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Qty");
                }
                //Used for the Armor modifications.
                else if (objXmlMod["rating"].InnerText.ToLower() == "body")
                {
                    nudRating.Maximum   = _objVehicle.Body;
                    nudRating.Minimum   = intMinRating;
                    nudRating.Enabled   = true;
                    lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Body");
                }
                //Used for Metahuman Adjustments.
                else if (objXmlMod["rating"].InnerText.ToLower() == "seats")
                {
                    nudRating.Maximum   = _objVehicle.TotalSeats;
                    nudRating.Minimum   = intMinRating;
                    nudRating.Enabled   = true;
                    lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Qty");
                }
                else
                {
                    if (Convert.ToInt32(objXmlMod["rating"].InnerText) > 0)
                    {
                        nudRating.Maximum   = Convert.ToInt32(objXmlMod["rating"].InnerText);
                        nudRating.Minimum   = intMinRating;
                        nudRating.Enabled   = true;
                        lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Rating");
                    }
                    else
                    {
                        nudRating.Minimum   = 0;
                        nudRating.Maximum   = 0;
                        nudRating.Enabled   = false;
                        lblRatingLabel.Text = LanguageManager.Instance.GetString("Label_Rating");
                    }
                }

                // Avail.
                // If avail contains "F" or "R", remove it from the string so we can use the expression.
                string strAvail     = string.Empty;
                string strAvailExpr = string.Empty;
                if (objXmlMod["avail"].InnerText.StartsWith("FixedValues"))
                {
                    int      intRating = Convert.ToInt32(nudRating.Value - 1);
                    string[] strValues = objXmlMod["avail"].InnerText.Replace("FixedValues(", string.Empty).Replace(")", string.Empty).Split(',');
                    if (intRating > strValues.Length || intRating < 0)
                    {
                        intRating = strValues.Length - 1;
                    }
                    strAvailExpr = strValues[intRating];
                }
                else
                {
                    strAvailExpr = objXmlMod["avail"].InnerText;
                }

                XPathExpression xprAvail;
                if (strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "F" || strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "R")
                {
                    strAvail = strAvailExpr.Substring(strAvailExpr.Length - 1, 1);
                    // Remove the trailing character if it is "F" or "R".
                    strAvailExpr = strAvailExpr.Substring(0, strAvailExpr.Length - 1);
                }
                try
                {
                    xprAvail      = nav.Compile(strAvailExpr.Replace("Rating", Math.Max(nudRating.Value, 1).ToString(GlobalOptions.InvariantCultureInfo)));
                    lblAvail.Text = Convert.ToInt32(nav.Evaluate(xprAvail)) + strAvail;
                }
                catch (XPathException)
                {
                    lblAvail.Text = objXmlMod["avail"].InnerText;
                }
                lblAvail.Text = lblAvail.Text.Replace("R", LanguageManager.Instance.GetString("String_AvailRestricted")).Replace("F", LanguageManager.Instance.GetString("String_AvailForbidden"));

                // Cost.
                int intItemCost = 0;
                if (objXmlMod["cost"].InnerText.StartsWith("Variable"))
                {
                    int    intMin  = 0;
                    int    intMax  = 0;
                    string strCost = objXmlMod["cost"].InnerText.Replace("Variable(", string.Empty).Replace(")", string.Empty);
                    if (strCost.Contains("-"))
                    {
                        string[] strValues = strCost.Split('-');
                        intMin = Convert.ToInt32(strValues[0]);
                        intMax = Convert.ToInt32(strValues[1]);
                    }
                    else
                    {
                        intMin = Convert.ToInt32(strCost.Replace("+", string.Empty));
                    }

                    if (intMax == 0)
                    {
                        intMax       = 1000000;
                        lblCost.Text = string.Format("{0:###,###,##0¥+}", intMin);
                    }
                    else
                    {
                        lblCost.Text = string.Format("{0:###,###,##0}", intMin) + "-" + string.Format("{0:###,###,##0¥}", intMax);
                    }

                    intItemCost = intMin;
                }
                else
                {
                    string strCost = string.Empty;
                    if (chkFreeItem.Checked)
                    {
                        strCost = "0";
                    }
                    else
                    {
                        if (objXmlMod["cost"].InnerText.StartsWith("FixedValues"))
                        {
                            int      intRating = Convert.ToInt32(nudRating.Value) - 1;
                            string[] strValues = objXmlMod["cost"].InnerText.Replace("FixedValues(", string.Empty).Replace(")", string.Empty).Split(',');
                            if (intRating < 0 || intRating > strValues.Length)
                            {
                                intRating = 0;
                            }
                            strCost = strValues[intRating];
                        }
                        else
                        {
                            strCost = objXmlMod["cost"].InnerText;
                        }
                        strCost = ReplaceStrings(strCost);
                    }

                    XPathExpression xprCost = nav.Compile(strCost);
                    int             intCost = Convert.ToInt32(Convert.ToDouble(nav.Evaluate(xprCost), GlobalOptions.InvariantCultureInfo));
                    intCost *= _intModMultiplier;

                    // Apply any markup.
                    double dblCost = Convert.ToDouble(intCost, GlobalOptions.InvariantCultureInfo);
                    dblCost *= 1 + (Convert.ToDouble(nudMarkup.Value, GlobalOptions.CultureInfo) / 100.0);

                    if (chkBlackMarketDiscount.Checked)
                    {
                        dblCost = dblCost - (dblCost * 0.90);
                    }

                    intCost      = Convert.ToInt32(dblCost);
                    lblCost.Text = string.Format("{0:###,###,##0¥}", intCost);

                    intItemCost = intCost;
                }

                // Update the Avail Test Label.
                lblTest.Text = _objCharacter.AvailTest(intItemCost, lblAvail.Text);

                // Slots.

                string strSlots = string.Empty;
                if (objXmlMod["slots"].InnerText.StartsWith("FixedValues"))
                {
                    string[] strValues = objXmlMod["slots"].InnerText.Replace("FixedValues(", string.Empty).Replace(")", string.Empty).Split(',');
                    strSlots = strValues[Convert.ToInt32(nudRating.Value) - 1];
                }
                else
                {
                    strSlots = objXmlMod["slots"].InnerText;
                }
                strSlots = ReplaceStrings(strSlots);
                XPathExpression xprSlots = nav.Compile(strSlots);
                lblSlots.Text = nav.Evaluate(xprSlots).ToString();

                if (objXmlMod["category"].InnerText != null)
                {
                    if (_arrCategories.Contains(objXmlMod["category"].InnerText))
                    {
                        lblVehicleCapacityLabel.Visible = true;
                        lblVehicleCapacity.Visible      = true;
                        lblVehicleCapacity.Text         = GetRemainingModCapacity(objXmlMod["category"].InnerText, Convert.ToInt32(lblSlots.Text));
                        tipTooltip.SetToolTip(lblVehicleCapacityLabel, LanguageManager.Instance.GetString("Tip_RemainingVehicleModCapacity"));
                    }
                    else
                    {
                        lblVehicleCapacityLabel.Visible = false;
                        lblVehicleCapacity.Visible      = false;
                    }

                    lblCategory.Text = objXmlMod["category"].InnerText;
                    if (objXmlMod["category"].InnerText == "Weapon Mod")
                    {
                        lblCategory.Text = LanguageManager.Instance.GetString("String_WeaponModification");
                    }
                    // Translate the Category if possible.
                    else if (GlobalOptions.Instance.Language != "en-us")
                    {
                        XmlNode objXmlCategory = _objXmlDocument.SelectSingleNode("/chummer/modcategories/category[. = \"" + objXmlMod["category"].InnerText + "\"]");
                        if (objXmlCategory != null && objXmlCategory.Attributes["translate"] != null)
                        {
                            lblCategory.Text = objXmlCategory.Attributes["translate"].InnerText;
                        }
                    }
                }

                if (objXmlMod["limit"] != null)
                {
                    // Translate the Limit if possible.
                    if (GlobalOptions.Instance.Language != "en-us")
                    {
                        XmlNode objXmlLimit = _objXmlDocument.SelectSingleNode("/chummer/limits/limit[. = \"" + objXmlMod["limit"].InnerText + "\"]");
                        if (objXmlLimit != null)
                        {
                            if (objXmlLimit.Attributes["translate"] != null)
                            {
                                lblLimit.Text = " (" + objXmlLimit.Attributes["translate"].InnerText + ")";
                            }
                            else
                            {
                                lblLimit.Text = " (" + objXmlMod["limit"].InnerText + ")";
                            }
                        }
                        else
                        {
                            lblLimit.Text = " (" + objXmlMod["limit"].InnerText + ")";
                        }
                    }
                    else
                    {
                        lblLimit.Text = " (" + objXmlMod["limit"].InnerText + ")";
                    }
                }
                else
                {
                    lblLimit.Text = string.Empty;
                }

                string strBook = _objCharacter.Options.LanguageBookShort(objXmlMod["source"].InnerText);
                string strPage = objXmlMod["page"].InnerText;
                if (objXmlMod["altpage"] != null)
                {
                    strPage = objXmlMod["altpage"].InnerText;
                }
                lblSource.Text = strBook + " " + strPage;

                tipTooltip.SetToolTip(lblSource, _objCharacter.Options.LanguageBookLong(objXmlMod["source"].InnerText) + " " + LanguageManager.Instance.GetString("String_Page") + " " + strPage);
            }
            _blnSkipUpdate = false;
        }
    public string DeleteLanguage(string id_delete)
    {
        XPathNodeIterator nodes;
        Language language_support = new Language();
        language_support.SetFile(HttpContext.Current.Session["language_support"].ToString());
        string files_language = "";

        HttpContext.Current.Session["id_lang_delete"] = id_delete;
        string str = "";
        string[] id = new string[50];
        if (id_delete.Length > 0)
        {
            try
            {
                //if (DeleteFile())
                //{

                string str_where = id_delete.Substring(0, id_delete.Length - 1);
                id = str_where.Split(',');

                string file_name = HttpContext.Current.Session["language_support"].ToString();
                XmlTextReader reader = new XmlTextReader(file_name);
                XmlDocument doc = new XmlDocument();
                doc.Load(reader);
                reader.Close();

                //Select the cd node with id
                XmlNode cd;
                XmlElement root = doc.DocumentElement;
                XPathNavigator nav = doc.CreateNavigator();
                XPathNodeIterator iterator;
                for (int i = 0; i < id.Length; i++)
                {

                    iterator = nav.Select("/lang_support/lang[id=" + id[i].ToString() + "]/url");
                    iterator.MoveNext();
                    files_language = iterator.Current.Value;
                    //nodes = language_support.GetLanguageById(id[i].ToString());
                    //while (nodes.MoveNext())
                    //{
                    //    nodes.Current.MoveToFirstChild();
                    //    nodes.Current.MoveToNext();
                    //    nodes.Current.MoveToNext();
                    //    nodes.Current.MoveToNext();
                    //    files_language =nodes.Current.ToString(); //+ ",";
                    //}

                    cd = root.SelectSingleNode("/lang_support/lang[id='" + id[i] + "']");
                    if (cd != null)
                    {
                        root.RemoveChild(cd);
                        File.Delete(HttpContext.Current.Session["path_data"].ToString() + files_language);
                        //save the output to a file
                        doc.Save(file_name);
                        str = "";
                    }
                }
                //HttpContext.Current.Session["file_language"] = files_language;
                //}
            }
            catch (Exception)
            {
                str = "Quyền cập nhật file bị khóa. Không thể xóa bỏ.";
                //Response.Write(ex.ToString());

            }
        }
        else
        {
            str = "Bạn phải chọn dữ liệu muốn xóa !";
        }
        return str;
    }
Example #12
0
 public XPathNodeIterator setupUpAndSelectForNodeIterator(string file, string xp)
 {
     XmlDocument doc = new XmlDocument();
     doc.Load(file);
     return doc.CreateNavigator().Select(xp);
 }
Example #13
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered GenerateNoteMapActivity.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace("GenerateNoteMapActivity.Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

            if (_service == null)
            {
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                _service     = serviceFactory.CreateOrganizationService(context.UserId);
                _privService = serviceFactory.CreateOrganizationService(null);
            }

            try
            {
                tracingService.Trace("Retriving Annotation");

                Annotation annotation = (Annotation)_privService.Retrieve(
                    Annotation.EntityLogicalName, context.PrimaryEntityId,
                    new ColumnSet(new string[] { "annotationid", "objectid" }));

                tracingService.Trace("Retriving Property List");

                jll_propertylist propertyList = (jll_propertylist)_privService.Retrieve(
                    jll_propertylist.EntityLogicalName, annotation.ObjectId.Id,
                    new ColumnSet(new string[] { "jll_autozooming", "jll_mapzoom", "jll_pageorientation" }));

                tracingService.Trace("Have data");

                EntityCollection rows = GetPropertyData(annotation.ObjectId.Id, _privService);

                if (rows.Entities.Any())
                {
                    XmlDocument xdoc         = new XmlDocument();
                    var         dataSetsNode = xdoc.CreateElement("datasets");
                    xdoc.AppendChild(dataSetsNode);
                    DocGeneration.MapHelper.SerialiseData(dataSetsNode, "parent", rows, tracingService);
                    XPathNavigator navigator = xdoc.CreateNavigator();

                    XPathNodeIterator _longitudeNodes = navigator.Select(@"//jll_longitude");
                    XPathNodeIterator _latitudeNodes  = navigator.Select(@"//jll_latitude");
                    XPathNodeIterator _dataNodes      = navigator.Select(@"//Entity");

                    if (_longitudeNodes.Count == 0 && _latitudeNodes.Count == 0)
                    {
                        return;
                    }

                    decimal coeff = 1.413542M;
                    decimal width = GetValue(_privService, "map_width", 1010);
                    //decimal width = 1010;
                    decimal height = (int)(width / coeff);
                    string  name   = @"landscape";

                    if (propertyList.jll_pageorientation != null)
                    {
                        //portrait
                        if (propertyList.jll_pageorientation.Value == 856480001)
                        {
                            height = GetValue(_privService, "map_height", 1010);
                            width  = (int)(1010 / coeff);
                            name   = @"portrait";
                        }
                    }

                    string bingMapsKey = GetBingMap(_privService);
                    string culture     = GetValue(_privService, @"BingMapCulture", @"en");
                    string pinType     = GetValue(_privService, @"PinType", @"0");

                    decimal?zoom        = DocGeneration.MapHelper.CheckZooming(propertyList.jll_mapzoom.IsNullToDecimal(), tracingService);
                    bool    autoZooming = (propertyList.jll_autozooming ?? true);
                    /*END OF */

                    string mapData = DocGeneration.MapHelper.GetMap(_longitudeNodes,
                                                                    _latitudeNodes,
                                                                    width, height, bingMapsKey, culture, zoom, autoZooming, null, null, pinType, null, _dataNodes, tracingService);

                    Annotation note = new Annotation()
                    {
                        AnnotationId = context.PrimaryEntityId,
                        Subject      = name, //string.Format("{0}/{1}", width, height),
                        IsDocument   = true,
                        DocumentBody = mapData,
                        FileName     = @"map.jpeg",
                        MimeType     = @"image/jpeg",
                        NoteText     = string.Format("{0} rows", rows.Entities.Count)
                    };
                    _privService.Update(note);
                }
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }
            tracingService.Trace("Exiting GenerateNoteMapActivity.Execute(), Correlation Id: {0}", context.CorrelationId);
        }
Example #14
0
        public void XsltDebugModeAndSortOrder(bool native, bool debug)
        {
            const string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<root>
    <node id=""1"" isDoc=""1"">
        <title>title-1</title>
        <node id=""3"" isDoc=""1"">
            <title>title-3</title>
            <node id=""7"" isDoc=""1"">
                <title>title-7</title>
            </node>
            <node id=""8"" isDoc=""1"">
                <title>title-8</title>
            </node>
        </node>
        <node id=""5"" isDoc=""1"">
            <title>title-5</title>
        </node>
    </node>
    <node id=""2"" isDoc=""1"">
        <title>title-2</title>
        <node id=""4"" isDoc=""1"">
            <title>title-4</title>
        </node>
        <node id=""6"" isDoc=""1"">
            <title>title-6</title>
        </node>
    </node>
</root>
";

            const string xslt     = @"<?xml version=""1.0"" encoding=""UTF-8""?>
<!DOCTYPE xsl:stylesheet [
    <!ENTITY nbsp ""&#x00A0;"">
]>
<xsl:stylesheet
  version=""1.0""
  xmlns:xsl=""http://www.w3.org/1999/XSL/Transform""
  xmlns:msxml=""urn:schemas-microsoft-com:xslt""
    xmlns:umbraco.library=""urn:umbraco.library"" xmlns:Exslt.ExsltCommon=""urn:Exslt.ExsltCommon"" xmlns:Exslt.ExsltDatesAndTimes=""urn:Exslt.ExsltDatesAndTimes"" xmlns:Exslt.ExsltMath=""urn:Exslt.ExsltMath"" xmlns:Exslt.ExsltRegularExpressions=""urn:Exslt.ExsltRegularExpressions"" xmlns:Exslt.ExsltStrings=""urn:Exslt.ExsltStrings"" xmlns:Exslt.ExsltSets=""urn:Exslt.ExsltSets"" xmlns:Examine=""urn:Examine""
    exclude-result-prefixes=""msxml umbraco.library Exslt.ExsltCommon Exslt.ExsltDatesAndTimes Exslt.ExsltMath Exslt.ExsltRegularExpressions Exslt.ExsltStrings Exslt.ExsltSets Examine "">

    <xsl:output method=""xml"" omit-xml-declaration=""yes"" />
    <xsl:param name=""currentPage""/>

    <xsl:template match=""/"">
        <!-- <xsl:for-each select=""/root/* [@isDoc]""> -->
        <!-- <xsl:for-each select=""$currentPage/root/* [@isDoc]""> -->
        <xsl:for-each select=""/macro/nav/root/* [@isDoc]"">
<xsl:text>! </xsl:text><xsl:value-of select=""title"" /><xsl:text>
</xsl:text>
            <xsl:for-each select=""./* [@isDoc]"">
<xsl:text>!! </xsl:text><xsl:value-of select=""title"" /><xsl:text>
</xsl:text>
                <xsl:for-each select=""./* [@isDoc]"">
<xsl:text>!!! </xsl:text><xsl:value-of select=""title"" /><xsl:text>
</xsl:text>
                </xsl:for-each>
            </xsl:for-each>
        </xsl:for-each>
    </xsl:template>

</xsl:stylesheet>
";
            const string expected = @"! title-1
!! title-3
!!! title-7
!!! title-8
!! title-5
! title-2
!! title-4
!! title-6
";

            // see http://www.onenaught.com/posts/352/xslt-performance-tip-dont-indent-output
            // why aren't we using an XmlWriter here?

            var transform = new XslCompiledTransform(debug);
            var xmlReader = new XmlTextReader(new StringReader(xslt))
            {
                EntityHandling = EntityHandling.ExpandEntities
            };
            var xslResolver = new XmlUrlResolver
            {
                Credentials = CredentialCache.DefaultCredentials
            };
            var args = new XsltArgumentList();

            // .Default is more restrictive than .TrustedXslt
            transform.Load(xmlReader, XsltSettings.Default, xslResolver);

            XPathNavigator macro;

            if (!native)
            {
                var source = new TestSource7();
                var nav    = new NavigableNavigator(source);
                //args.AddParam("currentPage", string.Empty, nav.Clone());

                var x = new XmlDocument();
                x.LoadXml(xml);

                macro = new MacroNavigator(new[]
                {
                    // it even fails like that => macro nav. issue?
                    new MacroNavigator.MacroParameter("nav", x.CreateNavigator()) // nav.Clone())
                }
                                           );
            }
            else
            {
                var doc = new XmlDocument();
                doc.LoadXml("<macro />");
                var nav = doc.CreateElement("nav");
                doc.DocumentElement.AppendChild(nav);
                var x = new XmlDocument();
                x.LoadXml(xml);
                nav.AppendChild(doc.ImportNode(x.DocumentElement, true));
                macro = doc.CreateNavigator();
            }

            var writer = new StringWriter();

            transform.Transform(macro, args, writer);

            // this was working with native, debug and non-debug
            // this was working with macro nav, non-debug
            // but was NOT working (changing the order of nodes) with macro nav, debug
            // was due to an issue with macro nav IsSamePosition, fixed

            //Debug.Print("--------");
            //Debug.Print(writer.ToString());
            Assert.AreEqual(expected.Lf(), writer.ToString().Lf());
        }
Example #15
0
        /// <summary>
        /// Obtener información Nodo Comporbante
        /// </summary>
        /// <param name="idComprobante">ID Comprobante</param>
        /// <returns></returns>
        public async Task <GenericResponse <Comprobante> > ObtenerNodoComprobante(string idComprobante)
        {
            var comprobante = new Comprobante();

            try
            {
                var resultado = await _baseDatos.SelectFirstAsync <NodoComprobante>(_queryNodoComprobante + idComprobante);

                if (resultado != null)
                {
                    if (resultado.tipoDeComprobante != "P")
                    {
                        comprobante.Version             = resultado.version;
                        comprobante.Serie               = resultado.serie;
                        comprobante.Folio               = resultado.folio;
                        comprobante.Fecha               = resultado.fecha.ToString("yyyy-MM-ddTHH:mm:ss");
                        comprobante.NoCertificado       = _facturaNumeroCertificado;
                        comprobante.FormaPago           = resultado.formaPago;
                        comprobante.FormaPagoSpecified  = !string.IsNullOrEmpty(resultado.formaPago) ? true : false;
                        comprobante.SubTotal            = TruncarDecimal(resultado.subtotal, resultado.decimales, true);
                        comprobante.Descuento           = TruncarDecimal(resultado.descuento, resultado.decimales, true);
                        comprobante.DescuentoSpecified  = resultado.descuento > 0 ? true : false;
                        comprobante.Moneda              = resultado.moneda;
                        comprobante.TipoCambio          = TruncarDecimal(resultado.tipoCambio, resultado.decimales, false);
                        comprobante.TipoCambioSpecified = resultado.tipoCambio > 0 ? true : false;
                        comprobante.Total               = TruncarDecimal(resultado.total, resultado.decimales, true);
                        comprobante.TipoDeComprobante   = resultado.tipoDeComprobante;
                        comprobante.MetodoPago          = resultado.metodoPago;
                        comprobante.MetodoPagoSpecified = !string.IsNullOrEmpty(resultado.metodoPago) ? true : false;
                        comprobante.LugarExpedicion     = resultado.lugarExpedicion;

                        //Cfdi Relacionados
                        var cfdiRelacionado = await ObtenerCfdiRelacionados(resultado.id.ToString());

                        comprobante.CfdiRelacionados = cfdiRelacionado != null ? cfdiRelacionado : null;

                        //Emisor
                        var emisor = await ObtenerNodoEmisor(resultado.id.ToString());

                        if (emisor != null)
                        {
                            comprobante.Emisor = emisor;
                        }
                        else
                        {
                            return new GenericResponse <Comprobante>()
                                   {
                                       Codigo = 2, Mensaje = $"NodoEmisor, no se encontró información del Comprobante {resultado.id}"
                                   }
                        };

                        //Receptor
                        var receptor = await ObtenerNodoReceptor(resultado.id.ToString());

                        if (receptor != null)
                        {
                            comprobante.Receptor = receptor;
                        }
                        else
                        {
                            return new GenericResponse <Comprobante>()
                                   {
                                       Codigo = 2, Mensaje = $"NodoReceptor, no se encontró información del Comprobante {resultado.id}"
                                   }
                        };

                        //Concepto
                        var conceptos = (await ObtenerNodoConcepto(resultado.id.ToString())).ToArray();
                        if (conceptos != null)
                        {
                            comprobante.Conceptos = conceptos;
                        }
                        else
                        {
                            return new GenericResponse <Comprobante>()
                                   {
                                       Codigo = 2, Mensaje = $"NodoConceptos, no se encontró información del Comprobante {resultado.id}"
                                   }
                        };

                        //Impuestos
                        var impuestos = await ObtenerNodoImpuestos(resultado.id.ToString());

                        if (impuestos != null)
                        {
                            comprobante.Impuestos = impuestos;
                        }
                        else
                        {
                            return new GenericResponse <Comprobante>()
                                   {
                                       Codigo = 2, Mensaje = $"NodoImpuestos, no se encontró información del Comprobante {resultado.id}"
                                   }
                        };

                        //Addenda
                        var addenda = await ObtenerNodoAddenda(resultado.id.ToString());

                        comprobante.Addenda = addenda != null ? addenda : null;
                    }
                    else if (resultado.tipoDeComprobante == "P")
                    {
                        comprobante.Version             = resultado.version;
                        comprobante.Serie               = resultado.serie;
                        comprobante.Folio               = resultado.folio;
                        comprobante.Fecha               = resultado.fecha.ToString("yyyy-MM-ddTHH:mm:ss");
                        comprobante.NoCertificado       = _facturaNumeroCertificado;
                        comprobante.SubTotal            = TruncarDecimal(resultado.subtotal, resultado.decimales, true);
                        comprobante.Descuento           = TruncarDecimal(resultado.descuento, resultado.decimales, true);
                        comprobante.DescuentoSpecified  = resultado.descuento > 0 ? true : false;
                        comprobante.Moneda              = resultado.moneda;
                        comprobante.TipoCambio          = TruncarDecimal(resultado.tipoCambio, resultado.decimales, false);
                        comprobante.TipoCambioSpecified = resultado.tipoCambio > 0 ? true : false;
                        comprobante.Total               = TruncarDecimal(resultado.total, resultado.decimales, true);
                        comprobante.TipoDeComprobante   = resultado.tipoDeComprobante;
                        comprobante.LugarExpedicion     = resultado.lugarExpedicion;

                        //Cfdi Relacionados
                        var cfdiRelacionado = await ObtenerCfdiRelacionados(resultado.id.ToString());

                        comprobante.CfdiRelacionados = cfdiRelacionado != null ? cfdiRelacionado : null;

                        //Emisor
                        var emisor = await ObtenerNodoEmisor(resultado.id.ToString());

                        if (emisor != null)
                        {
                            comprobante.Emisor = emisor;
                        }
                        else
                        {
                            return new GenericResponse <Comprobante>()
                                   {
                                       Codigo = 2, Mensaje = $"NodoEmisor, no se encontró información del Comprobante {resultado.id}"
                                   }
                        };

                        //Receptor
                        var receptor = await ObtenerNodoReceptor(resultado.id.ToString());

                        if (receptor != null)
                        {
                            comprobante.Receptor = receptor;
                        }
                        else
                        {
                            return new GenericResponse <Comprobante>()
                                   {
                                       Codigo = 2, Mensaje = $"NodoReceptor, no se encontró información del Comprobante {resultado.id}"
                                   }
                        };

                        //Concepto
                        var conceptos = (await ObtenerNodoConcepto(resultado.id.ToString())).ToArray();
                        if (conceptos != null)
                        {
                            comprobante.Conceptos = conceptos;
                        }
                        else
                        {
                            return new GenericResponse <Comprobante>()
                                   {
                                       Codigo = 2, Mensaje = $"NodoConceptos, no se encontró información del Comprobante {resultado.id}"
                                   }
                        };

                        //Addenda
                        var addenda = await ObtenerNodoAddenda(resultado.id.ToString());

                        comprobante.Addenda = addenda != null ? addenda : null;

                        comprobante.Complemento    = new ComprobanteComplemento[1];
                        comprobante.Complemento[0] = new ComprobanteComplemento();

                        var pago = await ObtenerNodoPagos(resultado.id.ToString());

                        if (pago != null)
                        {
                            XmlDocument nodoPago = new XmlDocument();

                            XmlSerializerNamespaces xmlNameSpacePago = new XmlSerializerNamespaces();
                            xmlNameSpacePago.Add("pago10", "http://www.sat.gob.mx/Pagos");
                            using (XmlWriter write = nodoPago.CreateNavigator().AppendChild())
                            {
                                new XmlSerializer(pago.GetType()).Serialize(write, pago, xmlNameSpacePago);
                            }

                            comprobante.Complemento[0].Any    = new XmlElement[1];
                            comprobante.Complemento[0].Any[0] = nodoPago.DocumentElement;
                        }
                        else
                        {
                            return(new GenericResponse <Comprobante>()
                            {
                                Codigo = 2, Mensaje = $"NodoPagos, no se encontró información del Comprobante {resultado.id}"
                            });
                        }
                    }


                    return(new GenericResponse <Comprobante>()
                    {
                        Data = comprobante
                    });
                }
                else
                {
                    return(new GenericResponse <Comprobante>()
                    {
                        Codigo = 2, Mensaje = $"NodoComprobante, no se encontró información del Comprobante {resultado.id}"
                    });
                }
            }
            catch (Exception ex)
            {
                return(new GenericResponse <Comprobante>()
                {
                    Codigo = 0, Mensaje = $"NodoComprobante, ObtenerNodoComprobante({idComprobante}). Excepción: {ex.Message}"
                });
            }
        }
Example #16
0
        public static List <WeatherDay> GetWeather(decimal dLatitude, decimal dLongitude, bool displayfahrenheit)
        {
            List <WeatherDay> weatherdays = new List <WeatherDay>();

            try
            {
                StringBuilder sXML          = new StringBuilder();
                string        sTempHighDay1 = "";
                string        sTempHighDay2 = "";
                string        sTempHighDay3 = "";
                string        sTempLowDay1  = "";
                string        sTempLowDay2  = "";
                string        sTempLowDay3  = "";
                string        sWeather1     = "";
                string        sWeather2     = "";
                string        sWeather3     = "";
                string        sIconURL1     = "";
                string        sIconURL2     = "";
                string        sIconURL3     = "";

                // Get three days worth of weather - coded to read to 4 levels of node hierarchy

                string sCurrentNode = "";
                string noaarest     = "http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdBrowserClientByDay.php?lat=" + dLatitude.ToString() + "&lon=" + dLongitude.ToString() + "&format=24+hourly&numDays=3";

                WebClient webclient   = new WebClient();
                string    sWeatherXML = webclient.DownloadString(noaarest);

                XmlDocument doc = new XmlDocument();
                doc.LoadXml(sWeatherXML);
                XPathNavigator nav1 = doc.CreateNavigator();
                nav1.MoveToRoot();
                nav1.MoveToFirstChild(); // dwml
                // Level 1 - find data node ---------------------------
                if (nav1.HasChildren)
                {
                    nav1.MoveToFirstChild();
                    do
                    {
                        if (nav1.NodeType == XPathNodeType.Element)
                        {
                            if (nav1.Name.ToLower() == "data")
                            {
                                // Level 2 - find the parameters node -----------------------------
                                if (nav1.HasChildren)
                                {
                                    XPathNavigator nav2 = nav1.Clone();
                                    nav2.MoveToFirstChild();
                                    do
                                    {
                                        if (nav2.NodeType == XPathNodeType.Element)
                                        {
                                            if (nav2.Name.ToLower() == "parameters")
                                            {
                                                // Level 3 - find the temperature, weather and conditions-icon nodes
                                                if (nav2.HasChildren)
                                                {
                                                    XPathNavigator nav3 = nav2.Clone();
                                                    nav3.MoveToFirstChild();
                                                    do
                                                    {
                                                        if (nav3.NodeType == XPathNodeType.Element)
                                                        {
                                                            if (nav3.Name.ToLower() == "temperature" || nav3.Name.ToLower() == "weather" || nav3.Name.ToLower() == "conditions-icon")
                                                            {
                                                                sCurrentNode = nav3.Name.ToLower();

                                                                // Level 4 - read the values
                                                                if (sCurrentNode == "temperature")
                                                                {
                                                                    if (nav3.HasAttributes)
                                                                    {
                                                                        XPathNavigator nava = nav3.Clone();
                                                                        nava.MoveToAttribute("type", "");
                                                                        if (nava.Value.ToLower() == "maximum")
                                                                        {
                                                                            XPathNavigator nav4a = nav3.Clone();
                                                                            nav4a.MoveToFirstChild();
                                                                            do
                                                                            {
                                                                                if (nav4a.NodeType == XPathNodeType.Element)
                                                                                {
                                                                                    if (nav4a.Name.ToLower() == "value")
                                                                                    {
                                                                                        if (String.IsNullOrEmpty(sTempHighDay1))
                                                                                        {
                                                                                            sTempHighDay1 = nav4a.Value;
                                                                                        }
                                                                                        else if (String.IsNullOrEmpty(sTempHighDay2))
                                                                                        {
                                                                                            sTempHighDay2 = nav4a.Value;
                                                                                        }
                                                                                        else if (String.IsNullOrEmpty(sTempHighDay3))
                                                                                        {
                                                                                            sTempHighDay3 = nav4a.Value;
                                                                                        }
                                                                                    }
                                                                                }
                                                                            } while (nav4a.MoveToNext());
                                                                        }
                                                                        else if (nava.Value.ToLower() == "minimum")
                                                                        {
                                                                            XPathNavigator nav4b = nav3.Clone();
                                                                            nav4b.MoveToFirstChild();
                                                                            do
                                                                            {
                                                                                if (nav4b.NodeType == XPathNodeType.Element)
                                                                                {
                                                                                    if (nav4b.Name.ToLower() == "value")
                                                                                    {
                                                                                        if (String.IsNullOrEmpty(sTempLowDay1))
                                                                                        {
                                                                                            sTempLowDay1 = nav4b.Value;
                                                                                        }
                                                                                        else if (String.IsNullOrEmpty(sTempLowDay2))
                                                                                        {
                                                                                            sTempLowDay2 = nav4b.Value;
                                                                                        }
                                                                                        else if (String.IsNullOrEmpty(sTempLowDay3))
                                                                                        {
                                                                                            sTempLowDay3 = nav4b.Value;
                                                                                        }
                                                                                    }
                                                                                }
                                                                            } while (nav4b.MoveToNext());
                                                                        }
                                                                    }
                                                                }
                                                                else if (sCurrentNode == "weather")
                                                                {
                                                                    XPathNavigator nav4c = nav3.Clone();
                                                                    nav4c.MoveToFirstChild();
                                                                    do
                                                                    {
                                                                        if (nav4c.NodeType == XPathNodeType.Element)
                                                                        {
                                                                            if (nav4c.Name.ToLower() == "weather-conditions")
                                                                            {
                                                                                XPathNavigator nav4ca = nav4c.Clone();
                                                                                nav4ca.MoveToAttribute("weather-summary", "");
                                                                                if (String.IsNullOrEmpty(sWeather1))
                                                                                {
                                                                                    sWeather1 = nav4ca.Value;
                                                                                }
                                                                                else if (String.IsNullOrEmpty(sWeather2))
                                                                                {
                                                                                    sWeather2 = nav4ca.Value;
                                                                                }
                                                                                else if (String.IsNullOrEmpty(sWeather3))
                                                                                {
                                                                                    sWeather3 = nav4ca.Value;
                                                                                }
                                                                            }
                                                                        }
                                                                    } while (nav4c.MoveToNext());
                                                                }
                                                                else if (sCurrentNode == "conditions-icon")
                                                                {
                                                                    XPathNavigator nav4d = nav3.Clone();
                                                                    nav4d.MoveToFirstChild();
                                                                    do
                                                                    {
                                                                        if (nav4d.NodeType == XPathNodeType.Element)
                                                                        {
                                                                            if (nav4d.Name.ToLower() == "icon-link")
                                                                            {
                                                                                if (String.IsNullOrEmpty(sIconURL1))
                                                                                {
                                                                                    sIconURL1 = nav4d.Value;
                                                                                }
                                                                                else if (String.IsNullOrEmpty(sIconURL2))
                                                                                {
                                                                                    sIconURL2 = nav4d.Value;
                                                                                }
                                                                                else if (String.IsNullOrEmpty(sIconURL3))
                                                                                {
                                                                                    sIconURL3 = nav4d.Value;
                                                                                }
                                                                            }
                                                                        }
                                                                    } while (nav4d.MoveToNext());
                                                                }
                                                            }
                                                        }
                                                    } while (nav3.MoveToNext());
                                                }
                                            }
                                        }
                                    } while (nav2.MoveToNext());
                                }
                            }
                        }
                    } while (nav1.MoveToNext());
                }

                WeatherDay weatherday1 = new WeatherDay();
                weatherday1.WeatherImage        = new System.Windows.Controls.Image();
                weatherday1.WeatherImage.Source = new BitmapImage(new Uri(GetImagePath(sWeather1), UriKind.Relative));
                weatherday1.DayOfWeek           = GetDay(Convert.ToInt32(DateTime.Today.DayOfWeek));
                weatherday1.Weather             = sWeather1;
                weatherday1.High = sTempHighDay1;
                if (!displayfahrenheit)
                {
                    weatherday1.High = ConvertFahrenheitToCelsius(weatherday1.High).ToString();
                }
                weatherday1.Low = sTempLowDay1;
                if (!displayfahrenheit)
                {
                    weatherday1.Low = ConvertFahrenheitToCelsius(weatherday1.Low).ToString();
                }
                weatherdays.Add(weatherday1);

                WeatherDay weatherday2 = new WeatherDay();
                weatherday2.WeatherImage        = new System.Windows.Controls.Image();
                weatherday2.WeatherImage.Source = new BitmapImage(new Uri(GetImagePath(sWeather2), UriKind.Relative));
                weatherday2.DayOfWeek           = GetDay(Convert.ToInt32(DateTime.Today.DayOfWeek));
                weatherday2.Weather             = sWeather2;
                weatherday2.High = sTempHighDay2;
                if (!displayfahrenheit)
                {
                    weatherday2.High = ConvertFahrenheitToCelsius(weatherday2.High).ToString();
                }
                weatherday2.Low = sTempLowDay2;
                if (!displayfahrenheit)
                {
                    weatherday2.Low = ConvertFahrenheitToCelsius(weatherday2.Low).ToString();
                }
                weatherdays.Add(weatherday2);

                WeatherDay weatherday3 = new WeatherDay();
                weatherday3.WeatherImage        = new System.Windows.Controls.Image();
                weatherday3.WeatherImage.Source = new BitmapImage(new Uri(GetImagePath(sWeather3), UriKind.Relative));
                weatherday3.DayOfWeek           = GetDay(Convert.ToInt32(DateTime.Today.DayOfWeek));
                weatherday3.Weather             = sWeather3;
                weatherday3.High = sTempHighDay3;
                if (!displayfahrenheit)
                {
                    weatherday3.High = ConvertFahrenheitToCelsius(weatherday3.High).ToString();
                }
                weatherday3.Low = sTempLowDay3;
                if (!displayfahrenheit)
                {
                    weatherday3.Low = ConvertFahrenheitToCelsius(weatherday3.Low).ToString();
                }
                weatherdays.Add(weatherday3);
            }
            catch
            {
                WeatherDay weatherday1 = new WeatherDay();
                weatherday1.WeatherImage        = new System.Windows.Controls.Image();
                weatherday1.WeatherImage.Source = new BitmapImage(new Uri("/Images/partlycloudy.png", UriKind.Relative));
                weatherday1.DayOfWeek           = "N/A";
                weatherday1.Weather             = "N/A";
                weatherday1.High = "N/A";
                weatherday1.Low  = "N/A";

                WeatherDay weatherday2 = weatherday1;
                WeatherDay weatherday3 = weatherday1;

                weatherdays.Add(weatherday1);
                weatherdays.Add(weatherday2);
                weatherdays.Add(weatherday3);
            }

            return(weatherdays);
        }
Example #17
0
        public override object InvokeXPathFunction(AlpheusXPathFunction f, AlpheusXsltContext xslt_context, object[] args, XPathNavigator doc_context)
        {
            for (int argc = 0; argc < args.Length; argc++)
            {
                if (args[argc] is string)
                {
                    args[argc] = ResolveXPathFunctionArgVariables((string)args[argc], xslt_context);
                }
            }
            switch (f.Prefix)
            {
            case "l":
                switch (f.Name)
                {
                case "any":
                    string            e;
                    XPathNodeIterator iter = (args[0] as XPathNodeIterator).Clone();
                    if (args.Count() == 1)
                    {
                        e = "./";
                    }
                    else
                    {
                        e = (string)args[1];
                    }
                    XPathExpression expr = this.CompileXPathExpression(e, doc_context);
                    if (expr == null)
                    {
                        Error("Failed to execute l:any with expression {0}.", e);
                        return(false);
                    }
                    object r;
                    while (iter.MoveNext())
                    {
                        r = iter.Current.Evaluate(expr);
                        if (r == null)
                        {
                            continue;
                        }
                        else if (r as bool? != null)
                        {
                            bool?b = r as bool?;
                            if (b.HasValue && b.Value)
                            {
                                return(true);
                            }
                        }
                        else if (r is XPathNodeIterator)
                        {
                            XPathNodeIterator i = r as XPathNodeIterator;
                            if (i.Count > 0)
                            {
                                return(true);
                            }
                        }
                        else if (r is double?)
                        {
                            double?d = r as double?;
                            if (d.HasValue)
                            {
                                return(true);
                            }
                        }
                        else if (r is string)
                        {
                            string s = (string)r;
                            if (!string.IsNullOrEmpty(s))
                            {
                                return(true);
                            }
                        }
                        else
                        {
                            throw new Exception("Unknown result type from evaluating expression " + e + " at iterator position " + iter.CurrentPosition);
                        }
                    }
                    return(f);

                default:
                    throw new NotImplementedException("The XPath function " + f.Prefix + ":" + f.Name + " is not implemented.");
                }

            case "db":
                switch (f.Name)
                {
                case "query":
                    if (this.AuditTarget is IDbAuditTarget)
                    {
                        IDbAuditTarget db = this.AuditTarget as IDbAuditTarget;
                        return(db.ExecuteDbQueryToXml(args));
                    }
                    else
                    {
                        this.AuditEnvironment.Error("The current target is not a database server or application and does not support queries.");
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml("<error>No Database</error>");
                        return(doc.CreateNavigator().Select("/"));
                    }

                default:
                    throw new NotImplementedException("The XPath function " + f.Prefix + ":" + f.Name + " is not supported by IDbAuditTarget.");
                }

            case "os":
                switch (f.Name)
                {
                case "exec":
                    string output = string.Empty, command = "", arguments = "";
                    if (args.Count() == 1)
                    {
                        command = (string)args[0];
                    }
                    else
                    {
                        command   = (string)args[0];
                        arguments = (string)args[1];
                    }
                    output = this.AuditEnvironment.OSExec(command, arguments);
                    this.AuditEnvironment.Debug("os:exec {0} {1} returned {2}.", command, arguments, string.IsNullOrEmpty(output) ? "null" : output);
                    return(output);

                default:
                    throw new NotImplementedException("The XPath function " + f.Prefix + ":" + f.Name + " is not supported by this audit target.");
                }

            case "fs":
                switch (f.Name)
                {
                case "unix-file-mode":
                    return(this.AuditEnvironment.GetUnixFileMode((string)args[0]));

                case "find-files":
                    return(this.AuditEnvironment.FindFiles((string)args[0], (string)args[1]));

                case "find-dirs":
                    return(this.AuditEnvironment.FindDirectories((string)args[0], (string)args[1]));

                case "is-symbolic-link":
                    return(this.AuditEnvironment.GetIsSymbolicLink((string)args[0]));

                case "symbolic-link-location":
                    return(this.AuditEnvironment.GetSymbolicLinkLocation((string)args[0]));

                default:
                    throw new NotImplementedException("The XPath function " + f.Prefix + ":" + f.Name + " is not supported by any audit target.");
                }

            case "ver":
                string version = (string)args[0];
                switch (f.Name)
                {
                case "lt":
                    return(this.Application.IsVulnerabilityVersionInPackageVersionRange("<" + version, this.Application.Version));

                case "gt":
                    return(this.Application.IsVulnerabilityVersionInPackageVersionRange(">" + version, this.Application.Version));

                case "eq":
                    return(this.Application.IsVulnerabilityVersionInPackageVersionRange(version, this.Application.Version));

                case "lte":
                    return(this.Application.IsVulnerabilityVersionInPackageVersionRange("<=" + version, this.Application.Version));

                case "gte":
                    return(this.Application.IsVulnerabilityVersionInPackageVersionRange(">=" + version, this.Application.Version));

                default:
                    throw new NotImplementedException("The XPath function " + f.Prefix + ":" + f.Name + " is not supported by any audit target.");
                }

            default:
                throw new NotImplementedException("The XPath function prefix" + f.Prefix + " is not supported by any audit targets.");
            }
        }
        private void Estadisticas_Load(object sender, EventArgs e)
        {
            try
            {
                ServiceWebMail sm    = new ServiceWebMail();
                XmlNode        nodos = sm.ListarAlumnosXml();
                XmlDocument    myXmlDocumentObject = new XmlDocument();
                myXmlDocumentObject.AppendChild(myXmlDocumentObject.ImportNode(nodos, true));


                //obtengo objeto para realizar la consulta
                XPathNavigator _Navegador = myXmlDocumentObject.CreateNavigator();

                //ejecuto la consulta
                XPathNodeIterator _Resultado = _Navegador.Select("/raiz/EstadisticaMail");

                //si hay resultado lo muestro;
                //El iterador tiene una propiedad count que me va a determinar la cantidad de nodos que puedo navegar
                if (_Resultado.Count > 0)
                {
                    while (_Resultado.MoveNext())
                    {
                        string nombre    = _Resultado.Current.SelectSingleNode("NombreUsuario").ToString();
                        string enviados  = _Resultado.Current.SelectSingleNode("MailsEnviados").ToString();
                        string recibidos = _Resultado.Current.SelectSingleNode("MailsRecibidos").ToString();

                        object[] row0 = { nombre, enviados, recibidos };
                        gridEstadistica.Rows.Add(row0);
                    }
                }

                //XmlNode nodeaux = myXmlDocumentObject.SelectSingleNode("/raiz");
                //XmlNodeList estadisticasMail = nodeaux.SelectNodes("EstadisticaMail");
                //foreach (XmlNode n in estadisticasMail)
                //{
                //    while (n.h)
                //    {
                //        n.NextSibling
                //        string nombreUsuario = n.InnerText;
                //    }

                //}



                //          // Create the query
                //var alumnos = from a in XElement.ReadFrom(.Elements("Alumno")
                //            select a;

                //        foreach (XmlNode n in myXmlDocumentObject)
                //        {
                //            object[] row0 = {n.};
                //            UsersListRepeater.Rows.Add(row0);
                //        }



                //sm.get
            }
            catch (Exception ex)
            {
                lblInfo.Text = ex.Message;
            }
        }
        public bool LoadDocument(string strFile)
        {
            bool ret = false;

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(strFile);
                XPathNavigator nav = doc.CreateNavigator();

                XPathNodeIterator iterProject = nav.Select("/CallFlow");
                while (iterProject.MoveNext())
                {
                    strExt = iterProject.Current.GetAttribute("Extension", string.Empty);
                }

                XPathNodeIterator iterCallFlow = nav.Select("/CallFlow");
                while (iterCallFlow.MoveNext())
                {
                    strProject         = iterCallFlow.Current.GetAttribute("Project", string.Empty);
                    strStartActivityID = iterCallFlow.Current.GetAttribute("Start", string.Empty);
                }

                XPathNodeIterator iterVar = nav.Select("/CallFlow/Variable");
                while (iterVar.MoveNext())
                {
                    string strVar = iterVar.Current.GetAttribute("val", string.Empty);
                    mapVar[strVar] = strVar;
                }

                XPathNodeIterator iterNode = nav.Select("/CallFlow/Node");
                while (iterNode.MoveNext())
                {
                    Node node = new Node();
                    node.NodeID = iterNode.Current.GetAttribute("id", string.Empty);
                    node.DocID  = iterNode.Current.GetAttribute("docID", string.Empty);
                    node.Text   = iterNode.Current.GetAttribute("LabelText", string.Empty);
                    node.Value  = iterNode.Current.GetAttribute("NodeValue", string.Empty);

                    mapNode[node.NodeID] = node;
                }

                XPathNodeIterator iterLink = nav.Select("/CallFlow/Link");
                while (iterLink.MoveNext())
                {
                    string strKey = iterLink.Current.GetAttribute("key", string.Empty);
                    string strVal = iterLink.Current.GetAttribute("val", string.Empty);

                    mapLink[mapNode[strKey]] = mapNode[strVal];
                }

                XPathNodeIterator iterActivity = nav.Select("/CallFlow/Activity");
                while (iterActivity.MoveNext())
                {
                    IActivity activity = ActivityCreator.Instance.CreateInstance(iterActivity.Current.GetAttribute("activityName", string.Empty));

                    if (activity != null)
                    {
                        activity.ActivityID   = iterActivity.Current.GetAttribute("activityID", string.Empty);
                        activity.ActivityName = iterActivity.Current.GetAttribute("activityName", string.Empty);
                        activity.Value        = iterActivity.Current.GetAttribute("activityValue", string.Empty);
                        activity.Description  = iterActivity.Current.GetAttribute("activityDesc", string.Empty);
                        activity.DocID        = iterActivity.Current.GetAttribute("docID", string.Empty);

                        XPathNodeIterator subNodes = nav.Select("/CallFlow/Activity[@activityID='" + activity.ActivityID + "']/EntryNode");
                        while (subNodes.MoveNext())
                        {
                            string strTmpNodeID = subNodes.Current.GetAttribute("id", string.Empty);
                            activity.Entry = mapNode[strTmpNodeID];
                        }

                        subNodes = nav.Select("/CallFlow/Activity[@activityID='" + activity.ActivityID + "']/Node");
                        while (subNodes.MoveNext())
                        {
                            string strTmpNodeID = subNodes.Current.GetAttribute("id", string.Empty);
                            activity.ResultNode.Add(mapNode[strTmpNodeID].NodeID, mapNode[strTmpNodeID]);
                        }

                        subNodes = nav.Select("/CallFlow/Activity[@activityID='" + activity.ActivityID + "']/PrimaryNode");
                        while (subNodes.MoveNext())
                        {
                            string strTmpNodeID = subNodes.Current.GetAttribute("id", string.Empty);
                            activity.PrimaryNode = mapNode[strTmpNodeID];
                        }

                        subNodes = nav.Select("/CallFlow/Activity[@activityID='" + activity.ActivityID + "']/Attrs");
                        while (subNodes.MoveNext())
                        {
                            string strAttrKey = subNodes.Current.GetAttribute("key", string.Empty);
                            activity.Attribute[strAttrKey] = subNodes.Current.GetAttribute("val", string.Empty);
                        }

                        mapActivity[activity.ActivityID] = activity;
                    }
                    else
                    {
                        ret = false;
                        return(ret);
                    }
                }

                XPathNodeIterator iterPage = nav.Select("/CallFlow/Page");
                while (iterPage.MoveNext())
                {
                    Page page = new Page();

                    page.FlowName      = iterPage.Current.GetAttribute("flowName", string.Empty);
                    page.DocID         = iterPage.Current.GetAttribute("docID", string.Empty);
                    page.EntryActivity = mapActivity[iterPage.Current.GetAttribute("entry", string.Empty)];

                    Dictionary <string, IActivity> .Enumerator lpActivity = mapActivity.GetEnumerator();
                    while (lpActivity.MoveNext())
                    {
                        KeyValuePair <string, IActivity> itemActivity = lpActivity.Current;

                        if (itemActivity.Value.DocID == page.DocID)
                        {
                            page.Activities.Add(itemActivity.Key, itemActivity.Value);
                        }
                    }
                    mapPage[page.DocID] = page;
                }

                ret = true;
            }
            catch (Exception ex)
            {
                ret = false;
            }

            return(ret);
        }
Example #20
0
 private XPathNavigator GetXmlDocumentNavigator(string xml)
 {
     document.LoadXml(xml);
     return(document.CreateNavigator());
 }
Example #21
0
        /// <summary>
        /// This method is used to execute the plug-in during the build process
        /// </summary>
        /// <param name="context">The current execution context</param>
        public void Execute(ExecutionContext context)
        {
            List <string> namespaceList = new List <string>();
            Dictionary <string, XmlNode> namespaceNodes = new Dictionary <string, XmlNode>();
            XmlDocument    toc;
            XPathNavigator root, navToc;
            XmlAttribute   attr;
            XmlNode        tocEntry, tocParent;

            string[] parts;
            string   name, parent, topicTitle;
            int      parentIdx, childIdx, entriesAdded;

            builder.ReportProgress("Retrieving namespace topic title from shared content...");

            toc = new XmlDocument();
            toc.Load(builder.PresentationStyleFolder + @"content\reference_content.xml");
            tocEntry = toc.SelectSingleNode("content/item[@id='namespaceTopicTitle']");

            if (tocEntry != null)
            {
                topicTitle = tocEntry.InnerText;
            }
            else
            {
                builder.ReportWarning("HTP0001", "Unable to locate namespace " +
                                      "topic title in reference content file.  Using default.");
                topicTitle = "{0} Namespace";
            }

            builder.ReportProgress("Creating namespace hierarchy...");

            toc = new XmlDocument();
            toc.Load(builder.WorkingFolder + "toc.xml");
            navToc = toc.CreateNavigator();

            // Get a list of the namespaces.  If a root namespace container
            // node is present, we need to look in it rather than the document
            // root node.
            root = navToc.SelectSingleNode("topics/topic[starts-with(@id, 'R:')]");

            if (root == null)
            {
                root = navToc.SelectSingleNode("topics");
            }

            foreach (XPathNavigator ns in root.Select("topic[starts-with(@id, 'N:')]"))
            {
                name = ns.GetAttribute("id", String.Empty);
                namespaceList.Add(name);
                namespaceNodes.Add(name, ((IHasXmlNode)ns).GetNode());
            }

            // See if any container nodes need to be created for namespaces
            // with a common root name.
            for (parentIdx = 0; parentIdx < namespaceList.Count; parentIdx++)
            {
                parts = namespaceList[parentIdx].Split('.');

                // Only do it for namespaces with a minimum number of parts
                if (parts.Length > minParts)
                {
                    for (childIdx = minParts; childIdx < parts.Length; childIdx++)
                    {
                        name = String.Join(".", parts, 0, childIdx);

                        if (!namespaceList.Contains(name))
                        {
                            if (namespaceList.FindAll(
                                    ns => ns.StartsWith(name + ".", StringComparison.Ordinal)).Count > 0)
                            {
                                // The nodes will be created later once
                                // we know where to insert them.
                                namespaceList.Add(name);
                                namespaceNodes.Add(name, null);
                            }
                        }
                    }
                }
            }

            // Sort them in reverse order
            namespaceList.Sort((n1, n2) => String.Compare(n2, n1, StringComparison.Ordinal));

            // If any container namespaces were added, create nodes for them
            // and insert them before the namespace ahead of them in the list.
            foreach (string key in namespaceList)
            {
                if (namespaceNodes[key] == null)
                {
                    tocEntry = toc.CreateElement("topic");
                    attr     = toc.CreateAttribute("id");

                    attr.Value = String.Format(CultureInfo.InvariantCulture,
                                               topicTitle, (key.Length > 2) ? key.Substring(2) : "Global");
                    tocEntry.Attributes.Append(attr);

                    parentIdx = namespaceList.IndexOf(key);
                    tocParent = namespaceNodes[namespaceList[parentIdx - 1]];
                    tocParent.ParentNode.InsertBefore(tocEntry, tocParent);
                    namespaceNodes[key] = tocEntry;
                }
            }

            for (parentIdx = 1; parentIdx < namespaceList.Count; parentIdx++)
            {
                parent       = namespaceList[parentIdx];
                entriesAdded = 0;

                // Check each preceding namespace.  If it starts with the
                // parent's name, insert it as a child of that one.
                for (childIdx = 0; childIdx < parentIdx; childIdx++)
                {
                    name = namespaceList[childIdx];

                    if (name.StartsWith(parent + ".", StringComparison.Ordinal))
                    {
                        tocEntry  = namespaceNodes[name];
                        tocParent = namespaceNodes[parent];

                        if (insertBelow && entriesAdded < tocParent.ChildNodes.Count)
                        {
                            tocParent.InsertAfter(tocEntry, tocParent.ChildNodes[
                                                      tocParent.ChildNodes.Count - entriesAdded - 1]);
                        }
                        else
                        {
                            tocParent.InsertBefore(tocEntry, tocParent.ChildNodes[0]);
                        }

                        namespaceList.RemoveAt(childIdx);
                        entriesAdded++;
                        parentIdx--;
                        childIdx--;
                    }
                }
            }

            toc.Save(builder.WorkingFolder + "toc.xml");
        }
Example #22
0
        public override bool Execute()
        {
            Log.LogMessage(MessageImportance.Low, "Starting XML Merge");

            string sourcePath = string.Empty;

            if (this.Source != null)
            {
                sourcePath = this.Source.GetMetadata("FullPath");
            }

            if (string.IsNullOrEmpty(sourcePath) || !File.Exists(sourcePath))
            {
                Log.LogError("File \'{0}\' does not exist", sourcePath);
                return(false);
            }

            string mergeSourcePath = string.Empty;

            if (this.MergeSource != null)
            {
                mergeSourcePath = this.MergeSource.GetMetadata("FullPath");
            }

            if (string.IsNullOrEmpty(mergeSourcePath) || !File.Exists(mergeSourcePath))
            {
                Log.LogError("File \'{0}\' does not exist", mergeSourcePath);
                return(false);
            }

            if (string.IsNullOrEmpty(this.SourceQuery))
            {
                Log.LogError("Source XPath query is empty");
                return(false);
            }

            if (string.IsNullOrEmpty(this.MergeQuery))
            {
                Log.LogError("Merge XPath query is empty");
                return(false);
            }

            try
            {
                var sourceXml = new XmlDocument();
                sourceXml.Load(sourcePath);

                XPathNavigator      sourceNavigator  = sourceXml.CreateNavigator();
                XmlNamespaceManager sourceNamespaces = new XmlNamespaceManager(sourceNavigator.NameTable);

                if (!String.IsNullOrEmpty(this.NamespacePrefix) && !String.IsNullOrEmpty(this.NamespaceUri))
                {
                    sourceNamespaces.AddNamespace(this.NamespacePrefix, this.NamespaceUri);
                }

                XPathNavigator insertAfterObject = sourceNavigator.SelectSingleNode(this.SourceQuery, sourceNamespaces);

                var mergeXml = new XmlDocument();
                mergeXml.Load(mergeSourcePath);

                XPathNavigator      mergeNavigator  = mergeXml.CreateNavigator();
                XmlNamespaceManager mergeNamespaces = new XmlNamespaceManager(mergeNavigator.NameTable);

                if (!String.IsNullOrEmpty(this.NamespacePrefix) && !String.IsNullOrEmpty(this.NamespaceUri))
                {
                    mergeNamespaces.AddNamespace(this.NamespacePrefix, this.NamespaceUri);
                }

                foreach (XPathNavigator item in mergeNavigator.Select(this.MergeQuery, mergeNamespaces))
                {
                    insertAfterObject.InsertAfter(item);
                }

                sourceXml.Save(this.Target.GetMetadata("FullPath"));
            }
            catch (Exception ex)
            {
                Log.LogWarningFromException(ex);
            }

            return(!Log.HasLoggedErrors);
        }
		// Set soundbank-related bool settings in the wproj file.
	public static bool EnableBoolSoundbankSettingInWproj(string SettingName, string WwiseProjectPath)
	{
		try
		{
			if (WwiseProjectPath.Length == 0)
			{
				//  The setup should not fail if there is no wproj file set. Silently succeed.
				return true;
			}
			
			XmlDocument doc = new XmlDocument();
			doc.PreserveWhitespace = true;
			doc.Load(WwiseProjectPath);
			XPathNavigator Navigator = doc.CreateNavigator();
			
			// Navigate the wproj file (XML format) to where our setting should be
			string pathInXml = String.Format("/WwiseDocument/ProjectInfo/Project/PropertyList/Property[@Name='{0}']", SettingName);
			XPathExpression expression = XPathExpression.Compile(pathInXml);
			XPathNavigator node = Navigator.SelectSingleNode(expression);
			if( node == null )
			{
				// Setting isn't in the wproj, add it
				// Navigate to the SoundBankHeaderFilePath property (it is always there)
				expression = XPathExpression.Compile("/WwiseDocument/ProjectInfo/Project/PropertyList/Property[@Name='SoundBankHeaderFilePath']");
				node = Navigator.SelectSingleNode(expression);
				if (node == null)
				{
					// SoundBankHeaderFilePath not in wproj, invalid wproj file
					UnityEngine.Debug.LogError("Could not find SoundBankHeaderFilePath property in Wwise project file. File is invalid.");
					return false;
				}
				
				// Add the setting right above SoundBankHeaderFilePath
				string propertyToInsert = string.Format("<Property Name=\"{0}\" Type=\"bool\" Value=\"True\"/>", SettingName);
				node.InsertBefore(propertyToInsert);
			}
			else
			{
				// Value is present, we simply have to modify it.
				if( node.GetAttribute("Value", "") == "False" )
				{
					// Modify the value to true
					if (!node.MoveToAttribute("Value", ""))
					{
						return false;
					}
					
					node.SetValue("True");
				}
				else
				{
					// Parameter already set, nothing to do!
					return true;
				}
			}
			
			doc.Save(WwiseProjectPath);
		}
		catch (Exception)
		{
			return false;
		}
		
		return true;
	}
Example #24
0
        public static void GetExample()
        {
            const string xmlString = "<?xml version=\"1.0\" encoding=\"UTF - 8\"?><product><description>Product 5</description><price>150.0</price><quantity>500</quantity></product>";

            Console.WriteLine("Showing node by using XmlReader: ");

            using (var stringReader = new StringReader(xmlString))
            {
                using (var xmlReader = XmlReader.Create(stringReader))
                {
                    xmlReader.MoveToContent();

                    xmlReader.ReadStartElement("product");

                    xmlReader.ReadStartElement("description");
                    Console.WriteLine($"Description: {xmlReader.ReadString()}");
                    xmlReader.ReadEndElement();

                    xmlReader.ReadStartElement("price");
                    Console.WriteLine($"Price: {xmlReader.ReadString()}");
                    xmlReader.ReadEndElement();

                    xmlReader.ReadStartElement();
                    Console.WriteLine($"Quantity: {xmlReader.ReadString()}");
                    xmlReader.ReadEndElement();
                }
            }

            var stringWriter = new StringWriter();

            using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings {
                Indent = true
            }))
            {
                xmlWriter.WriteStartDocument();

                xmlWriter.WriteStartElement("product");

                xmlWriter.WriteElementString("description", "product description");

                xmlWriter.WriteStartElement("price");
                xmlWriter.WriteValue(10.0m);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteStartElement("quantity");
                xmlWriter.WriteValue(10);
                xmlWriter.WriteEndElement();

                xmlWriter.WriteEndElement();
                xmlWriter.Flush();
            }

            Console.WriteLine($"Using XmlWiter: \n {stringWriter}");

            var xmlDocument = new XmlDocument();

            xmlDocument.LoadXml(xmlString);

            var xmlNodeList = xmlDocument.GetElementsByTagName("product");

            foreach (XmlNode node in xmlNodeList)
            {
                var descriptionXmlNode = node.ChildNodes.Item(0);
                var priceXmlNode       = node.ChildNodes.Item(1);
                var quantityXmlNode    = node.ChildNodes.Item(2);

                Console.WriteLine($"Using XmlDocument, XmlNodeList - Description: {descriptionXmlNode.InnerText}, Price: {priceXmlNode.InnerText}, Quantity: {quantityXmlNode.InnerText}");
            }

            var xPathNavigator = xmlDocument.CreateNavigator();
            var product        = xPathNavigator.SelectSingleNode("product");

            var descriptionNavigatorValue = product.SelectSingleNode("description").Value;
            var priceNavigatorValue       = product.SelectSingleNode("price").Value;
            var quantityNavigatorValue    = product.SelectSingleNode("quantity").Value;

            Console.WriteLine($"Using XmlDocument, XPathNavigator - Description: {descriptionNavigatorValue}, Price: {priceNavigatorValue}, Quantity: {quantityNavigatorValue}");

            Console.WriteLine(stringWriter.ToString());
        }
Example #25
0
 public string returnStringWithSetup(string file, string xp)
 {
     XmlDocument doc = new XmlDocument();
     doc.Load(file);
     return returnString(doc.CreateNavigator(), xp);
 }
Example #26
0
        /// <summary>
        /// Load and initialize the plug-ins used by this project
        /// </summary>
        /// <exception cref="BuilderException">This is thrown if a requested plug-in is not found</exception>
        private void LoadPlugIns()
        {
            Lazy <IPlugIn, IPlugInMetadata> plugIn;
            IPlugIn       instance;
            XmlDocument   config;
            StringBuilder sb = new StringBuilder(256);

            this.ReportProgress("Loading and initializing plug-ins...");
            loadedPlugIns = new Dictionary <string, IPlugIn>();

            var availablePlugs = componentContainer.GetExports <IPlugIn, IPlugInMetadata>();
            var projectPlugIns = new Dictionary <string, string>();

            // Get the project plug-ins first
            foreach (var kv in project.PlugInConfigurations)
            {
                if (!kv.Value.Enabled)
                {
                    this.ReportProgress("{0} plug-in is disabled and will not be loaded", kv.Key);
                }
                else
                {
                    projectPlugIns.Add(kv.Key, kv.Value.Configuration);
                }
            }

            // Add presentation style plug-in dependencies that are not in the project already
            foreach (var dp in presentationStyle.PlugInDependencies)
            {
                if (!projectPlugIns.ContainsKey(dp.Id))
                {
                    projectPlugIns.Add(dp.Id, dp.Configuration);
                }
            }

            // Note that a list of failures is accumulated as we may need to run the Completion Notification
            // plug-in to report the failures when done.
            foreach (var kv in projectPlugIns)
            {
                plugIn = null;

                try
                {
                    plugIn = availablePlugs.FirstOrDefault(p => p.Metadata.Id == kv.Key);

                    if (plugIn == null)
                    {
                        sb.AppendFormat("Error: Unable to locate plug-in '{0}' in any of the component or " +
                                        "project folders and it cannot be used.\r\n", kv.Key);
                        continue;
                    }

                    // For partial builds, only plug-ins that run in partial builds are loaded
                    if (this.PartialBuildType == PartialBuildType.None || plugIn.Metadata.RunsInPartialBuild)
                    {
                        // Plug-ins are singletons and will be disposed of by the composition container when it
                        // is disposed of.
                        instance = plugIn.Value;

                        config = new XmlDocument();
                        config.LoadXml(kv.Value);

                        instance.Initialize(this, config.CreateNavigator());

                        loadedPlugIns.Add(kv.Key, instance);
                    }
                }
                catch (Exception ex)
                {
                    BuilderException bex = ex as BuilderException;

                    if (bex != null)
                    {
                        sb.AppendFormat("{0}: {1}\r\n", bex.ErrorCode, bex.Message);
                    }
                    else
                    {
                        sb.AppendFormat("{0}: Unexpected error: {1}\r\n",
                                        (plugIn != null) ? plugIn.Metadata.Id : kv.Key, ex.ToString());
                    }
                }
            }

            if (sb.Length != 0)
            {
                sb.Insert(0, "Plug-in loading errors:\r\n");
                throw new BuilderException("BE0028", sb.ToString());
            }
        }
        private DropOffResponse DropOff(ref DropOffRequest request, bool isForPackageId)
        {
            DropOffResponse response = new DropOffResponse();
            try
            {
                if ((isForPackageId) && (string.IsNullOrEmpty(request.DopuPackageId)))
                    throw (new System.ArgumentNullException("DopuPackageId", AppSettings.NullInputEncountered));

                if (string.IsNullOrEmpty(request.LocalPatientId))
                    throw (new System.ArgumentNullException("LocalPatientId", AppSettings.NullInputEncountered));

                if (string.IsNullOrEmpty(request.Token))
                    throw (new System.ArgumentNullException("Token", AppSettings.NullInputEncountered));

                if (string.IsNullOrEmpty(request.FromName))
                    throw (new System.ArgumentNullException("FromName", AppSettings.NullInputEncountered));

                if (request.EmailTo.Count == 0)
                    throw (new System.ArgumentNullException("EmailTo", AppSettings.NullInputEncountered));

                foreach (string email in request.EmailTo)
                {
                    if (string.IsNullOrEmpty(email))
                        throw (new System.ArgumentNullException("EmailTo", AppSettings.NullInputEncountered));
                }

                if (string.IsNullOrEmpty(request.EmailFrom))
                    throw (new System.ArgumentNullException("EmailFrom", AppSettings.NullInputEncountered));

                if (string.IsNullOrEmpty(request.EmailSubject))
                    throw (new System.ArgumentNullException("EmailSubject", AppSettings.NullInputEncountered));

                if (string.IsNullOrEmpty(request.SecretQuestion))
                    throw (new System.ArgumentNullException("SecretQuestion", AppSettings.NullInputEncountered));

                if (string.IsNullOrEmpty(request.SecretAnswer))
                    throw (new System.ArgumentNullException("SecretAnswer", AppSettings.NullInputEncountered));

                if (request.Things.Count == 0)
                    throw (new System.ArgumentNullException("Things", AppSettings.NullInputEncountered));

                List<HealthRecordItem> newRecords = new List<HealthRecordItem>();

                foreach (string thing in request.Things)
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(thing);
                    XPathNavigator nav = doc.CreateNavigator();

                    XPathNavigator navTypeId = nav.SelectSingleNode("//type-id");
                    Guid typeId = new Guid(navTypeId.InnerXml);

                    XPathNavigator navData = nav.SelectSingleNode("//data-xml");
                    navData.MoveToFirstChild();

                    newRecords.Add(new HealthRecordItem(typeId, navData));
                }

                HealthVaultConnection hv = new HealthVaultConnection(request.Token);

                if (isForPackageId)
                    response.SecretCode = hv.DropOff(request.DopuPackageId,
                                                     request.FromName,
                                                     request.LocalPatientId,
                                                     request.SecretQuestion,
                                                     request.SecretAnswer,
                                                     ref newRecords);
                else
                    response.SecretCode = hv.DropOff(request.FromName,
                                                     request.LocalPatientId,
                                                     request.SecretQuestion,
                                                     request.SecretAnswer,
                                                     ref newRecords);

                // Compose the pickup URL using the Microsoft.Health.Web utilities...
                // e.g.  https://account.healthvault-ppe.com/patientwelcome.aspx?packageid=JKXF-JRMX-ZKZM-KGZM-RKKX
                // e.g. https://shellhostname/redirect.aspx?target=PICKUP&targetqs=packageid%3dJKYZ-QNMN-VHRX-ZGNR-GZNH

                response.PickupUrl = AppSettings.PickupUrl();
                response.PickupUrl += @"?packageid=";
                response.PickupUrl += response.SecretCode;

                string emailBody = AppSettings.DOPUemailTemplate.Replace("[PICKUP]", response.PickupUrl);
                emailBody = emailBody.Replace("[SECRET]", response.SecretCode);

                hv.SendInsecureMessageFromApplication(request.EmailTo, request.EmailFrom, request.EmailSubject, emailBody);
            }
            catch (Microsoft.Health.HealthServiceException hex)
            {
                response.Success = false;
                response.Message = hex.ToString();
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.Message = ex.Message;
                response.Stack = ex.StackTrace;
            }
            return (response);
        }
Example #28
0
        public void StartManually()
        {
            //connect to OD db.
            XmlDocument document = new XmlDocument();
            string      pathXml  = Path.Combine(Application.StartupPath, "FreeDentalConfig.xml");

            try{
                document.Load(pathXml);
            }
            catch {
                EventLog.WriteEntry("OpenDentHL7", DateTime.Now.ToLongTimeString() + " - Could not find " + pathXml, EventLogEntryType.Error);
                throw new ApplicationException("Could not find " + pathXml);
            }
            XPathNavigator Navigator = document.CreateNavigator();
            XPathNavigator nav;

            DataConnection.DBtype = DatabaseType.MySql;
            nav = Navigator.SelectSingleNode("//DatabaseConnection");
            string         computerName = nav.SelectSingleNode("ComputerName").Value;
            string         database     = nav.SelectSingleNode("Database").Value;
            string         user         = nav.SelectSingleNode("User").Value;
            string         password     = nav.SelectSingleNode("Password").Value;
            XPathNavigator verboseNav   = Navigator.SelectSingleNode("//HL7verbose");

            if (verboseNav != null && verboseNav.Value == "True")
            {
                IsVerboseLogging = true;
                EventLog.WriteEntry("OpenDentHL7", "Verbose mode.", EventLogEntryType.Information);
            }
            OpenDentBusiness.DataConnection dcon = new OpenDentBusiness.DataConnection();
            //Try to connect to the database directly
            try {
                dcon.SetDb(computerName, database, user, password, "", "", DataConnection.DBtype);
                //a direct connection does not utilize lower privileges.
                RemotingClient.RemotingRole = RemotingRole.ClientDirect;
            }
            catch {            //(Exception ex){
                throw new ApplicationException("Connection to database failed.");
            }
            //check db version
            string dbVersion = PrefC.GetString(PrefName.ProgramVersion);

            if (Application.ProductVersion.ToString() != dbVersion)
            {
                EventLog.WriteEntry("OpenDentHL7", "Versions do not match.  Db version:" + dbVersion + ".  Application version:" + Application.ProductVersion.ToString(), EventLogEntryType.Error);
                throw new ApplicationException("Versions do not match.  Db version:" + dbVersion + ".  Application version:" + Application.ProductVersion.ToString());
            }
            if (Programs.IsEnabled(ProgramName.eClinicalWorks) && !HL7Defs.IsExistingHL7Enabled())             //eCW enabled, and no HL7def enabled.
            //prevent startup:
            {
                long   progNum        = Programs.GetProgramNum(ProgramName.eClinicalWorks);
                string hl7Server      = ProgramProperties.GetPropVal(progNum, "HL7Server");
                string hl7ServiceName = ProgramProperties.GetPropVal(progNum, "HL7ServiceName");
                if (hl7Server == "")               //for the first time run
                {
                    ProgramProperties.SetProperty(progNum, "HL7Server", System.Environment.MachineName);
                    hl7Server = System.Environment.MachineName;
                }
                if (hl7ServiceName == "")               //for the first time run
                {
                    ProgramProperties.SetProperty(progNum, "HL7ServiceName", this.ServiceName);
                    hl7ServiceName = this.ServiceName;
                }
                if (hl7Server.ToLower() != System.Environment.MachineName.ToLower())
                {
                    EventLog.WriteEntry("OpenDentHL7", "The HL7 Server name does not match the name set in Program Links eClinicalWorks Setup.  Server name: " + System.Environment.MachineName
                                        + ", Server name in Program Links: " + hl7Server, EventLogEntryType.Error);
                    throw new ApplicationException("The HL7 Server name does not match the name set in Program Links eClinicalWorks Setup.  Server name: " + System.Environment.MachineName
                                                   + ", Server name in Program Links: " + hl7Server);
                }
                if (hl7ServiceName.ToLower() != this.ServiceName.ToLower())
                {
                    EventLog.WriteEntry("OpenDentHL7", "The HL7 Service Name does not match the name set in Program Links eClinicalWorks Setup.  Service name: " + this.ServiceName + ", Service name in Program Links: "
                                        + hl7ServiceName, EventLogEntryType.Error);
                    throw new ApplicationException("The HL7 Service Name does not match the name set in Program Links eClinicalWorks Setup.  Service name: " + this.ServiceName + ", Service name in Program Links: "
                                                   + hl7ServiceName);
                }
                EcwOldSendAndReceive();
                return;
            }
            HL7Def hL7Def = HL7Defs.GetOneDeepEnabled();

            if (hL7Def == null)
            {
                return;
            }
            if (hL7Def.HL7Server == "")
            {
                hL7Def.HL7Server = System.Environment.MachineName;
                HL7Defs.Update(hL7Def);
            }
            if (hL7Def.HL7ServiceName == "")
            {
                hL7Def.HL7ServiceName = this.ServiceName;
                HL7Defs.Update(hL7Def);
            }
            if (hL7Def.HL7Server.ToLower() != System.Environment.MachineName.ToLower())
            {
                EventLog.WriteEntry("OpenDentHL7", "The HL7 Server name does not match the name in the enabled HL7Def Setup.  Server name: " + System.Environment.MachineName + ", Server name in HL7Def: " + hL7Def.HL7Server,
                                    EventLogEntryType.Error);
                throw new ApplicationException("The HL7 Server name does not match the name in the enabled HL7Def Setup.  Server name: " + System.Environment.MachineName + ", Server name in HL7Def: " + hL7Def.HL7Server);
            }
            if (hL7Def.HL7ServiceName.ToLower() != this.ServiceName.ToLower())
            {
                EventLog.WriteEntry("OpenDentHL7", "The HL7 Service Name does not match the name in the enabled HL7Def Setup.  Service name: " + this.ServiceName + ", Service name in HL7Def: " + hL7Def.HL7ServiceName,
                                    EventLogEntryType.Error);
                throw new ApplicationException("The HL7 Service Name does not match the name in the enabled HL7Def Setup.  Service name: " + this.ServiceName + ", Service name in HL7Def: " + hL7Def.HL7ServiceName);
            }
            HL7DefEnabled = hL7Def;          //so we can access it later from other methods
            if (HL7DefEnabled.ModeTx == ModeTxHL7.File)
            {
                hl7FolderOut = HL7DefEnabled.OutgoingFolder;
                hl7FolderIn  = HL7DefEnabled.IncomingFolder;
                if (!Directory.Exists(hl7FolderOut))
                {
                    EventLog.WriteEntry("OpenDentHL7", "The outgoing HL7 folder does not exist.  Path is set to: " + hl7FolderOut, EventLogEntryType.Error);
                    throw new ApplicationException("The outgoing HL7 folder does not exist.  Path is set to: " + hl7FolderOut);
                }
                if (!Directory.Exists(hl7FolderIn))
                {
                    EventLog.WriteEntry("OpenDentHL7", "The incoming HL7 folder does not exist.  Path is set to: " + hl7FolderIn, EventLogEntryType.Error);
                    throw new ApplicationException("The incoming HL7 folder does not exist.  Path is set to: " + hl7FolderIn);
                }
                //start polling the folder for waiting messages to import.  Every 5 seconds.
                TimerCallback timercallbackReceive = new TimerCallback(TimerCallbackReceiveFiles);
                timerReceiveFiles = new System.Threading.Timer(timercallbackReceive, null, 5000, 5000);
                //start polling the db for new HL7 messages to send. Every 1.8 seconds.
                TimerCallback timercallbackSend = new TimerCallback(TimerCallbackSendFiles);
                timerSendFiles = new System.Threading.Timer(timercallbackSend, null, 1800, 1800);
            }
            else              //TCP/IP
            {
                CreateIncomingTcpListener();
                //start a timer to poll the database and to send messages as needed.  Every 6 seconds.  We increased the time between polling the database from 3 seconds to 6 seconds because we are now waiting 5 seconds for a message acknowledgment from eCW.
                TimerCallback timercallbackSendTCP = new TimerCallback(TimerCallbackSendTCP);
                timerSendTCP = new System.Threading.Timer(timercallbackSendTCP, null, 1800, 6000);
            }
        }
        public ActionResult OnPostImport(IFormFile xmlFile)
        {
            var uploads  = _hostingEnvironment.WebRootPath;
            var filePath = Path.Combine(uploads, xmlFile.FileName).ToString();

            if (xmlFile.ContentType.Equals("application/xml") || xmlFile.ContentType.Equals("text/xml"))
            {
                using (XmlReader xmlReader = XmlReader.Create(xmlFile.OpenReadStream()))
                {
                    var doc = new XmlDocument();
                    doc.Load(xmlReader);
                    var            nsmgr = new XmlNamespaceManager(doc.NameTable);
                    XPathNavigator nav   = doc.CreateNavigator();

                    nsmgr.AddNamespace("cac", @"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                    nsmgr.AddNamespace("cbc", @"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                    nsmgr.AddNamespace("ccts", @"urn:un:unece:uncefact:documentation:2");
                    nsmgr.AddNamespace("ds ", @"http://www.w3.org/2000/09/xmldsig#");
                    nsmgr.AddNamespace("ext", @"urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                    nsmgr.AddNamespace("qdt", @"urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
                    nsmgr.AddNamespace("udt", @"urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
                    nsmgr.AddNamespace("xsi", @"http://www.w3.org/2001/XMLSchema-instance");
                    nsmgr.AddNamespace("ns", @"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2");

                    GetTextFromXML getXml = new GetTextFromXML(nav, nsmgr);

                    documentDTO newDocument = new documentDTO()
                    {
                        ruc_empresa_cliente   = getXml.GetString(urlXmlSunat.ruc_empresa_cliente),
                        ruc_empresa_proveedor = getXml.GetString(urlXmlSunat.ruc_empresa_proveedor),
                        num_correlativo       = getXml.GetString(urlXmlSunat.id_factura).Contains("-") ? getXml.GetString(urlXmlSunat.id_factura).Split("-")[1] : "",
                        num_serie             = getXml.GetString(urlXmlSunat.id_factura).Contains("-") ? getXml.GetString(urlXmlSunat.id_factura).Split("-")[0] : "",
                        fis_elec      = false,
                        fecha_emision = getXml.GetDateHour(urlXmlSunat.dia_emision, urlXmlSunat.hora_emision),

                        monto_subtotal_afecto = getXml.GetAmount(urlXmlSunat.monto_subtotal_afecto),
                        monto_igv             = getXml.GetAmount(urlXmlSunat.monto_igv),
                        monto_total           = getXml.GetAmount(urlXmlSunat.monto_total),

                        monto_subtotal_inafecto = 0,
                    };



                    return(Ok(newDocument));

                    string a = "";

                    /*
                     * XmlDocument doc = new XmlDocument();
                     *
                     * doc.Load(xmlReader);
                     *
                     * //XPathDocument doc = new XPathDocument(xmlReader);
                     *
                     * XPathNavigator nav = doc.CreateNavigator();
                     * //object xx = nav.GetAttribute(@"/Invoice");
                     *
                     * XmlNamespaceManager nsmgr =
                     *       new XmlNamespaceManager(doc.NameTable);
                     *
                     *
                     *
                     *
                     * //nsmgr.AddNamespace("xmlns", @"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"); ;
                     * nsmgr.AddNamespace("cac" , @"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2");
                     * nsmgr.AddNamespace("cbc" , @"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2");
                     * nsmgr.AddNamespace("ccts" , @"urn:un:unece:uncefact:documentation:2");
                     * nsmgr.AddNamespace("ds ", @"http://www.w3.org/2000/09/xmldsig#");
                     * nsmgr.AddNamespace("ext" , @"urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2");
                     * nsmgr.AddNamespace("qdt" , @"urn:oasis:names:specification:ubl:schema:xsd:QualifiedDatatypes-2");
                     * nsmgr.AddNamespace("udt" , @"urn:un:unece:uncefact:data:specification:UnqualifiedDataTypesSchemaModule:2");
                     * nsmgr.AddNamespace("xsi", @"http://www.w3.org/2001/XMLSchema-instance");
                     *
                     * string xpath = @"/invoice/cac:PrepaidPayment";
                     * string xxx = @"/invoice/cac:InvoiceLine/cac:DocumentReference/cbc:ID";
                     *
                     * string pochito = @"cac:PrepaidPayment";
                     * string xxx2 = @"cac:InvoiceLine/cac:DocumentReference/cbc:ID";
                     *
                     * XPathNavigator element = nav.SelectSingleNode(xpath, nsmgr);
                     * XPathNavigator element2 = nav.SelectSingleNode(xxx, nsmgr);
                     * XPathNavigator element3 = nav.SelectSingleNode(pochito, nsmgr);
                     * XPathNavigator element4 = nav.SelectSingleNode(xxx2, nsmgr);
                     *
                     * XmlNodeList list = doc.SelectNodes(xpath, nsmgr);
                     * XmlNodeList list2 = doc.SelectNodes(xxx, nsmgr);
                     * XmlNodeList list3 = doc.SelectNodes(pochito, nsmgr);
                     * XmlNodeList list4 = doc.SelectNodes(xxx2, nsmgr);
                     *
                     * return Ok(list);
                     *
                     * /*
                     * var list = doc.XPathSelectElement(xpath, nsmgr);
                     * var list1 = doc.XPathSelectElement(xxx, nsmgr);
                     * var list2 = doc.XPathSelectElement(pochito, nsmgr);
                     * var list3 = doc.XPathSelectElement(xxx2, nsmgr);
                     *
                     *
                     * //XmlNodeList list = doc.Root.SetValue("//cbc:ID", manager);
                     *
                     * var id = doc.Root.XPathSelectElement("cbc:ID", nsmgr).Value;
                     *
                     *
                     * object o = nav.GetNamespace(xxx);
                     * //XmlNodeList xnl = root.SelectNodes(xpath, nsmgr);
                     *
                     * var x = doc.Root.XPathEvaluate(xxx, nsmgr);
                     *
                     * return Ok(element);
                     *
                     * Console.WriteLine("Element Prefix:" + element.Prefix +
                     *         " Local name:" + element.LocalName);
                     * Console.WriteLine("Namespace URI: " +
                     *          element.NamespaceURI);
                     */
                }
            }
            return(BadRequest());
        }
Example #30
0
    public static string GetWwiseSoundBankDestinationFolder(string Platform, string WwiseProjectPath)
    {
        try
        {
            if (WwiseProjectPath.Length == 0)
            {
                return "";
            }

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

            // Navigate the wproj file (XML format) to where generated soundbank paths are stored
            string PathExpression = string.Format("//Property[@Name='SoundBankPaths']/ValueList/Value[@Platform='{0}']", Platform);
            XPathExpression expression = XPathExpression.Compile(PathExpression);
            XPathNavigator node = Navigator.SelectSingleNode(expression);
            string Path = "";
            if( node != null )
            {
                Path = node.Value;
                #if !(UNITY_EDITOR_WIN || UNITY_XBOX360 || UNITY_XBOXONE || UNITY_METRO)
                AkBankPathUtil.ConvertToPosixPath(ref Path);
                #endif // #if !(UNITY_EDITOR_WIN || UNITY_XBOX360 || UNITY_XBOXONE || UNITY_METRO)
            }

            return Path;
        }
        catch( Exception )
        {
            // Error happened, return empty string
            return "";
        }
    }
		public void Execute()
		{
			XmlDocument document = new XmlDocument();
			document.Load(_xmlFileName);

			XPathNavigator navigator = document.CreateNavigator();
			XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);

			if (!string.IsNullOrEmpty(_prefix) && !string.IsNullOrEmpty(_namespace))
			{
				manager.AddNamespace(_prefix, _namespace);
			}

			XPathExpression expression = XPathExpression.Compile(_xpath, manager);
			XPathNodeIterator nodes = navigator.Select(expression);


			while (nodes.MoveNext())
				nodes.Current.SetValue(_value);

			using (XmlTextWriter writer = new XmlTextWriter(_xmlFileName, Encoding.UTF8))
			{
				writer.Formatting = Formatting.Indented;
				document.Save(writer);
				writer.Close();
			}
		}
Example #32
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;
    }
Example #33
0
        /// <summary>
        /// Returns true if legacy settings node is present in runsettings
        /// </summary>
        /// <param name="runsettingsXml">The run settings xml string</param>
        /// <param name="legacySettingsTelemetry">The telemetry data that needs to be captured</param>
        /// <returns></returns>
        public static bool TryGetLegacySettingElements(string runsettingsXml, out Dictionary <string, string> legacySettingsTelemetry)
        {
            legacySettingsTelemetry = new Dictionary <string, string>();
            try
            {
                using (var stream = new StringReader(runsettingsXml))
                    using (var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings))
                    {
                        var document = new XmlDocument();
                        document.Load(reader);
                        var runSettingsNavigator = document.CreateNavigator();

                        var node = runSettingsNavigator.SelectSingleNode(@"/RunSettings/LegacySettings");
                        if (node == null)
                        {
                            return(false);
                        }

                        var childNodes = node.SelectChildren(XPathNodeType.Element);

                        var legacySettingElements = new List <string>();
                        while (childNodes.MoveNext())
                        {
                            legacySettingElements.Add(childNodes.Current.Name);
                        }

                        foreach (var executionNodePath in ExecutionNodesPaths)
                        {
                            var executionNode = runSettingsNavigator.SelectSingleNode(executionNodePath);
                            if (executionNode != null)
                            {
                                legacySettingElements.Add(executionNode.Name);
                            }
                        }

                        if (legacySettingElements.Count > 0)
                        {
                            legacySettingsTelemetry.Add(LegacyElementsString, string.Join(", ", legacySettingElements));
                        }

                        var deploymentNode       = runSettingsNavigator.SelectSingleNode(@"/RunSettings/LegacySettings/Deployment");
                        var deploymentAttributes = GetNodeAttributes(deploymentNode);
                        if (deploymentAttributes != null)
                        {
                            legacySettingsTelemetry.Add(DeploymentAttributesString, string.Join(", ", deploymentAttributes));
                        }

                        var executiontNode       = runSettingsNavigator.SelectSingleNode(@"/RunSettings/LegacySettings/Execution");
                        var executiontAttributes = GetNodeAttributes(executiontNode);
                        if (executiontAttributes != null)
                        {
                            legacySettingsTelemetry.Add(ExecutionAttributesString, string.Join(", ", executiontAttributes));
                        }
                    }
            }
            catch (Exception ex)
            {
                EqtTrace.Error("Error while trying to read legacy settings. Message: {0}", ex.ToString());
                return(false);
            }

            return(true);
        }
Example #34
0
 public void init(IXPathNavigable navigable)
 {
     navigator = document.CreateNavigator();
     ns        = new XmlNamespaceManager(navigator.NameTable);
     ns.AddNamespace("u", "http://unitsofmeasure.org/ucum-essence");
 }
Example #35
0
        /// <summary>
        /// Make runsettings compatible with testhost of version 15.0.0-preview
        /// Due to bug https://github.com/Microsoft/vstest/issues/970 we need this function
        /// </summary>
        /// <param name="runsettingsXml">string content of runsettings </param>
        /// <returns>compatible runsettings</returns>
        public static string MakeRunsettingsCompatible(string runsettingsXml)
        {
            var updatedRunSettingsXml = runsettingsXml;

            if (!string.IsNullOrWhiteSpace(runsettingsXml))
            {
                using (var stream = new StringReader(runsettingsXml))
                    using (var reader = XmlReader.Create(stream, XmlRunSettingsUtilities.ReaderSettings))
                    {
                        var document = new XmlDocument();
                        document.Load(reader);

                        var runSettingsNavigator = document.CreateNavigator();

                        // Move navigator to RunConfiguration node
                        if (!runSettingsNavigator.MoveToChild(RunSettingsNodeName, string.Empty) ||
                            !runSettingsNavigator.MoveToChild(RunConfigurationNodeName, string.Empty))
                        {
                            EqtTrace.Error("InferRunSettingsHelper.MakeRunsettingsCompatible: Unable to navigate to RunConfiguration. Current node: " + runSettingsNavigator.LocalName);
                        }
                        else if (runSettingsNavigator.HasChildren)
                        {
                            var listOfInValidRunConfigurationSettings = new List <string>();

                            // These are the list of valid RunConfiguration setting name which old testhost understand.
                            var listOfValidRunConfigurationSettings = new HashSet <string>
                            {
                                "TargetPlatform",
                                "TargetFrameworkVersion",
                                "TestAdaptersPaths",
                                "ResultsDirectory",
                                "SolutionDirectory",
                                "MaxCpuCount",
                                "DisableParallelization",
                                "DisableAppDomain"
                            };

                            // Find all invalid RunConfiguration Settings
                            runSettingsNavigator.MoveToFirstChild();
                            do
                            {
                                if (!listOfValidRunConfigurationSettings.Contains(runSettingsNavigator.LocalName))
                                {
                                    listOfInValidRunConfigurationSettings.Add(runSettingsNavigator.LocalName);
                                }
                            } while (runSettingsNavigator.MoveToNext());

                            // Delete all invalid RunConfiguration Settings
                            if (listOfInValidRunConfigurationSettings.Count > 0)
                            {
                                if (EqtTrace.IsWarningEnabled)
                                {
                                    string settingsName = string.Join(", ", listOfInValidRunConfigurationSettings);
                                    EqtTrace.Warning(string.Format("InferRunSettingsHelper.MakeRunsettingsCompatible: Removing the following settings: {0} from RunSettings file. To use those settings please move to latest version of Microsoft.NET.Test.Sdk", settingsName));
                                }

                                // move navigator to RunConfiguration node
                                runSettingsNavigator.MoveToParent();

                                foreach (var s in listOfInValidRunConfigurationSettings)
                                {
                                    var nodePath = RunConfigurationNodePath + "/" + s;
                                    XmlUtilities.RemoveChildNode(runSettingsNavigator, nodePath, s);
                                }

                                runSettingsNavigator.MoveToRoot();
                                updatedRunSettingsXml = runSettingsNavigator.OuterXml;
                            }
                        }
                    }
            }

            return(updatedRunSettingsXml);
        }
Example #36
0
        private List <Appointment> ParseAppointmentResultSetXml(XmlDocument doc)
        {
            List <Appointment> result = new List <Appointment>();
            XPathNavigator     nav    = doc.CreateNavigator();
            bool active = nav.MoveToFirstChild();

            XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);

            ns.AddNamespace("dav", "DAV:");
            ns.AddNamespace("cal", "urn:schemas:calendar:");
            ns.AddNamespace("mail", "urn:schemas:mailheader:");
            ns.AddNamespace("f", "http://schemas.microsoft.com/mapi/proptag/");
            ns.AddNamespace("g", "http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/");
            ns.AddNamespace("h", "http://schemas.microsoft.com/mapi/id/{00062002-0000-0000-C000-000000000046}/");

            XmlNodeList nodes = doc.SelectNodes("//dav:response", ns);

            foreach (XmlNode node in nodes)
            {
                Appointment appt = new Appointment();

                appt.HRef = node.SelectSingleNode("dav:href", ns).InnerXml;
                XmlNode prop = node.SelectSingleNode("dav:propstat[1]/dav:prop", ns);

                appt.AllDayEvent =
                    GetPropertyAsBool(prop, "cal:alldayevent", ns);

                appt.Body =
                    GetPropertyAsXML(prop, "f:x1000001e", ns);

                appt.BusyStatus = ConversionsUtil.ParseBusyStatus(
                    GetPropertyAsString(prop, "cal:busystatus", appt.BusyStatus.ToString(), ns));

                appt.Comment =
                    GetPropertyAsString(prop, "dav:comment", ns);

                appt.Created =
                    GetPropertyAsDateTime(prop, "dav:creationdate", ns);

                appt.StartDate =
                    GetPropertyAsDateTime(prop, "cal:dtstart", ns);

                appt.EndDate =
                    GetPropertyAsDateTime(prop, "cal:dtend", ns);

                appt.InstanceType = (InstanceType)Enum.Parse(
                    typeof(InstanceType),
                    GetPropertyAsString(prop, "cal:instancetype", appt.InstanceType.ToString(), ns),
                    true);

                appt.IsPrivate =
                    GetPropertyAsBool(prop, "g:x8506", ns);

                appt.Location =
                    GetPropertyAsString(prop, "cal:location", ns);

                appt.MeetingStatus = (MeetingStatus)Enum.Parse(
                    typeof(MeetingStatus),
                    GetPropertyAsString(prop, "cal:meetingstatus", appt.MeetingStatus.ToString(), ns),
                    true);

                appt.Organizer =
                    GetPropertyAsString(prop, "cal:organizer", ns);

                appt.ResponseStatus = (ResponseStatus)GetPropertyAsInt(prop, "h:x8218", (int)appt.ResponseStatus, ns);

                appt.Subject =
                    GetPropertyAsString(prop, "mail:subject", ns);

                result.Add(appt);
            }

            return(result);
        }
Example #37
0
    // Reads the user settings (not the project settings) to check if there is an override currently defined for the soundbank generation folders.
    public static bool IsSoundbankOverrideEnabled(string wwiseProjectPath)
    {
        string userConfigFile = Path.Combine(Path.GetDirectoryName(wwiseProjectPath), Path.GetFileNameWithoutExtension(wwiseProjectPath) + "." + Environment.UserName + ".wsettings");

        if (!File.Exists(userConfigFile))
        {
            return false;
        }

        XmlDocument userConfigDoc = new XmlDocument();
        userConfigDoc.Load(userConfigFile);
        XPathNavigator userConfigNavigator = userConfigDoc.CreateNavigator();

        XPathNavigator userConfigNode = userConfigNavigator.SelectSingleNode(XPathExpression.Compile("//Property[@Name='SoundBankPathUserOverride' and @Value = 'True']"));

        return (userConfigNode != null);
    }
        private void UpdateGearInfo()
        {
            // Retrieve the information for the selected Accessory.
            XmlNode objXmlAccessory = _objXmlDocument.SelectSingleNode("/chummer/accessories/accessory[name = \"" + lstAccessory.SelectedValue + "\"]");

            if (objXmlAccessory == null)
            {
                return;
            }

            if (objXmlAccessory.InnerXml.Contains("<rc>"))
            {
                lblRC.Visible      = true;
                lblRCLabel.Visible = true;
                lblRC.Text         = objXmlAccessory["rc"]?.InnerText;
            }
            else
            {
                lblRC.Visible      = false;
                lblRCLabel.Visible = false;
            }
            int intMaxRating;

            if (int.TryParse(objXmlAccessory["rating"]?.InnerText, out intMaxRating) && intMaxRating > 1)
            {
                nudRating.Enabled      = true;
                nudRating.Visible      = true;
                lblRatingLabel.Visible = true;
                nudRating.Maximum      = intMaxRating;
            }
            else
            {
                nudRating.Enabled      = false;
                nudRating.Visible      = false;
                lblRatingLabel.Visible = false;
            }
            List <string> strMounts = new List <string>();

            foreach (string strItem in objXmlAccessory["mount"]?.InnerText?.Split('/'))
            {
                strMounts.Add(strItem);
            }
            strMounts.Add("None");

            List <string> strAllowed = new List <string>();

            foreach (string strItem in _strAllowedMounts.Split('/'))
            {
                strAllowed.Add(strItem);
            }
            strAllowed.Add("None");
            cboMount.Items.Clear();
            foreach (string strCurrentMount in strMounts)
            {
                if (!string.IsNullOrEmpty(strCurrentMount))
                {
                    foreach (string strAllowedMount in strAllowed)
                    {
                        if (strCurrentMount == strAllowedMount)
                        {
                            cboMount.Items.Add(strCurrentMount);
                        }
                    }
                }
            }
            if (cboMount.Items.Count <= 1)
            {
                cboMount.Enabled = false;
            }
            else
            {
                cboMount.Enabled = true;
            }
            cboMount.SelectedIndex = 0;

            List <string> strExtraMounts = new List <string>();

            if (objXmlAccessory.InnerXml.Contains("<extramount>"))
            {
                foreach (string strItem in objXmlAccessory["extramount"]?.InnerText?.Split('/'))
                {
                    strExtraMounts.Add(strItem);
                }
            }
            strExtraMounts.Add("None");

            cboExtraMount.Items.Clear();
            foreach (string strCurrentMount in strExtraMounts)
            {
                if (!string.IsNullOrEmpty(strCurrentMount))
                {
                    foreach (string strAllowedMount in strAllowed)
                    {
                        if (strCurrentMount == strAllowedMount)
                        {
                            cboExtraMount.Items.Add(strCurrentMount);
                        }
                    }
                }
            }
            if (cboExtraMount.Items.Count <= 1)
            {
                cboExtraMount.Enabled = false;
            }
            else
            {
                cboExtraMount.Enabled = true;
            }
            cboExtraMount.SelectedIndex = 0;
            if (cboMount.SelectedItem.ToString() != "None" && cboExtraMount.SelectedItem.ToString() != "None" &&
                cboMount.SelectedItem.ToString() == cboExtraMount.SelectedItem.ToString())
            {
                cboExtraMount.SelectedIndex += 1;
            }
            XPathNavigator nav = _objXmlDocument.CreateNavigator();
            // Avail.
            // If avail contains "F" or "R", remove it from the string so we can use the expression.
            string strAvail     = string.Empty;
            string strAvailExpr = objXmlAccessory["avail"]?.InnerText;

            if (!string.IsNullOrWhiteSpace(strAvailExpr))
            {
                lblAvail.Text = strAvailExpr;
                if (strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "F" ||
                    strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "R")
                {
                    strAvail = strAvailExpr.Substring(strAvailExpr.Length - 1, 1);
                    // Remove the trailing character if it is "F" or "R".
                    strAvailExpr = strAvailExpr.Substring(0, strAvailExpr.Length - 1);
                }
                try
                {
                    XPathExpression xprAvail = nav.Compile(strAvailExpr.Replace("Rating", nudRating.Value.ToString(GlobalOptions.CultureInfo)));
                    int             intTmp;
                    if (int.TryParse(nav.Evaluate(xprAvail)?.ToString(), out intTmp))
                    {
                        lblAvail.Text = intTmp.ToString() + strAvail;
                    }
                }
                catch (XPathException)
                {
                }
            }
            else
            {
                lblAvail.Text = string.Empty;
            }
            lblAvail.Text = lblAvail.Text.Replace("R", LanguageManager.GetString("String_AvailRestricted")).Replace("F", LanguageManager.GetString("String_AvailForbidden"));
            if (!chkFreeItem.Checked)
            {
                string strCost = "0";
                if (objXmlAccessory.TryGetStringFieldQuickly("cost", ref strCost))
                {
                    strCost = strCost.Replace("Weapon Cost", _decWeaponCost.ToString(GlobalOptions.InvariantCultureInfo))
                              .Replace("Rating", nudRating.Value.ToString(GlobalOptions.CultureInfo));
                }
                if (strCost.StartsWith("Variable"))
                {
                    decimal decMin = 0;
                    decimal decMax = decimal.MaxValue;
                    strCost = strCost.TrimStart("Variable", true).Trim("()".ToCharArray());
                    if (strCost.Contains('-'))
                    {
                        string[] strValues = strCost.Split('-');
                        decimal.TryParse(strValues[0], out decMin);
                        decimal.TryParse(strValues[1], out decMax);
                    }
                    else
                    {
                        decimal.TryParse(strCost.FastEscape('+'), out decMin);
                    }

                    if (decMax == decimal.MaxValue)
                    {
                        lblCost.Text = $"{decMin:###,###,##0.##¥+}";
                    }
                    else
                    {
                        lblCost.Text = $"{decMin:###,###,##0.##} - {decMax:###,###,##0.##¥}";
                    }

                    lblTest.Text = _objCharacter.AvailTest(decMax, lblAvail.Text);
                }
                else
                {
                    decimal decCost = 0.0m;
                    try
                    {
                        XPathExpression xprCost = nav.Compile(strCost);
                        decCost = Convert.ToDecimal(nav.Evaluate(xprCost), GlobalOptions.InvariantCultureInfo);
                    }
                    catch (XPathException)
                    {
                    }

                    // Apply any markup.
                    decCost *= 1 + (nudMarkup.Value / 100.0m);

                    lblCost.Text = $"{decCost:###,###,##0.##¥}";
                    lblTest.Text = _objCharacter.AvailTest(decCost, lblAvail.Text);
                }
            }
            else
            {
                lblCost.Text = $"{0:###,###,##0.##¥}";
                lblTest.Text = _objCharacter.AvailTest(0, lblAvail.Text);
            }

            string strBookCode = objXmlAccessory["source"]?.InnerText;
            string strBook     = _objCharacter.Options.LanguageBookShort(strBookCode);
            string strPage     = objXmlAccessory["page"]?.InnerText;

            objXmlAccessory.TryGetStringFieldQuickly("altpage", ref strPage);
            lblSource.Text = strBook + " " + strPage;

            tipTooltip.SetToolTip(lblSource, _objCharacter.Options.LanguageBookLong(strBookCode) + " " + LanguageManager.GetString("String_Page") + " " + strPage);
        }
Example #39
0
    private static void UpdateSoundbanksDestinationFolders(string WwiseProjectPath)
    {
        try
        {
            if (WwiseProjectPath.Length == 0)
                return;

            if (!File.Exists(WwiseProjectPath))
                return;

            DateTime t = File.GetLastWriteTime(WwiseProjectPath);
            if (t <= s_LastBankPathUpdate)
                return;

            s_LastBankPathUpdate = t;
            s_ProjectBankPaths.Clear();

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

            // Gather the mapping of Custom platform to Base platform
            XPathNodeIterator itpf = Navigator.Select("//Platform");
            s_BaseToCustomPF.Clear();
            foreach (XPathNavigator node in itpf)
            {
                HashSet<string> customList = null;
                string basePF = node.GetAttribute("ReferencePlatform", "");
                if (!s_BaseToCustomPF.TryGetValue(basePF, out customList))
                {
                    customList = new HashSet<string>();
                    s_BaseToCustomPF[basePF] = customList;
                }

                customList.Add(node.GetAttribute("Name", ""));
            }

            // Navigate the wproj file (XML format) to where generated soundbank paths are stored
            XPathNodeIterator it = Navigator.Select("//Property[@Name='SoundBankPaths']/ValueList/Value");
            foreach (XPathNavigator node in it)
            {
                string path = "";
                path = node.Value;
                AkBasePathGetter.FixSlashes(ref path);
                string pf = node.GetAttribute("Platform", "");
                s_ProjectBankPaths[pf] = path;
            }
        }
        catch (Exception ex)
        {
            // Error happened, return empty string
            Debug.LogError("Wwise: Error while reading project " + WwiseProjectPath + ".  Exception: " + ex.Message);
        }
    }
Example #40
0
        private void UpdateGearInfo()
        {
            // Retrieve the information for the selected Accessory.
            XmlNode objXmlAccessory = _objXmlDocument.SelectSingleNode("/chummer/accessories/accessory[name = \"" + lstAccessory.SelectedValue + "\"]");

            if (objXmlAccessory.InnerXml.Contains("<rc>"))
            {
                lblRC.Visible      = true;
                lblRCLabel.Visible = true;
                lblRC.Text         = objXmlAccessory["rc"].InnerText;
            }
            else
            {
                lblRC.Visible      = false;
                lblRCLabel.Visible = false;
            }
            if (Convert.ToInt32(objXmlAccessory["rating"].InnerText) > 0)
            {
                nudRating.Enabled      = true;
                nudRating.Visible      = true;
                lblRatingLabel.Visible = true;
                nudRating.Maximum      = Convert.ToInt32(objXmlAccessory["rating"].InnerText);
            }
            else
            {
                nudRating.Value        = Convert.ToInt32(objXmlAccessory["rating"].InnerText);
                nudRating.Visible      = false;
                lblRatingLabel.Visible = false;
            }

            string[] strMounts = objXmlAccessory["mount"].InnerText.Split('/');
            string   strMount  = "";

            foreach (string strCurrentMount in strMounts)
            {
                if (strCurrentMount != "")
                {
                    strMount += LanguageManager.Instance.GetString("String_Mount" + strCurrentMount) + "/";
                }
            }
            // Remove the trailing /
            if (strMount != "" && strMount.Contains('/'))
            {
                strMount = strMount.Substring(0, strMount.Length - 1);
            }

            lblMount.Tag  = objXmlAccessory["mount"].InnerText;
            lblMount.Text = strMount;
            // Avail.
            // If avail contains "F" or "R", remove it from the string so we can use the expression.
            string          strAvail     = "";
            string          strAvailExpr = objXmlAccessory["avail"].InnerText;
            XPathExpression xprAvail;
            XPathNavigator  nav = _objXmlDocument.CreateNavigator();

            if (strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "F" || strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "R")
            {
                strAvail = strAvailExpr.Substring(strAvailExpr.Length - 1, 1);
                // Remove the trailing character if it is "F" or "R".
                strAvailExpr = strAvailExpr.Substring(0, strAvailExpr.Length - 1);
            }
            try
            {
                xprAvail      = nav.Compile(strAvailExpr.Replace("Rating", nudRating.Value.ToString()));
                lblAvail.Text = (Convert.ToInt32(nav.Evaluate(xprAvail))).ToString() + strAvail;
            }
            catch
            {
                lblAvail.Text = objXmlAccessory["avail"].InnerText;
            }
            lblAvail.Text = lblAvail.Text.Replace("R", LanguageManager.Instance.GetString("String_AvailRestricted")).Replace("F", LanguageManager.Instance.GetString("String_AvailForbidden"));
            string strCost = objXmlAccessory["cost"].InnerText;

            strCost = strCost.Replace("Weapon Cost", _intWeaponCost.ToString()).Replace("Rating", nudRating.Value.ToString());
            if (chkFreeItem.Checked)
            {
                strCost = "0";
            }

            if (strCost.Contains("Variable"))
            {
                lblCost.Text = strCost;
                lblTest.Text = "";
            }
            else
            {
                XPathExpression xprCost = nav.Compile(strCost);
                int             intCost = Convert.ToInt32(Convert.ToDouble(nav.Evaluate(xprCost), GlobalOptions.Instance.CultureInfo));

                // Apply any markup.
                double dblCost = Convert.ToDouble(intCost, GlobalOptions.Instance.CultureInfo);
                dblCost *= 1 + (Convert.ToDouble(nudMarkup.Value, GlobalOptions.Instance.CultureInfo) / 100.0);
                intCost  = Convert.ToInt32(dblCost);

                lblCost.Text = String.Format("{0:###,###,##0¥}", intCost);
                lblTest.Text = _objCharacter.AvailTest(intCost, lblAvail.Text);
            }

            string strBook = _objCharacter.Options.LanguageBookShort(objXmlAccessory["source"].InnerText);
            string strPage = objXmlAccessory["page"].InnerText;

            if (objXmlAccessory["altpage"] != null)
            {
                strPage = objXmlAccessory["altpage"].InnerText;
            }
            lblSource.Text = strBook + " " + strPage;

            tipTooltip.SetToolTip(lblSource, _objCharacter.Options.LanguageBookLong(objXmlAccessory["source"].InnerText) + " " + LanguageManager.Instance.GetString("String_Page") + " " + strPage);
        }
Example #41
0
    protected void Page_Load(object sender, EventArgs e)
    {
        string username = Convert.ToString(Session["username"]);
            Label1.Text = "Welcome" + " " + " " + username;
            if (!IsPostBack)
            {
                // The page is being loaded and accessed for the first time.
                // Retrieve user input from the form.
                if (Request.QueryString["s"] == null)
                    // Set the default stock symbol to YHOO.
                    m_symbol = "YHOO";
                else
                    // Get the user's input.
                    m_symbol = Request.QueryString["s"].ToString().ToUpper();
                // Update the textbox value.
                txtSymbol.Value = m_symbol;
                // This DIV that contains text and DIVs that displays stock quotes and chart from Yahoo.
                // Set the innerHTML property to replaces the existing content of the DIV.
                divService.InnerHtml = "<br />";
                if (m_symbol.Trim() != "")
                {
                    try
                    {
                        // Return the stock quote data in XML format.
                        String arg = GetQuote(m_symbol.Trim());
                        if (arg == null)
                            return;

                        // Read XML.
                        // Declare an XmlDocument object to represents an XML document.
                        XmlDocument xd = new XmlDocument();
                        // Loads the XML data from a stream.
                        xd.LoadXml(arg);

                        // Read XSLT
                        // Declare an XslCompiledTransform object to transform XML data using an XSLT style sheet.
                        XslCompiledTransform xslt = new XslCompiledTransform();
                        // Use the Load method to load the Xsl transform object.
                        xslt.Load(Server.MapPath("stock.xsl"));

                        // Transform the XML document into HTML.
                        StringWriter fs = new StringWriter();
                        xslt.Transform(xd.CreateNavigator(), null, fs);
                        string result = fs.ToString();

                        // Replace the characters "&gt;" and "&lt;" back to "<" and ">".
                        divService.InnerHtml = "<br />" + result.Replace("&lt;", "<").Replace("&gt;", ">") + "<br />";

                        // Display stock charts.
                        String[] symbols = m_symbol.Replace(",", " ").Split(' ');
                        // Loop through each stock
                        for (int i = 0; i < symbols.Length; ++i)
                        {
                            if (symbols[i].Trim() == "")
                                continue;
                            int index = divService.InnerHtml.ToLower().IndexOf(symbols[i].Trim().ToLower() + " is invalid.");
                            // If index = -1, the stock symbol is valid.
                            if (index == -1)
                            {
                                // Use a random number to defeat cache.
                                Random random = new Random();
                                divService.InnerHtml += "<img id='imgChart_" + i.ToString() + "' src='http://ichart.finance.yahoo.com/b?s=" + symbols[i].Trim().ToUpper() + "& " + random.Next() + "' border=0><br />";
                                // 1 days
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(0," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div1d_" + i.ToString() + "'><b>1d</b></span></a>&nbsp;&nbsp;";
                                // 5 days
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(1," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div5d_" + i.ToString() + "'>5d</span></a>&nbsp;&nbsp;";
                                // 3 months
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(2," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div3m_" + i.ToString() + "'>3m</span></a>&nbsp;&nbsp;";
                                // 6 months
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(3," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div6m_" + i.ToString() + "'>6m</span></a>&nbsp;&nbsp;";
                                // 1 yeas
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(4," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div1y_" + i.ToString() + "'>1y</span></a>&nbsp;&nbsp;";
                                // 2 years
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(5," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div2y_" + i.ToString() + "'>2y</span></a>&nbsp;&nbsp;";
                                // 5 years
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(6," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='div5y_" + i.ToString() + "'>5y</span></a>&nbsp;&nbsp;";
                                // Max
                                divService.InnerHtml += "<a style='font-family: Arial, Helvetica, sans-serif; font-size: 14px; color: Blue;' href='javascript:changeChart(7," + i.ToString() + ", \"" + symbols[i].ToLower() + "\");'><span id='divMax_" + i.ToString() + "'>Max</span></a><br><br /><br />&nbsp;&nbsp;";
                            }
                        }
                    }
                    catch
                    {
                        // Handle exceptions
                    }
                }
            }
    }
Example #42
0
        //=====================================================================

        /// <summary>
        /// This is used to perform the actual conversion
        /// </summary>
        /// <returns>The new project filename on success.  An exception is
        /// thrown if the conversion fails.</returns>
        public override string ConvertProject()
        {
            XmlNamespaceManager nsm;
            XmlDocument         sourceFile;
            XPathNavigator      navProject, navProp;
            SandcastleProject   project = base.Project;
            string includePath, lastProperty = null;

            try
            {
                project.HelpTitle = project.HtmlHelpName =
                    Path.GetFileNameWithoutExtension(base.OldProjectFile);

                sourceFile = new XmlDocument();
                sourceFile.Load(base.OldProjectFile);
                nsm = new XmlNamespaceManager(sourceFile.NameTable);
                nsm.AddNamespace("prj", sourceFile.DocumentElement.NamespaceURI);

                navProject = sourceFile.CreateNavigator();

                // Get the name, topic style, and language ID
                lastProperty = "Name";
                navProp      = navProject.SelectSingleNode(
                    "//prj:Project/prj:PropertyGroup/prj:Name", nsm);
                if (navProp != null)
                {
                    project.HtmlHelpName = project.HelpTitle = navProp.Value;
                }

                lastProperty = "TopicStyle";
                navProp      = navProject.SelectSingleNode(
                    "//prj:Project/prj:PropertyGroup/prj:TopicStyle", nsm);
                if (navProp != null)
                {
                    project.PresentationStyle = PresentationStyleTypeConverter.FirstMatching(
                        navProp.Value);
                }

                lastProperty = "LanguageId";
                navProp      = navProject.SelectSingleNode(
                    "//prj:Project/prj:PropertyGroup/prj:LanguageId", nsm);
                if (navProp != null)
                {
                    project.Language = new CultureInfo(Convert.ToInt32(
                                                           navProp.Value, CultureInfo.InvariantCulture));
                }

                // Add the documentation sources
                lastProperty = "Dlls|Comments";
                foreach (XPathNavigator docSource in navProject.Select(
                             "//prj:Project/prj:ItemGroup/prj:Dlls|" +
                             "//prj:Project/prj:ItemGroup/prj:Comments", nsm))
                {
                    includePath = docSource.GetAttribute("Include", String.Empty);

                    if (!String.IsNullOrEmpty(includePath))
                    {
                        project.DocumentationSources.Add(includePath, null,
                                                         null, false);
                    }
                }

                // Add the dependencies
                lastProperty = "Dependents";
                foreach (XPathNavigator dependency in navProject.Select(
                             "//prj:Project/prj:ItemGroup/prj:Dependents", nsm))
                {
                    includePath = dependency.GetAttribute("Include", String.Empty);

                    if (includePath.IndexOfAny(new char[] { '*', '?' }) == -1)
                    {
                        project.References.AddReference(
                            Path.GetFileNameWithoutExtension(includePath),
                            includePath);
                    }
                    else
                    {
                        foreach (string file in Directory.GetFiles(
                                     Path.GetDirectoryName(includePath),
                                     Path.GetFileName(includePath)))
                        {
                            if (file.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
                                file.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
                            {
                                project.References.AddReference(
                                    Path.GetFileNameWithoutExtension(file),
                                    file);
                            }
                        }
                    }
                }

                project.SaveProject(project.Filename);
            }
            catch (Exception ex)
            {
                throw new BuilderException("CVT0005", String.Format(
                                               CultureInfo.CurrentCulture, "Error reading project " +
                                               "from '{0}' (last property = {1}):\r\n{2}",
                                               base.OldProjectFile, lastProperty, ex.Message), ex);
            }

            return(project.Filename);
        }
	// Parses the .wproj to find out where soundbanks are generated for the given path
	public static string GetWwiseSoundBankDestinationFolder(string Platform, string WwiseProjectPath)
	{
		try
		{
			if (WwiseProjectPath.Length == 0)
			{
				return "";
			}
			
			XmlDocument doc = new XmlDocument();
			doc.Load(WwiseProjectPath);
			XPathNavigator Navigator = doc.CreateNavigator();
			
			// Navigate the wproj file (XML format) to where generated soundbank paths are stored
			string PathExpression = string.Format("//Property[@Name='SoundBankPaths']/ValueList/Value[@Platform='{0}']", Platform);
			XPathExpression expression = XPathExpression.Compile(PathExpression);
			XPathNavigator node = Navigator.SelectSingleNode(expression);
			string Path = "";
			if( node != null )
			{
				Path = node.Value;
				AkBasePathGetter.FixSlashes(ref Path);
			}
			
			return Path;
		}
		catch( Exception )
		{
			// Error happened, return empty string
			return "";
		}
	}
Example #44
0
        /// <summary>
        /// Update the information for the selected Armor Mod.
        /// </summary>
        private void UpdateSelectedArmor()
        {
            // Retireve the information for the selected Accessory.
            XmlNode objXmlMod = _objXmlDocument.SelectSingleNode("/chummer/mods/mod[name = \"" + lstMod.SelectedValue + "\"]");

            // Extract the Avil and Cost values from the Cyberware info since these may contain formulas and/or be based off of the Rating.
            // This is done using XPathExpression.
            XPathNavigator nav = _objXmlDocument.CreateNavigator();

            lblA.Text = objXmlMod["armor"].InnerText;

            nudRating.Maximum = Convert.ToDecimal(objXmlMod["maxrating"].InnerText, GlobalOptions.Instance.CultureInfo);
            if (nudRating.Maximum <= 1)
            {
                nudRating.Enabled = false;
            }
            else
            {
                nudRating.Enabled = true;
                if (nudRating.Minimum == 0)
                {
                    nudRating.Value   = 1;
                    nudRating.Minimum = 1;
                }
            }

            string strAvail     = "";
            string strAvailExpr = "";

            strAvailExpr = objXmlMod["avail"].InnerText;

            XPathExpression xprAvail;

            if (strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "F" || strAvailExpr.Substring(strAvailExpr.Length - 1, 1) == "R")
            {
                strAvail = strAvailExpr.Substring(strAvailExpr.Length - 1, 1);
                // Remove the trailing character if it is "F" or "R".
                strAvailExpr = strAvailExpr.Substring(0, strAvailExpr.Length - 1);
            }
            try
            {
                xprAvail      = nav.Compile(strAvailExpr.Replace("Rating", nudRating.Value.ToString()));
                lblAvail.Text = (Convert.ToInt32(nav.Evaluate(xprAvail))).ToString() + strAvail;
            }
            catch
            {
                lblAvail.Text = objXmlMod["avail"].InnerText;
            }
            lblAvail.Text = lblAvail.Text.Replace("R", LanguageManager.Instance.GetString("String_AvailRestricted")).Replace("F", LanguageManager.Instance.GetString("String_AvailForbidden"));

            // Cost.
            string strCost = objXmlMod["cost"].InnerText.Replace("Rating", nudRating.Value.ToString());

            strCost = strCost.Replace("Armor Cost", _intArmorCost.ToString());
            XPathExpression xprCost = nav.Compile(strCost);

            // Apply any markup.
            double dblCost = Convert.ToDouble(nav.Evaluate(xprCost), GlobalOptions.Instance.CultureInfo);

            dblCost *= 1 + (Convert.ToDouble(nudMarkup.Value, GlobalOptions.Instance.CultureInfo) / 100.0);

            lblCost.Text = String.Format("{0:###,###,##0¥}", dblCost);

            int intCost = Convert.ToInt32(dblCost);

            lblTest.Text = _objCharacter.AvailTest(intCost, lblAvail.Text);

            // Capacity.
            // XPathExpression cannot evaluate while there are square brackets, so remove them if necessary.
            string strCapacity = objXmlMod["armorcapacity"].InnerText;

            // Handle YNT Softweave
            if (strCapacity.Contains("Capacity"))
            {
                lblCapacity.Text = "+50%";
            }
            else
            {
                if (strCapacity.StartsWith("FixedValues"))
                {
                    string[] strValues = strCapacity.Replace("FixedValues(", string.Empty).Replace(")", string.Empty).Split(',');
                    strCapacity = strValues[Convert.ToInt32(nudRating.Value) - 1];
                }

                strCapacity = strCapacity.Substring(1, strCapacity.Length - 2);
                XPathExpression xprCapacity = nav.Compile(strCapacity.Replace("Rating", nudRating.Value.ToString()));

                if (_objCapacityStyle == CapacityStyle.Standard)
                {
                    lblCapacity.Text = "[" + nav.Evaluate(xprCapacity) + "]";
                }
                else if (_objCapacityStyle == CapacityStyle.PerRating)
                {
                    lblCapacity.Text = "[" + nudRating.Value.ToString() + "]";
                }
                else if (_objCapacityStyle == CapacityStyle.Zero)
                {
                    lblCapacity.Text = "[0]";
                }
            }

            if (chkFreeItem.Checked)
            {
                lblCost.Text = String.Format("{0:###,###,##0¥}", 0);
            }

            string strBook = _objCharacter.Options.LanguageBookShort(objXmlMod["source"].InnerText);
            string strPage = objXmlMod["page"].InnerText;

            if (objXmlMod["altpage"] != null)
            {
                strPage = objXmlMod["altpage"].InnerText;
            }
            lblSource.Text = strBook + " " + strPage;

            tipTooltip.SetToolTip(lblSource, _objCharacter.Options.LanguageBookLong(objXmlMod["source"].InnerText) + " " + LanguageManager.Instance.GetString("String_Page") + " " + strPage);
        }
	public static bool SetSoundbankHeaderFilePath(string WwiseProjectPath, string SoundbankPath)
	{
		try
		{
			if (WwiseProjectPath.Length == 0)
			{
				//  The setup should not fail if there is no wproj file set. Silently succeed.
				return true;
			}
			
			XmlDocument doc = new XmlDocument();
			doc.PreserveWhitespace = true;
			doc.Load(WwiseProjectPath);
			XPathNavigator Navigator = doc.CreateNavigator();
			
			// Navigate to where the header file path is saved. The node has to be there, or else the wproj is invalid.
			XPathExpression expression = XPathExpression.Compile("/WwiseDocument/ProjectInfo/Project/PropertyList/Property[@Name='SoundBankHeaderFilePath']");
			XPathNavigator node = Navigator.SelectSingleNode(expression);
			if (node == null)
			{
				UnityEngine.Debug.LogError("Could not find SoundBankHeaderFilePath property in Wwise project file. File is invalid.");
				return false;
			}
			
			// Change the "Value" attribute
			if( !node.MoveToAttribute("Value", "") )
			{
				return false;
			}
			
			node.SetValue(SoundbankPath);
			doc.Save(WwiseProjectPath);
			return true;
		}
		catch (Exception)
		{
			// Error happened, return empty string
			return false;
		}
	}
Example #46
0
        /// <summary>
        /// Modifies the provided XML document to contain the service definition
        /// nodes needed for the specified project.
        /// </summary>
        /// <exception cref="ArgumentException">
        /// <paramref name="roleType"/> is not one of "Web" or "Worker".
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// A required element is missing from the document.
        /// </exception>
        internal static void UpdateServiceDefinition(XmlDocument doc, string roleType, string projectName)
        {
            var isWeb    = roleType == "Web";
            var isWorker = roleType == "Worker";

            if (isWeb == isWorker)
            {
                throw new ArgumentException("Unknown role type: " + (roleType ?? "(null)"), nameof(roleType));
            }

            var nav = doc.CreateNavigator();

            var ns = new XmlNamespaceManager(doc.NameTable);

            ns.AddNamespace("sd", "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition");

            var role = nav.SelectSingleNode(string.Format(CultureInfo.InvariantCulture,
                                                          "/sd:ServiceDefinition/sd:{0}Role[@name='{1}']", roleType, projectName
                                                          ), ns);

            if (role == null)
            {
                throw new InvalidOperationException("Missing role entry");
            }

            var startup = role.SelectSingleNode("sd:Startup", ns);

            if (startup != null)
            {
                startup.DeleteSelf();
            }

            role.AppendChildElement(null, "Startup", null, null);
            startup = role.SelectSingleNode("sd:Startup", ns);
            if (startup == null)
            {
                throw new InvalidOperationException("Missing Startup entry");
            }

            startup.ReplaceSelf(string.Format(CultureInfo.InvariantCulture, @"<Startup>
  <Task commandLine=""setup_{0}.cmd &gt; log.txt"" executionContext=""elevated"" taskType=""simple"">
    <Environment>
      <Variable name=""EMULATED"">
        <RoleInstanceValue xpath=""/RoleEnvironment/Deployment/@emulated"" />
      </Variable>
      <Variable name=""RUNTIMEID"" value=""node"" />
      <Variable name=""RUNTIMEURL"" value=""http://az413943.vo.msecnd.net/node/0.10.21.exe;http://nodertncu.blob.core.windows.net/iisnode/0.1.21.exe"" />
    </Environment>
  </Task>{1}
</Startup>", roleType.ToLowerInvariant(), isWorker ? @"<Task commandLine=""node.cmd .\startup.js"" executionContext=""elevated"" />" : string.Empty));

            if (isWorker)
            {
                var runtime = role.SelectSingleNode("sd:Runtime", ns);
                if (runtime != null)
                {
                    runtime.DeleteSelf();
                }
                role.AppendChildElement(null, "Runtime", null, null);

                runtime = role.SelectSingleNode("sd:Runtime", ns);
                if (startup == null)
                {
                    throw new InvalidOperationException("Missing Runtime entry");
                }

                runtime.ReplaceSelf(@"<Runtime>
  <Environment>
    <Variable name=""EMULATED"">
      <RoleInstanceValue xpath=""/RoleEnvironment/Deployment/@emulated"" />
    </Variable>
  </Environment>
  <EntryPoint>
    <ProgramEntryPoint commandLine=""node.cmd .\server.js"" setReadyOnProcessStart=""true"" />
  </EntryPoint>
</Runtime>");
            }
        }
 /// <summary>
 /// Show the contacts on the display
 /// </summary>
 /// <param name="EngageContacts">An </param>
 public void ShowContacts(XmlDocument EngageContacts)
 {
     //Show div that our XML control is in and bind to the control
     EngageUserContacts.Visible = true;
     Contacts.XPathNavigator = EngageContacts.CreateNavigator();
     Contacts.DataBind();
 }
Example #48
0
        public XmlColladaSchema(XmlDocument doc)
        {
            XPathNavigator navigator = doc.CreateNavigator();

            // Move to the first child element of the document. This will be the root element.
            //navigator.MoveToChild(XPathNodeType.Element);
            navigator.MoveToFirstChild();
            string uri = string.Empty;
            if (navigator.HasAttributes == true)
            {
                uri = navigator.NamespaceURI;
            }

            // Handle asset data
            XPathNodeIterator nodesIterator;
            nodesIterator = navigator.SelectChildren(XmlCollada.Library_Geometries.root, uri);
            if (nodesIterator.MoveNext())
            {
                _asset = new XmlCollada.Asset(nodesIterator, uri);
            }

            // Handle geometry library data
            nodesIterator = navigator.SelectChildren(XmlCollada.Library_Geometries.root, uri);
            if (nodesIterator.MoveNext())
            {
                _geometries = new XmlCollada.Library_Geometries(nodesIterator, uri);
            }

            // Handle effects data
            nodesIterator = navigator.SelectChildren(XmlCollada.Library_Effects.root, uri);
            if (nodesIterator.MoveNext())
            {
                _effects = new XmlCollada.Library_Effects(nodesIterator, uri);
            }

            // Handle material data
            nodesIterator = navigator.SelectChildren(XmlCollada.Library_Materials.root, uri);
            if (nodesIterator.MoveNext())
            {
                _materials = new XmlCollada.Library_Materials(nodesIterator, uri);
            }

            // Handle visual scene data
            nodesIterator = navigator.SelectChildren(XmlCollada.Library_Visual_Scenes.root, uri);
            if (nodesIterator.MoveNext())
            {
                _visualScenes = new XmlCollada.Library_Visual_Scenes(nodesIterator, uri);
            }

            // Handle image data
            nodesIterator = navigator.SelectChildren(XmlCollada.Library_Images.root, uri);
            if (nodesIterator.MoveNext())
            {
                _images = new XmlCollada.Library_Images(nodesIterator, uri);
            }

            // Handle the scene
            nodesIterator = navigator.SelectChildren(XmlCollada.Scene.root, uri);
            if (nodesIterator.MoveNext())
            {
                _scene = new XmlCollada.Scene(nodesIterator, uri);
            }
        }
Example #49
0
 public XPathNavigator setupUp(string file)
 {
     XmlDocument doc = new XmlDocument();
     doc.Load(file);
     return doc.CreateNavigator();
 }
Example #50
0
    public string Serialize(Account acc, Char chr, int time, string killer, bool firstBorn)
    {
        __Char = chr;
        XmlDocument xmlDoc = new XmlDocument();
        {
            XmlSerializer serializer = new XmlSerializer(this.GetType()); //makes legends take a few seconds to load
            using (var wtr = xmlDoc.CreateNavigator().AppendChild())
                serializer.Serialize(wtr, this);
            xmlDoc.DocumentElement.Attributes.RemoveAll();
        }
        XmlElement ac = xmlDoc.CreateElement("Account");
        XmlElement name = xmlDoc.CreateElement("Name");
        name.InnerText = acc.Name;
        ac.AppendChild(name);

        xmlDoc.SelectSingleNode("/Fame/Char").AppendChild(ac);

        SerializeBonus(xmlDoc, acc, chr, chr.CurrentFame, firstBorn);

        XmlElement basFame = xmlDoc.CreateElement("BaseFame");
        basFame.InnerText = chr.CurrentFame.ToString();
        xmlDoc.DocumentElement.AppendChild(basFame);
        XmlElement totalFame = xmlDoc.CreateElement("TotalFame");
        totalFame.InnerText = CalculateTotal(acc, chr, chr.CurrentFame, out firstBorn).ToString();
        xmlDoc.DocumentElement.AppendChild(totalFame);
        XmlElement deathTime = xmlDoc.CreateElement("CreatedOn");
        deathTime.InnerText = time.ToString();
        xmlDoc.DocumentElement.AppendChild(deathTime);
        XmlElement killed = xmlDoc.CreateElement("KilledBy");
        killed.InnerText = killer;
        xmlDoc.DocumentElement.AppendChild(killed);

        StringWriter result = new StringWriter();
        xmlDoc.Save(result);
        return result.ToString();
    }
Example #51
0
        //=====================================================================

        /// <inheritdoc />
        public override void Apply(XmlDocument targetDocument, IXmlNamespaceResolver context)
        {
            // Get the index entry content
            XPathExpression keyExpr = this.Key.Clone();

            keyExpr.SetContext(context);

            string keyValue = (string)targetDocument.CreateNavigator().Evaluate(keyExpr);

            XPathNavigator data = this.SourceIndex[keyValue];

            if (data == null && !String.IsNullOrWhiteSpace(keyValue))
            {
                if (this.IgnoreCase)
                {
                    data = this.SourceIndex[keyValue.ToLowerInvariant()];
                }

                if (data == null)
                {
                    // For certain inherited explicitly implemented interface members, Microsoft is using
                    // incorrect member IDs in the XML comments files and on the content service.  If the
                    // failed member ID looks like one of them, try using the broken ID for the look up.
                    string brokenId = keyValue;

                    if (reDictionaryEII.IsMatch(brokenId))
                    {
                        brokenId = reGenericEII.Replace(brokenId, "#I$1{TKey@TValue}#");
                    }
                    else
                    if (reGenericEII.IsMatch(brokenId))
                    {
                        brokenId = reGenericEII.Replace(brokenId, "#I$1{T}#");
                    }

                    // Don't bother if they are the same
                    if (brokenId != keyValue)
                    {
                        data = this.SourceIndex[brokenId];
                    }
                }
            }

            // Notify if no entry
            if (data == null)
            {
                this.ParentComponent.WriteMessage(this.MissingEntry, "No index entry found for key '{0}'.",
                                                  keyValue);
                return;
            }

            // Get the target node
            XPathExpression targetExpr = this.Target.Clone();

            targetExpr.SetContext(context);
            XPathNavigator target = targetDocument.CreateNavigator().SelectSingleNode(targetExpr);

            // notify if no target found
            if (target == null)
            {
                this.ParentComponent.WriteMessage(this.MissingTarget, "Target node '{0}' not found.",
                                                  targetExpr.Expression);
                return;
            }

            // get the source nodes
            XPathExpression sourceExpr = this.Source.Clone();

            sourceExpr.SetContext(context);
            XPathNodeIterator sources = data.CreateNavigator().Select(sourceExpr);

            // Append the source nodes to the target node
            foreach (XPathNavigator source in sources)
            {
                // If IsAttribute is true, add the source attributes to current target.  Otherwise append source
                // as a child element to target.
                if (this.IsAttribute && source.HasAttributes)
                {
                    string    sourceName = source.LocalName;
                    XmlWriter attributes = target.CreateAttributes();

                    source.MoveToFirstAttribute();

                    do
                    {
                        string attrValue = target.GetAttribute(String.Format(CultureInfo.InvariantCulture,
                                                                             "{0}_{1}", sourceName, source.Name), String.Empty);

                        if (string.IsNullOrEmpty(attrValue))
                        {
                            attributes.WriteAttributeString(String.Format(CultureInfo.InvariantCulture,
                                                                          "{0}_{1}", sourceName, source.Name), source.Value);
                        }
                    } while(source.MoveToNextAttribute());

                    attributes.Close();
                }
                else
                {
                    target.AppendChild(source);
                }
            }

            // Notify if no source found
            if (sources.Count == 0)
            {
                this.ParentComponent.WriteMessage(this.MissingSource, "Source node '{0}' not found.",
                                                  sourceExpr.Expression);
            }
        }
Example #52
0
        private List <string> ExecXpath(string attr, string xPathExpression, XmlDocument xmlDocument)
        {
            List <string> toReturn = new List <string>();

            var xpaths = Regex.Matches(xPathExpression, "{(.*?)}");

            if (xPathExpression.Contains("{") && xpaths.Count > 0)
            {
                //  if there is more than one xpath to look up in this value,
                //  object-{obj_id}-{part_id} then we want only one match for
                //  each xpath term
                if (xpaths.Count > 1 || xPathExpression.Substring(0, 1) != "{" || xPathExpression.Substring(xPathExpression.Length - 1, 1) != "}")
                {
                    bool matchedSomething = false;
                    foreach (Match xPath in xpaths)
                    {
                        string result;

                        XPathNavigator  nav  = xmlDocument.CreateNavigator();
                        XPathExpression expr = nav.Compile(RemoveClosingBrackets(xPath.Value));

                        switch (expr.ReturnType)
                        {
                        case XPathResultType.NodeSet:
                            XPathNodeIterator iterator = (XPathNodeIterator)nav.Select(expr);
                            if (iterator.Count == 1 || (xpaths.Count == 1 && iterator.Count > 0))
                            {
                                iterator.MoveNext();

                                if (iterator.Current.Value.Trim().Length > 0)
                                {
                                    matchedSomething = true;
                                }
                                xPathExpression = xPathExpression.Replace(xPath.Value, iterator.Current.Value);
                            }
                            else if (xpaths.Count != 1 && iterator.Count == 0)
                            {
                                throw new Exception("No match for " + xPath.Value + " in " + attr + "=\"" +
                                                    xPathExpression + "\"");
                            }
                            else if (xpaths.Count > 1)
                            {
                                throw new Exception("Multiple matches for " + xPath.Value + " in " + attr +
                                                    "=\"" + xPathExpression + "\"");
                            }
                            break;

                        case XPathResultType.String:
                            string st = (string)nav.Evaluate(expr);
                            if (!string.IsNullOrEmpty(st) && st.Trim().Length > 0)
                            {
                                matchedSomething = true;
                                xPathExpression  = xPathExpression.Replace(xPath.Value, st);
                            }
                            break;

                        case XPathResultType.Number:
                            //Assume it's a double
                            double dNumber = (double)nav.Evaluate(expr);
                            int    iNumber;
                            matchedSomething = true;
                            //if it can be an int, then make it so...
                            if (int.TryParse(dNumber.ToString(), out iNumber))
                            {
                                xPathExpression = xPathExpression.Replace(xPath.Value, iNumber.ToString());
                            }
                            else
                            {
                                xPathExpression = xPathExpression.Replace(xPath.Value, dNumber.ToString());
                            }
                            break;

                        default:
                            throw new Exception("No match for " + xPath.Value + " in " + attr + "=\"" + xPathExpression +
                                                "\"");
                        }
                    }

                    if (matchedSomething && !string.IsNullOrEmpty(xPathExpression.Trim()))
                    {
                        toReturn.Add(xPathExpression);
                    }
                }
                else
                {
                    //  quite happy to enumerate for all values which match the xpath
                    var    xpath = RemoveClosingBrackets(xPathExpression);
                    string result;

                    var matches = xmlDocument.SelectNodes(xpath);
                    foreach (XmlNode node in matches)
                    {
                        //  ignore empty strings
                        if (!string.IsNullOrEmpty(node.InnerText))
                        {
                            //  apply modification function if required
                            var v = xPathExpression.Replace("{" + xpath + "}", node.InnerText);
                            if (!string.IsNullOrEmpty(v.Trim()))
                            {
                                toReturn.Add(v);
                            }
                        }
                    }
                }
            }
            return(toReturn);
        }
Example #53
0
    private static HashSet<string> ParsePluginsXML(List<string> in_pluginFiles)
    {
        HashSet<string> newDlls = new HashSet<string>();
        foreach (string pluginFile in in_pluginFiles)
        {
            if (!File.Exists(pluginFile))
            {
                continue;
            }

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(pluginFile);
                XPathNavigator Navigator = doc.CreateNavigator();

                XPathNavigator pluginInfoNode = Navigator.SelectSingleNode("//PluginInfo");
                string boolMotion = pluginInfoNode.GetAttribute("Motion", "");

                XPathNodeIterator it = Navigator.Select("//Plugin");

                if (boolMotion == "true")
                    newDlls.Add("AkMotion");

                foreach (XPathNavigator node in it)
                {
                    //Some plugins are built-in the integration.  Ignore those.
                    uint pid = UInt32.Parse(node.GetAttribute("ID", ""));
                    foreach (uint builtID in s_BuiltInPluginIDs)
                    {
                        if (builtID == pid)
                        {
                            pid = 0;
                            break;  //Built in, don't try to mark the DLL.
                        }
                    }

                    if (pid == 0)
                        continue;

                    string dll = node.GetAttribute("DLL", "");
                    newDlls.Add(dll);
                }
            }
            catch (Exception ex)
            {
                Debug.LogError("Wwise: " + pluginFile + " could not be parsed. " + ex.Message);
            }
        }

        return newDlls;
    }
Example #54
0
        public void Update()
        {
            Exception retexception = null;

            try
            {
                var oldfeeditems = feeditems.Select(item => (FeedItem)item.Clone()).ToList();
                feedxml = Fetch(FeedUri);

                var xPathNavigator = feedxml.CreateNavigator();

                SetFeedTitle(xPathNavigator);
                SetFeedLink(xPathNavigator);
                SetFeedDescription(xPathNavigator);

                var xPathNodeIterator = xPathNavigator.Select("/rss/channel/item");

                feeditems.Clear();
                while (xPathNodeIterator.MoveNext())
                {
                    if (xPathNodeIterator.Current != null)
                    {
                        if (!xPathNodeIterator.Current.HasChildren)
                        {
                            continue;
                        }
                        var item = GetItemFromFeedEntry(xPathNodeIterator);

                        if (!oldfeeditems.Contains(item))
                        {
                            item.Updated = true;
                        }
                        feeditems.Add(item);
                    }
                }
            }
            catch (WebException ex)
            {
                retexception = ex;
            }
            catch (XmlException ex)
            {
                retexception = ex;
            }
            catch (NullReferenceException ex)
            {
                retexception = ex;
            }
            catch (IOException ex)
            {
                retexception = ex;
            }
            if (retexception != null)
            {
                HasError     = true;
                ErrorMessage = retexception.Message;
            }
            else
            {
                HasError     = false;
                ErrorMessage = null;
            }
            Loaded = true;
            FireUpdated();
        }
Example #55
0
        /// <summary>
        /// Gets the contents of the node specified by the XPath expression.
        /// </summary>
        /// <param name="xpath">The XPath expression used to determine which nodes to choose from.</param>
        /// <param name="document">The XML document to select the nodes from.</param>
        /// <param name="nodeIndex">The node index in the case where multiple nodes satisfy the expression.</param>
        /// <returns>
        /// The contents of the node specified by the XPath expression.
        /// </returns>
        private string GetNodeContents(string xpath, XmlDocument document, int nodeIndex)
        {
            string contents = null;
            Object result   = null;
            int    numNodes = 0;

            try {
                XmlNamespaceManager nsMgr = new XmlNamespaceManager(document.NameTable);
                foreach (XmlNamespace xmlNamespace in Namespaces)
                {
                    if (xmlNamespace.IfDefined && !xmlNamespace.UnlessDefined)
                    {
                        nsMgr.AddNamespace(xmlNamespace.Prefix, xmlNamespace.Uri);
                    }
                }
                XPathNavigator  nav  = document.CreateNavigator();
                XPathExpression expr = nav.Compile(xpath);
                expr.SetContext(nsMgr);
                result = nav.Evaluate(expr);
            } catch (Exception ex) {
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                       ResourceUtils.GetString("NA1155"), xpath),
                                         Location, ex);
            }

            if (result == null)
            {
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                       ResourceUtils.GetString("NA1156"), xpath),
                                         Location);
            }

            // When using XPathNavigator.Evaluate(),
            // the result of the expression can be one of Boolean, number,
            // string, or node set). This maps to Boolean, Double, String,
            // or XPathNodeIterator objects respectively.
            // So therefore if the result is not null, then there is at least
            // 1 node that matches.
            numNodes = 1;

            // If the result is a node set, then there could be multiple nodes.
            XPathNodeIterator xpathNodesIterator = result as XPathNodeIterator;

            if (xpathNodesIterator != null)
            {
                numNodes = xpathNodesIterator.Count;
            }

            Log(Level.Verbose, "Found '{0}' node{1} with the XPath expression '{2}'.",
                numNodes, numNodes > 1 ? "s" : "", xpath);

            if (xpathNodesIterator != null)
            {
                if (nodeIndex >= numNodes)
                {
                    throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                           ResourceUtils.GetString("NA1157"), nodeIndex), Location);
                }

                while (xpathNodesIterator.MoveNext())
                {
                    // CurrentPosition is 1-based.
                    if (xpathNodesIterator.CurrentPosition == (nodeIndex + 1))
                    {
                        // Get the entire node of the current xpathNodesIterator and return innerxml.
                        XmlNode currentNode = ((IHasXmlNode)xpathNodesIterator.Current).GetNode();
                        contents = currentNode.InnerXml;
                    }
                }
            }
            else
            {
                if (result is IFormattable)
                {
                    IFormattable formattable = (IFormattable)result;
                    contents = formattable.ToString(null, CultureInfo.InvariantCulture);
                }
                else
                {
                    contents = result.ToString();
                }
            }

            return(contents);
        }
Example #56
0
File: Map.cs Project: jadmz/HexMap
    /// <summary>
    /// Generates the map.
    /// </summary>
    protected virtual void generateMap()
    {
        // Get the size and extent
        Vector2 hexExtent = getHexExtent();
        Vector2 hexSize = getHexSize();

        // Get Row itr and stuff
        XmlDocument doc = new XmlDocument();
        doc.Load(MapFile);
        XPathNavigator rowNav = doc.CreateNavigator();
        XPathExpression rowExpr;
        rowExpr = rowNav.Compile("Map/Row");
        XPathNodeIterator rowItr = rowNav.Select(rowExpr);

        Vector2 mapSize = new Vector2(0, rowItr.Count);
        // For each row, or each y coordinate
        for(int i = 0; rowItr.MoveNext(); i++){
            float zpos = StartPosition.y + i*hexExtent.y*1.5F;
            float xOffset = hexExtent.x *i;

            // Get tile itr and stuff
            XPathNavigator tileNav = rowItr.Current;
            XPathExpression tileExpr = tileNav.Compile("Tile");
            XPathNodeIterator tileItr = tileNav.Select(tileExpr);

            // Set the map size and initialize
            if(mapSize.x == 0){
                mapSize.x = tileItr.Count;
            }
            if(_map == null){
                _map = new HexTile[(int)mapSize.x, (int)mapSize.y];
            }

            // For each column or x coordinate
            for(int j = 0; tileItr.MoveNext(); j++){
                float xPos = j*hexSize.x+xOffset-(i/2)*hexSize.x;
                Vector3 pos = new Vector3(xPos, 0, zpos);
                GameObject obj = (GameObject)Instantiate(HexPrefab);
                HexTile tile = obj.GetComponent<HexTile>();
                _map[j,i] = tile;
                tile.gameObject.transform.position = pos;
                tile.SetLocation(toMapPosition(j, i));
                tile.Map = this;
                this.setTile(tile, tileItr.Current.Clone());

                /*pos.z = pos.z-.01F;
                map[j,i].Shadow = (GameObject)Instantiate(ShadowPrefab);
                map[j,i].Shadow.transform.position =  pos;
                map[j,i].CanBeSeen = false;*/
            }
        }
    }