Ejemplo n.º 1
0
        /// <summary>
        /// loads a configuration from a xml-file - if there isn't one, use default settings
        /// </summary>
        public void ReadSettings()
        {
            bool dirty = false;

            Reset();
            try
            {
                System.Xml.XmlTextReader xmlConfigReader = new System.Xml.XmlTextReader("settings.xml");
                while (xmlConfigReader.Read())
                {
                    if (xmlConfigReader.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        switch (xmlConfigReader.Name)
                        {
                        case "display":
                            fullscreen  = Convert.ToBoolean(xmlConfigReader.GetAttribute("fullscreen"));
                            resolutionX = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionX"));
                            resolutionY = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionY"));

                            // validate resolution
                            // TODO

                            /*  if (!GraphicsAdapter.DefaultAdapter.SupportedDisplayModes.Any(x => x.Format == SurfaceFormat.Color &&
                             *                                                                x.Height == resolutionY && x.Width == resolutionX))
                             * {
                             *    ChooseStandardResolution();
                             *    dirty = true;
                             * } */
                            break;
                        }
                    }
                }
                xmlConfigReader.Close();
            }
            catch
            {
                // error in xml document - write a new one with standard values
                try
                {
                    Reset();
                    dirty = true;
                }
                catch
                {
                }
            }

            // override fullscreen resolutions
            if (fullscreen)
            {
                ResolutionX = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
                ResolutionY = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
            }

            if (dirty)
            {
                Save();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// loads a configuration from a xml-file - if there isn't one, use default settings
        /// </summary>
        public void ReadSettings()
        {
            bool dirty = false;
            Reset();
            try
            {
                System.Xml.XmlTextReader xmlConfigReader = new System.Xml.XmlTextReader("settings.xml");
                while (xmlConfigReader.Read())
                {
                    if (xmlConfigReader.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        switch (xmlConfigReader.Name)
                        {
                            case "display":
                                fullscreen = Convert.ToBoolean(xmlConfigReader.GetAttribute("fullscreen"));
                                resolutionX = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionX"));
                                resolutionY = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionY"));

                                // validate resolution
                                // TODO
                              /*  if (!GraphicsAdapter.DefaultAdapter.SupportedDisplayModes.Any(x => x.Format == SurfaceFormat.Color &&
                                                                                                x.Height == resolutionY && x.Width == resolutionX))
                                {
                                    ChooseStandardResolution();
                                    dirty = true;
                                } */
                                break;
                        }
                    }
                }
                xmlConfigReader.Close();
            }
            catch
            {
                // error in xml document - write a new one with standard values
                try
                {
                    Reset();
                    dirty = true;
                }
                catch
                {
                }
            }

            // override fullscreen resolutions
            if (fullscreen)
            {
                ResolutionX = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
                ResolutionY = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
            }

            if(dirty)
                Save();
        }
        VsICoreAnalyzerConfiguration VsICoreAnalyzerDescription.LoadConfiguration(System.Xml.XmlTextReader reader)
        {
            VsEdgeDetectionConfiguration config = new VsEdgeDetectionConfiguration();

            try
            {
                config.ThresholdStrong = int.Parse(reader.GetAttribute("ThresholdStrong"));
                config.ThresholdWeak   = int.Parse(reader.GetAttribute("ThresholdWeak"));
            }
            catch (Exception)
            {
            }
            return(config);
        }
Ejemplo n.º 4
0
        VsICoreAnalyzerConfiguration VsICoreAnalyzerDescription.LoadConfiguration(System.Xml.XmlTextReader reader)
        {
            VsMotionDetectionConfiguration config = new VsMotionDetectionConfiguration();

            try
            {
                config.ThresholdAlpha = int.Parse(reader.GetAttribute("ThresholdAlpha"));
                config.ThresholdSigma = int.Parse(reader.GetAttribute("ThresholdSigma"));
            }
            catch (Exception)
            {
            }
            return(config);
        }
Ejemplo n.º 5
0
        object VsICoreEncoderDescription.LoadConfiguration(System.Xml.XmlTextReader reader)
        {
            VsAviEncoderConfiguration config = new VsAviEncoderConfiguration();

            try
            {
                config.ImageWidth  = int.Parse(reader.GetAttribute("ImageWidth"));
                config.ImageHeight = int.Parse(reader.GetAttribute("ImageHeight"));
                config.CodecsName  = reader.GetAttribute("CodecsName");
                config.Quality     = int.Parse(reader.GetAttribute("Quality"));
            }
            catch (Exception)
            {
            }
            return((object)config);
        }
Ejemplo n.º 6
0
        string connStr()
        {
            string Retorno = "";
            string path    = System.IO.Directory.GetCurrentDirectory();

            string[] parts = path.Split('\\'); path = "";
            for (int i = 0; i < parts.Length - 2; i++)
            {
                path = path + parts[i].ToString() + "\\";
            }

            path = path + "config.xml";

            // Create an isntance of XmlTextReader and call Read method to read the file
            System.Xml.XmlTextReader textReader = new System.Xml.XmlTextReader(path);
            textReader.Read();
            // If the node has value
            while (textReader.Read())
            {
                //  Here we check the type of the node, in this case we are looking for element
                if (textReader.NodeType == System.Xml.XmlNodeType.Element)
                {
                    //  If the element is "profile"
                    if (textReader.Name == "add")
                    {
                        //  Add the attribute value of "username" to the listbox
                        Retorno = textReader.GetAttribute("connectionString");
                    }
                }
            }
            textReader.Close();
            return(Retorno);
        }
Ejemplo n.º 7
0
        private void ProcessResults(string xml_data, ref System.Collections.ArrayList identifiers)
        {
            System.Xml.XmlTextReader rd;
            rd = new System.Xml.XmlTextReader(xml_data);
            try
            {
                //System.Windows.Forms.MessageBox.Show("here");
                while (rd.Read())
                {
                    //This is where we find the head of the record,
                    //then process the values within the record.
                    //We also need to do character encoding here if necessary.

                    if (rd.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        //System.Windows.Forms.MessageBox.Show(rd.LocalName);
                        if (rd.LocalName == "str" && rd.GetAttribute("name") == "identifier")
                        {
                            identifiers.Add(rd.ReadString());
                        }
                    }
                }
            }
            catch { }
        }
Ejemplo n.º 8
0
    public static List <Parent> ReadParentsFromXml(string fileName)
    {
        List <Parent> parents = new List <Parent>();

        System.Xml.XmlTextReader doc = new System.Xml.XmlTextReader(fileName);
        Parent element = new Parent();

        while (doc.Read())
        {
            switch (doc.Name)
            {
            case "parents":
                if (doc.NodeType == System.Xml.XmlNodeType.EndElement)
                {
                    parents.Add(element);
                    element = new Parent();
                }
                break;

            case "child":
                if (doc.NodeType != System.Xml.XmlNodeType.EndElement)
                {
                    element.childs.Add(new Child(doc.GetAttribute(0)));
                }
                break;
            }
        }
        return(parents);
    }
Ejemplo n.º 9
0
        public static FiddlerModificHttpRuleCollection DeserializeRuleList()
        {
            string rulePath = "FreeHttp\\RuleData.xml";
            FiddlerModificHttpRuleCollection fiddlerModificHttpRuleCollection = null;

            if (File.Exists(rulePath))
            {
                FileStream myFileStream = new FileStream(rulePath, FileMode.Open);
                try
                {
                    using (System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(myFileStream))
                    {
                        reader.Normalization = false;
                        //版本控制
                        string ruleVersion = string.Empty;
                        //System.Version version = new Version("2.0.0");
                        while (reader.Read())
                        {
                            if (reader.NodeType == System.Xml.XmlNodeType.Element)
                            {
                                if (reader.Name == "FiddlerModificHttpRuleCollection")
                                {
                                    ruleVersion = reader.GetAttribute("ruleVersion");
                                    break;
                                }
                            }
                        }
                        if (string.IsNullOrEmpty(ruleVersion) || ruleVersion[0] == '1')
                        {
                            File.Copy(rulePath, rulePath + ".oldVersion", true);
                            XmlSerializer mySerializer = new XmlSerializer(typeof(FreeHttp.FiddlerHelper.VersionControlV1.FiddlerModificHttpRuleCollection));
                            fiddlerModificHttpRuleCollection = (FiddlerModificHttpRuleCollection)(FreeHttp.FiddlerHelper.VersionControlV1.FiddlerModificHttpRuleCollection)mySerializer.Deserialize(reader);
                        }
                        else if (ruleVersion[0] == '2')
                        {
                            XmlSerializer mySerializer = new XmlSerializer(typeof(FiddlerModificHttpRuleCollection));
                            fiddlerModificHttpRuleCollection = (FiddlerModificHttpRuleCollection)mySerializer.Deserialize(reader);
                        }
                        else
                        {
                            throw new Exception("unkonw ruleVersion", new Exception("this freehttp can not analysis the rule file , you should updata your freehttp"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("{0}\r\n{1}\r\nyour error rule file will back up in {2}", ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message, Directory.GetCurrentDirectory() + rulePath + ".lastErrorFile"), "load user rule fail");
                    _ = WebService.RemoteLogService.ReportLogAsync($"load user rule fail [{ex.ToString()}]", WebService.RemoteLogService.RemoteLogOperation.WindowLoad, WebService.RemoteLogService.RemoteLogType.Error);
                    File.Copy(rulePath, rulePath + ".lastErrorFile", true);
                }
                finally
                {
                    myFileStream.Close();
                }
            }
            return(fiddlerModificHttpRuleCollection);
        }
Ejemplo n.º 10
0
        private void LoadFromXml(System.Xml.XmlTextReader xml)
        {
            Clear();
            JobDefinitionGroup LastGroup = null;
            JobDefinition      LastJob   = null;

            while (!xml.EOF)
            {
                xml.Read();
                if (xml.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (xml.Depth == 1)
                    {
                        System.Diagnostics.Debug.Assert(xml.Name == "Menu");
                        m_Caption = xml.GetAttribute("Caption");
                    }
                    else if (xml.Depth == 2)
                    {
                        System.Diagnostics.Debug.Assert(xml.Name == "Group");
                        LastGroup         = AddGroup();
                        LastGroup.Caption = xml.GetAttribute("Caption");
                        LastGroup.Hint    = xml.GetAttribute("Hint");
                    }
                    else if (xml.Depth == 3)
                    {
                        System.Diagnostics.Debug.Assert(xml.Name == "Job");
                        LastJob             = LastGroup.Add();
                        LastJob.Caption     = xml.GetAttribute("Caption");
                        LastJob.Hint        = xml.GetAttribute("Hint");
                        LastJob.Application = xml.GetAttribute("Application");
                        string OptVal;
                        OptVal = xml.GetAttribute("WorkingDir");
                        if (OptVal != null)
                        {
                            LastJob.WorkingDir = OptVal;
                        }
                        OptVal = xml.GetAttribute("SuccessStatus");
                        if (OptVal != null)
                        {
                            LastJob.SuccessStatus = Convert.ToInt32(OptVal);
                        }
                    }
                    else if (xml.Depth == 4)
                    {
                        System.Diagnostics.Debug.Assert(xml.Name == "Arguments");
                        LastJob.Arguments = xml.ReadString();
                    }
                }
            }
        }
Ejemplo n.º 11
0
        VsICoreAnalyzerConfiguration VsICoreAnalyzerDescription.LoadConfiguration(System.Xml.XmlTextReader reader)
        {
            VsObjectDetectionConfiguration config = new VsObjectDetectionConfiguration();

            try
            {
                config.SelectedObject = int.Parse(reader.GetAttribute("SelectedObject"));
            }
            catch (Exception)
            {
            }
            return(config);
        }
Ejemplo n.º 12
0
        public static FiddlerModificHttpRuleCollection DeserializeRuleList()
        {
            string rulePath = "FreeHttp\\RuleData.xml";
            FiddlerModificHttpRuleCollection fiddlerModificHttpRuleCollection = null;

            if (File.Exists(rulePath))
            {
                FileStream myFileStream = new FileStream(rulePath, FileMode.Open);
                try
                {
                    using (System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(myFileStream))
                    {
                        reader.Normalization = false;
                        //版本控制
                        string ruleVersion = string.Empty;
                        //System.Version version = new Version("2.0.0");
                        while (reader.Read())
                        {
                            if (reader.NodeType == System.Xml.XmlNodeType.Element)
                            {
                                if (reader.Name == "FiddlerModificHttpRuleCollection")
                                {
                                    ruleVersion = reader.GetAttribute("ruleVersion");
                                    break;
                                }
                            }
                        }
                        if (string.IsNullOrEmpty(ruleVersion))
                        {
                            XmlSerializer mySerializer = new XmlSerializer(typeof(FreeHttp.FiddlerHelper.VersionControlV1.FiddlerModificHttpRuleCollection));
                            fiddlerModificHttpRuleCollection = (FiddlerModificHttpRuleCollection)(FreeHttp.FiddlerHelper.VersionControlV1.FiddlerModificHttpRuleCollection)mySerializer.Deserialize(reader);
                        }
                        else
                        {
                            XmlSerializer mySerializer = new XmlSerializer(typeof(FiddlerModificHttpRuleCollection));
                            fiddlerModificHttpRuleCollection = (FiddlerModificHttpRuleCollection)mySerializer.Deserialize(reader);
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(string.Format("{0}\r\n{1}", ex.Message, ex.Message, ex.InnerException == null ? "" : ex.InnerException.Message), "load user rule fail");
                    File.Copy(rulePath, rulePath + ".lastErrorFile", true);
                }
                finally
                {
                    myFileStream.Close();
                }
            }
            return(fiddlerModificHttpRuleCollection);
        }
Ejemplo n.º 13
0
 public 英単語の練習.Word readWordData()
 {
     while (true)
     {
         if (xtr.Read())
         {
             if (xtr.NodeType == System.Xml.XmlNodeType.Element && xtr.Name == "word")
             {
                 string name = this.unescape(xtr.GetAttribute("name"));                      //単語(英語)
                 string mean = this.unescape(xtr.GetAttribute("mean"));                      //意味(日本語)
                 System.Collections.ArrayList refWordList = new System.Collections.ArrayList();
                 string[] example = new string[] {};
                 string   part, conjugate; int shutsu, seikai;
                 this.readSubData(out part, out conjugate, out refWordList, ref example, out shutsu, out seikai);
                 return(new 英単語の練習.Word(name, (wordPart)part, conjugate.Split(new char[] { ';' }), mean, refWordList, example, shutsu, seikai));
             }
         }
         else
         {
             return(英単語の練習.Word.FileEnd);
         }
     }
 }
Ejemplo n.º 14
0
 public string this[string AttributeName] {
     get {
         if (HFile == null)
         {
             return(CAbc.EMPTY);
         }
         try {
             return(HFile.GetAttribute(AttributeName.Trim()));
         } catch (System.Exception Excpt) {
             Err.Add(Excpt);
         }
         return(CAbc.EMPTY);
     }
 }
Ejemplo n.º 15
0
            internal static BroadCastReply ParseAndGet_BroadCastReply_FromXMLDataString(string XMLString)
            {
                System.IO.StringReader   sr     = null;
                System.Xml.XmlTextReader m_xmlr = null;
                BroadCastReply           parsedBroadCartReplyfromXMLString = default(BroadCastReply);

                try
                {
                    sr     = new System.IO.StringReader(XMLString);
                    m_xmlr = new System.Xml.XmlTextReader(sr);
                    m_xmlr.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                }
                catch (System.Xml.XmlException)
                {
                    string msg;
                    msg = "Error trying to get XML format from Broad Cast Reply data string [" + XMLString + "]";
                }
                catch (Exception ex)
                {
                    string msg = "";
                    msg = "Error trying to parse Broad Cast Reply XML string : " + ex.Message;
                    throw (new Exception(msg));
                }
                m_xmlr.Read();
                string HeaderIdentifier = m_xmlr.Name;

                if (HeaderIdentifier != "BROADCAST_REPLY")
                {
                    throw (new System.Xml.XmlException("Invalid data socket header " + HeaderIdentifier + ". Must be \'BROADCAST_REPLY\'"));
                }
                else
                {
                    string replyIDName = "";
                    replyIDName = m_xmlr.GetAttribute("replyIDName");
                    if (replyIDName == null)
                    {
                        throw (new Exception("Invalid XML string for a BroadCastReply, the attribute replyIDName is missing. Can´t parse the string"));
                    }

                    string dataXMLString = "";
                    dataXMLString = m_xmlr.ReadInnerXml();
                    DataVariable var = default(DataVariable);
                    var = XMLDataFormatting.RetrieveDataVariableFromXMLString(dataXMLString);
                    parsedBroadCartReplyfromXMLString = new BroadCastReply(replyIDName, System.Convert.ToString(var.Name), var.Data);
                }
                return(parsedBroadCartReplyfromXMLString);
            }
Ejemplo n.º 16
0
        static public string GetDefaultPicURL(string journalName, string serverURL, bool community)
        {
            Uri uri = new Uri(new Uri(serverURL), string.Format(_foafpath,
                                                                (community ? "community" : "users"),
                                                                journalName));
            HttpWebRequest w      = HttpWebRequestFactory.Create(uri.AbsoluteUri, null);
            string         picURL = null;

            using (System.IO.Stream s = w.GetResponse().GetResponseStream())
            {
                System.Xml.XmlTextReader xr = new System.Xml.XmlTextReader(s);
                while (xr.Read())
                {
                    if (xr.NodeType == System.Xml.XmlNodeType.Element && xr.Name == "foaf:img")
                    {
                        picURL = xr.GetAttribute("rdf:resource");
                        break;
                    }
                }
                xr.Close();
            }
            return(picURL);
        }
Ejemplo n.º 17
0
        private void addFeedToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string newUrl = Microsoft.VisualBasic.Interaction.InputBox(_I18N.GetText("Enter URL:"), Application.ProductName);

            if (newUrl.Length == 0)
            {
                return;
            }
            this.staMain.Text = "";
            if (!newUrl.ToLowerInvariant().StartsWith("http"))
            {
                // TODO add https?
                newUrl = "http://" + newUrl;
            }
            //The MSDN documentation says it's best to create an XmlTextReader through .Create
            //rather than = new XmlTextReader. However, if you do it through new, you get an
            //XmlTextReader that doesn't choke on malformed XML, and if you do it through
            //.Create you choke on malformed XML. So clearly new is better!
            System.Xml.XmlTextReader xtr;
            try
            {
                xtr = new System.Xml.XmlTextReader(newUrl);
            }
            catch (System.UriFormatException ufe)
            {
                // Not a valid URL. Skip trying to analyse.
                MessageBox.Show(_I18N.GetText("Invalid URL:") + " " + ufe.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            catch (Exception ex)
            {
                // Unknown error - File Not Found, possibly - display and quit.
                MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string newFeedUrl        = "";
            string rootNodeName      = "";
            bool   finishedSearching = false;
            bool   readOK            = true;

            while (!xtr.EOF && !finishedSearching && readOK)
            {
                try
                {
                    readOK = xtr.Read();
                    if (xtr.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        string elementName = xtr.Name.ToLowerInvariant();
                        // If this is the first node then it is the root node.
                        // Remember the name so that we know what type of document
                        // the user has given us - Atom, RSS, or a web page to
                        // search.
                        System.Diagnostics.Debug.Print("Node:" + elementName);
                        if (rootNodeName.Length == 0)
                        {
                            rootNodeName = elementName;
                        }
                        if (rootNodeName == "html")
                        {
                            // This is an HTML file, scan it for RSS feeds.
                            if (elementName == "link")
                            {
                                // Got a link: is it valid?
                                if (xtr.HasAttributes)
                                {
                                    string href = xtr.GetAttribute("href");
                                    string rel  = xtr.GetAttribute("rel");
                                    if (rel.ToLowerInvariant() == "alternate" && href != "")
                                    {
                                        // Got it!
                                        newFeedUrl        = href;
                                        finishedSearching = true;
                                    }
                                }
                            }
                        }
                        else if (rootNodeName == "feed" || rootNodeName == "rss")
                        {
                            // It's an RSS/Atom feed, go ahead and add it
                            // without further checking, and stop reading
                            // this document.
                            newFeedUrl        = newUrl;
                            finishedSearching = true;
                        }
                    }
                }
                catch
                {
                    //Parsing error from the web page or XML = very common, carry on going
                    //until we find something useful.
                }
                System.Windows.Forms.Application.DoEvents();
            }
            xtr.Close();

            // OK, so we've examined the url the user gave us. Found anything?
            if (newFeedUrl == "")
            {
                // Failed to find anything!
                MessageBox.Show(_I18N.GetText("No RSS news feeds found"), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                // OK, try getting it.
                System.Xml.XmlTextReader newFeed = new System.Xml.XmlTextReader(newFeedUrl);
                string newTitle             = "";
                string newWebsiteUrl        = "";
                bool   foundTitleAndUrl     = false;
                bool   nextNodeIsTitle      = false;
                bool   nextNodeIsWebsiteUrl = false;
                readOK = true;
                while (!newFeed.EOF && !foundTitleAndUrl && readOK)
                {
                    try
                    {
                        readOK = newFeed.Read();
                        if (newFeed.NodeType == System.Xml.XmlNodeType.Element)
                        {
                            System.Diagnostics.Debug.Print("Node:" + newFeed.Name.ToLowerInvariant());
                            if (newFeed.Name.ToLowerInvariant() == "title")
                            {
                                if (newTitle == "")
                                {
                                    nextNodeIsTitle = true;
                                }
                            }
                            else if (newFeed.Name.ToLowerInvariant() == "link")
                            {
                                if (newWebsiteUrl == "")
                                {
                                    nextNodeIsWebsiteUrl = true;
                                }
                            }
                        }
                        else if (newFeed.NodeType == System.Xml.XmlNodeType.Text)
                        {
                            if (nextNodeIsTitle)
                            {
                                newTitle        = newFeed.Value;
                                nextNodeIsTitle = false;
                            }
                            if (nextNodeIsWebsiteUrl)
                            {
                                newWebsiteUrl        = newFeed.Value;
                                nextNodeIsWebsiteUrl = false;
                            }
                        }
                    }
                    catch
                    {
                        // Error in XML, very common, carry on.
                    }
                    if (newTitle.Length > 0 && newWebsiteUrl.Length > 0)
                    {
                        foundTitleAndUrl = true;
                    }
                    System.Windows.Forms.Application.DoEvents();
                }
                newFeed.Close();
                // OK, add to lists!
                if (foundTitleAndUrl)
                {
                    // Assume this is good.
                    this._Library.AddFeed(newFeedUrl, newTitle, newWebsiteUrl);
                    DisplayFeeds();
                    lblStatus.Text = _I18N.GetText("Added:") + " " + newTitle;
                    // Set focus to the new feed.
                    try
                    {
                        int i = 0;
                        foreach (System.Xml.XmlNode outline in this._Library.MyFeedsOPMLDocument.DocumentElement.SelectNodes("body/outline"))
                        {
                            string url = RSSLibraryClass.GetOutlineUrl(outline);
                            if (url == newFeedUrl)
                            {
                                lstFeeds.SelectedIndex = i;
                                break;
                            }
                            i++;
                        }
                    }
                    catch
                    {
                        // Fine, didn't set focus, carry on.
                    }

                    try
                    {
                        // Submission of RSS feed to database.
                        newTitle = System.Net.WebUtility.HtmlEncode(newTitle);
                        newUrl   = System.Net.WebUtility.HtmlEncode(newUrl);
                        System.Net.HttpWebRequest wr = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://data.webbie.org.uk/newRSSFeed.php?title=" + newTitle + "&url=" + newFeedUrl + "&language=" + this._I18N.GetLanguage());
                        wr.KeepAlive         = false;
                        wr.Method            = System.Net.WebRequestMethods.Http.Get;
                        wr.ContentType       = "text/html";
                        wr.AllowAutoRedirect = true;
                        wr.GetResponse();
                    }
                    catch
                    {
                        // Failed to connect and write feed information: record why to error log.
                        System.Diagnostics.EventLog.WriteEntry(Application.ProductName + " " + Application.ProductVersion, "Failed to submit new feed registration to WebbIE (" + newUrl + ")");
                    }
                }
                else
                {
                    // Not found a feed.
                    staMain.Text = this._I18N.GetText("0 feeds found.");
                }
            }
        }
Ejemplo n.º 18
0
        public Record GetRecord(string sidentifier, string sPrefix, ref Object objHandler)
        {
            System.IO.Stream objStream;
            Record objRecord;
            string tmp = "";
            System.Net.HttpWebRequest wr;
            System.Xml.XmlTextReader rd;

            if (sPrefix.Length == 0)
            {
                sPrefix = "oai_dc";
            }

            prequestURL = baseURL + "?verb=GetRecord&metadataPrefix=" + sPrefix + "&identifier=" + sidentifier;

            //======================================================
            // If you wanted to support additional metadata formats,
            // you would just need to have additional handlers.
            //======================================================

            try
            {
                wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL);
                wr.UserAgent = cUserAgent;
                System.Net.WebResponse response = wr.GetResponse();
                objStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(objStream);
                prawXML = reader.ReadToEnd();
                reader.Close();
                rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null);
            }
            catch (Exception e)
            {
                error.errorName = e.ToString();
                error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL;
                return null;
            }

            while (rd.Read())
            {
                if (rd.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (rd.Name == "responseDate")
                    {
                        presponseDate = rd.ReadString();
                    }
                    else if (rd.Name == "GetRecord")
                    {
                        do
                        {
                            if (rd.Name == "record")
                            {
                                tmp = ParseOAIContainer(ref rd, "record");
                                objRecord = new Record(tmp, ref objHandler);
                                return objRecord;
                            }
                            else rd.Read(); // Added the Read() and will never occur with the ReadInnerXml()

                        } while (rd.Name != "GetRecord"); // loop
                    }
                    else if (rd.Name == "error")
                    {
                        error.errorName = rd.GetAttribute("code");
                        error.errorDescription = rd.ReadString();
                        return null;
                    }
                }
            }

            return null;
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Load options.
        /// </summary>
        /// <param name="filePath">File name to load options from.</param>
        private void DoDeserialize(string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                global::System.IO.FileStream fileStream = null;
                try
                {
                    fileStream = global::System.IO.File.OpenRead(filePath);
                    if (fileStream.Length > 5)
                    {
                        using (global::System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(fileStream))
                        {
                            try
                            {
                                reader.MoveToContent();

                                // read attributes
                                string valueE = reader.GetAttribute("errorCategoryVisible");
                                if (valueE != null)
                                {
                                    this.ErrorCategoryVisible = Boolean.Parse(valueE);
                                }

                                string valueW = reader.GetAttribute("warningCategoryVisible");
                                if (valueW != null)
                                {
                                    this.WarningCategoryVisible = Boolean.Parse(valueW);
                                }

                                string valueI = reader.GetAttribute("infoCategoryVisible");
                                if (valueI != null)
                                {
                                    this.InfoCategoryVisible = Boolean.Parse(valueI);
                                }

                                string valueF = reader.GetAttribute("filteredCategoryVisible");
                                if (valueF != null)
                                {
                                    this.FilteredCategoryVisible = Boolean.Parse(valueF);
                                }

                                while (reader.Read())
                                {
                                    switch (reader.NodeType)
                                    {
                                    case System.Xml.XmlNodeType.Element:
                                    {
                                        DeserializeElement(reader, reader.Name);
                                        break;
                                    }
                                    }
                                }
                            }
                            finally
                            {
                                fileStream = null;
                            }
                        }
                    }
                }
                finally
                {
                    if (fileStream != null)
                    {
                        fileStream.Dispose();
                    }
                }
            }
        }
            internal static BroadcastableData ParseAndGet_BroadcastableData_FromXMLDataString(string XMLDataString)
            {
                System.IO.StringReader   sr     = null;
                System.Xml.XmlTextReader m_xmlr = null;

                string broadCasterName          = "";
                string broadCasterHost          = "";
                int    broadCasterListeningPort = 0;

                try
                {
                    sr     = new System.IO.StringReader(XMLDataString);
                    m_xmlr = new System.Xml.XmlTextReader(sr);
                    m_xmlr.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                }
                catch (System.Xml.XmlException)
                {
                    string msg;
                    msg = "Error trying to get XML format from broadcasted data string [" + XMLDataString + "]";
                }
                catch (Exception ex)
                {
                    string msg = "";
                    msg = "Error trying to parse broadcasted XML string : " + ex.Message;
                    throw (new Exception(msg));
                }
                m_xmlr.Read();
                string HeaderIdentifier = m_xmlr.Name;

                if (HeaderIdentifier != "BROADCASTED_DATA")
                {
                    throw (new System.Xml.XmlException("Invalid data header " + HeaderIdentifier + ". Must be \'BROADCASTED_DATA\'"));
                }
                else
                {
                    m_xmlr.Read();
                    string broadCasterHeader = m_xmlr.Name;
                    if (broadCasterHeader != "BROADCASTER_INFO")
                    {
                        throw (new System.Xml.XmlException("Invalid XML structure was expected a <BROADCASTER_INFO> and was found " + broadCasterHeader));
                    }
                    else
                    {
                        //*******************************************************
                        //gets the data broadcaster information
                        //*******************************************************
                        broadCasterName = m_xmlr.GetAttribute("name");
                        if (broadCasterName == null)
                        {
                            throw (new Exception("Can\'t determine the attribute NAME of the section <BROADCASTER_INFO> from XML String  [" + XMLDataString + "]"));
                        }

                        broadCasterHost = m_xmlr.GetAttribute("host");
                        if (broadCasterHost == null)
                        {
                            throw (new Exception("Can\'t determine the attribute HOST of the section <BROADCASTER_INFO> from XML String  [" + XMLDataString + "]"));
                        }

                        string PORT = m_xmlr.GetAttribute("listeningPort");

                        if (PORT == null)
                        {
                            throw (new Exception("Can\'t determine the attribute LISTENINGPORT of the section <BROADCASTER_INFO> from XML String  [" + XMLDataString + "]"));
                        }
                        broadCasterListeningPort = System.Convert.ToInt32(PORT);


                        //*******************************************************
                        //gets the data from the XML string
                        //*******************************************************
                        string dataValueAsString = "";
                        m_xmlr.Read();
                        m_xmlr.Read();
                        dataValueAsString = m_xmlr.ReadOuterXml();
                        DataVariable      var             = XMLDataFormatting.RetrieveDataVariableFromXMLString(dataValueAsString);
                        BroadcastableData broadCastedData = new BroadcastableData(broadCasterName, broadCasterHost, broadCasterListeningPort, System.Convert.ToString(var.Name), var.Data);
                        return(broadCastedData);
                    }
                }
            }
Ejemplo n.º 21
0
        private string GetBuildStage()
        {
            if (!controller.SelectedProject.Detail.IsConnected)
            { return string.Empty; }




            if (controller.SelectedProject.ProjectState != ProjectState.Building &&
                controller.SelectedProject.ProjectState != ProjectState.BrokenAndBuilding)
            { return controller.SelectedProject.Detail.ProjectDescription; }

            String currentBuildStage = controller.SelectedProject.Detail.CurrentBuildStage;
            if (currentBuildStage == null || currentBuildStage.Length == 0)
            { return string.Empty; }

            System.Text.StringBuilder SB = new System.Text.StringBuilder();
            System.IO.StringWriter BuildStage = new System.IO.StringWriter(SB);

            try
            {
                System.Xml.XmlTextReader XReader;
                System.Xml.XmlDocument XDoc = new System.Xml.XmlDocument();

                XDoc.LoadXml(controller.SelectedProject.Detail.CurrentBuildStage);
                XReader = new System.Xml.XmlTextReader(XDoc.OuterXml, System.Xml.XmlNodeType.Document, null);
                XReader.WhitespaceHandling = System.Xml.WhitespaceHandling.None;

                while (XReader.Read())
                {
                    XReader.MoveToContent();

                    if (XReader.AttributeCount > 0)
                    {
                        BuildStage.WriteLine("{0}  {1}", XReader.GetAttribute("Time"), XReader.GetAttribute("Data"));
                    }
                }
            }
            catch
            {
                BuildStage = new System.IO.StringWriter();
            }
            return BuildStage.ToString();
        }
Ejemplo n.º 22
0
        private string VerifyAdwaysAccount(string CustomerID, string AdwaysID, string AdwaysEmail)
        {
            try
            {
                string url = "http://club.pchome.net/union/icson/checkHashCode.php?code=" + txtPPCode.Text.Trim();
                System.Net.WebClient wc = new System.Net.WebClient();
                System.IO.Stream stream = wc.OpenRead(url);
                System.Xml.XmlReader xmlread = new System.Xml.XmlTextReader(stream);

                string ppResult = stream.ToString();

                stream.Close();
                wc.Dispose();

                while (xmlread.Read())
                {
                    if (xmlread.Name.ToUpper().Equals("RESULT"))
                    {
                        break;
                    }
                }

                string result = xmlread.GetAttribute(0).ToString();
                xmlread.Close();
                return result;
            }
            catch
            {
                return "-1";
            }
        }
        public ActionResult ImportaIntrebari(HttpPostedFileBase file)
        {
            if (file != null && file.ContentLength > 0)
            {
                try
                {
                    string path = Path.Combine(Server.MapPath("~/FisiereXML"), Path.GetFileName(file.FileName));
                    file.SaveAs(path);

                    /////////citim fisierul xml
                    System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(path);

                    Disciplina disCiplina  = null;
                    Capitole   capItol     = null;
                    Intrebari  intreBare   = null;
                    Raspunsuri rasPunsuri  = null;
                    int        idIntrebare = 0;

                    while (reader.Read())
                    {
                        reader.MoveToContent();
                        if (reader.NodeType == System.Xml.XmlNodeType.Element)
                        {
                            if (reader.Name == "Disciplina")
                            {
                                string s = reader.GetAttribute(0); // numele disciplinei


                                var v_dis = serviciu.GetDisciplinaByNume_Capitole(s);
                                disCiplina = v_dis;

                                if (disCiplina == null)
                                {
                                    // inseamna ca nu exista elemente
                                    // vom crea o noua disciplina

                                    disCiplina = new Disciplina
                                    {
                                        NumeDisciplina = s
                                    };

                                    disCiplina.State = State.Added;
                                    serviciu.DisciplinaUDI(disCiplina);
                                    disCiplina = serviciu.GetDisciplinaByNume_Capitole(s);
                                }
                            } // if disciplina

                            if (reader.Name == "capitol")
                            {
                                string numeCapitol = reader.GetAttribute(0); // numele capitolului

                                var var_cap = serviciu.GetCapitolByName(numeCapitol);
                                capItol = var_cap;
                                if (capItol == null)
                                {
                                    // inseamana ca nu exista elemente
                                    // vom crea un nou capitol
                                    capItol = new Capitole
                                    {
                                        NumeCapitol            = numeCapitol,
                                        DisciplinaIdDisciplina = disCiplina.IdDisciplina
                                    };

                                    capItol.State = State.Added;
                                    serviciu.CapitoleUDI(capItol);
                                    capItol = serviciu.GetCapitolByName(numeCapitol);
                                }
                            }
                        }

                        if (reader.NodeType == System.Xml.XmlNodeType.Element)
                        {
                            if (reader.Name == "intrebare")
                            {
                                reader.Read();
                                intreBare = new Intrebari
                                {
                                    CapitoleIdCapitol = capItol.IdCapitol,
                                    Intrebarea        = reader.Value
                                };

                                intreBare.State = State.Added;
                                serviciu.IntrebariUDI(intreBare);

                                idIntrebare = serviciu.GetMaxId();
                            }

                            //vom completa cu informatiile pentru raspuns
                            if (reader.Name == "raspunsMotivate")
                            {
                                rasPunsuri = new Raspunsuri();
                                rasPunsuri.IntrebariIdIntrebare = idIntrebare;
                            }

                            if (reader.Name == "raspuns")
                            {
                                reader.Read();
                                rasPunsuri.Raspuns = reader.Value;
                            }
                            if (reader.Name == "motivare")
                            {
                                reader.Read();
                                rasPunsuri.MotivareRaspuns = reader.Value;
                            }
                            if (reader.Name == "corect")
                            {
                                reader.Read();
                                rasPunsuri.RaspunsCorect = reader.Value == "f" ? 0 : 1;
                                rasPunsuri.State         = State.Added;
                                serviciu.RaspunsuriUDI(rasPunsuri);
                            }
                        }
                    }

                    ViewBag.Message = "Fisierul a fost incarcat cu succes";
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "Exceptie:" + ex.Message.ToString();
                }
            }
            else
            {
                ViewBag.Message = "Nu ai ales nici un fisier";
            }
            return(View());
        }
Ejemplo n.º 24
0
        public ListMetadataFormats listMetadataFormats(string sidentifier)
        {
            System.IO.Stream objStream;
            ListMetadataFormats objFormat = new ListMetadataFormats();
            System.Net.HttpWebRequest wr;
            System.Xml.XmlTextReader rd;

            if (sidentifier.Length == 0)
            {
                prequestURL = baseURL + "?verb=ListMetadataFormats";
            }
            else
            {
                prequestURL = baseURL + "?verb=ListMetadataFormats&identifier=" + sidentifier;
            }

            try
            {
                wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL);
                wr.UserAgent = cUserAgent;
                System.Net.WebResponse response = wr.GetResponse();
                objStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(objStream);
                prawXML = reader.ReadToEnd();
                reader.Close();
                rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null);
            }
            catch (Exception e)
            {
                error.errorName = e.ToString();
                error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL;
                return null;
            }

            while (rd.Read())
            {
                if (rd.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (rd.Name == "responseDate")
                    {
                        presponseDate = rd.ReadString();
                    }
                    else if (rd.Name == "ListMetadataFormats")
                    {
                        while (rd.Read())  // && rd.NodeType != System.Xml.XmlNodeType.EndElement)
                        {
                            switch (rd.Name)
                            {
                                case "metadataPrefix":
                                    objFormat.metadataPrefix.Add(ParseOAI(ref rd, "metadataPrefix"));
                                    break;
                                case "schema":
                                    objFormat.schema.Add(ParseOAI(ref rd, "schema"));
                                    break;
                                case "metadataNamespace":
                                    objFormat.metadataNamespace.Add(ParseOAI(ref rd, "metadataNamespace"));
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    else if (rd.Name == "error")
                    {
                        error.errorName = rd.GetAttribute("code");
                        error.errorDescription = rd.ReadString();
                        return null;
                    }
                }
            }

            rd.Close();
            return objFormat;
        }
Ejemplo n.º 25
0
            internal static P2PData ParseAndGet_P2PData_FromXMLDataString(string XMLString)
            {
                System.IO.StringReader   sr     = null;
                System.Xml.XmlTextReader m_xmlr = null;

                try
                {
                    sr     = new System.IO.StringReader(XMLString);
                    m_xmlr = new System.Xml.XmlTextReader(sr);
                    m_xmlr.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                }
                catch (System.Xml.XmlException)
                {
                    string msg;
                    msg = "Error trying to get XML format from  P2P Data string [" + XMLString + "]";
                }
                catch (Exception ex)
                {
                    string msg = "";
                    msg = "Error trying to parse P2P socket XML string : " + ex.Message;
                    throw (new Exception(msg));
                }
                m_xmlr.Read();
                string HeaderIdentifier = m_xmlr.Name;

                if (HeaderIdentifier != "P2P_DATA")
                {
                    throw (new System.Xml.XmlException("Invalid P2P data header " + HeaderIdentifier + ". Must be \'P2P_DATA\'"));
                }
                else
                {
                    //**********************************************************
                    //retrieves the data operation type
                    //**********************************************************

                    string operationID = "";
                    operationID = m_xmlr.GetAttribute("P2PDataOperationID");
                    if (operationID == null)
                    {
                        operationID = Guid.NewGuid().ToString();
                    }

                    //**********************************************************
                    //retrieves the data itself
                    //**********************************************************
                    m_xmlr.Read();
                    string       dataSectionName = m_xmlr.Name;
                    DataVariable variable        = default(DataVariable);
                    if (dataSectionName == "DATA")
                    {
                        string variableXMLstring = m_xmlr.ReadOuterXml();
                        variable = XMLDataFormatting.RetrieveDataVariableFromXMLString(variableXMLstring);
                    }
                    else
                    {
                        throw (new Exception("Invalid data XML section name \'" + dataSectionName + "\'. Is expected to be \'DATA\'"));
                    }

                    //**********************************************************
                    //retrieves the attributes table and its XML attributes
                    //**********************************************************
                    string dataAttributesSectionName = m_xmlr.Name;
                    P2PDataAttributesTable attrTAble = null;
                    int AttrCount = 0;

                    if (dataAttributesSectionName == "DATA_ATTRIBUTES")
                    {
                        string attributesCount = m_xmlr.GetAttribute("DataAttrCount");
                        if (!(attributesCount == null))
                        {
                            AttrCount = System.Convert.ToInt32(attributesCount);
                            if (AttrCount > 0)
                            {
                                string       attrTableXMLString = m_xmlr.ReadInnerXml();
                                DataVariable tableVar           = default(DataVariable);
                                tableVar  = XMLDataFormatting.RetrieveDataVariableFromXMLString(attrTableXMLString);
                                attrTAble = new P2PDataAttributesTable((CustomHashTable)tableVar.Data);
                            }
                        }
                        else
                        {
                            throw (new Exception("The parameter \'AttrCount\' is missing on the XML string in te section \'DATA_ATTRIBUTES\'"));
                        }
                    }
                    else
                    {
                        throw (new Exception("Invalid data attributes XML section name \'" + dataSectionName + "\'. Is expected to be \'DATA_ATTRIBUTES\'"));
                    }

                    P2PData data = default(P2PData);
                    data = new P2PData(operationID, System.Convert.ToString(variable.Name), variable.Data);
                    if (AttrCount > 0)
                    {
                        data.AttachAttributesTable(attrTAble);
                    }
                    return(data);
                }
            }
Ejemplo n.º 26
0
            public static SocketData ParseAndGet_SocketData_FromXMLDataString(string XMLString)
            {
                System.IO.StringReader   sr     = null;
                System.Xml.XmlTextReader m_xmlr = null;

                try
                {
                    sr     = new System.IO.StringReader(XMLString);
                    m_xmlr = new System.Xml.XmlTextReader(sr);
                    m_xmlr.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                }
                catch (System.Xml.XmlException)
                {
                    string msg;
                    msg = "Error trying to get XML format from data socket data string [" + XMLString + "]";
                }
                catch (Exception ex)
                {
                    string msg = "";
                    msg = "Error trying to parse data socket XML string : " + ex.Message;
                    throw (new Exception(msg));
                }
                m_xmlr.Read();
                string HeaderIdentifier = m_xmlr.Name;

                if (HeaderIdentifier != "SD")
                {
                    throw (new System.Xml.XmlException("Invalid data socket header " + HeaderIdentifier + ". Must be \'SD\'"));
                }
                else
                {
                    //**********************************************************
                    //retrieves the data transported on the XML
                    //**********************************************************
                    m_xmlr.Read();
                    string       dataSectionName = m_xmlr.Name;
                    DataVariable variable        = default(DataVariable);
                    if (dataSectionName == "DATA")
                    {
                        string variableXMLstring = m_xmlr.ReadOuterXml();
                        variable = XMLDataFormatting.RetrieveDataVariableFromXMLString(variableXMLstring);
                    }
                    else
                    {
                        throw (new Exception("Invalid data XML section name \'" + dataSectionName + "\'. Is expected to be \'DATA\'"));
                    }

                    //**********************************************************
                    //retrieves the attributes table and its XML attributes
                    //**********************************************************
                    string          dataAttributesSectionName = m_xmlr.Name;
                    AttributesTable attributesTable           = null;
                    int             AttrCount = 0;

                    if (dataAttributesSectionName == "SDAS")
                    {
                        string attributesCount = m_xmlr.GetAttribute("cn");
                        if (!(attributesCount == null))
                        {
                            AttrCount = System.Convert.ToInt32(attributesCount);
                            if (AttrCount > 0)
                            {
                                string       attrTableXMLString = m_xmlr.ReadInnerXml();
                                DataVariable tableVar           = default(DataVariable);
                                tableVar = XMLDataFormatting.RetrieveDataVariableFromXMLString(attrTableXMLString);
                                CustomHashTable table = default(CustomHashTable);
                                table           = (CustomHashTable)tableVar.Data;
                                attributesTable = new AttributesTable(table);
                            }
                        }
                        else
                        {
                            throw (new Exception("The parameter \'cn\' is missing on the XML string in te section \'SDAS\'"));
                        }
                    }
                    else
                    {
                        throw (new Exception("Invalid data attributes XML section name \'" + dataSectionName + "\'. Is expected to be \'SD_ATTRS\'"));
                    }

                    SocketData data = default(SocketData);
                    data = new SocketData(System.Convert.ToString(variable.Name), variable.Data);
                    if (AttrCount > 0)
                    {
                        data.AttachAttributesTable(attributesTable);
                    }
                    return(data);
                }
            }
        static Sdl.LanguagePlatform.Core.Segment TranslatedHtml2Segment(Sdl.LanguagePlatform.Core.Segment sourceSegment, string translatedText)
        {
            var htmlTagName       = "span"; // the only we feed for translation is span, so we expect the translation only has span tags too.
            var xmlFragment       = "<segment>" + translatedText + "</segment>";
            var xmlReader         = new System.Xml.XmlTextReader(xmlFragment, System.Xml.XmlNodeType.Element, null);
            var tagStack          = new Stack <Sdl.LanguagePlatform.Core.Tag>();
            var translatedSegment = new Sdl.LanguagePlatform.Core.Segment();

            try
            {
                while (xmlReader.Read())
                {
                    switch (xmlReader.NodeType)
                    {
                    case System.Xml.XmlNodeType.Element:
                        if (xmlReader.Name == htmlTagName)
                        {
                            var tagClass = xmlReader.GetAttribute("class");
                            var tagType  = (Sdl.LanguagePlatform.Core.TagType)
                                           Enum.Parse(typeof(Sdl.LanguagePlatform.Core.TagType), tagClass);
                            int id = Convert.ToInt32(xmlReader.GetAttribute("id"));
                            Sdl.LanguagePlatform.Core.Tag sourceTag = sourceSegment.FindTag(tagType, id);
                            if (tagType != Sdl.LanguagePlatform.Core.TagType.Standalone && !xmlReader.IsEmptyElement)
                            {
                                tagStack.Push(sourceTag);
                            }
                            translatedSegment.Add(sourceTag.Duplicate());
                            if (tagType != Sdl.LanguagePlatform.Core.TagType.Standalone && xmlReader.IsEmptyElement)
                            // the API translated <span></span> to <span/> (it does that if the tag is empty).
                            // must fetch the end tag as there is no EndElement to triger the next case block.
                            {
                                var endTag = sourceSegment.FindTag(Sdl.LanguagePlatform.Core.TagType.End, id);
                                translatedSegment.Add(endTag.Duplicate());
                            }
                        }
                        break;

                    case System.Xml.XmlNodeType.EndElement:
                    {
                        if (xmlReader.Name == htmlTagName)
                        {
                            var startTag = tagStack.Pop();
                            if (startTag.Type != Sdl.LanguagePlatform.Core.TagType.Standalone)
                            {
                                var endTag = sourceSegment.FindTag(
                                    Sdl.LanguagePlatform.Core.TagType.End, startTag.Anchor);
                                if (endTag != null)
                                {
                                    translatedSegment.Add(endTag.Duplicate());
                                }
                            }
                        }
                    }
                    break;

                    case System.Xml.XmlNodeType.Text:
                        translatedSegment.Add(xmlReader.Value);
                        break;

                    case System.Xml.XmlNodeType.Whitespace:
                        translatedSegment.Add(xmlReader.Value);
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception)
            {
                var    paintextSegment = new Sdl.LanguagePlatform.Core.Segment();
                string plaitext        = Regex.Replace(translatedText, "<[^>]+>", "");
                paintextSegment.Add(plaitext);
                return(paintextSegment);
            }

            return(translatedSegment);
        }
            internal static P2PDataRequest ParseAndGet_P2PDataRequest_FromXMLDataString(string XMLString)
            {
                System.IO.StringReader   sr     = null;
                System.Xml.XmlTextReader m_xmlr = null;

                try
                {
                    sr     = new System.IO.StringReader(XMLString);
                    m_xmlr = new System.Xml.XmlTextReader(sr);
                    m_xmlr.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                }
                catch (System.Xml.XmlException)
                {
                    string msg;
                    msg = "Error trying to get XML format from  P2PDataRequest Data string [" + XMLString + "]";
                }
                catch (Exception ex)
                {
                    string msg = "";
                    msg = "Error trying to parse P2PDataRequest  XML string : " + ex.Message;
                    throw (new Exception(msg));
                }
                m_xmlr.Read();
                string HeaderIdentifier = m_xmlr.Name;

                if (HeaderIdentifier != "P2P_DATAREQUEST")
                {
                    throw (new System.Xml.XmlException("Invalid P2PDataRequest header " + HeaderIdentifier + ". Must be \'P2P_DATAREQUEST\'"));
                }
                else
                {
                    string datanameToRequest = m_xmlr.GetAttribute("datanameToRequest");
                    if (datanameToRequest == null)
                    {
                        throw (new Exception("No dataname to retrieve attribute found in the P2PDataRequest XML String"));
                    }

                    m_xmlr.Read();
                    string AttributesSectionName = m_xmlr.Name;

                    if (AttributesSectionName != "DATA_REQUEST_PARAMETERS")
                    {
                        throw (new Exception("Invalid section name \'" + AttributesSectionName + "\'"));
                    }
                    string          parametersCountStr = m_xmlr.GetAttribute("ParametersCount");
                    int             numOfParameters    = 0;
                    CustomHashTable parametersTable    = null;

                    if (!(parametersCountStr == null))
                    {
                        numOfParameters = System.Convert.ToInt32(parametersCountStr);
                        if (numOfParameters > 0)
                        {
                            string       attrTableXMLString = m_xmlr.ReadInnerXml();
                            DataVariable tableVar           = default(DataVariable);
                            tableVar        = XMLDataFormatting.RetrieveDataVariableFromXMLString(attrTableXMLString);
                            parametersTable = (CustomHashTable)tableVar.Data;
                        }
                    }
                    else
                    {
                        throw (new Exception("The parameter \'AttrCount\' is missing on the XML string of the section \'REQUEST_ATTRIBUTES\'"));
                    }


                    P2PDataRequest dataRq = default(P2PDataRequest);
                    if (numOfParameters > 0)
                    {
                        if (!(parametersTable == null))
                        {
                            dataRq = new P2PDataRequest(datanameToRequest, parametersTable);
                        }
                        else
                        {
                            dataRq = new P2PDataRequest(datanameToRequest);
                        }
                    }
                    else
                    {
                        dataRq = new P2PDataRequest(datanameToRequest);
                    }
                    return(dataRq);
                }
            }
            internal static DataBroadCastHandler ParseAndGet_DataBroadCastHandler_FromXMLDataString(string XMLDataString)
            {
                System.IO.StringReader   sr     = null;
                System.Xml.XmlTextReader m_xmlr = null;

                try
                {
                    sr     = new System.IO.StringReader(XMLDataString);
                    m_xmlr = new System.Xml.XmlTextReader(sr);
                    m_xmlr.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                }
                catch (System.Xml.XmlException)
                {
                    string msg;
                    msg = "Error trying to get XML format from broadcasted data string [" + XMLDataString + "]";
                }
                catch (Exception ex)
                {
                    string msg = "";
                    msg = "Error trying to parse broadcasted XML string : " + ex.Message;
                    throw (new Exception(msg));
                }
                m_xmlr.Read();
                string HeaderIdentifier = m_xmlr.Name;

                if (HeaderIdentifier != "BROADCAST_HANDLER")
                {
                    throw (new System.Xml.XmlException("Invalid data header " + HeaderIdentifier + ". Must be \'BROADCAST_HANDLER\'"));
                }
                else
                {
                    //read the mode attribute from the current section "BROADCAST_HANDLER"
                    BroadCastMode mode    = default(BroadCastMode);
                    string        modeStr = m_xmlr.GetAttribute("broadcastMode");
                    switch (modeStr)
                    {
                    case "BroadCasterIsWaitingReply":
                        mode = BroadCastMode.BroadCasterIsWaitingReply;
                        break;

                    case "BroadCasterIsNotWaitingReply":
                        mode = BroadCastMode.BroadCasterIsNotWaitingReply;
                        break;

                    default:
                        mode = BroadCastMode.undefined;
                        break;
                    }

                    string broadCastIDName = "";
                    broadCastIDName = m_xmlr.GetAttribute("broadcastIDName");
                    if (broadCastIDName == null)
                    {
                        throw (new Exception("No attribute \'broadcastIDName\' in XML data string [" + XMLDataString + "]"));
                    }

                    //retrieves all the xml string of the broadcastable data section
                    m_xmlr.Read();
                    string               broadCastedXMLString = m_xmlr.ReadOuterXml();
                    BroadcastableData    data    = BroadcastableData.ParseAndGet_BroadcastableData_FromXMLDataString(broadCastedXMLString);
                    DataBroadCastHandler handler = new DataBroadCastHandler(mode, broadCastIDName, data);
                    return(handler);
                }
            }
Ejemplo n.º 30
0
        //=======================================================================
        // Sub/Function: identify
        // Description: Use this function to return the identifier information
        // from an OAI repository.
        //
        // example:
        // OAI objOAI = new OAI("http://memory.loc.gov/cgi-bin/oai2_0");
        // Identify objID = new Identify();
        //
        // objID = objOAI.identify();
        // Console.WriteLine("Base URL: " + objID.baseURL);
        // Console.WriteLine("Repository: " + objID.repositoryName);
        // Console.WriteLine("Deleted Records: "  + objID.deletedRecord);
        //=======================================================================
        public Identify identify()
        {
            System.IO.Stream objStream;
            Identify objID = new Identify();
            System.Net.HttpWebRequest wr;
            System.Xml.XmlTextReader rd;

            try
            {
                prequestURL = baseURL + "?verb=Identify";
                wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL);
                wr.UserAgent = cUserAgent;
                System.Net.WebResponse response = wr.GetResponse();
                objStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(objStream);
                prawXML = reader.ReadToEnd();
                reader.Close();
                rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null);
            }
            catch (Exception e)
            {
                error.errorName = e.ToString();
                error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL;
                return null;
            }

            while (rd.Read())
            {
                if (rd.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (rd.Name == "responseDate")
                    {
                        presponseDate = rd.ReadString();
                    }
                    else if (rd.Name == "Identify")
                    {
                        while (rd.Read() && rd.NodeType != System.Xml.XmlNodeType.EndElement)
                        {
                            switch (rd.Name)
                            {
                                case "repositoryName":
                                    objID.repositoryName = ParseOAI(ref rd, "repositoryName");
                                    break;
                                case "baseURL":
                                    objID.baseURL = ParseOAI(ref rd, "baseURL");
                                    break;
                                case "protocolVersion":
                                    objID.protocolVersion = ParseOAI(ref rd, "protocolVersion");
                                    break;
                                case "earliestDatestamp":
                                    objID.earliestDatestamp = ParseOAI(ref rd, "earliestDatestamp");
                                    break;
                                case "deletedRecord":
                                    objID.deletedRecord = ParseOAI(ref rd, "deletedRecord");
                                    break;
                                case "granularity":
                                    objID.granularity = ParseOAI(ref rd, "granularity");
                                    break;
                                case "adminEmail":
                                    objID.adminEmail.Add(ParseOAI(ref rd, "adminEmail"));
                                    break;
                                case "compression":
                                    objID.compression.Add(ParseOAI(ref rd, "compression"));
                                    break;
                                case "description":
                                    objID.description.Add(ParseOAIContainer(ref rd, "description"));
                                    break;
                            }
                        }
                    }
                    else if (rd.Name == "error")
                    {
                        error.errorName = rd.GetAttribute("code");
                        error.errorDescription = rd.ReadString();
                        return null;
                    }
                }
            }

            rd.Close();

            return objID;
        }
Ejemplo n.º 31
0
        static Avi1MinXmlPackage AVI_XML(string extAvidevName, char centerCode)
        {
            Avi1MinXmlPackage ret=null;
            System.Xml.XmlTextReader rd = new System.Xml.XmlTextReader("1min_avi_data.xml");
            System.DateTime xmlfiledate;
            while (rd.Read())
            {

                switch(rd.NodeType)
                {
                    case  System.Xml.XmlNodeType.Element:
                        Console.WriteLine(rd.Name);

                        if (rd.Name == "file_attribute")
                        {
                            Console.WriteLine(rd.GetAttribute("time"));
                            ret = new Avi1MinXmlPackage();
                            ret.datetime = System.Convert.ToDateTime(rd.GetAttribute("time"));
                        }
                        else
                            if (rd.Name == "avi_data")
                            {
                                if (rd.GetAttribute("eqId") != extAvidevName)
                                {
                                    rd.Skip();
                                    break;
                                }
                                Console.WriteLine("\t" + rd.GetAttribute("eqId"));
                            }
                            else if (rd.Name == "plateData")
                            {
                                Console.WriteLine("\t\t" + rd.GetAttribute("plateNo")+"\t"+rd.GetAttribute("catchTime"));
                                int catchSec=System.Convert.ToInt32(rd.GetAttribute("catchTime"));
                                ret.Items.Add(new RemoteInterface.MFCC.AVIPlateData(extAvidevName, ret.datetime.AddSeconds(catchSec), rd.GetAttribute("plateNo")));
                            }
                        break;

                }
            }

            return ret;
        }
Ejemplo n.º 32
0
        public ListIdentifier ListIdentifiers(string sPrefix,
            string sset,
            string sfrom,
            string suntil,
            ResumptionToken objToken)
        {
            System.IO.Stream objStream;
            ListIdentifier objList = new ListIdentifier();
            Identifiers objRecord;
            ResumptionToken myToken;
            string tmp = "";
            System.Net.HttpWebRequest wr;
            System.Xml.XmlTextReader rd;

            if (sPrefix.Length == 0)
            {
                sPrefix = "oai_dc";
            }

            if (objToken == null)
            {
                if (sset.Length != 0)
                {
                    sset = "&set=" + sset;
                }
                if (sfrom.Length != 0)
                {
                    sfrom = "&from=" + sfrom;
                }
                if (suntil.Length != 0)
                {
                    suntil = "&until=" + suntil;
                }

                prequestURL = baseURL + "?verb=ListIdentifiers&metadataPrefix=" + sPrefix + sset + sfrom + suntil;

            }
            else
            {
                prequestURL = baseURL + "?verb=ListIdentifiers&resumptionToken=" + objToken.resumptionToken;
                //This is where we handle the resumptionToken
            }
            //======================================================
            // If you wanted to support additional metadata formats,
            // you would just need to have additional handlers.
            //======================================================
            //Console.Write(sURL);
            try
            {
                wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL);
                wr.UserAgent = cUserAgent;
                System.Net.WebResponse response = wr.GetResponse();
                objStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(objStream);
                prawXML = reader.ReadToEnd();
                reader.Close();
                rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null);
            }
            catch (Exception e)
            {
                error.errorName = "badConnection";
                error.errorDescription = e.Message + "<br>Unable to connect to " + baseURL;
                return null;
            }

            while (rd.Read())
            {
                if (rd.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (rd.Name == "responseDate")
                    {
                        presponseDate = rd.ReadString();
                    }
                    else if (rd.Name == "ListIdentifiers")
                    {
                        do
                        {
                            if (rd.Name == "header")
                            {
                                tmp = rd.ReadOuterXml();
                                //tmp += ParseOAIContainer(ref rd, "header", true);
                                //Console.WriteLine("In the Function: " + tmp);
                                objRecord = new Identifiers(tmp);
                                objList.record.Add(objRecord);
                                //return objRecord;
                            }
                            else if (rd.Name == "resumptionToken")
                            {
                                tmp = rd.ReadOuterXml();
                                myToken = new ResumptionToken(tmp);
                                objList.token = myToken;
                            }
                            else rd.Read(); // Added the Read() and will never occur with the ReadInnerXml()

                        } while (rd.Name != "ListIdentifiers"); // loop
                    }
                    else if (rd.Name == "error")
                    {
                        error.errorName = rd.GetAttribute("code");
                        error.errorDescription = rd.ReadString();
                        rd.Close();
                        return null;
                    }
                }
            }

            rd.Close();
            return objList;
        }
Ejemplo n.º 33
0
        static void Main(string[] args)
        {
            try
            {
                Class.AppLogs      log            = new Class.AppLogs();
                Class.Orchestrator core           = new Class.Orchestrator();
                string             envioCorrectos = ConfigurationManager.AppSettings["destinationFolder"];
                int    factura           = 0;
                int    indexFileNameList = 0;
                String fecha             = String.Empty;
                string UUID           = String.Empty;
                string SATCertificate = String.Empty;
                string rfc            = String.Empty;
                log.CreateLog();
                core.delProcessedFiles(); // Borrado de archivos ya procesados
                Console.WriteLine("Inicia el proceso de sincronización en Epicor...");

                //Obtención de archivos XML
                core.obtainXMLFiles();
                if (core.collector.Equals(""))
                {
                    log.writeContentToFile("No se encontraron archivos que leer, termina la ejecución");
                }
                else
                {
                    log.writeContentToFile(core.collector);
                }

                // Iniciando conexión a Epicor
                Epicor10.EpiAdapters epicor = new EpiAdapters("vordmaker", "maker2016");

                //Obtención de datos fiscales por cada XML
                foreach (String item in core.filesPath)
                {
                    Console.WriteLine("\n");
                    Console.WriteLine("Obteniendo datos del archivo " + item);
                    log.writeContentToFile("\n");
                    log.writeContentToFile("Obteniendo datos del archivo " + item);

                    System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(item);

                    while (reader.Read())
                    {
                        if (reader.NodeType == System.Xml.XmlNodeType.Element)
                        {
                            if (reader.Name.Equals("cfdi:Emisor"))
                            {
                                if (reader.HasAttributes)
                                {
                                    Console.WriteLine("_cfdi:Emisor_");
                                    Console.WriteLine("Compañía: " + reader.GetAttribute("Nombre"));
                                    Console.WriteLine("RFC: " + reader.GetAttribute("Rfc"));
                                    rfc = reader.GetAttribute("Rfc");
                                    log.writeContentToFile("Compañía: " + reader.GetAttribute("Nombre"));
                                    log.writeContentToFile("RFC: " + reader.GetAttribute("Rfc"));
                                }
                            }

                            if (reader.Name.Equals("cfdi:Addenda"))
                            {
                                reader.ReadToFollowing("fa:AddendaComercial");
                                if (!reader.HasAttributes)
                                {
                                    reader.ReadToFollowing("fa:Empresa");
                                    factura = Convert.ToInt32(reader.GetAttribute("NumeroInterno"));
                                    Console.WriteLine("_cfdi:Empresa_");
                                    Console.WriteLine("Número Legal: " + reader.GetAttribute("NumeroLegal"));
                                    Console.WriteLine("Número Interno: " + reader.GetAttribute("NumeroInterno"));
                                    Console.WriteLine("Fecha Contable: " + reader.GetAttribute("FechaContable"));
                                    Console.WriteLine("Fecha Emision: " + reader.GetAttribute("FechaEmision"));

                                    log.writeContentToFile("Número Legal: " + reader.GetAttribute("NumeroLegal"));
                                    log.writeContentToFile("Número Interno: " + reader.GetAttribute("NumeroInterno"));
                                    log.writeContentToFile("Fecha Contable: " + reader.GetAttribute("FechaContable"));
                                    log.writeContentToFile("Fecha Emision: " + reader.GetAttribute("FechaEmision"));
                                }
                            }

                            if (reader.Name.Equals("cfdi:Complemento"))
                            {
                                reader.ReadToFollowing("tfd:TimbreFiscalDigital");
                                Console.WriteLine("_cfdi:Complemento_");
                                Console.WriteLine("UUID: " + reader.GetAttribute("UUID"));
                                UUID  = reader.GetAttribute("UUID");
                                fecha = reader.GetAttribute("FechaTimbrado");
                                Console.WriteLine("Fecha: " + reader.GetAttribute("FechaTimbrado"));
                                Console.WriteLine("SAT: " + reader.GetAttribute("noCertificadoSAT")); // Versión 3.2
                                SATCertificate = reader.GetAttribute("noCertificadoSAT");
                                log.writeContentToFile("UUID: " + reader.GetAttribute("UUID"));
                                log.writeContentToFile("Fecha: " + reader.GetAttribute("FechaTimbrado"));
                                log.writeContentToFile("SAT: " + reader.GetAttribute("noCertificadoSAT"));
                            }

                            /*
                             * if (reader.Name.Equals("cfdi:Comprobante"))
                             * {
                             *  if (reader.HasAttributes)
                             *  {
                             *      Console.WriteLine("_cfdi:Comprobante_");
                             *      Console.WriteLine("Version: " + reader.GetAttribute("version"));
                             *      Console.WriteLine("TipoComprobante: " + reader.GetAttribute("tipoDeComprobante"));
                             *  }
                             * }
                             */

                            /*
                             * if (reader.Name.Equals("cfdi:Receptor"))
                             * {
                             *  if (reader.HasAttributes)
                             *  {
                             *      Console.WriteLine("_cfdi:Receptor_");
                             *      Console.WriteLine("RFC: " + reader.GetAttribute("rfc"));
                             *  }
                             * }
                             */
                        }
                    }

                    //Actualizacion Epicor
                    Console.WriteLine("Actualizando UUID de la factura...");
                    string empresa = core.companyToConnect(rfc);
                    Console.WriteLine("Conectando a ... " + empresa);

                    epicor.setCompany(empresa);
                    if (epicor.EventCollector.Equals(""))
                    {
                        epicor.UpdateInvcHeader(factura, UUID, SATCertificate, fecha);
                        if (epicor.EventCollector.Equals(""))
                        {
                            Console.WriteLine("Actualización de datos completa.");
                            log.writeContentToFile("Actualización de datos completa.");

                            reader.Close();
                            string destination = System.IO.Path.Combine(envioCorrectos, core.fileNames[indexFileNameList]);
                            System.IO.File.Copy(item, destination);
                            System.IO.File.Delete(item);
                        }
                        else
                        {
                            Console.WriteLine("Ocurrió un error al actualizar la información \n" + epicor.EventCollector);
                            log.writeContentToFile("Ocurrió un error al actualizar la información \n" + epicor.EventCollector);
                        }
                    }
                    else
                    {
                        Console.WriteLine(epicor.EventCollector);
                        log.writeContentToFile(epicor.EventCollector);
                    }

                    Console.WriteLine("\n");
                    log.writeContentToFile("\n");
                    indexFileNameList++;
                }
                log.writeContentToFile("Hemos terminado !!!");
            }
            catch (Exception rmp)
            {
                Console.WriteLine(rmp.StackTrace);
            }
            Console.WriteLine("Hemos terminado !!!");
        }
Ejemplo n.º 34
0
        public static void initialize(Main pMain)
        {
            m_pMain = pMain;
            m_pWebClient = new CGWebClient();
            m_pWebClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler(m_pWebClient_DownloadFileCompleted);
            m_pWebClient.DownloadProgressChanged += new System.Net.DownloadProgressChangedEventHandler(m_pWebClient_DownloadProgressChanged);

            if (!System.IO.File.Exists(@"pak\Files\tile.p000"))
                m_pWebClient.DownloadFile(WEBSITE + "launcher/new_patch.xml", "patch.xml");
            else if (!System.IO.File.Exists(@"pak\World\_test$sample_1.p000"))
                m_pWebClient.DownloadFile(WEBSITE + "launcher/new_patch.xml", "patch.xml");
            else
                m_pWebClient.DownloadFile(WEBSITE + "launcher/patch.xml", "patch.xml");

            try
            {
                using (System.Xml.XmlTextReader pXmlTextReader = new System.Xml.XmlTextReader(Directory.GetCurrentDirectory() + "/patch.xml"))
                //using (System.Xml.XmlTextReader pXmlTextReader = new System.Xml.XmlTextReader( WEBSITE + "files/patch.xml"))
                {
                    int x = 0;

                    while (pXmlTextReader.ReadToFollowing("PATCHNODE"))
                    {
                        x++;
                        m_pMain.Status = "Interpreting Patch Information " + x + "...";
                        if (pXmlTextReader.MoveToFirstAttribute())
                        {
                            string strFilename = pXmlTextReader.GetAttribute("file").Replace("./", "");
                            string strCurrDir = System.IO.Directory.GetCurrentDirectory();
                            try
                            {
                                string Dir = Path.GetDirectoryName(strFilename);
                                if (!Directory.Exists(Dir) && Dir != "")
                                    Directory.CreateDirectory(Dir);
                            }
                            catch
                            {
                                m_pMain.Status = "Failed to create or read folder info.";
                            }
                            //foreach (string strTemp in strFilename.Split('/'))
                            //{
                            //    if (!strTemp.Contains("."))
                            //    {
                            //        System.IO.Directory.CreateDirectory(strTemp);
                            //        continue;
                            //    }
                            //}

                            uint nChecksum = 0;

                            if (pXmlTextReader.ReadToFollowing("CHECKSUM"))
                            {
                                nChecksum = (uint)pXmlTextReader.ReadElementContentAs(typeof(uint), null);
                            }
                            try
                            {
                                FileInfo FI = new FileInfo(strFilename);
                                if (strFilename.ToLower() == Path.GetFileName(Application.ExecutablePath).ToLower())
                                {
                                    FileInfo FI2 = new FileInfo(strFilename + "_");
                                    if (FI2.Exists)
                                        FI2.Delete();
                                    Thread.Sleep(500);
                                    FI.CopyTo(strFilename + "_");
                                    uint crc = getFileCrc(strFilename + "_");
                                    FI2 = new FileInfo(strFilename + "_");
                                    if (FI2.Exists)
                                        FI2.Delete();
                                    if (crc != nChecksum)
                                    {
                                        PatchSelf = true;
                                        m_pUpdateList.Add(strFilename);
                                    }
                                    continue;
                                }
                                if (!FI.Exists)
                                    m_pUpdateList.Add(strFilename);
                                else
                                {
                                    uint crc = getFileCrc(strFilename);
                                    if (crc != nChecksum)
                                    {
                                        m_pUpdateList.Add(strFilename);
                                    }
                                }
                            }
                            catch (Exception E)
                            {
                                if (E.Message.Contains("msvcr71.dll' because it is being used by another process"))
                                {
                                    //ignore because it's used by .net and gunz needs it...  note that this is a possible abuse for exploitation
                                }
                                else
                                {
                                    MessageBox.Show("Some of the files (" + strFilename + ") that need to be patched/edited are currently in use.  Make sure SoulHunterZ is closed.  If this error persists, restart your computer.", "Fatal Error");
                                    Application.Exit();
                                }
                            }

                            System.IO.Directory.SetCurrentDirectory(strCurrDir);
                        }
                    }
                }
            }
            catch
            {
                m_pMain.Status = "Failed to get or read patch info.";
                m_pWebClient.Dispose();
                return;
            }

            m_pMain.BarTotalMax = m_pUpdateList.Count;
            m_pMain.BarTotalVal = m_pMain.BarTotalMax;
            m_pMain.BarCurVal = m_pMain.BarCurMax;
            updateNext();
        }
Ejemplo n.º 35
0
Archivo: oai.cs Proyecto: reeset/oai.cs
		public ListRecord ListRecords(string sPrefix, 
			string sset, 
			string sfrom, 
			string suntil, 
			ResumptionToken objToken, 
			ref Object objHandler) 
		{
            int fail = 0;
            Restart:
			System.IO.Stream objStream;
			ListRecord objList = new ListRecord();
			Record objRecord;
			ResumptionToken myToken;
			string tmp = "";
			System.Net.HttpWebRequest wr = null;
            System.Xml.XmlTextReader rd = null;

			if (sPrefix.Length==0) 
			{
				sPrefix = "oai_dc";
			}

			if (objToken==null) 
			{
				if (sset.Length!=0) 
				{
					sset = "&set=" + sset;
				} 
				if (sfrom.Length!=0) 
				{
					sfrom = "&from=" + sfrom;
				}
				if (suntil.Length!=0) 
				{
					suntil = "&until=" + suntil;
				}

				prequestURL = baseURL + "?verb=ListRecords&metadataPrefix=" + sPrefix + sset + sfrom + suntil;

			} 
			else 
			{
				//This is where we handle the resumptionToken - McCown
				prequestURL = baseURL + "?verb=ListRecords&resumptionToken=" + objToken.resumptionToken;
			}
			//======================================================
			// If you wanted to support additional metadata formats, 
			// you would just need to have additional handlers.
			//======================================================
            try
            {
                wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL);
                //wr.Headers.Add("Host:" + System.Net.Dns.GetHostName());
                wr.UserAgent = cUserAgent + DateTime.Now.ToString();

                if (this.Timeout <= 0) { this.Timeout = 100000; }
                wr.Timeout = this.Timeout;

                System.Net.WebResponse response = wr.GetResponse();
                objStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(objStream);
                prawXML = reader.ReadToEnd();
                //System.Windows.Forms.MessageBox.Show(prawXML);
                reader.Close();
                response.Close();
                rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null);
                rd.Normalization = true;
            }
            catch (System.Net.WebException ee)
            {
                int sleepval = 3000;
                
                fail++;
                //System.Windows.Forms.MessageBox.Show(tt.ToString());
                //System.Windows.Forms.MessageBox.Show(ee.ToString());
                if (ee.Status == System.Net.WebExceptionStatus.ProtocolError)
                {
                    var response = ee.Response as System.Net.HttpWebResponse;
                    if (response != null)
                    {
                        if ((int)response.StatusCode == 503)
                        {
                            string retryafter = response.Headers["Retry-After"];
                            if (retryafter != null && IsNumeric(retryafter) == true)
                            {
                                {
                                    sleepval = System.Convert.ToInt32(retryafter) * 1000;
                                }
                            }
                        }
                    }

                    if (fail <= 4)
                    {
                        //System.Windows.Forms.MessageBox.Show(sleepval.ToString());
                        System.Threading.Thread.Sleep(sleepval);
                        goto Restart;
                    }
                    else
                    {
                        wr.Abort();
                        error.errorName = ee.ToString();
                        error.errorDescription = ee.Message + "\n<br>Unable to connect to " + baseURL;
                        return null;
                    }
                }
            }
            catch (Exception e)
            {
               // System.Windows.Forms.MessageBox.Show("2");
                if (wr != null)
                {
                    wr.Abort();
                }
                error.errorName = e.ToString();
                error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL;
                return null;
            }

            fail = 0;
			while (rd.Read()) 
			{
				if (rd.NodeType == System.Xml.XmlNodeType.Element) 
				{
					if (rd.Name == "responseDate")
					{
						presponseDate = rd.ReadString();
					}
					else if (rd.Name=="ListRecords") 
					{ 
						do 
						{
                            
							if (rd.Name=="record") 
							{
								tmp = ParseOAIContainer(ref rd, "record");
								objRecord = new Record(tmp,ref objHandler);
								objList.record.Add(objRecord);
								//return objRecord;
							} 
							else if (rd.Name=="resumptionToken") 
							{
								tmp=rd.ReadOuterXml();
								myToken = new ResumptionToken(tmp);
								objList.token = myToken;
							}
                            //else if (rd.Name.ToLower() == "OAI-PMH".ToLower())
                            //{
                            //    break;
                            //}
                            else if (rd.EOF == true)
                            {
                                error.errorName = "Empty ListRecords Request";
                                error.errorDescription = "No data was returned in the ListRecords Element.  This is likely an error.";
                                return null;
                            }
                            else rd.Read(); // Added the Read() and will never occur with the ReadInnerXml()

						} while (rd.Name!="ListRecords"); // loop
					} 
					else if (rd.Name=="error") 
					{
						error.errorName = rd.GetAttribute("code");
						error.errorDescription = rd.ReadString();
						return null;
					}
				}
			}

            
            return objList;
            

			
		}
            internal static P2PDataDeliveryResult ParseAndGet_P2PDataDeliveryResult_FromXMLDataString(string XMLString)
            {
                System.IO.StringReader   sr     = null;
                System.Xml.XmlTextReader m_xmlr = null;

                try
                {
                    sr     = new System.IO.StringReader(XMLString);
                    m_xmlr = new System.Xml.XmlTextReader(sr);
                    m_xmlr.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                }
                catch (System.Xml.XmlException)
                {
                    string msg;
                    msg = "Error trying to get XML format from  P2P Data string [" + XMLString + "]";
                }
                catch (Exception ex)
                {
                    string msg = "";
                    msg = "Error trying to parse P2P socket XML string : " + ex.Message;
                    throw (new Exception(msg));
                }
                m_xmlr.Read();
                string HeaderIdentifier = m_xmlr.Name;

                if (HeaderIdentifier != "P2P_DATA_DELIVERY_RESULT")
                {
                    throw (new System.Xml.XmlException("Invalid data header " + HeaderIdentifier + ". It was expected to be \'P2P_DATA_DELIVERY_RESULT\'"));
                }
                else
                {
                    //**********************************************************
                    //retrieves the data operation type
                    //**********************************************************

                    string P2PDataOperationID = "";
                    P2PDataOperationID = m_xmlr.GetAttribute("P2PDataOperationID");
                    if (P2PDataOperationID == null)
                    {
                        P2PDataOperationID = Guid.NewGuid().ToString();
                    }

                    string DeliveryResultType = "";
                    DeliveryResultType = m_xmlr.GetAttribute("DeliveryResultType");
                    if (DeliveryResultType == null)
                    {
                        DeliveryResultType = "DeliverySucceed";
                    }

                    //**********************************************************
                    //retrieves the data itself
                    //**********************************************************
                    m_xmlr.Read();
                    string       dataSectionName = m_xmlr.Name;
                    DataVariable variable;
                    if (dataSectionName == "DATA")
                    {
                        string variableXMLstring = m_xmlr.ReadOuterXml();
                        variable = XMLDataFormatting.RetrieveDataVariableFromXMLString(variableXMLstring);
                    }
                    else
                    {
                        throw (new Exception("Invalid data XML section name \'" + dataSectionName + "\'. Is expected to be \'DATA\'"));
                    }
                    string errorMEssage = System.Convert.ToString(variable.Data);

                    P2PDataDeliveryResult result = null;
                    switch (DeliveryResultType)
                    {
                    case "DeliveryFailure":
                        result = P2PDataDeliveryResult.GetFailureDeliveryResult(P2PDataOperationID, errorMEssage);
                        break;

                    case "DeliverySucceed":
                        result = P2PDataDeliveryResult.GetSucceedDeliveryResult(P2PDataOperationID);
                        break;
                    }
                    return(result);
                }
            }
Ejemplo n.º 37
0
        public ListSet ListSets(ResumptionToken objToken, ref Object objHandler)
        {
            System.IO.Stream objStream;
            OAI_LIST objRecord;
            ListSet objList = new ListSet();
            ResumptionToken myToken;
            string tmp = "";
            System.Net.HttpWebRequest wr;
            System.Xml.XmlTextReader rd;

            if (objToken == null)
            {
                prequestURL = baseURL + "?verb=ListSets";
            }
            else
            {
                prequestURL = baseURL + "?verb=ListSets&resumptionToken=" + objToken.resumptionToken;
                //This is where we handle the resumptionToken
            }
            //======================================================
            // If you wanted to support additional metadata formats,
            // you would just need to have additional handlers.
            //======================================================

            try
            {
                wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL);
                wr.UserAgent = cUserAgent;
                System.Net.WebResponse response = wr.GetResponse();
                objStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(objStream);
                prawXML = reader.ReadToEnd();
                reader.Close();
                rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null);
            }
            catch (Exception e)
            {
                error.errorName = e.ToString();
                error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL;
                return null;
            }

            while (rd.Read())
            {
                if (rd.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (rd.Name == "responseDate")
                    {
                        presponseDate = rd.ReadString();
                    }
                    else if (rd.Name == "ListSets")
                    {
                        //while (rd.Read())
                        do
                        {
                            if (rd.Name == "set")
                            {
                                objRecord = new OAI_LIST(rd.ReadInnerXml(), ref objHandler);
                                objList.listset.Add(objRecord);
                                //return objRecord;
                            }
                            else if (rd.Name == "resumptionToken")
                            {
                                tmp = rd.ReadOuterXml();
                                myToken = new ResumptionToken(tmp);
                                objList.token = myToken;
                            }
                            else rd.Read(); // Added the Read() and will never occur with the ReadInnerXml()

                        } while (rd.Name != "ListSets"); // loop
                    }
                    else if (rd.Name == "error")
                    {
                        error.errorName = rd.GetAttribute("code");
                        error.errorDescription = rd.ReadString();
                        return null;
                    }
                }
            }

            rd.Close();
            return objList;
        }
            internal static P2PDataRequestFailure ParseAndGet_P2PDataRequestFailure_FromXMLDataString(string XMLString)
            {
                System.IO.StringReader   sr     = null;
                System.Xml.XmlTextReader m_xmlr = null;

                try
                {
                    sr     = new System.IO.StringReader(XMLString);
                    m_xmlr = new System.Xml.XmlTextReader(sr);
                    m_xmlr.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                }
                catch (System.Xml.XmlException)
                {
                    string msg;
                    msg = "Error trying to get XML format from  P2PDataRequest Data string [" + XMLString + "]";
                }
                catch (Exception ex)
                {
                    string msg = "";
                    msg = "Error trying to parse P2PDataRequest  XML string : " + ex.Message;
                    throw (new Exception(msg));
                }
                m_xmlr.Read();
                string HeaderIdentifier = m_xmlr.Name;

                if (HeaderIdentifier != "P2P_DATA_REQUEST_FAILURE")
                {
                    throw (new System.Xml.XmlException("Invalid P2PDataRequestFailure header \'" + HeaderIdentifier + "\'. It was expected to be \'P2P_DATA_REQUEST_FAILURE\'"));
                }
                else
                {
                    //**********************************************************
                    //retrieves the data operation type
                    //**********************************************************
                    string P2PDataOperationID = "";
                    P2PDataOperationID = m_xmlr.GetAttribute("P2PDataOperationID");
                    if (P2PDataOperationID == null)
                    {
                        P2PDataOperationID = Guid.NewGuid().ToString();
                    }

                    //**********************************************************
                    //retrieves the data that holds the error message
                    //**********************************************************
                    m_xmlr.Read();
                    string       dataSectionName = m_xmlr.Name;
                    DataVariable variable        = default(DataVariable);
                    if (dataSectionName == "DATA")
                    {
                        string variableXMLstring = m_xmlr.ReadOuterXml();
                        variable = XMLDataFormatting.RetrieveDataVariableFromXMLString(variableXMLstring);
                    }
                    else
                    {
                        throw (new Exception("Invalid data XML section name \'" + dataSectionName + "\'. Is expected to be \'DATA\'"));
                    }
                    string errorMEssage = System.Convert.ToString(variable.Data);

                    //creates the object to return to caller
                    P2PDataRequestFailure reqFailure = new P2PDataRequestFailure(P2PDataOperationID, errorMEssage);
                    return(reqFailure);
                }
            }
Ejemplo n.º 39
0
        public OAI_Header(string sXML)
        {
            System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(sXML, System.Xml.XmlNodeType.Element, null);
            while (reader.Read() && reader.Name != "header") ;  // Keep searching until finding header

            if (reader.Name == "header")
            {
                status = reader.GetAttribute("status");

                while (reader.Read())
                {
                    switch (reader.Name)
                    {
                        case "identifier":
                            if (identifier.Length == 0)   // In case this is the DC indentifier
                                identifier = reader.ReadString();
                            break;
                        case "datestamp":
                            datestamp = reader.ReadString();
                            break;
                        case "setSpec":
                            setSpec.Add(reader.ReadString());
                            break;
                    }
                }
            }
        }
Ejemplo n.º 40
0
        /// <summary>
        /// deserialize xml document to name and description and optionally fill stream with content
        /// </summary>
        /// <param name="xml">xml containing data</param>
        /// <param name="name">Name attribute in xml</param>
        /// <param name="description">description attribute</param>
        /// <param name="outputStream">null if no content is not required</param>
        public static void XmlToTempFile(string xml, string tmpFilePath, out string name, out string description, out FluidTrade.Reporting.Interfaces.IStaticReportTranslation translator)
        {
            Stream outputStream = null;

            if (string.IsNullOrEmpty(tmpFilePath) == false)
            {
                outputStream = File.Open(tmpFilePath, FileMode.CreateNew);
            }
            name        = null;
            description = null;
            string base64File = null;
            string base64TranslationContent = null;

            translator = null;
            //create the xmlReader to walk the xml doc
            using (StringReader stringReader = new StringReader(xml))
            {
                using (System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(stringReader))
                {
                    xmlReader.WhitespaceHandling = System.Xml.WhitespaceHandling.Significant;
                    //read to get to the first node
                    xmlReader.Read();

                    //get the name and description attributes
                    name        = xmlReader.GetAttribute(Name);
                    description = xmlReader.GetAttribute(Description);


                    if (outputStream == null)
                    {
                        return;                        //dont need to do anymore
                    }
                    //get to the content
                    xmlReader.Read();
                    base64File = xmlReader.ReadElementContentAsString();

                    //get to the translator
                    if (xmlReader.NodeType != System.Xml.XmlNodeType.EndElement)
                    {
                        xmlReader.Read();
                        base64TranslationContent = xmlReader.ReadContentAsString();
                    }
                    xmlReader.ReadEndElement();
                }
            }

            //if no outputStream or no content in xml then nothing left to do
            if (outputStream == null || string.IsNullOrEmpty(base64File))
            {
                return;
            }

            //convert the content to bytes
            Byte[] bytes = Convert.FromBase64String(base64File);

            //write the bytes to the stream
            using (BinaryWriter binWriter = new BinaryWriter(outputStream))
            {
                binWriter.Write(bytes);
                binWriter.Flush();
            }


            if (string.IsNullOrEmpty(base64TranslationContent) == false)
            {
                //convert the content to bytes
                Byte[] translationBytes = Convert.FromBase64String(base64TranslationContent);

                System.Reflection.Assembly translationAssembly = AppDomain.CurrentDomain.Load(translationBytes);
                Type[] types = translationAssembly.GetTypes();
                foreach (Type t in types)
                {
                    if (t.GetInterface("FluidTrade.Reporting.Interfaces.IStaticReportTranslation") != null)
                    {
                        translator = Activator.CreateInstance(t) as FluidTrade.Reporting.Interfaces.IStaticReportTranslation;
                        break;
                    }
                }
            }
        }
Ejemplo n.º 41
0
 public ResumptionToken(string sXML)
 {
     System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(sXML, System.Xml.XmlNodeType.Element, null);
     while (reader.Read())
     {
         if (reader.Name == "resumptionToken")
         {
             expirationDate = reader.GetAttribute("expirationDate");
             completeListSize = reader.GetAttribute("completeListSize");
             cursor = reader.GetAttribute("cursor");
             resumptionToken = reader.ReadString();
         }
     }
 }
        /// <summary>
        /// Load options.
        /// </summary>
        /// <param name="filePath">File name to load options from.</param>
        private void DoDeserialize(string filePath)
        {
            if (System.IO.File.Exists(filePath))
            {
                global::System.IO.FileStream fileStream = null;
                try
                {
                    fileStream = global::System.IO.File.OpenRead(filePath);
                    if (fileStream.Length > 5)
                    {
                        using (global::System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(fileStream))
                        {
                            try
                            {
                                reader.MoveToContent();

                                // read attributes
                                string valueE = reader.GetAttribute("errorCategoryVisible");
                                if (valueE != null)
                                    this.ErrorCategoryVisible = Boolean.Parse(valueE);

                                string valueW = reader.GetAttribute("warningCategoryVisible");
                                if (valueW != null)
                                    this.WarningCategoryVisible = Boolean.Parse(valueW);

                                string valueI = reader.GetAttribute("infoCategoryVisible");
                                if (valueI != null)
                                    this.InfoCategoryVisible = Boolean.Parse(valueI);

                                string valueF = reader.GetAttribute("filteredCategoryVisible");
                                if (valueF != null)
                                    this.FilteredCategoryVisible = Boolean.Parse(valueF);

                                while (reader.Read())
                                {
                                    switch (reader.NodeType)
                                    {
                                        case System.Xml.XmlNodeType.Element:
                                            {
                                                DeserializeElement(reader, reader.Name);
                                                break;
                                            }
                                    }
                                }
                            }
                            finally
                            {
                                fileStream = null;
                            }
                        }
                    }
                }
                finally
                {
                    if (fileStream != null)
                        fileStream.Dispose();
                }
            }
        }
 //Method two: Get is medium trust (get if config is set as medium trust)
 private static bool IsMediumTrustSetInConfig()
 {
     bool result = false;
     try
     {
         string webConfigFile = System.IO.Path.Combine(System.Web.HttpContext.Current.Request.PhysicalApplicationPath, "web.config");
         System.Xml.XmlTextReader webConfigReader = new System.Xml.XmlTextReader(new System.IO.StreamReader(webConfigFile));
         webConfigReader.ReadToFollowing("trust");
         result = webConfigReader.GetAttribute("level") == "Medium";
         webConfigReader.Close(); //Close before return
         return result;
     }
     catch
     {
         return result;
     }
 }