LoadXml() public method

public LoadXml ( string xml ) : void
xml string
return void
        /// <summary>
        /// loads a xml from the web server
        /// </summary>
        /// <param name="_url">URL of the XML file</param>
        /// <returns>A XmlDocument object of the XML file</returns>
        public static XmlDocument LoadXml(string _url)
        {
            var xmlDoc = new XmlDocument();
            
            try
            {
                while (Helper.pingForum("forum.mods.de", 10000) == false)
                {
                    Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds...");
                    System.Threading.Thread.Sleep(15000);
                }

                xmlDoc.Load(_url);
            }
            catch (XmlException)
            {
                while (Helper.pingForum("forum.mods.de", 100000) == false)
                {
                    Console.WriteLine("Can't reach forum.mods.de right now, try again in 15 seconds...");
                    System.Threading.Thread.Sleep(15000);
                }

                WebClient client = new WebClient(); ;
                Stream stream = client.OpenRead(_url);
                StreamReader reader = new StreamReader(stream);
                string content = reader.ReadToEnd();

                content = RemoveTroublesomeCharacters(content);
                xmlDoc.LoadXml(content);
            }

            return xmlDoc;
        }
Exemplo n.º 2
1
 private void saveXml()
 {
     string error = String.Empty;
     XmlDocument modifiedXml = new XmlDocument();
     modifiedXml.LoadXml(txtXml.Text);
     pageNode.SetPersonalizationFromXml(HttpContext.Current, modifiedXml, out error);
 }
Exemplo n.º 3
1
        public GeoIP()
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://freegeoip.net/xml/");
                request.Proxy = null;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream dataStream = response.GetResponseStream();
                StreamReader reader = new StreamReader(dataStream);
                string responseString = reader.ReadToEnd();
                reader.Close();
                dataStream.Close();
                response.Close();

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

                WANIP = doc.SelectSingleNode("Response//Ip").InnerXml.ToString();
                Country = (!string.IsNullOrEmpty(doc.SelectSingleNode("Response//CountryName").InnerXml.ToString())) ? doc.SelectSingleNode("Response//CountryName").InnerXml.ToString() : "Unknown";
                CountryCode = (!string.IsNullOrEmpty(doc.SelectSingleNode("Response//CountryCode").InnerXml.ToString())) ? doc.SelectSingleNode("Response//CountryCode").InnerXml.ToString() : "-";
                Region = (!string.IsNullOrEmpty(doc.SelectSingleNode("Response//RegionName").InnerXml.ToString())) ? doc.SelectSingleNode("Response//RegionName").InnerXml.ToString() : "Unknown";
                City = (!string.IsNullOrEmpty(doc.SelectSingleNode("Response//City").InnerXml.ToString())) ? doc.SelectSingleNode("Response//City").InnerXml.ToString() : "Unknown";
            }
            catch
            {
                WANIP = "-";
                Country = "Unknown";
                CountryCode = "-";
                Region = "Unknown";
                City = "Unknown";
            }
        }
Exemplo n.º 4
1
        private void DlgTips_Load(object sender, EventArgs e)
        {   
            try
            {
                string strxml = "";
                using (StreamReader streamReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("Johnny.Kaixin.WinUI.Resources.Versions.config")))
                {
                    strxml = streamReader.ReadToEnd();
                }

                XmlDocument objXmlDoc = new XmlDocument();
                objXmlDoc.LoadXml(strxml);

                if (objXmlDoc == null)
                    return;

                DataView dv = GetData(objXmlDoc, "ZrAssistant/Versions");

                for (int ix = 0; ix < dv.Table.Rows.Count; ix++)
                {
                    _versionList.Add(dv.Table.Rows[ix][0].ToString(), dv.Table.Rows[ix][1].ToString());
                    cmbVersion.Items.Add(dv.Table.Rows[ix][0].ToString());
                }

                chkNeverDisplay.Checked = Properties.Settings.Default.NeverDisplay;
                cmbVersion.SelectedIndex = 0;
                SetTextValue();
                btnOk.Select();
            }
            catch (Exception ex)
            {
                Program.ShowMessageBox("DlgTips", ex);
            }
        }
Exemplo n.º 5
0
        public RssParser (string url, string xml)
        {
            this.url = url;
            xml = xml.TrimStart ();
            doc = new XmlDocument ();
            try {
                doc.LoadXml (xml);
            } catch (XmlException e) {
                bool have_stripped_control = false;
                StringBuilder sb = new StringBuilder ();

                foreach (char c in xml) {
                    if (Char.IsControl (c) && c != '\n') {
                        have_stripped_control = true;
                    } else {
                        sb.Append (c);
                    }
                }

                bool loaded = false;
                if (have_stripped_control) {
                    try {
                        doc.LoadXml (sb.ToString ());
                        loaded = true;
                    } catch (Exception) {
                    }
                }

                if (!loaded) {
                    Hyena.Log.Exception (e);
                    throw new FormatException ("Invalid XML document.");
                }
            }
            CheckRss ();
        }
Exemplo n.º 6
0
		public void Add ()
		{
			XmlSchemaSet ss = new XmlSchemaSet ();
			XmlDocument doc = new XmlDocument ();
			doc.LoadXml ("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' />");
			ss.Add (null, new XmlNodeReader (doc)); // null targetNamespace
			ss.Compile ();

			// same document, different targetNamespace
			ss.Add ("ab", new XmlNodeReader (doc));

			// Add(null, xmlReader) -> targetNamespace in the schema
			doc.LoadXml ("<xs:schema xmlns:xs='http://www.w3.org/2001/XMLSchema' targetNamespace='urn:foo' />");
			ss.Add (null, new XmlNodeReader (doc));

			Assert.AreEqual (3, ss.Count);

			bool chameleon = false;
			bool ab = false;
			bool urnfoo = false;

			foreach (XmlSchema schema in ss.Schemas ()) {
				if (schema.TargetNamespace == null)
					chameleon = true;
				else if (schema.TargetNamespace == "ab")
					ab = true;
				else if (schema.TargetNamespace == "urn:foo")
					urnfoo = true;
			}
			Assert.IsTrue (chameleon, "chameleon schema missing");
			Assert.IsTrue (ab, "target-remapped schema missing");
			Assert.IsTrue (urnfoo, "target specified in the schema ignored");
		}
        /// <summary>
        /// Load language files
        /// </summary>
        public static List<MultiLangEngine> LoadLanguages()
        {
            List<MultiLangEngine> languages = new List<MultiLangEngine>();

            /* Check if language dir exists
             * 1. If it does, scan it
             * 2. If it doesn't, skip it
             */
            string langPath = Environment.CurrentDirectory + @"\lang\";
            if (Directory.Exists(langPath))
            {
                // 1
                languages = MultiLangEngine.ScanDirectory(langPath);
            }

            /* 
             * Load built-in language files
             */
            try
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(Properties.Resources.dwas2_en_US);
                languages.Add(new MultiLangEngine(xmldoc));
                xmldoc.LoadXml(Properties.Resources.dwas2_zh_CN);
                languages.Add(new MultiLangEngine(xmldoc));
            }
            catch (Exception ex)
            {
                // skip
            }

            return languages;
        }
Exemplo n.º 8
0
 public XmlDocument execStoredProc(String strProcName, XmlDocument strParameters)
 {
     XmlDocument Result = new XmlDocument();
     SqlConnection sConn = new SqlConnection();
     sConn = getPooledConnection(sConn);
     try
     {
         sConn.Open();
         SqlCommand command = new SqlCommand(strProcName, sConn);
         command.CommandType = CommandType.StoredProcedure;
         command.Parameters.Add("@p", SqlDbType.Xml).Value = strParameters.InnerXml;
         SqlParameter result = command.Parameters.Add
                    ("@r", SqlDbType.Xml);
         result.Direction = ParameterDirection.Output;
         command.ExecuteNonQuery();
         Result.LoadXml(result.Value.ToString());
         sConn.Close();
     }
     catch (Exception exp)
     {
         Result.LoadXml(exp.ToString());
         sConn.Close();
     }
     return (Result);
 }
Exemplo n.º 9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            uToolsCore.Authorize();

            string mediaID = HttpUtility.UrlDecode(HttpContext.Current.Request.QueryString["mediaID"]);
            XmlDocument resultDocument = new XmlDocument();

            try
            {

                XPathNodeIterator xn = umbraco.library.GetMedia(Convert.ToInt32(mediaID), true);
                xn.MoveNext();

                resultDocument.LoadXml("<uTools>" + xn.Current.OuterXml + "</uTools>");
            }

            catch (Exception e2)
            {
                resultDocument.LoadXml("<uTools><noResults/></uTools>");
            }

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ContentType = "text/xml";
            HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
            resultDocument.Save(HttpContext.Current.Response.Output);
            HttpContext.Current.Response.End();
        }
Exemplo n.º 10
0
    public void TestCompFilter()
    {
      var uut = new CompFilter(ResourceType.VEVENT);
      var xmlDoc = new XmlDocument();

      xmlDoc.LoadXml(AddNamespace(uut.ToXml()));

      Assert.AreEqual(1, xmlDoc.GetElementsByTagName("C:comp-filter").Count);
      var element = xmlDoc.GetElementsByTagName("C:comp-filter")[0];
      Assert.AreEqual(ResourceType.VEVENT.ToString(), element.Attributes["name"].Value);
      Assert.AreEqual(0, element.ChildNodes.Count);

      uut.AddChild(new TimeRangeFilter() { Start = new DateTime(2000, 1, 1, 21, 0, 0) });
      xmlDoc.LoadXml(AddNamespace(uut.ToXml()));
      element = xmlDoc.GetElementsByTagName("C:comp-filter")[0];

      Assert.AreEqual(1, element.ChildNodes.Count);

      try
      {
        uut.AddChild(new TimeRangeFilter());
        Assert.Fail();
      }
      catch (InvalidFilterException) { }

      uut = new CompFilter(ResourceType.VCALENDAR);
      uut.AddChild(new IsNotDefinedFilter());
      try
      {
        uut.AddChild(new CompFilter(ResourceType.VEVENT));
        Assert.Fail();
      }
      catch (InvalidFilterException) { }
    }
        public List<string> ParsePMIDs(string xml)
        {
            if(string.IsNullOrEmpty(xml))
                return null;
            //Debug.Print(xml.Length);
            //Debug.WriteLine(xml);
            List<string> list = new List<string>();
            XmlDocument xdoc = new XmlDocument();
            try
            {
                xdoc.LoadXml(xml);
            }
            catch //(WebException ex)
            {
                xdoc.LoadXml(xml);
            }
            XmlNode cnode = xdoc.SelectSingleNode("/eSearchResult/Count");
            if(cnode ==null)
                return null;
            int total = int.Parse(cnode.InnerText);
            if (total == 0)
            {
                list.Add("-1");

            }
            else
            {
                XmlNodeList nodelist = xdoc.SelectNodes("/eSearchResult/IdList/Id");
                foreach (XmlNode node in nodelist)
                {
                    list.Add(node.InnerText);
                }
            }
            return list;
        }
Exemplo n.º 12
0
        public TimedTextStyles(Subtitle subtitle)
        {
            InitializeComponent();

            _subtitle = subtitle;
            _xml = new XmlDocument();
            try
            {
                _xml.LoadXml(subtitle.Header);
                var xnsmgr = new XmlNamespaceManager(_xml.NameTable);
                xnsmgr.AddNamespace("ttml", "http://www.w3.org/ns/ttml");
                if (_xml.DocumentElement.SelectSingleNode("ttml:head", xnsmgr) == null)
                    _xml.LoadXml(new TimedText10().ToText(new Subtitle(), "tt")); // load default xml
            }
            catch
            {
                _xml.LoadXml(new TimedText10().ToText(new Subtitle(), "tt")); // load default xml
            }
            _nsmgr = new XmlNamespaceManager(_xml.NameTable);
            _nsmgr.AddNamespace("ttml", "http://www.w3.org/ns/ttml");
            _xmlHead = _xml.DocumentElement.SelectSingleNode("ttml:head", _nsmgr);

            foreach (FontFamily ff in FontFamily.Families)
                comboBoxFontName.Items.Add(ff.Name.Substring(0, 1).ToLower() + ff.Name.Substring(1));

            InitializeListView();

            _previewTimer.Interval = 200;
            _previewTimer.Tick += RefreshTimerTick;
        }
    public void TestHandleMessage() {
      try {
        ContextStore.AddKey("SoapMethod", "get");

        XmlDocument xDoc = new XmlDocument();
        xDoc.LoadXml(SoapMessages_v201406.GetAccountAlerts);
        XmlElement xRequest = (XmlElement) xDoc.SelectSingleNode("/Example/SOAP/Response");
        xDoc.LoadXml(xRequest.InnerText);
        AlertService service = (AlertService) user.GetService(AdWordsService.v201406.AlertService);

        AdWordsCallListener.Instance.HandleMessage(xDoc, service, SoapMessageDirection.IN);

        Assert.AreEqual(user.GetTotalOperationCount(), 2);
        Assert.AreEqual(user.GetOperationCountForLastCall(), 2);
        ApiCallEntry[] callEntries = user.GetCallDetails();
        Assert.AreEqual(callEntries.Length, 1);
        ApiCallEntry callEntry = user.GetCallDetails()[0];

        Assert.AreEqual(callEntry.OperationCount, 2);
        Assert.AreEqual(callEntry.Method, "get");
        Assert.AreEqual(callEntry.Service.Signature.ServiceName, "AlertService");
      } finally {
        ContextStore.RemoveKey("SoapMethod");
      }
    }
Exemplo n.º 14
0
 public VariantDefinition(VariantVersion version)
 {
     XmlDocument doc = new XmlDocument();
     if (version.Definition != string.Empty)
         doc.LoadXml(version.Definition);
     else
         doc.LoadXml("<game><board viewBox=\"0 0 100 100\"/></game>");
     Version = version;
     Xml = doc;
 }
Exemplo n.º 15
0
        public static XmlNode ParseXml(string xml, bool isDoc)
        {
            XmlDocument doc = new XmlDocument();

            if (isDoc)
                doc.LoadXml(xml);
            else
                doc.LoadXml("<root>" + xml + "</root>");

            return doc.DocumentElement;
        }
Exemplo n.º 16
0
        /// <summary>
        /// Creates the guide entry from the given text and relvant attributes
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="hiddenStatus"></param>
        /// <param name="style"></param>
        /// <param name="editing"></param>
        /// <returns></returns>
        static public XmlElement CreateGuideEntry(string text, int hiddenStatus, GuideEntryStyle style, int canRead)
        {

            XmlDocument doc = new XmlDocument();
            if (hiddenStatus > 0 && canRead == 0)
            {
                doc.LoadXml("<GUIDE><BODY>This article has been hidden pending moderation.</BODY></GUIDE>");
            }
            else
            {
                try
                {
                    switch (style)
                    {
                        case GuideEntryStyle.GuideML:
                            text = text.Trim();
                            text = Entities.ReplaceEntitiesWithNumericValues(text);
                            //text = HtmlUtils.ReplaceCRsWithBRs(text);
                            text = HtmlUtils.EscapeNonEscapedAmpersands(text);
                            doc.PreserveWhitespace = true;
                            doc.LoadXml(text);
                            AdjustFootnotes(doc);
                            //doc["GUIDE"]["BODY"].InnerXml = HtmlUtils.ReplaceCRsWithBRs(doc["GUIDE"]["BODY"].InnerXml);
                            break;

                        case GuideEntryStyle.PlainText:
                            doc.LoadXml(StringUtils.PlainTextToGuideML(text));
                            break;

                        case GuideEntryStyle.Html:
                            doc.LoadXml("<GUIDE><BODY><PASSTHROUGH><![CDATA[" + text + "]]></PASSTHROUGH></BODY></GUIDE>");
                            break;

                        default:
                            goto case GuideEntryStyle.GuideML;//null styles are generally guideml...
                        //throw new NotImplementedException("Don't know what type of entry we've got here!");
                    }
                }
                catch (XmlException e)
                {
                    //If something has gone wrong log stuff
                    DnaDiagnostics.Default.WriteExceptionToLog(e);

                    var errorMessage = Regex.Replace(e.Message, "position +[0-9][0-9]* ", "", RegexOptions.IgnoreCase);

                    var xmlException = new XmlException(errorMessage, e);

                    throw new ApiException("GuideML Transform Failed", xmlException);
                }
            }

            return doc.DocumentElement;
        }
Exemplo n.º 17
0
        protected override XmlDocument CloudFileAccountInformationXml()
        {
            var xmlDocument = new XmlDocument();
            if (containers.Count > 0)
            {
                xmlDocument.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><account name=\"MossoCloudFS_5d8f3dca-7eb9-4453-aa79-2eea1b980353\"><container><name>container</name><count>0</count><bytes>0</bytes></container></account>");
                return xmlDocument;
            }

            xmlDocument.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><account name=\"MossoCloudFS_5d8f3dca-7eb9-4453-aa79-2eea1b980353\"></account>");
            return xmlDocument;
        }
Exemplo n.º 18
0
        protected override XmlDocument CloudFileContainerInformationXml()
        {
            XmlDocument xmlDocument = new XmlDocument();
            if (objects.Count > 0)
            {
                xmlDocument.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><container name=\"testcontainername\"><object><name>object</name><hash>4281c348eaf83e70ddce0e07221c3d28</hash><bytes>14</bytes><content_type>application/octet-stream</content_type><last_modified>2009-02-03T05:26:32.612278</last_modified></object></container>");
                return xmlDocument;
            }

            xmlDocument.LoadXml("<?xml version=\"1.0\" encoding=\"UTF-8\"?><container name=\"testcontainername\"></container>");
            return xmlDocument;
        }
Exemplo n.º 19
0
 public void matchTest()
 {
     XmlDocument node = new XmlDocument();
     node.LoadXml("<match name=\"test\" value=\"10\"/>");
     RuleMatch rule = new RuleMatch(node.FirstChild, null);
     List<Option> fields; // ignore it anyway
     Dictionary<String, Option> env = new Dictionary<string, Option>();
     env.Add("test", new OptionInt("test", 10, 0, 255, 1));
     Assert.IsNotNull(rule.match(env, null, out fields));
     node.LoadXml("<match name=\"test\" value=\"0\"/>");
     rule = new RuleMatch(node.FirstChild, null);
     Assert.IsNull(rule.match(env, null, out fields));
 }
Exemplo n.º 20
0
        /// <summary>
        /// Retorna o XML em formato de string do retorno do evento;
        /// </summary>
        /// <returns></returns>
        public string ExecuteEvento()
        {
            try
            {
                string sDados = this.GetMsgDados();
                XmlDocument xRet = new XmlDocument();

                if (Acesso.TP_AMB == 1)
                {
                    HLP.GeraXml.WebService.AN_PRODUCAO_RecepcaoEvento.nfeCabecMsg cabec = new HLP.GeraXml.WebService.AN_PRODUCAO_RecepcaoEvento.nfeCabecMsg();
                    HLP.GeraXml.WebService.AN_PRODUCAO_RecepcaoEvento.RecepcaoEvento ws2 = new HLP.GeraXml.WebService.AN_PRODUCAO_RecepcaoEvento.RecepcaoEvento();

                    cabec.versaoDados = "1.00";
                    cabec.cUF = "91";// Acesso.cUF.ToString();
                    ws2.ClientCertificates.Add(Acesso.cert_NFe);
                    ws2.nfeCabecMsgValue = cabec;
                    XmlDocument xmlCanc = new XmlDocument();
                    xmlCanc.LoadXml(sDados);
                    XmlNode xNodeCanc = xmlCanc.DocumentElement;
                    string sRet = ws2.nfeRecepcaoEvento(xNodeCanc).OuterXml;
                    xRet.LoadXml(sRet);

                }
                else if (Acesso.TP_AMB == 2)
                {
                    //HLP.GeraXml.WebService.v2_Homologacao_NFeRecepcaoEvento_SP.nfeCabecMsg cabec = new HLP.GeraXml.WebService.v2_Homologacao_NFeRecepcaoEvento_SP.nfeCabecMsg();
                    //HLP.GeraXml.WebService.v2_Homologacao_NFeRecepcaoEvento_SP.RecepcaoEvento ws2 = new HLP.GeraXml.WebService.v2_Homologacao_NFeRecepcaoEvento_SP.RecepcaoEvento();


                    HLP.GeraXml.WebService.AN_HOMOLOGACAO_RecepcaoEvento.nfeCabecMsg cabec = new HLP.GeraXml.WebService.AN_HOMOLOGACAO_RecepcaoEvento.nfeCabecMsg();
                    HLP.GeraXml.WebService.AN_HOMOLOGACAO_RecepcaoEvento.RecepcaoEvento ws2 = new HLP.GeraXml.WebService.AN_HOMOLOGACAO_RecepcaoEvento.RecepcaoEvento();

                    cabec.versaoDados = "1.00";
                    cabec.cUF = "91"; // Acesso.cUF.ToString();
                    ws2.ClientCertificates.Add(Acesso.cert_NFe);
                    ws2.nfeCabecMsgValue = cabec;
                    XmlDocument xmlCanc = new XmlDocument();
                    xmlCanc.LoadXml(sDados);
                    XmlNode xNodeCanc = xmlCanc.DocumentElement;
                    string sRet = ws2.nfeRecepcaoEvento(xNodeCanc).OuterXml;
                    xRet.LoadXml(sRet);

                }
                return xRet.InnerXml;
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
Exemplo n.º 21
0
        public static XmlNode StringToXml(string xmlText, string backupOuterTag)
        {
            XmlDocument xmldoc = new XmlDocument();
            try
            {
                xmldoc.LoadXml(xmlText);
            }
            catch
            {
                xmldoc.LoadXml("<" + backupOuterTag + ">" + xmlText + "</" + backupOuterTag + ">");
            }

            return xmldoc.ChildNodes[xmldoc.ChildNodes.Count - 1];
        }
 private static XmlNode GetResponseNode(string output)
 {
     var xml = new XmlDocument();
     try
     {
         xml.LoadXml(output);
     }
     catch(XmlException)
     {
         string errorXml = string.Format("<?xml version=\"1.0\" encoding=\"utf-8\" ?><response status=\"error\" version=\"1.2\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://api.7digital.com/1.2/static/7digitalAPI.xsd\" ><error code=\"9001\"><errorMessage>{0}</errorMessage></error></response>", output);
         xml.LoadXml(errorXml);
     }
     return xml.SelectSingleNode("/response");
 }
Exemplo n.º 23
0
        public RdfParser(string uri, string xml)
        {
            this.uri = uri;
            this.document = new XmlDocument();

            try {
                document.LoadXml(xml);
            } catch (XmlException e) {
                Globals.Exception(e);
                bool have_stripped_control = false;
                StringBuilder sb = new StringBuilder ();

                foreach (char c in xml) {
                    if (Char.IsControl(c) && c != '\n') {
                        have_stripped_control = true;
                    } else {
                        sb.Append(c);
                    }
                }

                bool loaded = false;
                if (have_stripped_control) {
                    try {
                        document.LoadXml(sb.ToString ());
                        loaded = true;
                    } catch (Exception) {
                    }
                }

                if (!loaded) {
                }
            }
            mgr = new XmlNamespaceManager(document.NameTable);
            mgr.AddNamespace("rss10", "http://purl.org/rss/1.0/");
            mgr.AddNamespace("content", "http://purl.org/rss/1.0/modules/content/");
            mgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");

            XmlNodeList channodes = document.SelectNodes("//rss10:channel", mgr);
            foreach ( XmlNode node in channodes ) {
                Name = GetXmlNodeText(node, "rss10:title");
                Subtitle = GetXmlNodeText(node, "rss10:description");
            }

            XmlNodeList nodes = document.SelectNodes("//rss10:item", mgr);

            Items = new ArrayList();
            foreach (XmlNode node in nodes) {
                items.Add(ParseItem(node));
            }
        }
Exemplo n.º 24
0
        public override System.Xml.XmlNode ToXMl(System.Xml.XmlDocument data)
        {
            XmlDocument xd = new XmlDocument();
            try
            {
                xd.LoadXml(this.Value.ToString());
            }
            catch (Exception e)
            {
                xd.LoadXml(defaultXML);
            }

            return data.ImportNode(xd.DocumentElement, true);
        }
Exemplo n.º 25
0
        public override System.Xml.XmlNode ToXMl(System.Xml.XmlDocument data)
        {
            XmlDocument xd = new XmlDocument();
            try
            {
                xd.LoadXml(this.Value.ToString());
            }
            catch (Exception e)
            {
                string initialValue = "<list><item indent=\"0\"/></list>";
                xd.LoadXml(initialValue);
            }

            return data.ImportNode(xd.DocumentElement, true);
        }
        private static XmlDocument CreateXmlDocV3(string targetZone)
        {
            XmlDocument document = new XmlDocument();
            switch (targetZone)
            {
                case "LocalIntranet":
                    document.LoadXml("<PermissionSet class=\"System.Security.PermissionSet\" version=\"1\" ID=\"Custom\" SameSite=\"site\">\n<IPermission class=\"System.Security.Permissions.EnvironmentPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Read=\"USERNAME\" />\n<IPermission class=\"System.Security.Permissions.FileDialogPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Unrestricted=\"true\" />\n<IPermission class=\"System.Security.Permissions.IsolatedStorageFilePermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Allowed=\"AssemblyIsolationByUser\" UserQuota=\"9223372036854775807\" Expiry=\"9223372036854775807\" Permanent=\"True\" />\n<IPermission class=\"System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Flags=\"ReflectionEmit\" />\n<IPermission class=\"System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Flags=\"Assertion, Execution, BindingRedirects\" />\n<IPermission class=\"System.Security.Permissions.UIPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Unrestricted=\"true\" />\n<IPermission class=\"System.Net.DnsPermission, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Unrestricted=\"true\" />\n<IPermission class=\"System.Drawing.Printing.PrintingPermission, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" version=\"1\" Level=\"DefaultPrinting\" />\n<IPermission class=\"System.Security.Permissions.MediaPermission, WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" version=\"1\" Audio=\"SafeAudio\" Video=\"SafeVideo\" Image=\"SafeImage\" />\n<IPermission class=\"System.Security.Permissions.WebBrowserPermission, WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" version=\"1\" Level=\"Safe\" />\n</PermissionSet>");
                    return document;

                case "Internet":
                    document.LoadXml("<PermissionSet class=\"System.Security.PermissionSet\" version=\"1\" ID=\"Custom\" SameSite=\"site\">\n<IPermission class=\"System.Security.Permissions.FileDialogPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Access=\"Open\" />\n<IPermission class=\"System.Security.Permissions.IsolatedStorageFilePermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Allowed=\"ApplicationIsolationByUser\" UserQuota=\"512000\" />\n<IPermission class=\"System.Security.Permissions.SecurityPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Flags=\"Execution\" />\n<IPermission class=\"System.Security.Permissions.UIPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" version=\"1\" Window=\"SafeTopLevelWindows\" Clipboard=\"OwnClipboard\" />\n<IPermission class=\"System.Drawing.Printing.PrintingPermission, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" version=\"1\" Level=\"SafePrinting\" />\n<IPermission class=\"System.Security.Permissions.MediaPermission, WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" version=\"1\" Audio=\"SafeAudio\" Video=\"SafeVideo\" Image=\"SafeImage\" />\n<IPermission class=\"System.Security.Permissions.WebBrowserPermission, WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\" version=\"1\" Level=\"Safe\" />\n</PermissionSet>");
                    return document;
            }
            throw new ArgumentException(string.Empty, "targetZone");
        }
Exemplo n.º 27
0
        public override string ToText(Subtitle subtitle, string title)
        {
            string xmlStructure =
                "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + Environment.NewLine +
                "<EEG708Captions/>";

            XmlDocument xml = new XmlDocument();
            xml.LoadXml(xmlStructure);

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                XmlNode paragraph = xml.CreateElement("Caption");
                XmlAttribute start = xml.CreateAttribute("timecode");
                start.InnerText = EncodeTimeCode(p.StartTime);
                paragraph.Attributes.Append(start);
                XmlNode text = xml.CreateElement("Text");
                text.InnerText = p.Text;
                paragraph.AppendChild(text);
                xml.DocumentElement.AppendChild(paragraph);

                paragraph = xml.CreateElement("Caption");
                start = xml.CreateAttribute("timecode");
                start.InnerText = EncodeTimeCode(p.EndTime);
                paragraph.Attributes.Append(start);
                xml.DocumentElement.AppendChild(paragraph);
            }

            return ToUtf8XmlString(xml);
        }
Exemplo n.º 28
0
        public void ConfigurationMessagesTest()
        {
            try {
                LogLog.EmitInternalMessages = false;
                LogLog.InternalDebugging = true;

                XmlDocument log4netConfig = new XmlDocument();
                log4netConfig.LoadXml(@"
                <log4net>
                  <appender name=""LogLogAppender"" type=""log4net.Tests.LoggerRepository.LogLogAppender, log4net.Tests"">
                    <layout type=""log4net.Layout.SimpleLayout"" />
                  </appender>
                  <appender name=""MemoryAppender"" type=""log4net.Appender.MemoryAppender"">
                    <layout type=""log4net.Layout.SimpleLayout"" />
                  </appender>
                  <root>
                    <level value=""ALL"" />
                    <appender-ref ref=""LogLogAppender"" />
                    <appender-ref ref=""MemoryAppender"" />
                  </root>  
                </log4net>");

                ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString());
                rep.ConfigurationChanged += new LoggerRepositoryConfigurationChangedEventHandler(rep_ConfigurationChanged);

                ICollection configurationMessages = XmlConfigurator.Configure(rep, log4netConfig["log4net"]);

                Assert.IsTrue(configurationMessages.Count > 0);
            }
            finally {
                LogLog.EmitInternalMessages = true;
                LogLog.InternalDebugging = false;
            }
        }
Exemplo n.º 29
0
 public static XmlDocument StreamToXml(Stream stream)
 {
     var xmlDoc = new XmlDocument();
     var reader = new StreamReader(stream);
     xmlDoc.LoadXml(reader.ReadToEnd());
     return xmlDoc;
 }
Exemplo n.º 30
0
		public void SetUp()
		{
			TestHelper.SetupLog4NetForTests();
			Umbraco.Core.Configuration.UmbracoSettings.UseLegacyXmlSchema = false;
			_httpContextFactory = new FakeHttpContextFactory("~/Home");
			//ensure the StateHelper is using our custom context
			StateHelper.HttpContext = _httpContextFactory.HttpContext;
			
			_umbracoContext = new UmbracoContext(_httpContextFactory.HttpContext, 
				new ApplicationContext(), 
				new DefaultRoutesCache(false));

			_umbracoContext.GetXmlDelegate = () =>
				{
					var xDoc = new XmlDocument();

					//create a custom xml structure to return

					xDoc.LoadXml(GetXml());
					//return the custom x doc
					return xDoc;
				};

			_publishedContentStore = new DefaultPublishedContentStore();			
		}
Exemplo n.º 31
0
    /// <summary>
    /// BlockScript limits the number of queries that can be sent to the API in a 24 hour period. This API displays the
    /// total number of queries allowed by your license key and the total number of queries remaining
    /// in the current 24 hour period. A query to lookup an IP takes the form of:
    /// </summary>
    /// <returns></returns>
    public static string GetQueriesRemaining()
    {
        try
        {
            using (var client = new MyWebClient())
            {
                string results             = client.DownloadString(ApiUrl + "?blockscript=api&api_key=" + ApiKey + "&action=queries");
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(results);

                string parsedResult = doc.SelectSingleNode("//response/msg/text()").Value;

                return(parsedResult);
            }
        }
        catch (Exception ex)
        {
            ErrorLogger.Log(ex);
            return("n/a");
        }
    }
Exemplo n.º 32
0
    public void initLevels()
    {
        string dataPath = Application.persistentDataPath + "/";

        //string assetPath = "Resources/Levels";
        TextAsset[] filesToCopy = Resources.LoadAll <TextAsset>("Levels");
        Debug.Log("Found " + filesToCopy.Length + " levels in resources");
        System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
        //FilePanel fp = new FilePanel();
        //FileInfo[] fileNames = fp.ReadFilesInFolder(assetPath);
        foreach (TextAsset file in filesToCopy)
        {
            xmldoc.LoadXml(file.text);
            if (!File.Exists(dataPath + "/" + file.name + ".xml"))
            {
                // File doesn't exist, move it from assets folder to data directory
                //File.Copy(assetPath + "/" + file.Name, dataPath + "/" + file.Name);
                xmldoc.Save(dataPath + "/" + file.name + ".xml");
            }
        }
    }
Exemplo n.º 33
0
    /// <summary>
    /// Gets the web response as a XML document
    /// </summary>
    protected static System.Xml.XmlDocument GetWebResponseAsXml(WebResponse response)
    {
        string streamText     = "";
        var    responseStream = response.GetResponseStream();

        using (responseStream)
        {
            var streamReader = new StreamReader(responseStream);
            using (streamReader)
            {
                streamText = streamReader.ReadToEnd();
                streamReader.Close();
            }
            responseStream.Close();
        }

        var xmlDoc = new System.Xml.XmlDocument();

        xmlDoc.LoadXml(streamText);
        return(xmlDoc);
    }
Exemplo n.º 34
0
    public override void toControl(Hashtable values)
    {
        //base.toControl(values);
        object o = values[fieldName];

        if (o != null)
        {
            string xmlString = o.ToString();
            System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
            if (!string.IsNullOrEmpty(xmlString))
            {
                xmlDoc.LoadXml(xmlString);
                System.Xml.XmlNodeList xmlNodeList = xmlDoc.DocumentElement.GetElementsByTagName(xmlNodeName);
                if (xmlNodeList.Count > 0)
                {
                    textbox.Text = xmlNodeList[0].InnerXml;
                    return;
                }
            }
        }
        textbox.Text = string.Empty;
    }
Exemplo n.º 35
0
    public override void toValues(Hashtable values)
    {
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        if (!values.ContainsKey(fieldName))
        {
            System.Xml.XmlElement rootNode = xmlDoc.CreateElement(fieldName);
            xmlDoc.AppendChild(rootNode);
            values.Add(fieldName, xmlDoc.InnerXml);
        }
        else
        {
            xmlDoc.LoadXml(values[fieldName].ToString());
        }

        if (checkbox.Checked)
        {
            System.Xml.XmlElement xmlElement = xmlDoc.CreateElement(xmlNodeName);
            xmlElement.InnerText = "YES";
            xmlDoc.DocumentElement.AppendChild(xmlElement);
            values[fieldName] = xmlDoc.InnerXml;
        }
    }
Exemplo n.º 36
0
    public override void toValues(Hashtable values)
    {
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        if (!values.ContainsKey(fieldName))
        {
            System.Xml.XmlElement rootNode = xmlDoc.CreateElement(fieldName);
            xmlDoc.AppendChild(rootNode);
            values.Add(fieldName, xmlDoc.InnerXml);
        }
        else
        {
            xmlDoc.LoadXml(values[fieldName].ToString());
        }

        if (!label.Text.Equals(string.Empty))
        {
            System.Xml.XmlElement xmlElement = xmlDoc.CreateElement(xmlNodeName);
            xmlElement.InnerText = label.Text.Trim();
            xmlDoc.DocumentElement.AppendChild(xmlElement);
            values[fieldName] = xmlDoc.InnerXml;
        }
    }
Exemplo n.º 37
0
    public static string RequestPaymentStatus(string requestXml, string apiUrl)
    {
        HttpWebRequest  httpWebRequest;
        HttpWebResponse httpWebResponse;
        StreamWriter    streamWriter;
        StreamReader    streamReader;
        string          status = string.Empty;
        string          stringResult;

        httpWebRequest               = HttpWebRequest.Create(apiUrl) as HttpWebRequest;
        httpWebRequest.Method        = "POST";
        httpWebRequest.ContentLength = requestXml.Length;
        httpWebRequest.ContentType   = "application/x-www-form-urlencoded";

        streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
        streamWriter.Write(requestXml);
        streamWriter.Close();

        httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
        streamReader    = new StreamReader(httpWebResponse.GetResponseStream());
        stringResult    = streamReader.ReadToEnd();


        string xmlstring = stringResult;

        System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
        xd.LoadXml(xmlstring);
        if (xd.SelectSingleNode("status/error/code") != null)
        {
            status = GetTransactionErrorDescription(xd.SelectSingleNode("status/error/code").InnerText.ToString());
        }
        else
        {
            System.Xml.XmlNode DescriptionNode = xd.SelectSingleNode("/status/ewallet/status");
            status = DescriptionNode.InnerText.ToString();
        }
        streamReader.Close();
        return(status);
    }
Exemplo n.º 38
0
    protected void btnShippingCalculate_Click(object sender, EventArgs e)
    {
        try
        {
            string  xmlresult          = SendSMS("10", "10", "10", "3216", txtZip.Text, Session["TotalWeightCK"].ToString(), ddlServiceType.SelectedValue);
            DataSet ds                 = new DataSet();
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(xmlresult);
            ds.ReadXml(new System.IO.StringReader(doc.OuterXml));

            dt = ds.Tables[0];
            if (dt.Rows.Count > 0)
            {
                ViewState["ShippingCost"] = Convert.ToString(dt.Rows[0]["total_cost"]).Trim();
            }
            Repeater1.DataSource = ds;
            Repeater1.DataBind();
        }
        catch
        {
            Page.RegisterStartupScript("Msg1", "<script>alert('Please enter valid values');</script>");
        }
    }
Exemplo n.º 39
0
    /// <summary>
    /// create a log file for every month.
    /// </summary>
    private static void CreateLogFile(bool IsWeb)
    {
        string strPath      = string.Empty;
        string strDirectory = string.Empty;
        string strMonth     = System.DateTime.Now.Month.ToString();
        string strYear      = System.DateTime.Now.Year.ToString();
        string strMsg       = "<CMS></CMS>";

        try
        {
            strDocName = strYear + "_" + strMonth + ".xml";
            if (IsWeb)
            {
                strPath = HttpContext.Current.Request.MapPath(HttpContext.Current.Request.ApplicationPath) + "\\ErrorLog\\";
            }
            else
            {
                strPath = System.Environment.CurrentDirectory + "\\ErrorLog\\";
            }
            if (!System.IO.Directory.Exists(strPath))
            {
                System.IO.Directory.CreateDirectory(strPath);
            }

            strDocName = strPath + strDocName;

            if (!System.IO.File.Exists(strPath + strYear + "_" + strMonth + ".xml"))
            {
                System.Xml.XmlDocument objXmlDoc = new System.Xml.XmlDocument();
                objXmlDoc.LoadXml(strMsg);
                objXmlDoc.Save(strDocName);
            }
        }
        catch
        {
        }
    }
Exemplo n.º 40
0
    public static int GetPointsLeft()
    {
        int balance = -1;

        try
        {
            using (var client = new MyWebClient())
            {
                //Try get balance info
                string results             = client.DownloadString(Balance_ApiUrl + "?key=" + ApiKey);
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(results);
                if (doc.SelectSingleNode("//failed/error_code") != null)
                {
                    // There is an lookup error
                    throw new MsgException(doc.SelectSingleNode("//failed/error_code/text()").Value + ": " + doc.SelectSingleNode("//failed/error_msg/text()").Value + "\"");
                }
                else if (doc.SelectSingleNode("//response/balance") == null)
                {
                    // Service unavailable
                    throw new MsgException("The ProxStop service seems to be temporarily unavailable");
                }
                balance = Convert.ToInt32(doc.SelectSingleNode("//response/balance").InnerText);
                return(balance);
            }
        }
        catch (MsgException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            //ErrorLogger.Log(ex);
            throw ex;
        }
    }
Exemplo n.º 41
0
        /// <summary>
        /// 将简单的xml字符串转换成为LIST
        /// </summary>
        /// <typeparam name="T">类型,仅仅支持int/long/datetime/string/double/decimal/object</typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static List <T> xmlToList <T>(string xml)
        {
            Type     tp   = typeof(T);
            List <T> list = new List <T>();

            if (xml == null || string.IsNullOrEmpty(xml))
            {
                return(list);
            }
            try
            {
                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                doc.LoadXml(xml);
                if (tp == typeof(string) | tp == typeof(int) | tp == typeof(long) | tp == typeof(DateTime) | tp == typeof(double) | tp == typeof(decimal))
                {
                    System.Xml.XmlNodeList nl = doc.SelectNodes("/root/item");
                    if (nl.Count == 0)
                    {
                        return(list);
                    }
                    else
                    {
                        foreach (System.Xml.XmlNode node in nl)
                        {
                            if (tp == typeof(string))
                            {
                                list.Add((T)(object)Convert.ToString(node.InnerText));
                            }
                            else if (tp == typeof(int))
                            {
                                list.Add((T)(object)Convert.ToInt32(node.InnerText));
                            }
                            else if (tp == typeof(long))
                            {
                                list.Add((T)(object)Convert.ToInt64(node.InnerText));
                            }
                            else if (tp == typeof(DateTime))
                            {
                                list.Add((T)(object)Convert.ToDateTime(node.InnerText));
                            }
                            else if (tp == typeof(double))
                            {
                                list.Add((T)(object)Convert.ToDouble(node.InnerText));
                            }
                            else if (tp == typeof(decimal))
                            {
                                list.Add((T)(object)Convert.ToDecimal(node.InnerText));
                            }
                            else
                            {
                                list.Add((T)(object)node.InnerText);
                            }
                        }
                        return(list);
                    }
                }
                else
                {
                    //如果是自定义类型就需要反序列化了
                    System.Xml.XmlNodeList nl = doc.SelectNodes("/root/items/" + typeof(T).Name);
                    if (nl.Count == 0)
                    {
                        return(list);
                    }
                    else
                    {
                        foreach (System.Xml.XmlNode node in nl)
                        {
                            list.Add(XMLToObject <T>(node.OuterXml));
                        }
                        return(list);
                    }
                }
            }
            catch (XmlException ex)
            {
                throw new ArgumentException("不是有效的XML字符串", "xml");
            }
            catch (InvalidCastException e)
            {
                throw new ArgumentException("指定的数据类型不匹配", "T");
            }
            catch (Exception exx)
            {
                throw exx;
            }
        }
Exemplo n.º 42
0
        public override System.Xml.XmlNode Decrypt(System.Xml.XmlNode encryptedNode)
        {
            try
            {
                var doc         = new System.Xml.XmlDocument();
                var sectionName = encryptedNode.Attributes.GetNamedItem("section").Value;
                var node        = doc.CreateNode(System.Xml.XmlNodeType.Element, sectionName, "");


                if (string.IsNullOrEmpty(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath))
                {
                    node.InnerXml = encryptedNode.InnerXml;
                    return(node);
                }

                //put code here to connect to the external configuration source and pull your configuration data
                var t       = Type.GetType(ExternalConfigurationSourceFactory);
                var factory = Activator.CreateInstance(Type.GetType(ExternalConfigurationSourceFactory)) as IExternalConfigurationSourceFactory;


                var externalConfigurationLocator = ExternalConfigurationLocator;
                if (!File.Exists(externalConfigurationLocator))
                {
                    externalConfigurationLocator = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, ExternalConfigurationLocator);

                    if (!File.Exists(externalConfigurationLocator))
                    {
                        externalConfigurationLocator = Path.Combine(AppDomain.CurrentDomain.SetupInformation.PrivateBinPath, ExternalConfigurationLocator);

                        if (!File.Exists(externalConfigurationLocator) && ExternalConfigurationLocator.StartsWith(".."))
                        {
                            ExternalConfigurationLocator = "../" + ExternalConfigurationLocator;
                            externalConfigurationLocator = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, ExternalConfigurationLocator);
                        }
                    }
                }

                var externalConfigurationSource = factory.Create(externalConfigurationLocator);

                var section = new StringBuilder();
                section.Append("<").Append(sectionName).Append(">");

                // Put code here to process the external configuration data and put it into a valid XML Node
                var configurationItems = externalConfigurationSource.ReadSource();
                var solution           = Config.Solution;
                var environment        = Config.Solution.Environments[Environment];
                UpdateReferenceProperties(solution, environment, null, environment);


                if (!string.IsNullOrEmpty(Audience))
                {
                    //Append items for each Audience Property
                    var audience = environment.Audiences[Audience];
                    if (audience == null)
                    {
                        return(null);
                    }

                    UpdateReferenceProperties(solution, environment, null, audience);
                    var children = encryptedNode.ChildNodes.Cast <XmlNode>();
                    AddNode(section, children, "aud:Environment", Environment);
                    AddNode(section, children, "aud:Audience", Audience);
                    AddNode(section, children, "aud:AppName", AppName);
                    AddNode(section, children, "ConfigSource", ExternalConfigurationLocator);

                    foreach (var property in audience.GetProperties())
                    {
                        var childNode = children.Where(n => n.Name == "add" && n.Attributes.GetNamedItem("key").Value == "aud:" + property.Key).SingleOrDefault();
                        if (childNode == null)
                        {
                            section.Append("<add key=\"aud:").Append(property.Key).Append("\" value=\"").Append(property.Value).Append("\" />");
                        }
                        else
                        {
                            section.Append("<add key=\"aud:").Append(property.Key).Append("\" value=\"").Append(childNode.Attributes.GetNamedItem("value").Value).Append("\" />");
                        }
                    }
                }

                if (!string.IsNullOrEmpty(Client))
                {
                    //Append items for each Audience Property
                    var client = environment.Clients[Client];
                    if (client == null)
                    {
                        return(null);
                    }

                    UpdateReferenceProperties(solution, environment, null, client);
                    var children = encryptedNode.ChildNodes.Cast <XmlNode>();
                    AddNode(section, children, "cl:Environment", Environment);
                    AddNode(section, children, "cl:Client", Client);
                    AddNode(section, children, "cl:AppName", AppName);
                    AddNode(section, children, "ConfigSource", ExternalConfigurationLocator);

                    foreach (var property in client.GetProperties())
                    {
                        var childNode = children.Where(n => n.Name == "add" && n.Attributes.GetNamedItem("key").Value == "cl:" + property.Key).SingleOrDefault();
                        if (childNode == null)
                        {
                            section.Append("<add key=\"cl:").Append(property.Key).Append("\" value=\"").Append(property.Value).Append("\" />");
                        }
                        else
                        {
                            section.Append("<add key=\"cl:").Append(property.Key).Append("\" value=\"").Append(childNode.Attributes.GetNamedItem("value").Value).Append("\" />");
                        }
                    }
                }


                if (!string.IsNullOrEmpty(Environment) && !string.IsNullOrEmpty(AppName))
                {
                    var server = Config.Solution.Environments[Environment].Servers[AppName];

                    //Append items for each Audience Property
                    if (server == null)
                    {
                        return(null);
                    }
                    UpdateReferenceProperties(solution, environment, server, server);

                    foreach (var property in server.GetProperties())
                    {
                        var children  = encryptedNode.ChildNodes.Cast <XmlNode>();
                        var childNode = children.Where(n => n.Name == "add" && n.Attributes.GetNamedItem("key").Value == "svr:" + property.Key).SingleOrDefault();
                        if (childNode == null)
                        {
                            section.Append("<add key=\"svr:").Append(property.Key).Append("\" value=\"").Append(property.Value).Append("\" />");
                        }
                        else
                        {
                            section.Append("<add key=\"svr:").Append(property.Key).Append("\" value=\"").Append(childNode.Attributes.GetNamedItem("value").Value).Append("\" />");
                        }
                    }
                }

                foreach (var item in configurationItems)
                {
                    // Perform a check here of all child nodes of the encryptedNode which is the data inside the<EncryptedData>
                    // tag of the section in the web/ app.config
                    var children  = encryptedNode.ChildNodes.Cast <XmlNode>();
                    var childNode = children.Where(n => n.Name == "add" && n.Attributes.GetNamedItem("key").Value == item.Key).SingleOrDefault();
                    if (childNode == null)
                    {
                        section.Append("<add key=\"").Append(item.Key).Append("\" value=\"").Append(item.Value).Append("\" />");
                    }
                    else
                    {
                        section.Append("<add key=\"").Append(item.Key).Append("\" value=\"").Append(childNode.Attributes.GetNamedItem("value").Value).Append("\" />");
                    }
                }

                //We need to account for any existing items that were not found in the external source
                foreach (XmlNode localItem in encryptedNode.ChildNodes)
                {
                    // Perform a check here of all child nodes of the encryptedNode which is the data inside the<EncryptedData>
                    // tag of the section in the web/ app.config
                    if (localItem.Name == "add")
                    {
                        //Create fully qualified property name  i.e. Env:AppName:Setting
                        string   settingName = localItem.Attributes.GetNamedItem("key").Value;
                        string[] parts       = settingName.Split(':');
                        switch (parts.Count())
                        {
                        case 0:
                            settingName = string.Format("{0}:{1}:{2}:{3}", Environment, NodeId, AppName, settingName);
                            break;

                        case 1:
                            settingName = string.Format("{0}:{1}:{2}", Environment, NodeId, settingName);
                            break;
                        }

                        if (!configurationItems.ContainsKey(settingName))
                        {
                            //Local Override
                            section.Append("<add key=\"").Append(localItem.Attributes.GetNamedItem("key").Value).Append("\" value=\"").Append(localItem.Attributes.GetNamedItem("value").Value).Append("\" />");
                        }
                        else
                        {
                            section.Append("<add key=\"").Append(settingName).Append("\" value=\"").Append(configurationItems[settingName]).Append("\" />");
                        }
                    }
                }

                section.Append("</").Append(sectionName).Append(">");
                doc.LoadXml(section.ToString());
                return(doc.DocumentElement);
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Exception in Decrypt method: " + ex.Message, ex);
            }
        }
Exemplo n.º 43
0
        private void mLaunchButton_Click(object sender, RoutedEventArgs e)
        {
            if (mLaunchButton.Content.ToString() == "Stop")
            {
                mTimer.Stop();

                if (mISession != null)
                {
                    mISession.closeSession();
                }

                mLaunchButton.Content = "Launch";

                if (mISampleGrabberCall != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(mISampleGrabberCall.getTopologyNode());
                }

                return;
            }

            var lSourceNode = mSourcesComboBox.SelectedItem as XmlNode;

            if (lSourceNode == null)
            {
                return;
            }

            var lNode = lSourceNode.SelectSingleNode("Source.Attributes/Attribute[@Name='MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK']/SingleValue/@Value");

            if (lNode == null)
            {
                return;
            }

            string lSymbolicLink = lNode.Value;

            lSourceNode = mStreamsComboBox.SelectedItem as XmlNode;

            if (lSourceNode == null)
            {
                return;
            }

            lNode = lSourceNode.SelectSingleNode("@Index");

            if (lNode == null)
            {
                return;
            }

            uint lStreamIndex = 0;

            if (!uint.TryParse(lNode.Value, out lStreamIndex))
            {
                return;
            }

            lSourceNode = mMediaTypesComboBox.SelectedItem as XmlNode;

            if (lSourceNode == null)
            {
                return;
            }

            lNode = lSourceNode.SelectSingleNode("@Index");

            if (lNode == null)
            {
                return;
            }

            uint lMediaTypeIndex = 0;

            if (!uint.TryParse(lNode.Value, out lMediaTypeIndex))
            {
                return;
            }

            lNode = lSourceNode.SelectSingleNode("MediaTypeItem[@Name='MF_MT_FRAME_SIZE']/Value.ValueParts/ValuePart[1]/@Value");

            if (lNode == null)
            {
                return;
            }

            uint lVideoWidth = 0;

            if (!uint.TryParse(lNode.Value, out lVideoWidth))
            {
                return;
            }

            lNode = lSourceNode.SelectSingleNode("MediaTypeItem[@Name='MF_MT_FRAME_SIZE']/Value.ValueParts/ValuePart[2]/@Value");

            if (lNode == null)
            {
                return;
            }

            uint lVideoHeight = 0;

            if (!uint.TryParse(lNode.Value, out lVideoHeight))
            {
                return;
            }

            int lWidthInBytes;

            mCaptureManager.getStrideForBitmapInfoHeader(
                MFVideoFormat_RGB32,
                lVideoWidth,
                out lWidthInBytes);

            lsampleByteSize = (uint)Math.Abs(lWidthInBytes) * lVideoHeight;

            mData = new byte[lsampleByteSize];

            var lSinkControl = mCaptureManager.createSinkControl();

            string lxmldoc = "";

            mCaptureManager.getCollectionOfSinks(ref lxmldoc);

            XmlDocument doc = new XmlDocument();

            doc.LoadXml(lxmldoc);

            var lSinkNode = doc.SelectSingleNode("SinkFactories/SinkFactory[@GUID='{759D24FF-C5D6-4B65-8DDF-8A2B2BECDE39}']");

            if (lSinkNode == null)
            {
                return;
            }

            var lContainerNode = lSinkNode.SelectSingleNode("Value.ValueParts/ValuePart[1]");

            if (lContainerNode == null)
            {
                return;
            }

            setContainerFormat(lContainerNode);

            lSinkControl.createSinkFactory(
                mReadMode,
                out mSinkFactory);

            mSinkFactory.createOutputNode(
                MFMediaType_Video,
                MFVideoFormat_RGB32,
                lsampleByteSize,
                out mISampleGrabberCall);

            if (mISampleGrabberCall != null)
            {
                byte[] lData = new byte[lsampleByteSize];

                mTimer.Tick += delegate
                {
                    if (mISampleGrabberCall == null)
                    {
                        return;
                    }

                    uint lByteSize = 0;

                    try
                    {
                        mISampleGrabberCall.readData(lData, out lByteSize);
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        if (lByteSize > 0)
                        {
                            mDisplayImage.Source = FromArray(lData, lVideoWidth, lVideoHeight, mChannels);
                        }
                    }
                };

                var lSampleGrabberCallNode = mISampleGrabberCall.getTopologyNode();

                if (lSampleGrabberCallNode == null)
                {
                    return;
                }

                object lPtrSourceNode;

                var lSourceControl = mCaptureManager.createSourceControl();

                if (lSourceControl == null)
                {
                    return;
                }

                lSourceControl.createSourceNode(
                    lSymbolicLink,
                    lStreamIndex,
                    lMediaTypeIndex,
                    lSampleGrabberCallNode,
                    out lPtrSourceNode);

                List <object> lSourceMediaNodeList = new List <object>();

                lSourceMediaNodeList.Add(lPtrSourceNode);

                var lSessionControl = mCaptureManager.createSessionControl();

                if (lSessionControl == null)
                {
                    return;
                }

                mISession = lSessionControl.createSession(
                    lSourceMediaNodeList.ToArray());

                if (mISession == null)
                {
                    return;
                }

                mISession.startSession(0, Guid.Empty);

                mLaunchButton.Content = "Stop";

                mWebCamControl = lSourceControl.createWebCamControl(lSymbolicLink);

                if (mWebCamControl != null)
                {
                    string lXMLstring;

                    mWebCamControl.getCamParametrs(out lXMLstring);

                    XmlDataProvider lXmlDataProvider = (XmlDataProvider)this.Resources["XmlWebCamParametrsProvider"];

                    if (lXmlDataProvider == null)
                    {
                        return;
                    }

                    System.Xml.XmlDocument ldoc = new System.Xml.XmlDocument();

                    ldoc.LoadXml(lXMLstring);

                    lXmlDataProvider.Document = ldoc;
                }

                mTimer.Start();
            }
        }
Exemplo n.º 44
0
        public String AnalysisXml(string ReqXml)
        {
            string ResXml  = string.Empty;
            string ReqCode = string.Empty;

            try
            {
                System.Xml.XmlDocument xmldoc = new System.Xml.XmlDocument();
                xmldoc.LoadXml(ReqXml);

                //请求指令
                ReqCode = xmldoc.SelectSingleNode("JTW91G/MsgData/ReqHeader/ReqCode").InnerText;

                Trade.CTrade trade   = new Trade.CTrade();
                MarOrdersLn  orderln = new MarOrdersLn();

                orderln.Mac          = xmldoc.SelectSingleNode("JTW91G/MsgData/ReqHeader/Mac").InnerText;
                orderln.LoginID      = xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/LoginId").InnerText;
                orderln.TradeAccount = xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/TradeAccount").InnerText;
                orderln.CurrentTime  = Convert.ToDateTime(xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/Orders/Order/CurrentTime").InnerText);

                //可以不设置止盈止损价 如果为空 不能直接转换
                string ProfitPrice = xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/Orders/Order/ProfitPrice").InnerText;
                string LossPrice   = xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/Orders/Order/LossPrice").InnerText;
                orderln.ProfitPrice = Convert.ToDouble(string.IsNullOrEmpty(ProfitPrice) ? "0" : ProfitPrice);
                orderln.LossPrice   = Convert.ToDouble(string.IsNullOrEmpty(LossPrice) ? "0" : LossPrice);

                string MaxPrice = xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/Orders/Order/MaxPrice").InnerText;
                orderln.MaxPrice = Convert.ToDouble(string.IsNullOrEmpty(MaxPrice) ? "0" : MaxPrice);

                orderln.OrderType   = xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/Orders/Order/OrderType").InnerText;
                orderln.ProductCode = xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/Orders/Order/ProductCode").InnerText;
                orderln.Quantity    = Convert.ToDouble(xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/Orders/Order/Quantity").InnerText);
                orderln.RtimePrices = Convert.ToDouble(xmldoc.SelectSingleNode("JTW91G/MsgData/DataBody/Orders/Order/RtimePrices").InnerText);

                //   orderln.UserType = 0; //客户端没有传递这个值 内部调用默认赋值0 表示普通用户
                orderln.OrderMoney = 0; //客户端没有传递这个值 这个值本身也没有使用 随便赋个值
                Marketorders orders = trade.GetMarketorders(orderln);

                if (!orders.Result)
                {
                    string CodeDesc   = ResCode.UL005Desc;
                    string ReturnCode = GssGetCode.GetCode(orders.ReturnCode, orders.Desc, ref CodeDesc);
                    ResXml = GssResXml.GetResXml(ReqCode, ReturnCode, CodeDesc, string.Format("<DataBody></DataBody>"));
                }
                else
                {
                    StringBuilder strb = new StringBuilder();
                    strb.Append("<Order>");
                    strb.AppendFormat("<OrderId>{0}</OrderId>", orders.TradeOrder.OrderId);
                    strb.AppendFormat("<ProductName>{0}</ProductName>", orders.TradeOrder.ProductName);
                    strb.AppendFormat("<ProductCode>{0}</ProductCode>", orders.TradeOrder.ProductCode);
                    strb.AppendFormat("<PriceCode>{0}</PriceCode>", orders.TradeOrder.PriceCode);
                    strb.AppendFormat("<OrderPrice>{0}</OrderPrice>", orders.TradeOrder.OrderPrice);
                    strb.AppendFormat("<Quantity>{0}</Quantity>", orders.TradeOrder.Quantity);
                    strb.AppendFormat("<UseQuantity>{0}</UseQuantity>", orders.TradeOrder.UseQuantity);
                    strb.AppendFormat("<OccMoney>{0}</OccMoney>", orders.TradeOrder.OccMoney);
                    strb.AppendFormat("<LossPrice>{0}</LossPrice>", orders.TradeOrder.LossPrice);
                    strb.AppendFormat("<ProfitPrice>{0}</ProfitPrice>", orders.TradeOrder.ProfitPrice);
                    strb.AppendFormat("<OrderType>{0}</OrderType>", orders.TradeOrder.OrderType);
                    strb.AppendFormat("<OrderTime>{0}</OrderTime>", orders.TradeOrder.OrderTime.ToString(Const.dateformat));
                    strb.AppendFormat("<TradeFee>{0}</TradeFee>", orders.TradeOrder.TradeFee);
                    strb.AppendFormat("<StorageFee>{0}</StorageFee>", orders.TradeOrder.StorageFee);
                    strb.AppendFormat("<TotalWeight>{0}</TotalWeight>", orders.TradeOrder.TotalWeight);
                    strb.Append("</Order>");
                    StringBuilder fundinfo = new StringBuilder();
                    fundinfo.Append("<FundInfo>");
                    fundinfo.AppendFormat("<Money>{0}</Money>", orders.MoneyInventory.FdInfo.Money);
                    fundinfo.AppendFormat("<OccMoney>{0}</OccMoney>", orders.MoneyInventory.FdInfo.OccMoney);
                    fundinfo.AppendFormat("<FrozenMoney>{0}</FrozenMoney>", orders.MoneyInventory.FdInfo.FrozenMoney);
                    fundinfo.Append("</FundInfo>");
                    //响应消息体
                    string DataBody = string.Format("<DataBody><Orders>{0}</Orders>{1}</DataBody>", strb.ToString(), fundinfo.ToString());

                    ResXml = GssResXml.GetResXml(ReqCode, ResCode.UL004, ResCode.UL004Desc, DataBody);
                }
            }
            catch (Exception ex)
            {
                com.individual.helper.LogNet4.WriteErr(ex);

                //业务处理失败
                ResXml = GssResXml.GetResXml(ReqCode, ResCode.UL005, ResCode.UL005Desc, string.Format("<DataBody></DataBody>"));
            }
            return(ResXml);
        }
Exemplo n.º 45
0
        public static async Task GenerateRSS(int?count = null)
        {
            count = count ?? Settings.Current.PerPageRSS;
            if (!Settings.Current.DisableRSS)
            {
                if (System.IO.File.Exists(RSSFilePath))
                {
                    System.IO.File.Delete(RSSFilePath);
                }
                string                 title    = Settings.Current.DefaultTitle;
                string                 logo     = Settings.Current.LogoFrontPage;
                string                 location = Settings.Current.ExternalBaseUrl.TrimEnd('/');
                StringBuilder          frameXml = new StringBuilder();
                System.Xml.XmlDocument rssfeed  = new System.Xml.XmlDocument();

                frameXml.Append("<rss version=\"2.0\">");
                frameXml.Append("<channel>");
                frameXml.Append($"<title>{title}</title>");
                frameXml.Append($"<link>{location}</link>");
                frameXml.Append($"<description>{title}></description>");
                frameXml.Append($"<lastBuildDate>{string.Format("{0:R}", DateTime.Now)}</lastBuildDate>");
                frameXml.Append("<language>en-us</language>");
                if (!string.IsNullOrEmpty(logo))
                {
                    frameXml.Append("<image>");
                    frameXml.Append($"<title>{title}</title>");
                    frameXml.Append($"<link>{location}</link>");
                    frameXml.Append($"<url>{location}/images/system/{logo}</url>");
                    frameXml.Append("</image>");
                }
                frameXml.Append("</channel>");
                frameXml.Append("</rss>");
                rssfeed.LoadXml(frameXml.ToString());
                var rssChannel = rssfeed.SelectSingleNode("/rss/channel");

                var posts = (await _postService.ListPosts(false))
                            .OrderByDescending(p => p.CreatedUTC)
                            .Take(count.Value)
                            .ToList();
                if ((posts != null) && (posts.Count > 0))
                {
                    var postXml = new StringBuilder();
                    foreach (var post in posts)
                    {
                        var postDate = string.Format("{0:R}", post.CreatedUTC.Value);
                        postXml.Append("<item>");
                        postXml.Append($"<title>{System.Net.WebUtility.HtmlEncode(post.Name)}</title>");
                        postXml.Append($"<link>{location}/post/view/{post.CreatedYear}/{post.CreatedMonth}/{post.UniqueName}</link>");
                        postXml.Append($"<pubDate>{postDate}</pubDate>");
                        postXml.Append($"<description>{post.Data.DataTruncate(-1)}</description>");
                        postXml.Append("</item>");
                    }
                    rssChannel.InnerXml += postXml.ToString();

                    using (var feedStream = System.IO.File.OpenWrite(RSSFilePath))
                    {
                        rssfeed.Save(feedStream);
                    }
                }
            }
        }
Exemplo n.º 46
0
        public MainWindow()
        {
            InitializeComponent();

            try
            {
                mCaptureManager = new CaptureManager("CaptureManager.dll");
            }
            catch (System.Exception exc)
            {
                try
                {
                    mCaptureManager = new CaptureManager();
                }
                catch (System.Exception exc1)
                {
                }
            }

            if (mCaptureManager == null)
            {
                return;
            }

            {
                XmlDataProvider lXmlDataProvider = (XmlDataProvider)this.Resources["XmlLogProvider"];

                if (lXmlDataProvider == null)
                {
                    return;
                }

                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

                string lxmldoc = "";

                mCaptureManager.getCollectionOfSources(ref lxmldoc);

                if (string.IsNullOrEmpty(lxmldoc))
                {
                    return;
                }

                doc.LoadXml(lxmldoc);

                lXmlDataProvider.Document = doc;
            }


            {
                XmlDataProvider lXmlDataProvider = (XmlDataProvider)this.Resources["XmlSampleAccumulatorsProvider"];

                if (lXmlDataProvider == null)
                {
                    return;
                }

                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

                string lxmldoc = "";

                mCaptureManager.createStreamControl().getCollectionOfStreamControlNodeFactories(ref lxmldoc);

                if (string.IsNullOrEmpty(lxmldoc))
                {
                    return;
                }

                doc.LoadXml(lxmldoc);

                lXmlDataProvider.Document = doc;
            }



            mTimer.Interval = new TimeSpan(100000);

            mWebCamParametrsTab.AddHandler(Slider.ValueChangedEvent, new RoutedEventHandler(mParametrSlider_ValueChanged));

            mWebCamParametrsTab.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(mParametrSlider_Checked));

            mWebCamParametrsTab.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(mParametrSlider_Checked));
        }
Exemplo n.º 47
0
        public List <Person> AdventureWorksDBConnection()
        {
            //using (var context = new AdventureWorksDBContext())
            //{

            //    context.Database.Connection.Open();
            //    string sqlCommand = "Select * From Person.Person Where BusinessEntityID = 27";

            //    context.Database.ExecuteSqlCommand(sqlCommand);

            //    context.SaveChanges();
            //}
            string         result    = "";
            SqlDataReader  reader    = null;
            SqlDataAdapter sda       = null;
            DataTable      dt        = new DataTable();
            DataSet        ds        = new DataSet();
            List <Person>  lstPerson = new List <Person>();

            SqlConnection conn = new SqlConnection();

            conn.ConnectionString = ConfigurationManager.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString;
            //conn.ConnectionString = @"Data Source=localhost;Initial Catalog=AdventureWorks2017;Integrated Security=True; MultipleActiveResultSets=True";

            using (conn)
            {
                conn.Open();

                var sqlCommand = new SqlCommand();
                sqlCommand.Connection  = conn;
                sqlCommand.CommandText = "Select * From Person.Person Where BusinessEntityID = 27";

                string queryString = "Select * From Person.Person Where BusinessEntityID = 27";
                sda = new SqlDataAdapter(queryString, conn);
                sda.Fill(dt);
                sda.Fill(ds);


                lstPerson = new List <Person>(dt.Rows.Count);
                foreach (DataRow row in dt.Rows)
                {
                    Person      person = new Person();
                    XmlDocument xmlDoc = new System.Xml.XmlDocument();
                    //xmlDoc.Load(row[10].ToString());
                    xmlDoc.LoadXml(row[10].ToString());

                    person.BusinessEntityID = (int)row[0];
                    person.PersonType       = (row[1] == null) ? string.Empty : (string)row[1];
                    person.NameStyle        = (row[2] == null) ? false : (bool)row[2];
                    //person.Title   = (row[3] == null) ? string.Empty : (string)row[3];
                    person.Title                 = (row[3] == DBNull.Value) ? string.Empty : row[2].ToString();
                    person.FirstName             = (row[4] == null) ? string.Empty : (string)row[4];
                    person.MiddleName            = (row[5] == null) ? string.Empty : (string)row[5];
                    person.LastName              = (row[6] == null) ? string.Empty : (string)row[6];
                    person.Suffix                = (row[7] == DBNull.Value) ? string.Empty : row[7].ToString();;
                    person.EmailPromotion        = (int)row[8];
                    person.AdditionalContactInfo = (row[9] == DBNull.Value) ? string.Empty : row[9].ToString();
                    person.Demographics          = xmlDoc.DocumentElement;

                    //person.Rowguid = (SqlGuid)row[11];
                    person.Rowguid = (row[11] == DBNull.Value) ? string.Empty : row[11].ToString();
                    //person.ModifiedDate = (SqlDateTime)row[12];

                    lstPerson.Add(person);
                }

                conn.Close();
            }
            return(lstPerson);
        }
Exemplo n.º 48
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/xml";
        Response.Charset     = "UTF-8";

        if (Request["R_PageNumber"] == null || Request["R_PageNumber"].ToString().Trim() == "")
        {
            Response.Write(geterrmod("获取数据失败!"));
            return;
        }
        if (Request["R_PageSize"] == null || Request["R_PageSize"].ToString().Trim() == "")
        {
            Response.Write(geterrmod("获取数据失败!"));
            return;
        }
        if (Request["jkname"] == null || Request["jkname"].ToString().Trim() == "")
        {
            Response.Write(geterrmod("获取数据失败!"));
            return;
        }
        string jkname = Request["jkname"].ToString();

        jkname = HttpUtility.UrlDecode(jkname, System.Text.Encoding.UTF8);
        string currentpage = Request["R_PageNumber"].ToString();
        string PageSize    = Request["R_PageSize"].ToString();

        try
        {
            DataSet   dsjieguo   = new DataSet();
            DataTable dt_request = RequestForUI.Get_parameter_forUI(Request);
            object[]  re_ds      = IPC.Call(jkname, new object[] { dt_request });
            if (re_ds[0].ToString() == "ok")
            {
                //这个就是得到远程方法真正的返回值,不同类型的,自行进行强制转换即可。
                dsjieguo = (DataSet)re_ds[1];
            }
            else
            {
                Response.Write(geterrmod(re_ds[1].ToString()));
                return;
            }

            //转换xml
            System.IO.StringWriter writer = new System.IO.StringWriter();
            if (!dsjieguo.Tables.Contains("主要数据"))
            {
                Response.Write(geterrmod("没有主要数据!"));
                return;
            }
            dsjieguo.Tables["主要数据"].WriteXml(writer);


            //为图表增加新的解析
            string fujaitubiao_str = "<chartYHB>";
            if (dsjieguo.Tables.Contains("饼图数据"))
            {
                System.IO.StringWriter writer_bing = new System.IO.StringWriter();
                dsjieguo.Tables["饼图数据"].WriteXml(writer_bing);
                fujaitubiao_str = fujaitubiao_str + writer_bing;
            }

            for (int t = 0; t < dsjieguo.Tables.Count; t++)
            {
                if (dsjieguo.Tables[t].TableName.IndexOf("曲线图数据") >= 0)
                {
                    System.IO.StringWriter writer_quxian = new System.IO.StringWriter();
                    dsjieguo.Tables[t].WriteXml(writer_quxian);
                    fujaitubiao_str = fujaitubiao_str + writer_quxian;
                }
            }
            fujaitubiao_str = fujaitubiao_str + "</chartYHB>";

            string xmlstr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
                            + "<invoices>" + fujaitubiao_str + "<request>true</request><currentpage>" + currentpage + "</currentpage><totalpages>" + dsjieguo.Tables["附加数据"].Rows[0]["分页数"].ToString() + "</totalpages><totalrecords>" + dsjieguo.Tables["附加数据"].Rows[0]["记录数"].ToString() + "</totalrecords>"
                            + writer.ToString() + "</invoices>";



            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(xmlstr);
            doc.Save(Response.OutputStream);
        }
        catch (Exception ex)
        {
            Response.Write(geterrmod("获取数据失败,执行错误!"));
            return;
        }
    }
Exemplo n.º 49
0
        private async void ShowEVRStream(object sender, RoutedEventArgs e)
        {
            if (mShowBtn.Content.ToString() == "Show")
            {
                mEVRStreamParametrsTab.IsEnabled = true;

                mShowBtn.Content = "Hide";

                if (mIEVRStreamControl == null)
                {
                    return;
                }


                XmlDataProvider lXmlDataProvider = (XmlDataProvider)this.Resources["XmlEVRStreamFiltersProvider"];

                if (lXmlDataProvider == null)
                {
                    return;
                }


                System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

                string lxmldoc = await mIEVRStreamControl.getCollectionOfFiltersAsync(
                    mEVROutputNode);

                if (string.IsNullOrEmpty(lxmldoc))
                {
                    return;
                }

                doc.LoadXml(lxmldoc);

                lXmlDataProvider.Document = doc;



                lXmlDataProvider = (XmlDataProvider)this.Resources["XmlEVRStreamOutputFeaturesProvider"];

                if (lXmlDataProvider == null)
                {
                    return;
                }


                doc = new System.Xml.XmlDocument();

                lxmldoc = await mIEVRStreamControl.getCollectionOfOutputFeaturesAsync(
                    mEVROutputNode);

                if (string.IsNullOrEmpty(lxmldoc))
                {
                    return;
                }

                doc.LoadXml(lxmldoc);

                lXmlDataProvider.Document = doc;
            }
            else if (mShowBtn.Content.ToString() == "Hide")
            {
                mEVRStreamParametrsTab.IsEnabled = false;

                mShowBtn.Content = "Show";
            }
        }
Exemplo n.º 50
0
    public void AddControls(
        string strXML,
        PlaceHolder plaPlaceHolder,
        Page pagMain,
        bool bolShowNonFixed)
    {
        System.Xml.XmlDocument docXML;
        System.Xml.XmlNodeList lstSections;
        int             intCounter;
        string          strSectionType;
        string          strIsFixed;
        bool            bolIsFixed;
        ISectionControl secSection;
        Control         ctrTemp;

        docXML = new System.Xml.XmlDocument();

        docXML.LoadXml(strXML);

        lstSections = docXML.DocumentElement.SelectNodes("/package/section");

        //System.Diagnostics.Debug.WriteLine("lstSections.Count: " + lstSections.Count.ToString());

        for (intCounter = 0;
             intCounter < lstSections.Count;
             intCounter++)
        {
            //System.Diagnostics.Debug.WriteLine("Section Type: " + lstSections[intCounter].Attributes["type"]);

            if (lstSections[intCounter].Attributes["type"] != null)
            {
                strSectionType = lstSections[intCounter].Attributes["type"].Value;

                bolIsFixed = true;

                if (lstSections[intCounter].Attributes["isfixed"] != null)
                {
                    strIsFixed = lstSections[intCounter].Attributes["isfixed"].Value;

                    if (strIsFixed.ToLower() == "false")
                    {
                        bolIsFixed = false;
                    }
                }

                //System.Diagnostics.Debug.WriteLine(strSectionType);

                switch (strSectionType)
                {
                case "html":
                    if ((!bolShowNonFixed) && (!bolIsFixed))
                    {
                        continue;
                    }

                    //System.Diagnostics.Trace.WriteLine(lstSections[intCounter].ToString());

                    ctrTemp = pagMain.LoadControl(SECTION_HTML);

                    secSection = (ISectionControl)ctrTemp;

                    secSection.SetSection(lstSections[intCounter]);

                    plaPlaceHolder.Controls.Add(ctrTemp);

                    break;

                case "auction":

                    OnAuctionTypeReached(plaPlaceHolder);

                    break;

                default:
                    break;
                }
            }
        }
    }
Exemplo n.º 51
0
        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                mCaptureManager = new CaptureManager("CaptureManager.dll");
            }
            catch (System.Exception exc)
            {
                try
                {
                    mCaptureManager = new CaptureManager();
                }
                catch (System.Exception exc1)
                {
                }
            }

            if (mCaptureManager == null)
            {
                return;
            }

            XmlDataProvider lXmlDataProvider = (XmlDataProvider)this.Resources["XmlLogProvider"];

            if (lXmlDataProvider == null)
            {
                return;
            }

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

            string lxmldoc = await mCaptureManager.getCollectionOfSourcesAsync();

            if (string.IsNullOrEmpty(lxmldoc))
            {
                return;
            }

            doc.LoadXml(lxmldoc);

            lXmlDataProvider.Document = doc;

            mWebCamParametrsTab.AddHandler(Slider.ValueChangedEvent, new RoutedEventHandler(mParametrSlider_ValueChanged));

            mWebCamParametrsTab.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(mParametrSlider_Checked));

            mWebCamParametrsTab.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(mParametrSlider_Checked));



            mEVRStreamFiltersTabItem.AddHandler(Slider.ValueChangedEvent, new RoutedEventHandler(mEVRStreamFilterSlider_ValueChanged));

            mEVRStreamFiltersTabItem.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(mEVRStreamFilterSlider_Checked));

            mEVRStreamFiltersTabItem.AddHandler(CheckBox.UncheckedEvent, new RoutedEventHandler(mEVRStreamFilterSlider_Checked));



            mEVRStreamOutputFeaturesTabItem.AddHandler(Slider.ValueChangedEvent, new RoutedEventHandler(mEVRStreamOutputFeaturesSlider_ValueChanged));



            mIEVRStreamControl = await mCaptureManager.createEVRStreamControlAsync();
        }
Exemplo n.º 52
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // By default (false) it uses SQLite database (Database.db). You can switch to MS Access database (Database.mdb) by setting UseMDB = true
            // The SQLite loads dynamically its DLL from TreeGrid distribution, it chooses 32bit or 64bit assembly
            // The MDB can be used only on 32bit IIS mode !!! The ASP.NET service program must have write access to the Database.mdb file !!!
            bool UseMDB = false;

            // --- Response initialization ---
            Response.ContentType = "text/xml";
            Response.Charset     = "utf-8";
            Response.AppendHeader("Cache-Control", "max-age=1, must-revalidate");
            System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

            // --- Database initialization ---
            string Path = System.IO.Path.GetDirectoryName(Context.Request.PhysicalPath);
            System.Data.IDbConnection           Conn = null;
            System.Data.Common.DbDataAdapter    Sql  = null;
            System.Data.Common.DbCommandBuilder Bld  = null;
            string SqlStr = "SELECT * FROM TableData";
            System.Reflection.Assembly SQLite = null; // Required only for SQLite database

            if (UseMDB)                               // For MS Acess database
            {
                Conn = new System.Data.OleDb.OleDbConnection("Data Source=\"" + Path + "\\..\\Database.mdb\";Mode=Share Deny None;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Engine Type=5;Provider=\"Microsoft.Jet.OLEDB.4.0\";Jet OLEDB:System database=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1");
                Sql  = new System.Data.OleDb.OleDbDataAdapter(SqlStr, (System.Data.OleDb.OleDbConnection)Conn);
            }
            else // For SQLite database
            {
                SQLite = System.Reflection.Assembly.LoadFrom(Path + "\\..\\..\\..\\Server\\SQLite" + (IntPtr.Size == 4 ? "32" : "64") + "\\System.Data.SQLite.DLL");
                Conn   = (System.Data.IDbConnection)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteConnection"), "Data Source=" + Path + "\\..\\Database.db");
                Sql    = (System.Data.Common.DbDataAdapter)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteDataAdapter"), SqlStr, Conn); //*/
            }

            System.Data.DataTable D = new System.Data.DataTable();
            Sql.Fill(D);

            // --- Save data to database ---
            System.Xml.XmlDocument X = new System.Xml.XmlDocument();
            string XML = Request["TGData"];
            if (XML != "" && XML != null)
            {
                X.LoadXml(HttpUtility.HtmlDecode(XML));
                System.Xml.XmlNodeList Ch = X.GetElementsByTagName("Changes");
                if (Ch.Count > 0)
                {
                    foreach (System.Xml.XmlElement I in Ch[0])
                    {
                        string id = I.GetAttribute("id");
                        System.Data.DataRow R;
                        if (I.GetAttribute("Added") == "1")
                        {
                            R       = D.NewRow();
                            R["ID"] = id;
                            D.Rows.Add(R);
                        }
                        else
                        {
                            R = D.Select("[ID]='" + id + "'")[0];
                        }

                        if (I.GetAttribute("Deleted") == "1")
                        {
                            R.Delete();
                        }
                        else if (I.GetAttribute("Added") == "1" || I.GetAttribute("Changed") == "1")
                        {
                            if (I.HasAttribute("Project"))
                            {
                                R["Project"] = I.GetAttribute("Project");
                            }
                            if (I.HasAttribute("Resource"))
                            {
                                R["Resource"] = I.GetAttribute("Resource");
                            }
                            if (I.HasAttribute("Week"))
                            {
                                R["Week"] = System.Double.Parse(I.GetAttribute("Week"));
                            }
                            if (I.HasAttribute("Hours"))
                            {
                                R["Hours"] = System.Double.Parse(I.GetAttribute("Hours"));
                            }
                        }
                    }
                }

                if (UseMDB)
                {
                    new System.Data.OleDb.OleDbCommandBuilder((System.Data.OleDb.OleDbDataAdapter)Sql);     // For MS Acess database
                }
                else
                {
                    Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteCommandBuilder"), Sql); // For SQLite database
                }
                Sql.Update(D);                                                                                // Updates changed to database
                D.AcceptChanges();
                X.RemoveAll();
                Response.Write("<Grid><IO Result='0'/></Grid>");
            }

            // --- Load data from database ---
            else
            {
                System.Xml.XmlElement G, BB, B, I;
                G  = X.CreateElement("Grid"); X.AppendChild(G);
                BB = X.CreateElement("Body"); G.AppendChild(BB);
                B  = X.CreateElement("B"); BB.AppendChild(B);
                foreach (System.Data.DataRow R in D.Rows)
                {
                    I = X.CreateElement("I");
                    B.AppendChild(I);
                    I.SetAttribute("id", R[0].ToString());
                    I.SetAttribute("Project", R[1].ToString());
                    I.SetAttribute("Resource", R[2].ToString());
                    I.SetAttribute("Week", R[3].ToString());
                    I.SetAttribute("Hours", R[4].ToString());
                }
                Response.Write(X.InnerXml);
            }
        }  catch (Exception E)
        {
            Response.Write("<Grid><IO Result=\"-1\" Message=\"Error in TreeGrid example:&#x0a;&#x0a;" + E.Message.Replace("&", "&amp;").Replace("<", "&lt;").Replace("\"", "&quot;") + "\"/></Grid>");
        }
    }
Exemplo n.º 53
0
        /// <summary>
        /// 读取共享文件的所有内容,只读取key-value的类型
        /// </summary>
        /// <param name="file"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        private ShareFileInfo HandleXmlFile(FileInfo file, string xml)
        {
            var reader = new System.Xml.XmlDocument();

            reader.LoadXml(xml);
            if (reader.ChildNodes == null || reader.ChildNodes.Count <= 1)
            {
                return(null);
            }

            var config = reader.ChildNodes[1];

            if (config == null || config.HasChildNodes == false)
            {
                return(null);
            }

            var list         = new List <KeyValueTuple <string, string> >(config.ChildNodes.Count);
            var templateNode = config.ChildNodes[0];

            if (templateNode.Name.IsNotEquals("template"))
            {
                throw new Exception(string.Format("share file {0} first children node must be template node;", file.FullName));
            }

            var tvalue = templateNode.Attributes.GetNamedItem("value");

            if (tvalue == null || tvalue.Value.IsNullOrWhiteSpace())
            {
                throw new Exception(string.Format("share file {0} template node must be has value attribute;", file.FullName));
            }

            if (tvalue.Value.IsNotEquals("true", StringComparison.OrdinalIgnoreCase))
            {
                throw new Exception(string.Format("share file {0} template value must been true,so is not a template file;", file.FullName));
            }

            var tsharename = templateNode.Attributes.GetNamedItem("sharename");

            if (tsharename == null || tsharename.Value.IsNullOrWhiteSpace())
            {
                throw new Exception(string.Format("share file {0} template node must be has sharename attribute;", file.FullName));
            }

            list.Add(new KeyValueTuple <string, string>("template", tvalue.Value));
            list.Add(new KeyValueTuple <string, string>("sharename", tsharename.Value));

            foreach (XmlNode node in config.ChildNodes)
            {
                if (node == templateNode)
                {
                    continue;
                }

                var key   = node.Attributes.GetNamedItem("key");
                var value = node.Attributes.GetNamedItem("value");

                if (node.HasChildNodes)
                {
                    var keyname = string.Empty;
                    var name    = node.Attributes.GetNamedItem("name");
                    if (name != null && name.Value != null)
                    {
                        keyname = name.Value;
                    }
                    else
                    {
                        var id = node.Attributes.GetNamedItem("id");
                        if (id != null && id.Value != null)
                        {
                            keyname = id.Value;
                        }
                        else
                        {
                            if (key != null)
                            {
                                keyname = key.Value;
                            }
                            else if (value != null)
                            {
                                keyname = value.Value;
                            }
                        }
                    }

                    throw new Exception(string.Format("share file {0} must be key-vlue type,the key {1} content has childnodes;", file.FullName, keyname, node.NodeType));
                }

                if (key != null && key.Value.IsNotNullOrWhiteSpace() && value != null)
                {
                    list.Add(new KeyValueTuple <string, string>(key.Value, value.Value));
                }
            }

            var shareName = list.FirstOrDefault(ta => ta.Key == "sharename");

            if (shareName != null)
            {
                list.Remove(shareName);
            }

            var template = list.FirstOrDefault(ta => ta.Key == "template");

            if (template != null)
            {
                list.Remove(template);
            }

            var istemplate = template?.Value.IsEquals("true");

            return(new ShareFileInfo(shareName?.Value, istemplate.HasValue ? istemplate.Value : false, list.Select(ta => new ShareFileInfo.ShareNodeInfo(ta.Key, ta.Value)).ToList()));
        }
Exemplo n.º 54
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // --- Database initialization ---
        string Path = System.IO.Path.GetDirectoryName(Context.Request.PhysicalPath);

        System.Data.IDbConnection        Conn = null;
        System.Data.Common.DbDataAdapter Sql  = null;
        string SqlStr = "SELECT * FROM TableData";

        System.Reflection.Assembly SQLite = null; // Required only for SQLite database

        if (UseMDB)                               // For MS Acess database
        {
            Conn = new System.Data.OleDb.OleDbConnection("Data Source=\"" + Path + "\\..\\Database.mdb\";Mode=Share Deny None;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Registry Path=;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Engine Type=5;Provider=\"Microsoft.Jet.OLEDB.4.0\";Jet OLEDB:System database=;Jet OLEDB:SFP=False;persist security info=False;Extended Properties=;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Create System Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;User ID=Admin;Jet OLEDB:Global Bulk Transactions=1");
            Sql  = new System.Data.OleDb.OleDbDataAdapter(SqlStr, (System.Data.OleDb.OleDbConnection)Conn);
        }
        else // For SQLite database
        {
            SQLite = System.Reflection.Assembly.LoadFrom(Path + "\\..\\..\\..\\Server\\SQLite" + (IntPtr.Size == 4 ? "32" : "64") + "\\System.Data.SQLite.DLL");
            Conn   = (System.Data.IDbConnection)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteConnection"), "Data Source=" + Path + "\\..\\Database.db");
            Sql    = (System.Data.Common.DbDataAdapter)Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteDataAdapter"), SqlStr, Conn); //*/
        }
        System.Data.DataTable D = new System.Data.DataTable();
        Sql.Fill(D);

        // --- Response initialization ---
        Response.ContentType = "text/html";
        Response.Charset     = "utf-8";
        Response.AppendHeader("Cache-Control", "max-age=1, must-revalidate");
        System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");

        System.Xml.XmlDocument X = new System.Xml.XmlDocument();

        // --- Save data to database ---
        string XML = TGData.Value;

        if (XML != "" && XML != null)
        {
            X.LoadXml(HttpUtility.HtmlDecode(XML));
            System.Xml.XmlNodeList Ch = X.GetElementsByTagName("Changes");
            if (Ch.Count > 0)
            {
                foreach (System.Xml.XmlElement I in Ch[0])
                {
                    string id = I.GetAttribute("id");
                    System.Data.DataRow R;
                    if (I.GetAttribute("Added") == "1")
                    {
                        R       = D.NewRow();
                        R["ID"] = id;
                        D.Rows.Add(R);
                    }
                    else
                    {
                        R = D.Select("[ID]='" + id + "'")[0];
                    }

                    if (I.GetAttribute("Deleted") == "1")
                    {
                        R.Delete();
                    }
                    else if (I.GetAttribute("Added") == "1" || I.GetAttribute("Changed") == "1")
                    {
                        if (I.HasAttribute("Project"))
                        {
                            R["Project"] = I.GetAttribute("Project");
                        }
                        if (I.HasAttribute("Resource"))
                        {
                            R["Resource"] = I.GetAttribute("Resource");
                        }
                        if (I.HasAttribute("Week"))
                        {
                            R["Week"] = System.Double.Parse(I.GetAttribute("Week"));
                        }
                        if (I.HasAttribute("Hours"))
                        {
                            R["Hours"] = System.Double.Parse(I.GetAttribute("Hours"));
                        }
                    }
                }
            }
            if (UseMDB)
            {
                new System.Data.OleDb.OleDbCommandBuilder((System.Data.OleDb.OleDbDataAdapter)Sql);      // For MS Acess database
            }
            else
            {
                Activator.CreateInstance(SQLite.GetType("System.Data.SQLite.SQLiteCommandBuilder"), Sql); // For SQLite database
            }
            Sql.Update(D);                                                                                // Updates changed to database
            D.AcceptChanges();
            X.RemoveAll();
        }

        // --- Load data from database ---
        {
            System.Xml.XmlElement G, BB, B, I;
            G  = X.CreateElement("Grid"); X.AppendChild(G);
            BB = X.CreateElement("Body"); G.AppendChild(BB);
            B  = X.CreateElement("B"); BB.AppendChild(B);
            foreach (System.Data.DataRow R in D.Rows)
            {
                I = X.CreateElement("I");
                B.AppendChild(I);
                I.SetAttribute("id", R[0].ToString());
                I.SetAttribute("Project", R[1].ToString());
                I.SetAttribute("Resource", R[2].ToString());
                I.SetAttribute("Week", R[3].ToString());
                I.SetAttribute("Hours", R[4].ToString());
            }
            TGData.Value = X.InnerXml;
        }
    }
Exemplo n.º 55
0
        /// <summary>
        /// Consulta status da Transação
        /// </summary>
        /// <param name="idTransacao">ID da transação na Akatus.</param>
        public Akatus.ConsultaStatus.Retorno consultaStatusTransacao(string idTransacao)
        {
            //Armazena dados de retorno
            Akatus.ConsultaStatus.Retorno retorno;

            #region Obtém XML

            //URL de Destino (http://www.akatus.com/api/v1/transacao-simplificada/ID_TRANSACAO_AKATUS.xml?email=EMAIL_RECEBEDOR&api_key=TOKEN_GERADO_AKATUS)
            string urlDestino = string.Format("{0}/{1}.xml?email={2}&api_key={3}", Akatus.Config.Ambiente == Akatus.Enums.Ambiente.producao ? urlProducao : urlTestes, idTransacao, Akatus.Config.Email, Akatus.Config.ApiKey);

            //Pega Dados
            string resultado = Akatus.Rest.get(urlDestino);

            //Verifica se o XML é válido
            bool isValidXml = Akatus.Util.IsValidXML(resultado);

            if (isValidXml == true)
            {
                //Cria XML
                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();

                //Carrega XML
                xmlDoc.LoadXml(resultado);

                //Pega dados
                System.Xml.XmlNodeList xmlResults = xmlDoc.GetElementsByTagName("resposta");

                if (xmlResults.Count > 0)
                {
                    System.Xml.XmlNode xmlResult = xmlResults[0];

                    //Preenche dados de retorno
                    retorno = new Akatus.ConsultaStatus.Retorno();

                    #region Seta propriedades

                    retorno.Valor           = Akatus.Util.parseDecimalWithoutSeparator(xmlResult["valor"].InnerText);
                    retorno.DataCriacao     = Akatus.Util.parseDateTime(xmlResult["data_criacao"].InnerText);
                    retorno.DataStatusAtual = Akatus.Util.parseDateTime(xmlResult["data_status_atual"].InnerText);

                    string status = xmlResult["status"].InnerText;

                    //Seta status
                    if (status == "Aguardando Pagamento")
                    {
                        retorno.Status = Akatus.Enums.StatusTransacao.aguardandoPagamento;
                    }
                    else if (status == "Em Análise")
                    {
                        retorno.Status = Akatus.Enums.StatusTransacao.emAnalise;
                    }
                    else if (status == "Aprovado")
                    {
                        retorno.Status = Akatus.Enums.StatusTransacao.aprovado;
                    }
                    else if (status == "Cancelado")
                    {
                        retorno.Status = Akatus.Enums.StatusTransacao.cancelado;
                    }
                    else if (status == "Processando")
                    {
                        retorno.Status = Akatus.Enums.StatusTransacao.processando;
                    }
                    else if (status == "Completo")
                    {
                        retorno.Status = Akatus.Enums.StatusTransacao.completo;
                    }
                    else if (status == "Devolvido")
                    {
                        retorno.Status = Akatus.Enums.StatusTransacao.devolvido;
                    }
                    else if (status == "Estornado")
                    {
                        retorno.Status = Akatus.Enums.StatusTransacao.estornado;
                    }
                    else if (status == "Chargeback")
                    {
                        retorno.Status = Akatus.Enums.StatusTransacao.chargeback;
                    }

                    retorno.Referencia = xmlResult["referencia"].InnerText;

                    #endregion
                }
                else
                {
                    //Erro
                    throw new System.ArgumentException("O XML não retornou nós filhos", resultado);
                }
            }
            else
            {
                //Erro
                throw new System.ArgumentException("Formato de XML inválido", resultado);
            }

            #endregion

            //Retorna resposta
            return(retorno);
        }
Exemplo n.º 56
0
        protected void btnPubMedSearch_OnClick(object sender, EventArgs e)
        {
            string value = "";

            if (rdoPubMedKeyword.Checked)
            {
                string andString = "";
                value = "(";
                if (txtSearchAuthor.Text.Length > 0)
                {
                    string inputString = txtSearchAuthor.Text.Trim();

                    inputString = inputString.Replace("\r\n", "|");
                    // Added line to handle multiple authors for Firefox
                    inputString = inputString.Replace("\n", "|");

                    string[] split = inputString.Split('|');

                    for (int i = 0; i < split.Length; i++)
                    {
                        value     = value + andString + "(" + split[i] + "[Author])";
                        andString = " AND ";
                    }
                }
                if (txtSearchAffiliation.Text.Length > 0)
                {
                    value     = value + andString + "(" + txtSearchAffiliation.Text + "[Affiliation])";
                    andString = " AND ";
                }
                if (txtSearchKeyword.Text.Length > 0)
                {
                    value = value + andString + "((" + txtSearchKeyword.Text + "[Title/Abstract]) OR (" + txtSearchKeyword.Text + "[MeSH Terms]))";
                }
                value = value + ")";
            }
            else if (rdoPubMedQuery.Checked)
            {
                value = txtPubMedQuery.Text;
            }

            string orString = "";
            string idValues = "";

            //if (chkPubMedExclude.Checked)
            //{
            //    if (grdEditPublications.Rows.Count > 0)
            //    {
            //        value = value + " not (";
            //        foreach (GridViewRow gvr in grdEditPublications.Rows)
            //        {
            //            value = value + orString + (string)grdEditPublications.DataKeys[gvr.RowIndex]["PubID"]) + "[uid]";
            //            orString = " OR ";
            //        }
            //        value = value + ")";
            //    }
            //}

            if (chkPubMedExclude.Checked)
            {
                foreach (GridViewRow gvr in grdEditPublications.Rows)
                {
                    HiddenField hdn = (HiddenField)gvr.FindControl("hdnPMID");
                    idValues = idValues + orString + hdn.Value;
                    orString = ",";
                }
            }


            Hashtable MyParameters = new Hashtable();

            string uri = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=pubmed&usehistory=y&retmax=100&retmode=xml&term=" + value;

            System.Xml.XmlDocument myXml = new System.Xml.XmlDocument();
            myXml.LoadXml(this.HttpPost(uri, "Catalyst", "text/plain"));

            XmlNodeList xnList;
            string      queryKey = "";
            string      webEnv   = "";

            xnList = myXml.SelectNodes("/eSearchResult");

            foreach (XmlNode xn in xnList)
            {
                // if (xn["QueryKey"] != null)
                queryKey = xn["QueryKey"].InnerText;
                //if(xn["WebEnv"] !=null)
                webEnv = xn["WebEnv"].InnerText;
            }

            //string queryKey = MyGetXmlNodeValue(myXml, "QueryKey", "");
            //string webEnv = MyGetXmlNodeValue(myXml, "WebEnv", "");

            uri = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?retmin=0&retmax=100&retmode=xml&db=Pubmed&query_key=" + queryKey + "&webenv=" + webEnv;
            myXml.LoadXml(this.HttpPost(uri, "Catalyst", "text/plain"));

            string pubMedAuthors = "";
            string pubMedTitle   = "";
            string pubMedSO      = "";
            string pubMedID      = "";
            string seperator     = "";

            PubMedResults.Tables.Clear();
            PubMedResults.Tables.Add("Results");
            PubMedResults.Tables["Results"].Columns.Add(new System.Data.DataColumn("pmid"));
            PubMedResults.Tables["Results"].Columns.Add(new System.Data.DataColumn("citation"));
            PubMedResults.Tables["Results"].Columns.Add(new System.Data.DataColumn("checked"));

            XmlNodeList docSums = myXml.SelectNodes("eSummaryResult/DocSum");

            foreach (XmlNode docSum in docSums)
            {
                pubMedAuthors = "";
                pubMedTitle   = "";
                pubMedSO      = "";
                pubMedID      = "";
                seperator     = "";
                XmlNodeList authors = docSum.SelectNodes("Item[@Name='AuthorList']/Item[@Name='Author']");
                foreach (XmlNode author in authors)
                {
                    pubMedAuthors = pubMedAuthors + seperator + author.InnerText;
                    seperator     = ", ";
                }
                pubMedTitle = docSum.SelectSingleNode("Item[@Name='Title']").InnerText;
                pubMedSO    = docSum.SelectSingleNode("Item[@Name='SO']").InnerText;
                pubMedID    = docSum.SelectSingleNode("Id").InnerText;

                if (!idValues.Contains(pubMedID))
                {
                    DataRow myDataRow = PubMedResults.Tables["Results"].NewRow();
                    myDataRow["pmid"]     = pubMedID;
                    myDataRow["checked"]  = "0";
                    myDataRow["citation"] = pubMedAuthors + "; " + pubMedTitle + "; " + pubMedSO;
                    PubMedResults.Tables["Results"].Rows.Add(myDataRow);
                    PubMedResults.AcceptChanges();
                }
            }

            grdPubMedSearchResults.DataSource = PubMedResults;
            grdPubMedSearchResults.DataBind();

            lblPubMedResultsHeader.Text = "PubMed Results (" + PubMedResults.Tables["Results"].Rows.Count.ToString() + ")";

            if (PubMedResults.Tables[0].Rows.Count == 0)
            {
                lnkUpdatePubMed.Visible = false;
                pnlAddAll.Visible       = false;
            }

            pnlAddPubMedResults.Visible = true;
            upnlEditSection.Update();
        }
Exemplo n.º 57
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="retXml"></param>
        /// <returns></returns>
        public OfSUPSupplyResult ConversionToSupplyResult(string retXml)
        {
            OfSUPSupplyResult model = new OfSUPSupplyResult();

            if (!string.IsNullOrEmpty(retXml))
            {
                System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.LoadXml(retXml);

                model.status = xmlDoc.GetElementsByTagName("status")[0].InnerText;
                model.msg    = xmlDoc.GetElementsByTagName("msg")[0].InnerText;

                #region dataList
                StringBuilder suporders = new StringBuilder();

                List <OfSUPGetOrderdataList> dataList = new List <OfSUPGetOrderdataList>();
                XmlNodeList xnl = xmlDoc.GetElementsByTagName("data");
                foreach (XmlNode xnf in xnl)
                {
                    OfSUPGetOrderdataList item = new OfSUPGetOrderdataList();
                    foreach (XmlNode xnf1 in xnf.ChildNodes)
                    {
                        if (xnf1.Name == "reqId")
                        {
                            item.reqId = xnf1.InnerText;
                        }
                        else if (xnf1.Name == "fields")
                        {
                            item.fields = xnf1.InnerText;
                        }
                        else if (xnf1.Name == "dataList")
                        {
                            item.dataList = xnf1.OuterXml;

                            if (!string.IsNullOrEmpty(xnf1.OuterXml))
                            {
                                XmlNodeList xnl2 = xmlDoc.GetElementsByTagName(xnf1.OuterXml);
                                foreach (XmlNode xnf2 in xnf.ChildNodes)
                                {
                                    if (xnf2.Name == "order_id")
                                    {
                                        if (suporders.Length == 0)
                                        {
                                            suporders.AppendFormat("{0}", xnf2.InnerText);
                                        }
                                        else
                                        {
                                            suporders.AppendFormat(",{0}", xnf2.InnerText);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    dataList.Add(item);
                }
                model.orderids = suporders.ToString();
                model.data     = dataList;
                #endregion
            }
            return(model);
        }
Exemplo n.º 58
0
        private static string ReadComment(string source, ResolveResult rr, IEmitter emitter, JsDocComment comment)
        {
            var xml = new StringBuilder("<comment>" + newLine);

            if (source != null)
            {
                foreach (var line in source.Split(newLine))
                {
                    var trimmedLine = line.Trim();

                    if (string.IsNullOrEmpty(trimmedLine))
                    {
                        continue;
                    }

                    xml.Append(System.Text.RegularExpressions.Regex.Replace(line, @"\/\/\/\s*", "") + newLine);
                }

                xml.Append("</comment>");

                var doc = new System.Xml.XmlDocument();

                try
                {
                    doc.LoadXml(xml.ToString());
                }
                catch (XmlException)
                {
                    return("");
                }

                foreach (XmlNode node in doc.GetElementsByTagName("summary"))
                {
                    comment.Descriptions.Add(HandleNode(node));
                }

                foreach (XmlNode node in doc.GetElementsByTagName("remark"))
                {
                    comment.Remarks.Add(HandleNode(node));
                }

                foreach (XmlNode node in doc.GetElementsByTagName("typeparam"))
                {
                    string name = null;
                    var    attr = node.Attributes["name"];
                    if (attr != null)
                    {
                        name = attr.Value.Trim();
                    }

                    var param = comment.Parameters.FirstOrDefault(p => p.Name == name);
                    if (param == null)
                    {
                        param = new JsDocParam
                        {
                            Name = "[name]",
                            Type = "[type]"
                        };

                        comment.Parameters.Add(param);
                    }

                    attr = node.Attributes["type"];
                    if (attr != null)
                    {
                        param.Type = attr.Value;
                    }
                    else if (rr != null)
                    {
                        param.Type = "Function";
                    }

                    var text = HandleNode(node);
                    if (!string.IsNullOrEmpty(text))
                    {
                        param.Desc = text;
                    }
                }

                foreach (XmlNode node in doc.GetElementsByTagName("param"))
                {
                    string name = null;
                    var    attr = node.Attributes["name"];
                    if (attr != null)
                    {
                        name = attr.Value.Trim();
                    }

                    var param = comment.Parameters.FirstOrDefault(p => p.Name == name);
                    if (param == null)
                    {
                        continue;
                    }

                    attr = node.Attributes["type"];
                    if (attr != null)
                    {
                        param.Type = attr.Value;
                    }
                    else if (rr != null)
                    {
                        param.Type = XmlToJsDoc.GetParamTypeName(param.Name, rr, emitter);
                    }

                    var text = HandleNode(node);
                    if (!string.IsNullOrEmpty(text))
                    {
                        param.Desc = text;
                    }
                }

                foreach (XmlNode node in doc.GetElementsByTagName("returns"))
                {
                    JsDocParam param = null;
                    if (comment.Returns.Any())
                    {
                        param = comment.Returns.FirstOrDefault();
                    }
                    else
                    {
                        param = new JsDocParam
                        {
                            Type = "[type]"
                        };

                        comment.Returns.Add(param);
                    }

                    var attr = node.Attributes["name"];
                    if (attr != null)
                    {
                        param.Name = attr.Value.Trim();
                    }

                    if (string.IsNullOrWhiteSpace(param.Type))
                    {
                        attr = node.Attributes["type"];
                        if (attr != null)
                        {
                            param.Type = attr.Value.Trim();
                        }
                        else if (rr != null)
                        {
                            param.Type = XmlToJsDoc.GetParamTypeName(null, rr, emitter);
                        }
                    }

                    var text = HandleNode(node);
                    if (!string.IsNullOrEmpty(text))
                    {
                        param.Desc = text;
                    }
                }

                foreach (XmlNode node in doc.GetElementsByTagName("example"))
                {
                    var           codeNodes = node.SelectNodes("code");
                    StringBuilder sb        = new StringBuilder();

                    foreach (XmlNode codeNode in codeNodes)
                    {
                        sb.Append(codeNode.InnerText + newLine);
                        node.RemoveChild(codeNode);
                    }

                    var code    = sb.ToString();
                    var caption = HandleNode(node);
                    comment.Examples.Add(new Tuple <string, string>(caption, code));
                }

                foreach (XmlNode node in doc.GetElementsByTagName("exception"))
                {
                    var attr          = node.Attributes["cref"];
                    var exceptionType = "";

                    if (attr != null)
                    {
                        try
                        {
                            exceptionType = XmlToJsDoc.ToJavascriptName(emitter.BridgeTypes.Get(attr.InnerText).Type, emitter);
                        }
                        catch
                        {
                            // ignored
                        }
                    }

                    var caption = HandleNode(node);
                    comment.Throws.Add(new Tuple <string, string>(caption, exceptionType));
                }

                foreach (XmlNode node in doc.GetElementsByTagName("seealso"))
                {
                    var attr = node.Attributes["cref"];
                    var cref = "";

                    if (attr != null)
                    {
                        cref = attr.InnerText;
                    }

                    comment.SeeAlso.Add(cref);
                }

                foreach (XmlNode node in doc.GetElementsByTagName("value"))
                {
                    var valueParam = comment.Parameters.FirstOrDefault(p => p.Name == "value");
                    if (valueParam != null)
                    {
                        valueParam.Desc = HandleNode(node);
                    }
                }
            }

            return(comment.ToString());
        }
Exemplo n.º 59
0
        static public XmlDocument ParseRequest(string aXmlVar, ref bool aZip, ref bool aCrypt, byte[] aEncryptionKey)
        {
            XmlDocument aRet = null;

            aEncryptionKey = (aEncryptionKey != null && aEncryptionKey.Length == 16) ? aEncryptionKey : System.Text.Encoding.ASCII.GetBytes("1234567890123456");
            try
            {
                if (string.IsNullOrEmpty(aXmlVar))
                {
                    return(aRet);
                }

                System.Xml.XmlDocument aXmlRequest = new System.Xml.XmlDocument();
                aXmlRequest.LoadXml(aXmlVar);
                byte[] aBytes     = null;
                int    aSizeByAtt = int.Parse(aXmlRequest.DocumentElement.Attributes["size"].Value);
                aZip   = (aXmlRequest.DocumentElement.HasAttribute("crypt") && aXmlRequest.DocumentElement.Attributes["crypt"].Value != "0");
                aCrypt = (aXmlRequest.DocumentElement.HasAttribute("zip") && aXmlRequest.DocumentElement.Attributes["zip"].Value != "0");

                if (aZip || aCrypt)
                {
                    string aHex = aXmlRequest.DocumentElement.InnerText;
                    aBytes = new byte[aHex.Length / 2];
                    for (int i = 0; i < aHex.Length; i += 2)
                    {
                        string a2Hex = aHex.Substring(i, 2);
                        aBytes[i / 2] = byte.Parse(a2Hex, System.Globalization.NumberStyles.AllowHexSpecifier);
                    }

                    if (aCrypt)
                    {
                        if (aEncryptionKey == null)
                        {
                            aEncryptionKey = System.Text.Encoding.ASCII.GetBytes("1234567890123456");
                        }
                        Rijndael iCryptoService = new RijndaelManaged();
                        iCryptoService.KeySize   = 128;
                        iCryptoService.BlockSize = 256;
                        iCryptoService.Mode      = CipherMode.ECB;//.CBC;//.ECB;
                        iCryptoService.Padding   = PaddingMode.None;

                        MemoryStream aMemoryStream = new MemoryStream();
                        iCryptoService.Padding = PaddingMode.None;
                        iCryptoService.GenerateIV();
                        byte[]       aIv           = aIv = iCryptoService.IV;
                        CryptoStream aCryptoStream = new CryptoStream(aMemoryStream, iCryptoService.CreateDecryptor(aEncryptionKey, aIv), CryptoStreamMode.Write);
                        aCryptoStream.Write(aBytes, 0, (int)aBytes.Length);
                        aCryptoStream.FlushFinalBlock();
                        aBytes = aMemoryStream.ToArray();
                    }

                    if (aZip)
                    {
                        // 2 first bytes are length (high first)
                        int          aZipLen;
                        int          aOff    = 0;
                        MemoryStream aOutput = new MemoryStream();
                        while (aOutput.Position < aSizeByAtt && aOff < aBytes.Length)
                        {
                            aZipLen = BitConverter.ToInt16(aBytes, aOff);
                            if (aZipLen == 0)
                            {
                                break;
                            }
                            aOff += 2;
                            MemoryStream aInput = new MemoryStream();
                            //write the incoming bytes to the MemoryStream
                            aInput.Write(aBytes, aOff, aZipLen);
                            //set our position to the start of the Stream
                            aInput.Position = 0;
                            System.IO.Compression.DeflateStream aDeflateStream = new DeflateStream(aInput, CompressionMode.Decompress, true);
                            int    aBufLen = 32000;
                            byte[] aBuf    = new byte[aBufLen];
                            Int16  aUtfLen = 0;
                            while (true)
                            {
                                int aNumRead = aDeflateStream.Read(aBuf, 0, aBufLen);
                                if (aNumRead <= 0)
                                {
                                    break;
                                }
                                if (aUtfLen == 0)
                                {
                                    aUtfLen = BitConverter.ToInt16(aBuf, 0);
                                    if (aNumRead > 2)
                                    {
                                        aOutput.Write(aBuf, 2, aNumRead - 2);
                                    }
                                }
                                else
                                {
                                    aOutput.Write(aBuf, 0, aNumRead);
                                }
                            }
                            aDeflateStream.Close();
                            aOff += aZipLen;
                        }
                        aBytes = aOutput.ToArray();
                        aOutput.Close();
                    }
                    string aUtfXml = System.Text.Encoding.UTF8.GetString(aBytes, 0, aSizeByAtt);
                    aRet = new XmlDocument();
                    aRet.LoadXml(aUtfXml);
                }
                else
                {
                    for (int aC = 0; aXmlRequest.DocumentElement.HasChildNodes && aC < aXmlRequest.DocumentElement.ChildNodes.Count; aC++)
                    {
                        if (aXmlRequest.DocumentElement.ChildNodes[aC].NodeType == XmlNodeType.Element)
                        {
                            aRet = new XmlDocument();
                            aRet.LoadXml(aXmlRequest.DocumentElement.ChildNodes[aC].OuterXml);
                            break;
                        }
                    }
                }
            }
            catch
            {
                aRet = null;
            }
            return(aRet);
        }
Exemplo n.º 60
0
        private void mLaunchButton_Click(object sender, RoutedEventArgs e)
        {
            if (mLaunchButton.Content.ToString() == "Stop")
            {
                mTimer.Stop();

                if (mISession != null)
                {
                    mISession.closeSession();
                }

                mLaunchButton.Content = "Launch";

                mTakePhotoButton.IsEnabled = false;

                return;
            }

            mTimer = new DispatcherTimer();

            mTimer.Interval = new TimeSpan(100000);

            var lSourceNode = mSourcesComboBox.SelectedItem as XmlNode;

            if (lSourceNode == null)
            {
                return;
            }

            var lNode = lSourceNode.SelectSingleNode("Source.Attributes/Attribute[@Name='MF_DEVSOURCE_ATTRIBUTE_SOURCE_TYPE_VIDCAP_SYMBOLIC_LINK']/SingleValue/@Value");

            if (lNode == null)
            {
                return;
            }

            string lSymbolicLink = lNode.Value;

            uint lStreamIndex = 0;

            lSourceNode = mMediaTypesComboBox.SelectedItem as XmlNode;

            if (lSourceNode == null)
            {
                return;
            }

            lNode = lSourceNode.SelectSingleNode("@Index");

            if (lNode == null)
            {
                return;
            }

            uint lMediaTypeIndex = 0;

            if (!uint.TryParse(lNode.Value, out lMediaTypeIndex))
            {
                return;
            }

            lNode = lSourceNode.SelectSingleNode("MediaTypeItem[@Name='MF_MT_FRAME_SIZE']/Value.ValueParts/ValuePart[1]/@Value");

            if (lNode == null)
            {
                return;
            }

            uint lVideoWidth = 0;

            if (!uint.TryParse(lNode.Value, out lVideoWidth))
            {
                return;
            }

            mVideoWidth = lVideoWidth;

            lNode = lSourceNode.SelectSingleNode("MediaTypeItem[@Name='MF_MT_FRAME_SIZE']/Value.ValueParts/ValuePart[2]/@Value");

            if (lNode == null)
            {
                return;
            }

            uint lVideoHeight = 0;

            if (!uint.TryParse(lNode.Value, out lVideoHeight))
            {
                return;
            }

            mVideoHeight = lVideoHeight;

            int lWidthInBytes;

            mCaptureManager.getStrideForBitmapInfoHeader(
                MFVideoFormat_RGB32,
                lVideoWidth,
                out lWidthInBytes);

            lsampleByteSize = (uint)Math.Abs(lWidthInBytes) * lVideoHeight;

            mData = new byte[lsampleByteSize];

            var lSinkControl = mCaptureManager.createSinkControl();


            //  create Spread node

            var lStreamControl = mCaptureManager.createStreamControl();

            ISpreaderNodeFactory lSpreaderNodeFactory = null;

            if (!lStreamControl.createStreamControlNodeFactory(
                    Guid.Parse("{85DFAAA1-4CC0-4A88-AE28-8F492E552CCA}"),
                    ref lSpreaderNodeFactory))
            {
                return;
            }


            // create Sample Accumulator node factory

            ISpreaderNodeFactory lSampleAccumulatorNodeFactory = null;

            XmlNode lselectedSampleAccumulatorXml = (XmlNode)mSampleAccumulatorComboBox.SelectedItem;

            if (lselectedSampleAccumulatorXml == null)
            {
                return;
            }

            var lAttrNode = lselectedSampleAccumulatorXml.SelectSingleNode("@GUID");

            if (lAttrNode == null)
            {
                return;
            }

            if (!lStreamControl.createStreamControlNodeFactory(
                    Guid.Parse(lAttrNode.Value),
                    ref lSampleAccumulatorNodeFactory))
            {
                return;
            }

            lAttrNode = lselectedSampleAccumulatorXml.SelectSingleNode("@Samples");

            if (lAttrNode == null)
            {
                return;
            }

            if (!int.TryParse(lAttrNode.Value, out mSampleCount))
            {
                return;
            }


            string lxmldoc = "";

            XmlDocument doc = new XmlDocument();


            mCaptureManager.getCollectionOfSinks(ref lxmldoc);


            doc.LoadXml(lxmldoc);

            var lSinkNode = doc.SelectSingleNode("SinkFactories/SinkFactory[@GUID='{759D24FF-C5D6-4B65-8DDF-8A2B2BECDE39}']");

            if (lSinkNode == null)
            {
                return;
            }

            // create view output.

            var lContainerNode = lSinkNode.SelectSingleNode("Value.ValueParts/ValuePart[2]");

            if (lContainerNode == null)
            {
                return;
            }

            setContainerFormat(lContainerNode);

            lSinkControl.createSinkFactory(
                mReadMode,
                out mSinkFactory);

            lNode = lSourceNode.SelectSingleNode("MediaTypeItem[@Name='MF_MT_SUBTYPE']/SingleValue/@Value");

            if (lNode == null)
            {
                return;
            }

            mSinkFactory.createOutputNode(
                MFMediaType_Video,
                MFVideoFormat_RGB32,
                lsampleByteSize,
                out mISampleGrabberCall);

            if (mISampleGrabberCall != null)
            {
                byte[] lData = new byte[lsampleByteSize];


                mTimer.Tick += delegate
                {
                    if (mISampleGrabberCall == null)
                    {
                        return;
                    }

                    uint lByteSize = 0;

                    try
                    {
                        mISampleGrabberCall.readData(lData, out lByteSize);
                    }
                    catch (Exception)
                    {
                    }
                    finally
                    {
                        if (lByteSize > 0)
                        {
                            mDisplayImage.Source = FromArray(lData, lVideoWidth, lVideoHeight, 4);
                        }
                    }
                };


                // create take photo output

                lContainerNode = lSinkNode.SelectSingleNode("Value.ValueParts/ValuePart[3]");

                if (lContainerNode == null)
                {
                    return;
                }

                setContainerFormat(lContainerNode);

                ISampleGrabberCallSinkFactory lSinkFactory = null;

                lSinkControl.createSinkFactory(
                    mReadMode,
                    out lSinkFactory);

                lNode = lSourceNode.SelectSingleNode("MediaTypeItem[@Name='MF_MT_SUBTYPE']/SingleValue/@Value");

                if (lNode == null)
                {
                    return;
                }

                if (lNode.Value == "MFVideoFormat_MJPG")
                {
                    lSinkFactory.createOutputNode(
                        MFMediaType_Video,
                        MFVideoFormat_MJPG,
                        lsampleByteSize,
                        out mISampleGrabberCallPull);

                    mIsMJPG = true;
                }
                else
                {
                    mIsMJPG = false;

                    lSinkFactory.createOutputNode(
                        MFMediaType_Video,
                        MFVideoFormat_RGB32,
                        lsampleByteSize,
                        out mISampleGrabberCallPull);
                }

                // connect take photo output with sample accumulator


                var lISampleGrabberCallPullNode = mISampleGrabberCallPull.getTopologyNode();

                if (lISampleGrabberCallPullNode == null)
                {
                    return;
                }

                List <object> lSampleAccumulatorList = new List <object>();

                lSampleAccumulatorList.Add(lISampleGrabberCallPullNode);

                object lSampleAccumulatorNode = null;

                lSampleAccumulatorNodeFactory.createSpreaderNode(lSampleAccumulatorList, out lSampleAccumulatorNode);


                // connect view output and take photo output with spreader node



                var lSampleGrabberCallNode = mISampleGrabberCall.getTopologyNode();

                if (lSampleGrabberCallNode == null)
                {
                    return;
                }



                List <object> llSpreaderNodeList = new List <object>();

                llSpreaderNodeList.Add(lSampleAccumulatorNode);

                llSpreaderNodeList.Add(lSampleGrabberCallNode);

                object lSpreaderNode = null;

                lSpreaderNodeFactory.createSpreaderNode(llSpreaderNodeList, out lSpreaderNode);


                object lPtrSourceNode;

                var lSourceControl = mCaptureManager.createSourceControl();

                if (lSourceControl == null)
                {
                    return;
                }

                lSourceControl.createSourceNode(
                    lSymbolicLink,
                    lStreamIndex,
                    lMediaTypeIndex,
                    lSpreaderNode,
                    out lPtrSourceNode);

                List <object> lSourceMediaNodeList = new List <object>();

                lSourceMediaNodeList.Add(lPtrSourceNode);

                var lSessionControl = mCaptureManager.createSessionControl();

                if (lSessionControl == null)
                {
                    return;
                }

                mISession = lSessionControl.createSession(
                    lSourceMediaNodeList.ToArray());

                if (mISession == null)
                {
                    return;
                }

                if (!mISession.startSession(0, Guid.Empty))
                {
                    return;
                }

                mLaunchButton.Content = "Stop";

                mWebCamControl = lSourceControl.createWebCamControl(lSymbolicLink);

                if (mWebCamControl != null)
                {
                    string lXMLstring;

                    mWebCamControl.getCamParametrs(out lXMLstring);

                    XmlDataProvider lXmlDataProvider = (XmlDataProvider)this.Resources["XmlWebCamParametrsProvider"];

                    if (lXmlDataProvider == null)
                    {
                        return;
                    }

                    System.Xml.XmlDocument ldoc = new System.Xml.XmlDocument();

                    ldoc.LoadXml(lXMLstring);

                    lXmlDataProvider.Document = ldoc;
                }

                mTimer.Start();

                mTakePhotoButton.IsEnabled = true;
            }
        }