Наследование: IXPathNavigable
Пример #1
5
        /// <summary>
        /// Processes the record.
        /// </summary>
        protected override void ProcessRecord()
        {
            this.WriteVerbose("Formatting log");
            using (var xmlReader = new StringReader(this.Log))
            {
                var xpath = new XPathDocument(xmlReader);
                using (var writer = new StringWriter())
                {
                    var transform = new XslCompiledTransform();
                    Func<string, string> selector = file => !Path.IsPathRooted(file) ? Path.Combine(Environment.CurrentDirectory, file) : file;
                    foreach (var fileToLoad in this.FormatFile.Select(selector))
                    {
                        this.WriteVerbose("Loading format file " + fileToLoad);
                        using (var stream = File.OpenRead(fileToLoad))
                        {
                            using (var reader = XmlReader.Create(stream))
                            {
                                transform.Load(reader);
                                transform.Transform(xpath, null, writer);
                            }
                        }
                    }

                    this.WriteObject(writer.GetStringBuilder().ToString(), false);
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Tries to extract the BluRay title.
        /// </summary>
        /// <returns></returns>
        public string GetTitle()
        {
            string metaFilePath = Path.Combine(DirectoryBDMV.FullName, @"META\DL\bdmt_eng.xml");
              if (!File.Exists(metaFilePath))
            return null;

              try
              {
            XPathDocument metaXML = new XPathDocument(metaFilePath);
            XPathNavigator navigator = metaXML.CreateNavigator();
            if (navigator.NameTable != null)
            {
              XmlNamespaceManager ns = new XmlNamespaceManager(navigator.NameTable);
              ns.AddNamespace("", "urn:BDA:bdmv;disclib");
              ns.AddNamespace("di", "urn:BDA:bdmv;discinfo");
              navigator.MoveToFirst();
              XPathNavigator node = navigator.SelectSingleNode("//di:discinfo/di:title/di:name", ns);
              if (node != null)
            return node.ToString().Trim();
            }
              }
              catch (Exception e)
              {
            ServiceRegistration.Get<ILogger>().Error("BDMEx: Meta File Error: ", e);
              }
              return null;
        }
        public HttpResponseMessage Get(string id)
        {
            try
            {
                TrataRetorno objRetorno = new TrataRetorno();
                List<Indice> Indices = new List<Indice>();
                string urlInicial = "http://finance.yahoo.com/webservice/v1/symbols/";
                string urlFinal = "/quote?format=xml&view=detail";
                string[] stringSeparators = new string[] { "," };
                string[] result;

                result = id.Split(stringSeparators, StringSplitOptions.None);
                foreach (string s in result)
                {
                    XPathDocument doc = new XPathDocument(urlInicial + s + urlFinal);
                    Indices.Add(objRetorno.TratarRetorno(doc));
                }

                return Request.CreateResponse(HttpStatusCode.OK, Indices); ;
            }
            catch (KeyNotFoundException)
            {
                string mensagem = string.Format("Não foi possível criptografar a entrada: ", id);
                HttpError error = new HttpError(mensagem);
                return Request.CreateResponse(HttpStatusCode.NotFound, error);
            }
        }
Пример #4
0
        static string[] Affichage_M1()
        {
            string nomDuDocXML = "M1.xml";

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

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

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

            //parcourir le resultat
            //---------------------
            string[] nodeContent = { "", "", "", "" };

            while (nodes.MoveNext())                       // pour chaque réponses XPath (on est au niveau d'un noeud BD)
            {
                nodeContent[0] = nodes.Current.ToString(); //nom du client
                nodes.MoveNext();
                nodeContent[1] = nodes.Current.ToString(); //adresse client
                nodes.MoveNext();
                nodeContent[2] = nodes.Current.ToString(); //date
                nodes.MoveNext();
                nodeContent[3] = nodes.Current.ToString(); //arrondissement = theme (ici 16e)
            }
            return(nodeContent);
        }
Пример #5
0
        public void Apply (XmlDocument targetDocument, IXmlNamespaceResolver context) {

            XPathExpression local_file_expression = file_expression.Clone();
            local_file_expression.SetContext(context);

            XPathExpression local_source_expression = source_expression.Clone();
            local_source_expression.SetContext(context);

            XPathExpression local_target_expression = target_expression.Clone();
            local_target_expression.SetContext(context);

            string file_name = (string) targetDocument.CreateNavigator().Evaluate(local_file_expression);
            string file_path = Path.Combine(root_directory, file_name);

            if (!File.Exists(file_path)) return;
            XPathDocument sourceDocument = new XPathDocument(file_path);

            XPathNavigator target_node = targetDocument.CreateNavigator().SelectSingleNode(local_target_expression);
            if (target_node == null) return;

            XPathNodeIterator source_nodes = sourceDocument.CreateNavigator().Select(local_source_expression);
            foreach (XPathNavigator source_node in source_nodes) {
                target_node.AppendChild(source_node);
            }
       
        }
		private void AddTargets (string map, string input, string baseOutputPath, XPathExpression outputXPath, string link, XPathExpression formatXPath, XPathExpression relativeToXPath) {

			XPathDocument document = new XPathDocument(map);

			XPathNodeIterator items = document.CreateNavigator().Select("/*/item");
			foreach (XPathNavigator item in items) {

				string id = (string) item.Evaluate(artIdExpression);
				string file = (string) item.Evaluate(artFileExpression);
				string text = (string) item.Evaluate(artTextExpression);

				id = id.ToLower();
				string name = Path.GetFileName(file);

				ArtTarget target = new ArtTarget();
				target.Id = id;
				target.InputPath = Path.Combine(input, file);
				target.baseOutputPath = baseOutputPath;
                target.OutputXPath = outputXPath;
                
                if (string.IsNullOrEmpty(name)) target.LinkPath = link;
                else target.LinkPath = string.Format("{0}/{1}", link, name);
                
				target.Text = text;
                target.Name = name;
                target.FormatXPath = formatXPath;
                target.RelativeToXPath = relativeToXPath;

				targets[id] = target;
				// targets.Add(id, target);
            }

	    }
Пример #7
0
        /// <summary>
        /// Returns the line number and line position of the specified XML node.
        /// </summary>
        /// <param name="xmlFileFullPathName">The fully qualified path name to the XML file.</param>
        /// <param name="xpath">The XPath of the XML node to get the location of.</param>
        /// <param name="lineNumber">If the return value is true, the line number of the specified XML element.</param>
        /// <param name="linePosition">If the return value is true, the posiiton on the line of the specified XML element.</param>
        /// <returns>True if the element is found, otherwise false.</returns>
        public static bool GetTextLocationOfXmlNode(string xmlFileFullPathName, string xpath, out int lineNumber, out int linePosition)
        {
            bool isElementFound;
            XPathDocument xpathSlashDoc = new XPathDocument(xmlFileFullPathName);
            XPathNavigator navSlashDoc = xpathSlashDoc.CreateNavigator();
            XPathNodeIterator itr = navSlashDoc.Select(xpath);
            if (itr.Count > 0 && itr.MoveNext())
            {
                IXmlLineInfo lineInfo = itr.Current as IXmlLineInfo;
                DiagnosticService.Assert(lineInfo != null, "Line Information not available.");

                if (lineInfo != null)
                {
                    lineNumber = lineInfo.LineNumber;
                    linePosition = lineInfo.LinePosition;
                }
                else
                {
                    lineNumber = -1;
                    linePosition = -1;
                }
                Debug.WriteLine(itr.Current.Name + "(" + lineNumber + ","+ linePosition +")");
                isElementFound = true;
            }
            else
            {
                lineNumber = -1;
                linePosition = -1;
                isElementFound = false;
            }
            return isElementFound;
        }
Пример #8
0
        static void Main(string[] args)
        {
            if (args.Length != 2 || args.Any(p => p == "/?" || p == "-?")) {
            ShowHelp();
             }

             try {
            var doc = new XPathDocument(args[0]);
            XPathNavigator nav = doc.CreateNavigator();

            var o = nav.Evaluate(args[1]);
            if (o is XPathNodeIterator) {
               var iter = o as XPathNodeIterator;
               while (iter.MoveNext()) {
                  Console.WriteLine(iter.Current.Value);
               }
            }
            else {
               Console.WriteLine(o);
            }
             }
             catch (Exception ex) {
            Console.WriteLine(ex);
            Environment.Exit(1);
             }
        }
Пример #9
0
		private ContentItem ReadDocument(XPathDocument xpd)
		{
			XPathNavigator navigator = xpd.CreateNavigator();
			OnMovingToRootItem(navigator);

			return OnReadingItem(navigator);
		}
Пример #10
0
        public bool CancelAppointment(HackExchangeContext context, CalendarItem appointment)
        {
            var url = context.Endpoint;
            var request = new HttpRequestMessage(HttpMethod.Post, url);
            var postBodyTemplate = LoadXml("CancelAppointment");
            var postBody = string.Format(postBodyTemplate, appointment.Id, appointment.ChangeKey);
            request.Content = new StringContent(postBody, Encoding.UTF8, "text/xml");

            var clientHandler = new HttpClientHandler()
            {
                Credentials = context.Credentials
            };
            using (var client = new HttpClient(clientHandler))
            {
                var response = client.SendAsync(request).Result;
                var responseBody = response.Content.ReadAsStringAsync().Result;

                var doc = new XPathDocument(new StringReader(responseBody));
                var nav = doc.CreateNavigator();
                var nsManager = new XmlNamespaceManager(nav.NameTable);
                nsManager.AddNamespace("m", "http://schemas.microsoft.com/exchange/services/2006/messages");
                nsManager.AddNamespace("t", "http://schemas.microsoft.com/exchange/services/2006/types");

                var responseClass = EvaluateXPath(nav, nsManager, "//m:DeleteItemResponseMessage/@ResponseClass");
                return responseClass == "Success";
            }
        }
Пример #11
0
        static void Exo1()
        {
            string nomDuDocXML = "bdtheque.xml";

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

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

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

            //parcourir le resultat
            //---------------------

            while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud BD)
            {
                // a compléter
            }

            expr = nav.Compile(maRequeteXpath);
        }
Пример #12
0
        public string GetTweets()
        {
            // Uppgift 6:
            var twitter = new WebConsumer(TwitterConsumer.ServiceDescription, this.TokenManager);
            XPathDocument updates = new XPathDocument(TwitterConsumer.GetUpdates(twitter, this.AccessToken).CreateReader());
            XPathNavigator nav = updates.CreateNavigator();
            var parsedUpdates = from status in nav.Select("/statuses/status").OfType<XPathNavigator>()
                                where !status.SelectSingleNode("user/protected").ValueAsBoolean
                                select new
                                {
                                    User = status.SelectSingleNode("user/name").InnerXml,
                                    Status = status.SelectSingleNode("text").InnerXml,
                                };

            StringBuilder tableBuilder = new StringBuilder();
            tableBuilder.Append("<table><tr><td>Name</td><td>Update</td></tr>");

            foreach (var update in parsedUpdates)
            {
                tableBuilder.AppendFormat(
                    "<tr><td>{0}</td><td>{1}</td></tr>",
                    HttpUtility.HtmlEncode(update.User),
                    HttpUtility.HtmlEncode(update.Status));
            }
            tableBuilder.Append("</table>");
            return tableBuilder.ToString();
        }
Пример #13
0
        static XPathUtils()
        {
            XmlDocument doc = new XmlDocument();
              doc.AppendChild(doc.CreateElement("DocumentRoot"));

              _emptyXPathDocument = new XPathDocument(new XmlNodeReader(doc));
        }
Пример #14
0
 /// <summary>
 /// Read and apply persistent form display data (Size, Position, and WindowState)
 /// </summary>
 /// <param name="form">Form to be set</param>
 internal static void ReadPersistentFormData(System.Windows.Forms.Form form)
 {
     try {
         StreamReader reader = new StreamReader(Application.ExecutablePath + ".formdata.xml", Encoding.UTF8);
         XPathDocument doc = new XPathDocument(reader);
         XPathNavigator nav = doc.CreateNavigator();
         try {
             XPathNodeIterator iterator = nav.Select(String.Format("//Forms/{0}/PersistentData", form.Name));
             iterator.MoveNext();
             form.WindowState = (FormWindowState)Enum.Parse(form.WindowState.GetType(), iterator.Current.GetAttribute("WindowState",	""), false);
             if (form.WindowState == FormWindowState.Normal) {
                 form.Top	= Convert.ToInt16(iterator.Current.GetAttribute("Top",		"").ToString());
                 form.Left	= Convert.ToInt16(iterator.Current.GetAttribute("Left",		"").ToString());
                 form.Width	= Convert.ToInt16(iterator.Current.GetAttribute("Width",	"").ToString());
                 form.Height	= Convert.ToInt16(iterator.Current.GetAttribute("Height",	"").ToString());
             }
         }
         catch {
         }
         finally {
             reader.Close();
         }
     }
     catch {
     }
 }
Пример #15
0
        static int Main(string[] args)
        {
            Console.WriteLine("XMLTo v0.1 [www.mosa-project.org]");
            Console.WriteLine("Copyright 2009 by the MOSA Project. Licensed under the New BSD License.");
            Console.WriteLine("Written by Philipp Garcia ([email protected])");
            Console.WriteLine();
            Console.WriteLine("Usage: XMLTo <xml file> <xsl file> <output file>");
            Console.WriteLine();

            if (args.Length < 3)
             {
                Console.Error.WriteLine("ERROR: Missing arguments");
                return -1;
            }

            try {
                XPathDocument myXPathDoc = new XPathDocument(args[0]);
                XslCompiledTransform myXslTrans = new XslCompiledTransform();
                myXslTrans.Load(args[1]);
                XmlTextWriter myWriter = new XmlTextWriter(args[2], null);
                myXslTrans.Transform(myXPathDoc, null, myWriter);

                return 0;
            }
            catch (Exception e) {
                Console.Error.WriteLine("Exception: {0}", e.ToString());
                return -1;
            }
        }
Пример #16
0
		public String GetDetail(String name, String log, DetailEnum detail)
		{
			String xsl = null;

			if (detail == DetailEnum.Summary)
			{
				return GetSummary(name, log);
			}
			else if (detail == DetailEnum.Compilation)
			{
				xsl = GetXslFullFileName("compile.xsl");
			}
			else if (detail == DetailEnum.Modifications)
			{
				xsl = GetXslFullFileName("modifications.xsl");
			}
			else if (detail == DetailEnum.UnitTestsDetail)
			{
				xsl = GetXslFullFileName("unittests.xsl");
			}
			else if (detail == DetailEnum.UnitTestsSummary)
			{
				xsl = GetXslFullFileName("AlternativeNUnitDetails.xsl");
			}

			String content = cruiseManager.GetLog(name, log);

			XPathDocument document = new XPathDocument(new StringReader(content));

			return logTransformer.Transform(document, xsl);
		}
Пример #17
0
        public bool GenerateReport(string fileName)
        {
            bool retCode = false;
            ResetReportViwer();

            XslCompiledTransform xslt = new XslCompiledTransform();
            xslt.Load(rptXslPath);

            if ( File.Exists(fileName) == true)
            {
                XPathDocument myXPathDoc = new XPathDocument(fileName);
                StringWriter sw = new StringWriter();
                XmlWriter xmlWriter = new XmlTextWriter(sw);

                // using makes sure that we flush the writer at the end
                xslt.Transform(myXPathDoc, null, xmlWriter);
                xmlWriter.Flush();
                xmlWriter.Close();

                string xml = sw.ToString();

                HtmlDocument htmlDoc = axBrowser.Document;
                htmlDoc.Write(xml);
                retCode = true;
            }
            else
            {

                retCode = false;
            }

            return retCode;
        }
Пример #18
0
        public Episode(FileInfo file, Season seasonparent)
            : base(file.Directory)
        {
            String xmlpath = file.Directory.FullName + "/metadata/" + Path.GetFileNameWithoutExtension(file.FullName) + ".xml";
            if (!File.Exists(xmlpath))
            {
                Valid = false;
                return;
            }
            EpisodeXml = new XPathDocument(xmlpath);
            EpisodeNav = EpisodeXml.CreateNavigator();
            EpisodeFile = file;

            _season = seasonparent;

            transX = 200;
            transY = 100;

            backdropImage = _season.backdropImage;

            XPathNodeIterator nodes = EpisodeNav.Select("//EpisodeID");
            nodes.MoveNext();
            folderImage = file.Directory.FullName + "/metadata/" + nodes.Current.Value + ".jpg";

            if (!File.Exists(folderImage))
                folderImage = "/Images/nothumb.jpg";
            title = this.asTitle();

            videoURL = EpisodeFile.FullName;

            LoadImage(folderImage);
        }
Пример #19
0
 public EnumCollection Process(EnumCollection enums)
 {
     var nav = new XPathDocument(Overrides).CreateNavigator();
     enums = ProcessNames(enums, nav);
     enums = ProcessConstants(enums, nav);
     return enums;
 }
Пример #20
0
        /// -----------------------------------------------------------------------------
        /// <summary>
        /// This Constructor creates a new PackageInstaller instance
        /// </summary>
        /// <param name="package">A PackageInfo instance</param>
        /// <history>
        /// 	[cnurse]	01/21/2008  created
        /// </history>
        /// -----------------------------------------------------------------------------
        public PackageInstaller(PackageInfo package)
        {
            IsValid = true;
            DeleteFiles = Null.NullBoolean;
            Package = package;
            if (!string.IsNullOrEmpty(package.Manifest))
            {
				//Create an XPathDocument from the Xml
                var doc = new XPathDocument(new StringReader(package.Manifest));
                XPathNavigator nav = doc.CreateNavigator().SelectSingleNode("package");
                ReadComponents(nav);
            }
            else
            {
                ComponentInstallerBase installer = InstallerFactory.GetInstaller(package.PackageType);
                if (installer != null)
                {
					//Set package
                    installer.Package = package;

                    //Set type
                    installer.Type = package.PackageType;
                    _componentInstallers.Add(0, installer);
                }
            }
        }
Пример #21
0
 public override void LoadFile(Stream stream)
 {
     string p = AnnotationPlugIn.GenerateDataRecordPath();
     // t|1|OrderDetails,_Annotation_Attachment20091219164153Z|10248|11
     Match m = Regex.Match(this.Value, "_Annotation_Attachment(\\w+)\\|");
     string fileName = Path.Combine(p, (m.Groups[1].Value + ".xml"));
     XPathNavigator nav = new XPathDocument(fileName).CreateNavigator().SelectSingleNode("/*");
     fileName = Path.Combine(p, ((Path.GetFileNameWithoutExtension(fileName) + "_")
                     + Path.GetExtension(nav.GetAttribute("fileName", String.Empty))));
     if (!(this.Value.StartsWith("t|")))
     {
         this.ContentType = nav.GetAttribute("contentLength", String.Empty);
         HttpContext.Current.Response.ContentType = this.ContentType;
     }
     this.FileName = nav.GetAttribute("fileName", String.Empty);
     Stream input = File.OpenRead(fileName);
     try
     {
         byte[] buffer = new byte[(1024 * 64)];
         long offset = 0;
         long bytesRead = input.Read(buffer, 0, buffer.Length);
         while (bytesRead > 0)
         {
             stream.Write(buffer, 0, Convert.ToInt32(bytesRead));
             offset = (offset + bytesRead);
             bytesRead = input.Read(buffer, 0, buffer.Length);
         }
     }
     finally
     {
         input.Close();
     }
 }
        public void QueryAndNamespace()
        {
            try
            {
                var output = "";
                var path = Server.MapPath("~/App_Data/bookstore.xml");
                XPathDocument document = new XPathDocument(path);
                XPathNavigator navigator = document.CreateNavigator();
                XPathExpression query = navigator.Compile("/bookstore:bookstore/bookstore:book");
                XmlNamespaceManager manager = new XmlNamespaceManager(navigator.NameTable);
                manager.AddNamespace("bookstore", "urn:newbooks-schema");
                query.SetContext(manager);
                XPathNodeIterator nodes = navigator.Select(query);

                while (nodes.MoveNext())
                {
                    output += nodes.Current.OuterXml;
                }

                Textarea4.InnerHtml = output;
            }
            catch (Exception ex)
            {
                Textarea4.InnerHtml = ex.Message;
            }
        }
Пример #23
0
		void LoadFile(string filepath) {
			var xml = new XPathDocument(filepath).CreateNavigator();
			ProjectPath = Val(xml, "/Settings/ProjectPath");
			PropertyFilepath = Val(xml, "/Settings/PropertyFilepath");
			LesseeFilepath = Val(xml, "/Settings/LesseeFilepath");
			AutoSave = Boolean.Parse(Val(xml, "/Settings/AutoSave"));
		}
Пример #24
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            var resourcefile = Server.MapPath(LocalResourceFile + ".ascx.resx");
            if (File.Exists(resourcefile))
            {
                var document = new XPathDocument(resourcefile);
                var navigator = document.CreateNavigator();

                var nodes = navigator.Select("/root/data[starts-with(@name, 'WhatsNew')]/@name");

                var releasenotes = new List<ReleaseInfo>();

                while (nodes.MoveNext())
                {
                    var key = nodes.Current.Value;
                    var version = string.Format(Localization.GetString("notestitle.text", LocalResourceFile), key.Replace("WhatsNew.", string.Empty));
                    releasenotes.Add(new ReleaseInfo(Localization.GetString(key, LocalResourceFile), version));
                }

                releasenotes.Sort(CompareReleaseInfo);

                WhatsNewList.DataSource = releasenotes;
                WhatsNewList.DataBind();

                header.InnerHtml = Localization.GetString("header.text", LocalResourceFile);
                footer.InnerHtml = Localization.GetString("footer.text", LocalResourceFile);
            }
        }
Пример #25
0
        /// <inheritdoc />
        public override XPathNavigator this[string key]
        {
            get
            {
                string xml;

                // Try the in-memory cache first
                XPathNavigator content = base[key];

                // If not found there, try the database caches if there are any
                if(content == null && esentCaches.Count != 0)
                    foreach(var c in esentCaches)
                        if(c.TryGetValue(key, out xml))
                        {
                            // Convert the XML to an XPath navigator
                            using(StringReader textReader = new StringReader(xml))
                                using(XmlReader reader = XmlReader.Create(textReader, settings))
                                {
                                    XPathDocument document = new XPathDocument(reader);
                                    content = document.CreateNavigator();
                                }
                        }

                return content;
            }
        }
Пример #26
0
        public KeyboardLayoutType GetKeyboardLayoutType(string locale)
        {
            if (String.IsNullOrEmpty(locale))
                return KeyboardLayoutType.US;

            // Get the layout type - US, European etc. The locale in the XML file must be upper case!
            string expression = @"/keyboards/keyboard[locale='" + locale.ToUpper(CultureInfo.InvariantCulture) + "']";

            XPathNodeIterator iterator;

            using (Stream xmlstream = GetXMLDocumentAsStream(_keyboardfilename))
            {
                XPathDocument document = new XPathDocument(xmlstream);
                XPathNavigator nav = document.CreateNavigator();

                iterator = nav.Select(expression);
            }

            int value = 0; // Default to US 

            if (iterator.Count == 1)
            {
                iterator.MoveNext();
                string layout = GetElementValue("layout", iterator.Current);
                if (String.IsNullOrEmpty(layout) == false)
                {
                    value = Int32.Parse(layout, CultureInfo.InvariantCulture.NumberFormat);
                }
            }

            return (KeyboardLayoutType)value;
        }
Пример #27
0
        private static StringBuilder Transform(string gcmlPath)
        {
            if(!File.Exists(gcmlPath))
            {
                throw new GCMLFileNotFoundException("The GCML File" + gcmlPath + " does not exist.");
            }

            if(!File.Exists(xsltFilePath))
            {
                throw new XSLTFileNotFoundException("The XSLT File" + xsltFilePath + " does not exist.");
            }

            StringBuilder sb = new StringBuilder();
            XmlTextReader xmlSource = new XmlTextReader(gcmlPath);
            XPathDocument xpathDoc = new XPathDocument(xmlSource);
            XslCompiledTransform xsltDoc = new XslCompiledTransform();

            xsltDoc.Load(xsltFilePath);

            StringWriter sw = new StringWriter(sb);
            try
            {
                xsltDoc.Transform(xpathDoc, null, sw);
            }
            catch (XsltException except)
            {
                Console.WriteLine(except.Message);
                throw except;
            }

            return sb;
        }
Пример #28
0
        public void RunXslt(String xsltFile, String xmlDataFile, String outputXml)
        {
            XPathDocument input = new XPathDocument(xmlDataFile);

            XslTransform myXslTrans = new XslTransform() ;
            XmlTextWriter output = null;
            try
            {
                myXslTrans.Load(xsltFile);

                output = new XmlTextWriter(outputXml, null);
                output.Formatting = Formatting.Indented;

                myXslTrans.Transform(input, null, output);

            }
            catch (Exception e)
            {
                String msg = e.Message;
                if (msg.IndexOf("InnerException") >0)
                {
                    msg = e.InnerException.Message;
                }

                MessageBox.Show("Error: " + msg + "\n" + e.StackTrace, "Xslt Error File: " + xsltFile, MessageBoxButtons.OK, MessageBoxIcon.Error);

            }
            finally
            {
                try { output.Close(); }
                catch (Exception) { }
            }
        }
Пример #29
0
		public override void PopulateTree (Tree tree)
		{
			XPathNavigator n = new XPathDocument (Path.Combine (basedir, "toc.xml")).CreateNavigator ();
			n.MoveToRoot ();
			n.MoveToFirstChild ();
			PopulateNode (n.SelectChildren ("node", ""), tree.RootNode);
		}
Пример #30
0
        public static string Transform(string xml, string xslPath)
        {
            try
            {
                //create an XPathDocument using the reader containing the XML
                MemoryStream m = new MemoryStream(System.Text.Encoding.Default.GetBytes(xml));

                XPathDocument xpathDoc = new XPathDocument(new StreamReader(m));

                //Create the new transform object
                XslCompiledTransform transform = new XslCompiledTransform();

                //String to store the resulting transformed XML
                StringBuilder resultString = new StringBuilder();

                XmlWriter writer = XmlWriter.Create(resultString);

                transform.Load(xslPath);

                transform.Transform(xpathDoc,writer);
               
                return resultString.ToString();
            }
            catch (Exception e)
            {

                Console.WriteLine("Exception: {0}", e.ToString());
                return e.ToString();
            }
        }
 public ResinConf(String file)
 {
   _xPathDoc = new XPathDocument(file);
   _docNavigator = _xPathDoc.CreateNavigator();
   _xmlnsMgr = new XmlNamespaceManager(_docNavigator.NameTable);
   _xmlnsMgr.AddNamespace("caucho", "http://caucho.com/ns/resin");
 }
Пример #32
0
 static AutoUpdateHepler()
 {
     string str = FileUtility.ApplicationRootPath + @"\update";
     if (LoggingService.IsInfoEnabled)
     {
         LoggingService.Info("读取升级配置:" + str);
     }
     XmlConfigSource source = null;
     if (System.IO.File.Exists(str + ".cxml"))
     {
         XmlTextReader decryptXmlReader = new CryptoHelper(CryptoTypes.encTypeDES).GetDecryptXmlReader(str + ".cxml");
         IXPathNavigable document = new XPathDocument(decryptXmlReader);
         source = new XmlConfigSource(document);
         decryptXmlReader.Close();
     }
     else if (System.IO.File.Exists(str + ".xml"))
     {
         source = new XmlConfigSource(str + ".xml");
     }
     if (source != null)
     {
         softName = source.Configs["FtpSetting"].GetString("SoftName", string.Empty);
         version = source.Configs["FtpSetting"].GetString("Version", string.Empty);
         server = source.Configs["FtpSetting"].GetString("Server", string.Empty);
         user = source.Configs["FtpSetting"].GetString("User", string.Empty);
         password = source.Configs["FtpSetting"].GetString("Password", string.Empty);
         path = source.Configs["FtpSetting"].GetString("Path", string.Empty);
         liveup = source.Configs["FtpSetting"].GetString("LiveUp", string.Empty);
         autoupdate = source.Configs["FtpSetting"].GetString("autoupdate", string.Empty);
     }
 }
Пример #33
0
    public static double Evaluate(string expression)
    {
        var doc       = new System.Xml.XPath.XPathDocument(new System.IO.StringReader("<r/>"));
        var nav       = doc.CreateNavigator();
        var newString = expression;

        newString = (new System.Text.RegularExpressions.Regex(@"([\+\-\*])")).Replace(newString, " ${1} ");
        newString = newString.Replace("/", " div ").Replace("%", " mod ");
        return((double)nav.Evaluate("number(" + newString + ")"));
    }
Пример #34
0
        static string[] Affichage_M2()
        {
            string nomDuDocXML = "M2.xml";

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

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

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

            //parcourir le resultat
            //---------------------
            string[] nodeContent = { "", "", "", "", "", "", "", "", "", "" };
            Console.WriteLine("Affichage du message de reservation envoye au client...\n");
            while (nodes.MoveNext())
            {
                nodeContent[0] = nodes.Current.ToString();
                nodes.Current.MoveToNext();
                nodeContent[1] = nodes.Current.ToString();
                nodes.Current.MoveToNext();
                nodeContent[2] = nodes.Current.ToString();
                nodes.Current.MoveToNext();
                nodes.Current.MoveToFirstChild();
                nodeContent[3] = nodes.Current.ToString();
                nodes.Current.MoveToNext();
                nodeContent[4] = nodes.Current.ToString();
                nodes.Current.MoveToParent();
                nodes.Current.MoveToNext();
                nodes.Current.MoveToFirstChild();
                nodeContent[5] = nodes.Current.ToString();
                nodes.Current.MoveToNext();
                nodeContent[6] = nodes.Current.ToString();
                nodes.Current.MoveToNext();
                nodeContent[7] = nodes.Current.ToString();
                nodes.Current.MoveToParent();
                nodes.Current.MoveToNext();
                nodes.Current.MoveToFirstChild();
                nodeContent[8] = nodes.Current.ToString();
                nodes.Current.MoveToNext();
                nodeContent[9] = nodes.Current.ToString();
                break;
            }
            return(nodeContent);
        }
Пример #35
0
    protected IEnumerable <ImageItem> GetTemplates(bool withThumbnails)
    {
        string templatesListFile = Path.Combine(_templateFolder, "Templates.xml");

        if (File.Exists(templatesListFile))
        {
            using (FileStream fs = new FileStream(templatesListFile, FileMode.Open, FileAccess.Read))
            {
                System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(fs);
                foreach (XPathNavigator nav in
                         doc.CreateNavigator().Select("/Templates/TemplateItem/@FileName"))
                {
                    string fileName = Path.IsPathRooted(nav.Value) ? nav.Value : Path.Combine(_templateFolder, nav.Value);
                    yield return(new ImageItem(fileName, withThumbnails));
                }
            }
        }
    }
Пример #36
0
        public static string GetValueByXPath(string filename, string xpath)
        {
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentException($"{nameof(filename)} is null or empty.", nameof(filename));
            }
            if (string.IsNullOrEmpty(xpath))
            {
                throw new ArgumentException($"{nameof(xpath)} is null or empty.", nameof(xpath));
            }

            XElement root = XElement.Parse(File.ReadAllText(filename));
            var      temp = new System.Xml.XPath.XPathDocument(filename);

            var navigator = temp.CreateNavigator();

            var match = navigator.SelectSingleNode(xpath);

            if (match == null)
            {
                return(null);
            }
            else
            {
                return(match.Value);

                /*
                 * if (match is XAttribute)
                 * {
                 *  return ((XAttribute)match).Value;
                 * }
                 * else if (match is XElement)
                 * {
                 *  return ((XElement)match).Value;
                 * }
                 * else
                 * {
                 *  throw new InvalidOperationException(
                 *      String.Format("Unsupported object type '{0}'.",
                 *      match.GetType().FullName));
                 * }
                 */
            }
        }
Пример #37
0
        static void Exo1()
        {
            string nomDuDocXML = "bdtheque.xml";

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

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

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

            //parcourir le resultat
            //---------------------

            while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud BD)
            {
                string titre  = nodes.Current.SelectSingleNode("titre").InnerXml;
                string auteur = ", écrit par " + nodes.Current.SelectSingleNode("auteur").InnerXml;
                string isbn   = ", Numéro ISBN : " + nodes.Current.GetAttribute("isbn", "");

                string pages = "";
                if (nodes.Current.SelectSingleNode("nombre_pages") != null)
                {
                    pages = " (" + nodes.Current.SelectSingleNode("nombre_pages").InnerXml + " pages)";
                }
                Console.WriteLine(titre + pages + auteur + isbn);

                Console.WriteLine("");
                // a compléter
            }
        }
Пример #38
0
        public string GetXmlPage(string templatePath, string dataPath)
        {
            if (templatePath == null)
            {
                throw new ArgumentNullException("Missing xslt template path. Set XsltTemplatePath for ILayoutService in controller's constructor");
            }

            string xsl = templatePath;
            string xml = dataPath;

            System.Xml.XPath.XPathDocument doc   = new System.Xml.XPath.XPathDocument(xml);
            XslCompiledTransform           trans = new System.Xml.Xsl.XslCompiledTransform();

            trans.Load(xsl);

            StringWriter writer = new StringWriter();

            trans.Transform(doc, null, writer);

            var decoded = HttpUtility.HtmlDecode(writer.ToString());

            return(decoded.ToString());
        }
Пример #39
0
        public static XPathNavigator GetXPathDocument(Type type)
        {
            //load xml
            var typeName = type.Assembly.GetName().Name;

            System.Xml.XPath.XPathDocument xpath;
            if (!XmlCache.ContainsKey(typeName))
            {
                var path = HttpContext.Current.Server.MapPath(string.Format("~/bin/{0}.xml", typeName));
                if (!System.IO.File.Exists(path))
                {
                    return(null);
                }
                xpath = new System.Xml.XPath.XPathDocument(path);
                if (!XmlCache.ContainsKey(type.Assembly.GetName().Name))
                {
                    //double check
                    XmlCache.TryAdd(type.Assembly.GetName().Name, xpath.CreateNavigator());
                }
            }

            return(XmlCache.ContainsKey(typeName) ? XmlCache[typeName] : null);
        }
Пример #40
0
        static List <string> LectureM3(string[] sejour, List <List <string> > logement)
        {
            string[] client      = new string[6];
            string   nomDuDocXML = "M3.xml";

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


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

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

            //parcourir le resultat
            //---------------------
            string temp1 = null;

            while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud sejour)
            {
                temp1 = nodes.Current.InnerXml;
            }
            //autre requete
            maRequeteXPath = "/sejour/refLogement";
            expr           = nav.Compile(maRequeteXPath);
            nodes          = nav.Select(expr);// exécution de la requête XPath
            string temp2 = null;

            while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud sejour)
            {
                temp2 = nodes.Current.InnerXml;
            }

            //autre requete
            maRequeteXPath = "/sejour/validation";
            expr           = nav.Compile(maRequeteXPath);
            nodes          = nav.Select(expr);// exécution de la requête XPath
            string temp3 = null;;

            while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud sejour)
            {
                temp3 = nodes.Current.InnerXml;
            }

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

            if (temp3 == "confirmé")
            {
                string          connectionString = "SERVER=localhost;PORT=3306;DATABASE=loueur;UID=root;PASSWORD='';";
                MySqlConnection connection       = new MySqlConnection(connectionString);
                connection.Open();

                MySqlCommand command = connection.CreateCommand();
                command.CommandText = "USE AgenceEscapade;";
                MySqlDataReader reader;
                reader = command.ExecuteReader();
                reader.Close();
                command.CommandText = "UPDATE sejour set etatDossier = true ,idRoom = '" + temp2 + "' WHERE numSejour ='" + temp1 + "';";
                reader = command.ExecuteReader();
                reader.Close();
                connection.Close();
                if (temp2 == logement[0][3])
                {
                    for (int i = 0; i < logement[0].Count; i++)
                    {
                        temp.Add(logement[0][i]);
                    }
                }
                else if (temp2 == logement[1][3])
                {
                    for (int i = 0; i < logement[1].Count; i++)
                    {
                        temp.Add(logement[1][i]);
                    }
                }
                else
                {
                    for (int i = 0; i < logement[2].Count; i++)
                    {
                        temp.Add(logement[2][i]);
                    }
                }
            }
            else
            {
                //on dit que la voiture est libre finalement
                string          connectionString = "SERVER=localhost;PORT=3306;DATABASE=loueur;UID=root;PASSWORD='';";
                MySqlConnection connection       = new MySqlConnection(connectionString);
                connection.Open();

                MySqlCommand command = connection.CreateCommand();
                command.CommandText = "USE AgenceEscapade;";
                MySqlDataReader reader;
                reader = command.ExecuteReader();
                reader.Close();
                command.CommandText = "UPDATE voiture SET dispo=true WHERE immat ='" + sejour[8] + "';";
                reader = command.ExecuteReader();
                reader.Close();
                command.CommandText = "INSERT INTO AgenceEscapade.`maintenance`(numMaint,`dateM`,`immatt`,`motif`,`note`) VALUES(CONCAT('M', ROUND(RAND() * 1000)), DATE(NOW()), '" + sejour[8] + "', 'Déplacement voiture', null);";
                reader = command.ExecuteReader();
                reader.Close();
                connection.Close();

                //On écrit un message au client pour lui dire que ce n'est pas réalisable
                XmlDocument docXml = new XmlDocument();

                // création de l'en-tête XML (no <=> pas de DTD associée)
                docXml.CreateXmlDeclaration("1.0", "UTF-8", "no");

                XmlElement racine = docXml.CreateElement("dossier");
                racine.SetAttribute("etatdossier", "impossible");
                racine.SetAttribute("numSejour", sejour[0]);
                docXml.AppendChild(racine);

                XmlElement autreBalise  = docXml.CreateElement("client");
                XmlElement baliseEnfant = docXml.CreateElement("codeC");
                baliseEnfant.InnerText = sejour[1];
                autreBalise.AppendChild(baliseEnfant);
                baliseEnfant           = docXml.CreateElement("prenom");
                baliseEnfant.InnerText = sejour[3];
                autreBalise.AppendChild(baliseEnfant);
                baliseEnfant           = docXml.CreateElement("nom");
                baliseEnfant.InnerText = sejour[2];
                autreBalise.AppendChild(baliseEnfant);
                racine.AppendChild(autreBalise);

                autreBalise            = docXml.CreateElement("sejour");
                baliseEnfant           = docXml.CreateElement("semaine");
                baliseEnfant.InnerText = sejour[6];
                autreBalise.AppendChild(baliseEnfant);
                baliseEnfant           = docXml.CreateElement("annee");
                baliseEnfant.InnerText = sejour[5];
                autreBalise.AppendChild(baliseEnfant);
                baliseEnfant           = docXml.CreateElement("theme");
                baliseEnfant.InnerText = sejour[11];
                autreBalise.AppendChild(baliseEnfant);
                baliseEnfant           = docXml.CreateElement("info");
                baliseEnfant.InnerText = "séjour impossible, veuillez choisir une autre date";
                autreBalise.AppendChild(baliseEnfant);
                racine.AppendChild(autreBalise);
                docXml.Save("M4.xml");

                temp = null;
            }
            return(temp);
        }
Пример #41
0
        static void SendFiles(string _fileName, string _dir)
        {
            TextWriter tw = null;

            var dic = new Dictionary <string, Findings>();

            if (optumFindings == null)
            {
                optumFindings = new List <Findings>();
            }
            else
            {
                optumFindings.Clear();
            }


            List <string> thisRun     = new List <string>();
            int           loop        = 0;
            int           lineCounter = 0;

            try
            {
                log.LogInformation(String.Format("In SendFiles {0} {1}", _fileName, _dir));
                string     user         = "******";
                string     password     = "******";
                string     claimsDotXml = _fileName;
                WebRequest req          = WebRequest.Create("https://realtimeecontent.com/ws/claims5x");

                req.Method      = "POST";
                req.ContentType = "application/xml";
                req.Credentials = new NetworkCredential(user, password);
                FileStream fs       = new FileStream(claimsDotXml, FileMode.Open);
                string     outFile  = String.Format(@"{0}\OUT\{1}.out", _dir, Path.GetFileName(_fileName));
                string     outFile2 = String.Format(@"{0}\OUT\{1}2.out", _dir, Path.GetFileName(_fileName));

                if (File.Exists(outFile))
                {
                    File.Delete(outFile);
                }

                log.LogInformation(String.Format("Creating File {0} ", outFile));
                tw = File.CreateText(outFile);


                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                using (Stream reqStream = req.GetRequestStream())
                {
                    byte[] buffer    = new byte[1024];
                    int    bytesRead = 0;
                    while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        reqStream.Write(buffer, 0, bytesRead);
                    }
                    fs.Close();
                }

                System.Net.HttpWebResponse resp = req.GetResponse() as System.Net.HttpWebResponse;
                if (resp.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    System.Xml.XPath.XPathDocument  xmlDoc = new System.Xml.XPath.XPathDocument(resp.GetResponseStream());
                    System.Xml.XPath.XPathNavigator nav    = xmlDoc.CreateNavigator();
                    //Console.WriteLine("Claim A5 had {0} Edits.", nav.Evaluate("count(/claim-responses/claim-response[@claim-id='43']/edit)"));
                    //Console.WriteLine(nav.Evaluate("/claim-responses/claim-response/edit"));
                    lineCounter++;
                    loop = 1;
                    XPathNodeIterator xPathIterator = nav.Select("/claim-responses//claim-response");
                    int    errLine = 0;
                    int    lastConflictFound = 0, iClaimLine = 0;
                    string lastClaim = "";
                    foreach (XPathNavigator claimResponse in xPathIterator)
                    {
                        XPathNavigator onav = claimResponse.SelectSingleNode("@claim-id");
                        string         id   = onav == null ? string.Empty : onav.Value;

                        try {
                            thisRun.Add(id);
                        }catch (Exception mex)
                        {
                            log.LogError(mex.Message);
                        }

                        if (id.CompareTo("20170309T33K00018") == 0)
                        {
                            errLine = 0;
                        }

                        XPathNodeIterator ixPathIterator = claimResponse.Select("edit");
                        bool hasEdits  = false;
                        int  noOfEdits = 0;
                        foreach (XPathNavigator editLines in ixPathIterator)
                        {
                            hasEdits = true;
                            noOfEdits++;
                            onav = editLines.SelectSingleNode("@line");
                            string claimLine = onav == null ? string.Empty : onav.Value;
                            string key       = id.Trim() + "|" + claimLine.Trim();

                            ClaimLinesIndex _cli;
                            try
                            {
                                iClaimLine = int.Parse(claimLine);
                            }
                            catch (Exception ex)
                            {
                                iClaimLine = 0;
                            }
                            if (iClaimLine > lastConflictFound)
                            {
                                string myId = "";
                                lastConflictFound = iClaimLine;
                            }

                            XPathNavigator inav        = editLines.SelectSingleNode("description");
                            string         description = editLines == null ? string.Empty : inav.Value;

                            //if (description.Contains("[Pattern 10372]"))
                            //    hasEdits = false;

                            //inav = editLines.SelectSingleNode("edit-conflict");
                            string editConflict = ""; // editLines == null ? string.Empty : inav.Value;

                            inav = editLines.SelectSingleNode("edit-type");
                            string editType = editLines == null ? string.Empty : inav.Value;

                            inav = editLines.SelectSingleNode("mnemonic");
                            string mnemonic = editLines == null ? string.Empty : inav.Value;


                            Findings opFind = new Findings();
                            opFind.id          = id;
                            opFind.lineNo      = claimLine;
                            opFind.editType    = editType;
                            opFind.mnemonic    = mnemonic;
                            opFind.editConflit = editConflict;
                            opFind.description = description;
                            optumFindings.Add(opFind);


                            if (!claimLinesList.ContainsKey(key))
                            {
                                log.LogError(String.Format("The claim does not contain {0}", key));
                                _cli            = new ClaimLinesIndex();
                                _cli.claim      = id;
                                _cli.hasDU      = true;
                                _cli.lineNo     = "-99";
                                _cli.claimIndex = "-99";
                            }
                            else
                            {
                                _cli = claimLinesList[key];
                            }
                            if (!_cli.hasDU)
                            {
                                if (!description.Contains("50.0%")) // Ignore Optum
                                {
                                    Findings findings = new Findings();
                                    findings.id          = id;
                                    findings.claimIndex  = _cli.claimIndex;
                                    findings.editType    = editType;
                                    findings.mnemonic    = mnemonic;
                                    findings.editConflit = editConflict;
                                    findings.description = description;
                                    try {
                                        dic.Add(String.Format("{0}{1}{2}", id, _cli.claimIndex, (++errLine).ToString()), findings);
                                    }catch (Exception mex)
                                    {
                                        log.LogError(mex.Message);
                                    }
                                }
                                else
                                {
                                    if (noOfEdits == 1) // this is the only edit for the claim and it's a wrong one mMP
                                    {
                                        hasEdits = false;
                                    }
                                    noOfEdits--;
                                }
                            }
                        }
                        if (hasEdits == false)
                        { // claim does not have any edits
                          //string percentage = "";
                          //ClaimLinesIndex _cli;
                          //int found = 0;

                            //if (found == 0)
                            //{
                            if (IsCleanClaim(id, claimLinesList))
                            {
                                Findings findings = new Findings();
                                findings.id          = id;
                                findings.claimIndex  = "0";
                                findings.editType    = "";
                                findings.mnemonic    = "";
                                findings.editConflit = "";
                                findings.description = "";
                                try {
                                    dic.Add(String.Format("{0}{1}{2}", id, findings.claimIndex, (++errLine).ToString()), findings);
                                }catch (Exception mex)
                                {
                                    log.LogError(mex.Message);
                                }
                            }

                            //tw.WriteLine("************ Claim {0} is clean ********", id);
                            //}
                        }
                    }
                    //FinishTheEdits(lastConflictFound - 1, lastClaim, claimLinesList, dic, errLine);
                }
                ReviewClaimLineList(tw);
                optumFindings.Clear();
                dic.Clear();
                dic = null;
                tw.Close();
            }
            catch (Exception ex)
            {
                log.LogError(String.Format("Sending Files {0}", ex.Message));
            }
            finally
            {
                //claimLinesList.Clear();
                thisRun.Clear();
            }
        }
Пример #42
0
        static void Analyse_M3(string[] info_client, Logement l)
        {
            string nomDuDocXML = "M3.xml";

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

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

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

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

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

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

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


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

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

            else
            {
                Console.WriteLine("Annulation du sejour...");
            }
        }
Пример #43
0
        static string[] LectureM1()
        {
            string[] client      = new string[12];
            string   nomDuDocXML = "M1.xml";

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

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

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

            //parcourir le resultat
            //---------------------

            while (nodes.MoveNext()) // pour chaque réponses XPath (on est au niveau d'un noeud sejour)
            {
                Console.Write("Client : " + nodes.Current.SelectSingleNode("genre").InnerXml);
                Console.WriteLine("." + nodes.Current.SelectSingleNode("nom").InnerXml);
                client[0] = nodes.Current.SelectSingleNode("nom").InnerXml;
                client[1] = nodes.Current.SelectSingleNode("prenom").InnerXml;
                client[2] = nodes.Current.SelectSingleNode("age").InnerXml;
                client[3] = nodes.Current.SelectSingleNode("adresseC").InnerXml;
                client[4] = nodes.Current.SelectSingleNode("email").InnerXml;
                client[5] = nodes.Current.SelectSingleNode("telephone").InnerXml;
            }

            //autre requete
            maRequeteXPath = "/sejour/adresse";
            expr           = nav.Compile(maRequeteXPath);
            nodes          = nav.Select(expr); // exécution de la requête XPath
            while (nodes.MoveNext())           // pour chaque réponses XPath (on est au niveau d'un noeud sejour)
            {
                Console.Write("Adresse : " + nodes.Current.SelectSingleNode("rue").InnerXml);
                Console.Write("," + nodes.Current.SelectSingleNode("ville").InnerXml);
                Console.WriteLine("," + nodes.Current.SelectSingleNode("codepostal").InnerXml);
                client[6] = nodes.Current.SelectSingleNode("rue").InnerXml;
                client[7] = nodes.Current.SelectSingleNode("ville").InnerXml;
                client[8] = nodes.Current.SelectSingleNode("codepostal").InnerXml;
            }
            //autre requete
            maRequeteXPath = "/sejour/date";
            expr           = nav.Compile(maRequeteXPath);
            nodes          = nav.Select(expr); // exécution de la requête XPath
            while (nodes.MoveNext())           // pour chaque réponses XPath (on est au niveau d'un noeud sejour)
            {
                Console.Write("Date du séjour (semaine-année) : " + nodes.Current.SelectSingleNode("semaine").InnerXml);
                Console.WriteLine("-" + nodes.Current.SelectSingleNode("annee").InnerXml);
                client[9]  = nodes.Current.SelectSingleNode("semaine").InnerXml;
                client[10] = nodes.Current.SelectSingleNode("annee").InnerXml;
            }
            //autre requete
            maRequeteXPath = "/sejour/sjour";
            expr           = nav.Compile(maRequeteXPath);
            nodes          = nav.Select(expr); // exécution de la requête XPath
            while (nodes.MoveNext())           // pour chaque réponses XPath (on est au niveau d'un noeud sejour)
            {
                Console.WriteLine("Theme : " + nodes.Current.InnerXml);
                client[11] = nodes.Current.InnerXml;
            }
            return(client);
        }
Пример #44
0
    protected void templateRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        ClearTemplateSelection();

        //change style of selected item
        HtmlControl li = (HtmlControl)e.Item.FindControl("listItem");

        if (string.IsNullOrEmpty(li.Attributes["class"]))
        {
            li.Attributes["class"] = "selectedTemplate";
        }
        else
        {
            li.Attributes["class"] += " selectedTemplate";
        }

        //get image file and regions
        string file = null;
        List <NamedRectangleRegion> regions = new List <NamedRectangleRegion>();

        System.Globalization.NumberFormatInfo numberInfo = new System.Globalization.NumberFormatInfo();
        numberInfo.NumberDecimalSeparator = ".";

        string templatesListFile = Path.Combine(_templateFolder, "Templates.xml");

        if (File.Exists(templatesListFile))
        {
            using (FileStream fs = new FileStream(templatesListFile, FileMode.Open, FileAccess.Read))
            {
                System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(fs);
                foreach (XPathNavigator nav in
                         doc.CreateNavigator().Select("/Templates/TemplateItem"))
                {
                    string fileName = Path.IsPathRooted(nav.GetAttribute("FileName", nav.NamespaceURI)) ? nav.Value : Path.Combine(_templateFolder, nav.GetAttribute("FileName", nav.NamespaceURI));
                    if (fileName.GetHashCode().ToString() == e.CommandArgument.ToString())
                    {
                        file = fileName;
                        foreach (XPathNavigator regionNavigator in nav.Select("Regions/Region"))
                        {
                            string name = regionNavigator.GetAttribute("Name", regionNavigator.NamespaceURI);
                            float  left = float.Parse(
                                regionNavigator.GetAttribute("Left", regionNavigator.NamespaceURI), numberInfo);
                            float top = float.Parse(
                                regionNavigator.GetAttribute("Top", regionNavigator.NamespaceURI), numberInfo);
                            float width = float.Parse(
                                regionNavigator.GetAttribute("Width", regionNavigator.NamespaceURI), numberInfo);
                            float height = float.Parse(
                                regionNavigator.GetAttribute("Height", regionNavigator.NamespaceURI), numberInfo);

                            regions.Add(new NamedRectangleRegion(name,
                                                                 new System.Drawing.RectangleF(left, top, width, height)));
                        }
                        break;
                    }
                }
            }
        }

        if (!string.IsNullOrEmpty(file) && File.Exists(file))
        {
            photoLabel.CanvasViewer.Canvas.History.Enable = photoLabel.CanvasViewer.Canvas.History.TrackingEnabled = false;

            photoLabel.BackgroundImage = file;

            //remove previous regions
            photoLabel.RemoveAllRegions();

            //add new regions
            photoLabel.AddRegions(regions);
            //select last region
            photoLabel.CurrentRegion = regions[regions.Count - 1];

            //clear canvas history
            photoLabel.CanvasViewer.Canvas.History.Clear();
            photoLabel.CanvasViewer.Canvas.History.Enable = photoLabel.CanvasViewer.Canvas.History.TrackingEnabled = true;
        }
    }