Example #1
16
    public static string MetaBuild()
    {
        var sb = new StringBuilder();

            sb.AppendLine("\\\\ hello");

            foreach (var proj in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.*proj"))
            {
                sb.AppendLine("\\\\ file: " + proj);

                var xml = new XmlDocument();
                xml.Load(proj);
                var nm = new XmlNamespaceManager(xml.NameTable);
                nm.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");

                foreach (var reference in xml.SelectNodes(@"x:Project\x:ItemGroup\x:Reference"))
                {
                    sb.AppendLine("\\\\" + reference);
                }
                foreach (var reference in xml.SelectNodes(@"x:Project\x:ItemGroup\x:Reference"))
                {
                    sb.AppendLine("\\\\" + reference);
                }
            }
            return sb.ToString();
    }
Example #2
8
    static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();
        for (int i = 0; i < files.Length; ++i)
        {
            doc.Load(files[i]);
            List<double> tt = new List<double>();

            foreach (XmlElement timing in doc.SelectNodes("//timing"))
            {
                double val = Convert.ToDouble(timing.GetAttribute("nanosecondsPerLog"), CultureInfo.InvariantCulture);
                tt.Add(val);
            }
            timings.Add(tt);
        }
        int ordinal = 0;

        foreach (XmlElement el in doc.SelectNodes("//timing"))
        {
            string section = ((XmlElement)el.ParentNode).GetAttribute("logger");

            if (ordinal % 4 == 0)
            {
                Console.WriteLine();
                Console.WriteLine("\"{0}\"\t\"NLog\"\t\"Log4Net\"", section);
            }
            Console.Write("\"{0}\"", el.GetAttribute("name"));
            for (int i = 0; i < files.Length; ++i)
            {
                Console.Write("\t{0}",Math.Round(timings[i][ordinal],3));
            }
            Console.WriteLine();
            ordinal++;
        }
    }
Example #3
5
    protected void btn_login_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("~/XML/User.xml"));

        XmlNode root = doc.DocumentElement;

        XmlNodeList nodes_name = doc.SelectNodes("/users/user/name");
        XmlNodeList nodes_pwd = doc.SelectNodes("/users/user/pwd");

        // Kaksoiserittelyn takia mikä tahansa username/password kombinaatio toimii -> korjaukseen
        ReadXmlNodesNames(nodes_name);
        ReadXmlNodesPwd(nodes_pwd);

        if (Session["Username"] != null && Session["Pwd"] != null)
        {
            lbl_success.Text = "Successfully logged in.";
            Session["Login"] = true;
        }
        else
        {
            lbl_success.Text = "Failed to login.";
        }

        /*    if (name == txt_name.Text && pwd == txt_pwd.Text)
        {
            lbl_success.Text = "Successful login.";
        }
        else
        {
            lbl_success.Text = name;
           // lbl_success.Text = "Login failed.";
        }
         */
    }
Example #4
3
        /// <summary>
    /// 根据权限初始化菜单
    /// </summary>
    /// <param name="xmlDoc"></param>
    private XmlDocument InitRightMenu(XmlDocument xmlDoc)
    {
        if (IsVisitor)//--如果是访客则只有总线概况、服务管理两个模块的权限
        {
            foreach (XmlNode node in xmlDoc.SelectNodes("/Demos/DemoGroup"))
            {
                if (node.Attributes["Text"].Value != "总线概况" &&
                    node.Attributes["Text"].Value != "服务管理")
                {
                    node.ParentNode.RemoveChild(node);
                }
            }
        }
        else
        {
            if (!IsSystemAdmin)
            {
                foreach (XmlNode node in xmlDoc.SelectNodes("/Demos/DemoGroup"))
                {
                    if (node.Attributes["Text"].Value == "系统管理")
                    {
                        node.ParentNode.RemoveChild(node);
                    }
                }
            }
        }
        

        return xmlDoc;
    }
Example #5
0
 public XmlNodeList DatasourceforRepeater(string strHtml)
 {
     XmlDocument xmlDoc = new XmlDocument();
     xmlDoc.LoadXml(strHtml);
     XmlNodeList xml = xmlDoc.SelectNodes("root");
     XmlNodeList xn = xmlDoc.SelectNodes("root/AddContacts");
     return xml;
 }
Example #6
0
 /// <summary>
 /// XML文档转换成JSON数据
 /// </summary>
 /// <param name="xmldoc">XML数据文件</param>
 /// <returns>返回JSON格式数据记录,以数组方式返回</returns>
 public static string ToJson(XmlDocument xmldoc)
 {
     if (null == xmldoc || null == xmldoc.DocumentElement)
         return "";
     XmlNode xn = xmldoc.SelectSingleNode("/././.");
     if (null == xn)
         return "[]";
     List<string> tables = new List<string>();
     XmlNodeList xnlist = xmldoc.SelectNodes("/./.");
     tables.Add(xnlist[0].Name);
     foreach (XmlNode xnnode in xnlist)
     {
         bool isexist = false;
         foreach (string t in tables)
         {
             isexist = xnnode.Name == t;
             if (isexist) break;
         }
         if (isexist) continue;
         tables.Add(xnnode.Name);
     }
     StringBuilder sb = new StringBuilder();
     string ft = "\"{0}\":\"{1}\"";
     if (tables.Count > 1)
         sb.Append("{");
     foreach (string t in tables)
     {
         if (tables.Count > 1)
         {
             if (t == tables[0])
                 sb.AppendFormat("\"{0}\":", t);
             else
                 sb.AppendFormat(",\"{0}\":", t);
         }
         XmlNodeList xnrowlist = xmldoc.SelectNodes("/./" + t);
         sb.Append("[");
         foreach (XmlNode xnrow in xnrowlist)
         {
             if (xnrowlist[0] == xnrow)
                 sb.Append("{");
             else
                 sb.Append(",{");
             if (null != xnrow.FirstChild)
                 sb.AppendFormat(ft, xnrow.FirstChild.Name, xnrow.FirstChild.InnerText.Replace("\"", "\\\""));
             for (int i = 1; i < xnrow.ChildNodes.Count; i++)
                 sb.AppendFormat("," + ft, xnrow.ChildNodes[i].Name, xnrow.ChildNodes[i].InnerText.Replace("\"", "\\\""));
             sb.Append("}");
         }
         sb.Append("]");
     }
     if (tables.Count > 1)
         sb.Append("}");
     return sb.ToString();
 }
Example #7
0
    public Cartelera getCartelCine()
    {
        doc = new XmlDocument();
        try
        {
            doc.Load("http://www.cinepolis.com.mx/iphone/xml-iphone.aspx?query=cartelera&ci=" + cartel.CiudadID);
        }
        catch (Exception e) { return null; }

        try
        {
            complejoInfo = doc.SelectSingleNode("//Cartelera//Complejo[@Complejoid='" + cartel.ComplejoID + "']");
            cartel.Complejo = complejoInfo.Attributes.GetNamedItem("Nombre").Value;
            cartel.Latitud = complejoInfo.ChildNodes[1].InnerText.Trim();
            cartel.Longitud = complejoInfo.ChildNodes[2].InnerText.Trim();

            Complejos_peli = doc.SelectNodes("//Cartelera//Complejo[@Complejoid='" + cartel.ComplejoID + "']/Pelicula");
            foreach (XmlNode complejo_peli in Complejos_peli)
            {
                peli = new Pelicula();
                string Horario_Peli = "";
                peli.PeliculaID = complejo_peli.FirstChild.InnerText;

                Complejos_hora = doc.SelectNodes("//Cartelera//Complejo/Pelicula[Peliculaid='" + peli.PeliculaID + "']/Horarios/Horario");
                foreach (XmlNode horario in Complejos_hora)
                {
                    Horario_Peli += horario.InnerText + " - ";
                }

                peliculaInfo = doc.SelectSingleNode("//Peliculas//Pelicula[@Peliculaid='" + peli.PeliculaID + "']");

                peli.Nombre = peliculaInfo.Attributes.GetNamedItem("Nombre").Value;
                peli.Clasificacion = peliculaInfo.ChildNodes[1].InnerText;
                peli.Calificacion = peliculaInfo.ChildNodes[4].InnerText;
                peli.Descripcion = peliculaInfo.ChildNodes[6].InnerText;
                peli.Director = peliculaInfo.ChildNodes[7].InnerText;
                peli.Actor = peliculaInfo.ChildNodes[8].InnerText;
                peli.Duracion = peliculaInfo.ChildNodes[16].InnerText;
                peli.Trailer = peliculaInfo.ChildNodes[19].InnerText;
                peli.Horarios = Horario_Peli;

                cartel.Peliculas.Add(peli);

            }
        }
        catch (Exception e) { return null;}
        return cartel;
    }
    static void Main(string[] args)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(@"..\..\..\catalogue.xml");

        var artists = new Dictionary<string, int>();
        string XPath = "/catalogue/album/artist";
        XmlNodeList artistsList = doc.SelectNodes(XPath);

        foreach (XmlNode node in artistsList)
        {
            if(!artists.ContainsKey(node.InnerText))
            {
                artists.Add(node.InnerText, 1);
            }else
            {
                artists[node.InnerText]++;
            }
        }

        foreach (var artist in artists)
        {
            Console.WriteLine("{0} - {1}", artist.Key, artist.Value);
        }
    }
Example #9
0
    static void Main()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("../../../catalog.xml");
        string xPathQuery = "/catalog/album";

        XmlNodeList albumsList = xmlDoc.SelectNodes(xPathQuery);
        Hashtable hash = new Hashtable();
        List<string> autors = new List<string>();

        foreach (XmlNode node in albumsList)
        {
            string autorName = node.SelectSingleNode("artist").InnerText;
            if (!hash.ContainsKey(autorName))
            {
                hash.Add(autorName,1);
                autors.Add(autorName);
            }
            else
            {
                int count = (int)hash[autorName];
                hash[autorName] = count + 1;
            }
        }

        foreach (var autor in autors)
        {
            Console.WriteLine("Autor: {0} have {1} albums in the catalog.", autor, hash[autor]);
        }
    }
	private static void postProcessWP8Build(string pathToBuiltProject) {
		string manifestFilePath = Path.Combine( Path.Combine (pathToBuiltProject, PlayerSettings.productName), "Properties/WMAppManifest.xml");

		if (!File.Exists (manifestFilePath)) {
			UnityEngine.Debug.LogError ("Windows Phone manifest not found: " + manifestFilePath);
			return;
		}

		XmlDocument manifest = new XmlDocument ();
		manifest.Load(manifestFilePath);

		XmlNode capabilities = manifest.SelectSingleNode ("//Capabilities");
		XmlNodeList matchingCapability = manifest.SelectNodes("//Capability[@Name='ID_CAP_IDENTITY_DEVICE']");
		if (matchingCapability.Count == 0) {
			XmlElement newCapability = manifest.CreateElement("Capability");
			newCapability.SetAttribute("Name", "ID_CAP_IDENTITY_DEVICE");
			capabilities.AppendChild(newCapability);
		}

		matchingCapability = manifest.SelectNodes("//Capability[@Name='ID_CAP_PUSH_NOTIFICATION']");
		if (matchingCapability.Count == 0) {
			XmlElement newCapability = manifest.CreateElement("Capability");
			newCapability.SetAttribute("Name", "ID_CAP_PUSH_NOTIFICATION");
			capabilities.AppendChild(newCapability);
		}

		manifest.Save (manifestFilePath);

		UnityEngine.Debug.Log ("Windows Phone manifest sucessfully patched");
	}
    static void Main()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("../../bookmarks.xml");
        string xPathQuery = "/bookmarks/bookmark";

        XmlNodeList bookmarksList = xmlDoc.SelectNodes(xPathQuery);
        foreach (XmlNode bookmarkNode in bookmarksList)
        {
            string username = bookmarkNode.GetChildText("username");
            string title = bookmarkNode.GetChildText("title");
            string url = bookmarkNode.GetChildText("url");
            string allTags = bookmarkNode.GetChildText("tags");
            string notes = bookmarkNode.GetChildText("notes");

            //string[] tags = allTags.Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries);
            string[] tags = { };
            if (allTags != null)
            {
                tags = allTags.Split(',');

                for (int i = 0; i < tags.Length; i++)
                {
                    tags[i] = tags[i].Trim();
                }
            }
            //Console.WriteLine(username);

            AddBookmark(username, title, url, tags, notes);


        }
    }
Example #12
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (Session["Applicant"] == null)
     {
         Button_Submit.Visible = false;
     }
        var xmlDoc2 = new XmlDocument();
        //xmlDoc2.Load(@"E:\BU\2014spring\EC512\Project\Fullsite\FullSite1.0\Company\answers.xml");
        string location = Server.MapPath("~/Company/answers.xml");
        xmlDoc2.Load(@location);
        var nodes = xmlDoc2.SelectNodes("/Answers/AnswerSet[last()]/Answer");
        Label1.Text=nodes[0].InnerText;
        Label2.Text = nodes[1].InnerText;
        Label3.Text = nodes[2].InnerText;
        Label4.Text = nodes[3].InnerText;
        Label5.Text = nodes[4].InnerText;
        Label6.Text = nodes[5].InnerText;
        Label7.Text = nodes[6].InnerText;
        Label8.Text = nodes[7].InnerText;
        Label9.Text = nodes[8].InnerText;
        Label10.Text = nodes[9].InnerText;
        Label11.Text = nodes[10].InnerText;
        Label12.Text = nodes[11].InnerText;
        Label13.Text = nodes[12].InnerText;
        Label14.Text = nodes[13].InnerText;
        Label15.Text = nodes[14].InnerText;
        if (Session["Applicant"] != null)
        {
        SqlDataSource1.Insert();
        Response.Redirect("Applicant_Profile.aspx");
        }
 }
Example #13
0
    static void ComplexSearch(XmlTextWriter writer)
    {
        BookstoreEntities context = new BookstoreEntities();
        using (context)
        {
            XmlDocument doc = new XmlDocument();
            doc.Load(Bookstore.Data.Settings.Default.complexSearchReadFile);
            XmlNodeList queries = doc.SelectNodes("/review-queries/query");
            foreach (XmlNode query in queries)
            {
                string type = query.Attributes["type"].Value;
                if (type == "by-period")
                {
                    string start = query.SelectSingleNode("start-date").InnerText;
                    string end = query.SelectSingleNode("end-date").InnerText;
                    IList<Review> found =
                        BookstoreDAL.FindReviewPeriod(start, end, context);
                    WriteResultSet(writer, found);
                }
                else if (type == "by-author")
                {
                    string author = query.SelectSingleNode("author-name").InnerText;
                    IList<Review> found =
                        BookstoreDAL.FindReviewAuthor(author, context);
                    WriteResultSet(writer, found);
                }

                SearchLogsImporter.AddLog(DateTime.Now, query.OuterXml);
            }
        }
    }
Example #14
0
 protected void Page_Load(object sender, EventArgs e)
 {
     System.Net.WebClient wc = new System.Net.WebClient();
     string eksemmelle = "";
     wc.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
     try
     {
         eksemmelle = wc.DownloadString("http://www.hindu.com/rss/01hdline.xml");
     }
     catch (Exception e1)
     {
         ex = e1;
     }
     if (!string.IsNullOrEmpty(eksemmelle))
     {
         XmlDocument doc = new XmlDocument();
         doc.LoadXml(eksemmelle);
         XmlNodeList list = doc.SelectNodes("rss/channel/item");
         foreach (XmlNode node in list)
             RenderNewsItem(node.SelectSingleNode("title").InnerText, node.SelectSingleNode("link").InnerText, node.SelectSingleNode("description").InnerText, node.SelectSingleNode("pubDate").InnerText);
     }
     else
     {
         RenderNewsItem(ex.Message,ex.ToString(),ex.Message,"121212");
     }
 }
    static void Main()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("../../MoreBooks.xml");
        string xPathQuery = "/catalog/book";

        XmlNodeList booksList = xmlDoc.SelectNodes(xPathQuery);
        foreach (XmlNode bookNode in booksList)
        {
            XmlNodeList authorsNode = bookNode.SelectSingleNode("authors").SelectNodes("author");
            List<string> authors = new List<string>();
            foreach (XmlNode authorN in authorsNode)
            {
                authors.Add(authorN.GetChildAuthorText("author"));    
            }
            
            string title = bookNode.GetChildText("title");
            string isbn = bookNode.GetChildText("isbn");
            string price = bookNode.GetChildText("price");
            string website = bookNode.GetChildText("web-site");

            XmlNodeList reviewsNode = bookNode.SelectSingleNode("reviews").SelectNodes("review");
            List<Review> reviews = new List<Review>();
            foreach (XmlNode reviewN in reviewsNode)
            {
                
            }

            BookstoreDAL.AddBookComplex(authors, title, isbn, price, website);

        }


    }
Example #16
0
	void Awake ()
	{
		infoCarrier = GameObject.Find ("InfoCarrier");

		if (infoCarrier != null) {
			//Set text components
			LevelInfo ics = infoCarrier.GetComponent<LevelInfo> ();
			LevelText.text = string.Format ("{0}/{1}", 
			                               ics.CurrentLevel + 1, 
			                               ics.TotalLevels);

			XmlDocument xmlDoc = new XmlDocument ();

			//Load puzzles.xml
			xmlDoc.Load (Path.Combine (Application.persistentDataPath, "Puzzles.xml"));

			//Select first group, then pack and last level
			XmlNode level = xmlDoc.SelectNodes ("packs/packGroup") [ics.CurrentPack / 10].ChildNodes [ics.CurrentPack % 10].ChildNodes [ics.CurrentLevel];

			for (int i = 0; i < level.ChildNodes.Count; i++) {

				XmlNode ring = level.ChildNodes [i];
				for (int j = 0; j < ring.ChildNodes.Count; j++) {

					rings [i].GetChild (j).gameObject.GetComponent<SegmentColor> ().SetColor (int.Parse (ring.ChildNodes [j].InnerXml));
				}
			}
		}
	}
	public static void Main (string [] args)
	{
		bool outAll = false;
		bool details = false;
		bool stopOnError = false;
		string filter = null;
		foreach (string arg in args) {
			switch (arg) {
			case "--outall":
				outAll = true; break;
			case "--details":
				details = true; break;
			case "--stoponerror":
				stopOnError = true; break;
			default:
				filter = arg; break;
			}
		}

		try {
			XmlDocument doc = new XmlDocument ();
			doc.Load ("test/RNCTest.xml");
			int success = 0;
			int failure = 0;
			foreach (XmlElement el in doc.SelectNodes ("/RNCTestCases/TestCase")) {
				string id = el.GetAttribute ("id");
				if (filter != null && id.IndexOf (filter) < 0)
					continue;
				if (outAll)
					Console.WriteLine ("testing " + id);
				bool isValid = el.GetAttribute ("legal") == "true";
				RncParser p = new RncParser (new NameTable ());
				try {
					string s = new StreamReader ("test" + Path.DirectorySeparatorChar + el.GetAttribute ("path")).ReadToEnd ();
					p.Parse (new StringReader (s));
					if (isValid) {
						success++;
//						Console.Error.WriteLine ("valid " + id);
					} else {
						failure++;
						Console.Error.WriteLine ("INCORRECTLY VALID   " + id);
					}
				} catch (Exception ex) {
					if (isValid) {
						if (stopOnError)
							throw;
						failure++;
						Console.Error.WriteLine ("INCORRECTLY INVALID " + id + " --> " + (details ? ex.ToString () : ex.Message));
					} else {
						success++;
//						Console.Error.WriteLine ("invalid " + id);
					}
				}
			}
			Console.Error.WriteLine ("Total success: " + success);
			Console.Error.WriteLine ("Total failure: " + failure);
		} catch (Exception ex) {
			Console.Error.WriteLine ("Unexpected Exception: " + ex);
		}
	}
Example #18
0
 protected void Button1_Click(object sender, EventArgs e)
 {
     XmlDocument document = new XmlDocument();
     string serverPath = Public.GetServerPath();
     document.Load(serverPath + @"\\bin\\DataMessage.xml");
     foreach (XmlNode node in document.SelectNodes("/DataMessage/DataTableItem"))
     {
         XmlElement element = (XmlElement)node;
         if (element.GetAttribute("TableName") == this.txtTableNameVal.Value.Trim())
         {
             element.SetAttribute("TableName", this.txtTableName.Text.Trim());
             element.SetAttribute("Text", this.txtTableChina.Text.Trim());
             foreach (XmlNode node2 in element.ChildNodes)
             {
                 XmlElement element2 = (XmlElement)node2;
                 if (element2.GetAttribute("ColumnName") == this.txtColNameVal.Value.Trim())
                 {
                     element2.InnerText = this.txtColChina.Text.Trim();
                     element2.SetAttribute("ColumnName", this.txtColName.Text.Trim());
                     element2.SetAttribute("ColumnType", this.ddlDataType.SelectedValue);
                     break;
                 }
             }
             break;
         }
     }
     document.Save(serverPath + @"\\bin\\DataMessage.xml");
     Public.Show("修改成功!");
     this.ClearForm();
     this.BindTableMess();
     this.ddlTableName_SelectedIndexChanged(sender, e);
 }
    public void SetAppTypeProduct()
    {
        try
        {
            XmlDocument doc = new XmlDocument();
            string xpath = Server.MapPath("../data/xml/configproduct.xml");
            XmlTextReader reader = new XmlTextReader(xpath);
            doc.Load(reader);
            reader.Close();
            XmlNodeList nodes = doc.SelectNodes("/root/product");
            int numnodes = nodes.Count;
            for (int i = 0; i < numnodes; i++)
            {
                string nameapp = nodes.Item(i).ChildNodes[0].InnerText;
                string idtype = nodes.Item(i).ChildNodes[1].InnerText;
                string appunit = nodes.Item(i).ChildNodes[2].InnerText;
                string unit = nodes.Item(i).ChildNodes[3].InnerText;
                if (nameapp.Length > 0 && idtype.Length > 0)
                {
                    Application[nameapp] = int.Parse(idtype);
                }
                if (appunit.Length > 0 && unit.Length > 0)
                {
                    Application[appunit] = unit;
                }
            }
        }
        catch
        {

        }
    }
Example #20
0
    void OnTriggerEnter2D(Collider2D collisionInfo)
    {
        if (collisionInfo.tag == "Player")
        {
            //---Get Item info---
            //Read in Items.xml
            XmlDocument ItemsDoc = new XmlDocument();
            ItemsDoc.LoadXml(Resources.Load("ItemFile/Items").ToString());

            foreach (XmlNode node in ItemsDoc.SelectNodes("Items/ItemsList/Item")) //Get info of ItemID
            {
                if (this.name.Contains(node.SelectSingleNode("ObjectName").InnerText) == true) //if (this.name == node.SelectSingleNode("ObjectName").InnerText)
                {
                    ItemID = int.Parse(node.SelectSingleNode("ID").InnerText);
                    ItemName = node.SelectSingleNode("Name").InnerText;
                    break;
                }
            }

            //---Show "press x to pick up item"---
            TextMessage.text = "Press X to pick up " + ItemName; //<- Do Keyboard or xbox controller button
            TextMessage.gameObject.SetActive(true);

            //enable pickup
            PressToPickUp = true;
        }
    }
Example #21
0
    /* This method extracts the data from the temporary XML object and places it
     * in runtime movement object that will be processed on the spot.
    */
    IEnumerator ExtractMovement(XmlDocument xml)
    {
        Movement movement;

        //Set the name of the test being run in the global variable
        gs.setTestName(xml.SelectSingleNode("Test/Name").InnerText);

        //Move through each tagged item within the xml document
        foreach (XmlNode node in xml.SelectNodes("Test/Movement")){
            movement = new Movement();

            //Extract and assign tagged items within the xmlDoc to object variables within Movement class
            movement.MovementID = node.SelectSingleNode("MovementId").InnerText;
            movement.MovementDesc = node.SelectSingleNode("MovementDesc").InnerText;

            //Assign MovementDetails to Movement Class variables
            foreach (XmlNode detail in node.SelectNodes("MovementDetail")){
                movement.Sequence = detail.SelectSingleNode("SequenceId").InnerText;
                movement.Path = detail.SelectSingleNode("Path").InnerText;
                movement.PathDesc = detail.SelectSingleNode("PathDesc").InnerText;
                movement.Gait = detail.SelectSingleNode("Gait").InnerText;

                //Call LoadMovement Coroutine method and pass movement object
                //and wait for the finish of Coroutine to process further information.
                yield return StartCoroutine(ProcessMovement(movement));
            }
        }
    }
Example #22
0
    /* 11. Write a program, which extract from the file catalog.xml the prices for all albums,
     * published 5 years ago or earlier. Use XPath query.*/

    static void Main(string[] args)
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("../../catalog.xml");
        string xPathQuery = "/catalog/album";

        XmlNodeList albums = xmlDoc.SelectNodes(xPathQuery);

        var prices = new List<decimal>();

        foreach (XmlNode album in albums)
        {
            var year = int.Parse(album.SelectSingleNode("year").InnerText);
            var publishDate = new DateTime(year, 1, 1);
            if (DateTime.Now.Year - publishDate.Year > 5)
            {
                prices.Add(decimal.Parse(album.SelectSingleNode("price").InnerText));
            }
        }

        foreach (var price in prices)
        {
            Console.WriteLine(price);
        }
    }
    private void FillLanguageDDL()
    {
        string LngFile = string.Empty;
        XmlDocument XmlDoc;
        XmlNodeList ObjXmlNodeList;
        int i = 1;

        try
        {
            LngFile = Path.Combine(HttpContext.Current.Request.PhysicalApplicationPath, ConfigurationManager.AppSettings[Constants.WebConfigKey.LanguageFile]);
            XmlDoc = new XmlDocument();
            XmlDoc.Load(LngFile);

            ObjXmlNodeList = XmlDoc.SelectNodes("/" + Constants.XmlFile.Language.Tags.Root + "/" + "child::node()");

            ddlLanguage.Items.Clear();
            ddlLanguage.Items.Insert(0, new ListItem("-- Select Language --", "-1"));

            foreach (XmlNode data in ObjXmlNodeList)
            {
                ddlLanguage.Items.Insert(i, new ListItem(data.Attributes[Constants.XmlFile.Language.Tags.LanguageAttributes.Name].Value, data.Attributes[Constants.XmlFile.Language.Tags.LanguageAttributes.Code].Value));
                i++;
            }
        }
        catch (Exception ex)
        {
            Global.CreateExceptionString(ex, null);
        }
    }
Example #24
0
    public static List<LeftMenu> Load()
    {
        XmlDocument xml = new XmlDocument();
            xml.Load(HttpContext.Current.Request.PhysicalApplicationPath + "/App_Data/Menu.config");
            List<LeftMenu> menus = new List<LeftMenu>();
            XmlNodeList menuNodes = xml.SelectNodes("Menus/Menu");
            foreach (XmlNode menuNode in menuNodes)
            {
                LeftMenu menu = new LeftMenu();
                menu.Code = menuNode.Attributes["code"].Value;
                menu.Title = menuNode.Attributes["title"].Value;
                menu.Href = menuNode.Attributes["href"].Value;
                menu.Img = menuNode.Attributes["img"].Value;

                foreach (XmlNode linkNode in menuNode.ChildNodes)
                {
                    MenuLink link = new MenuLink();
                    link.Code = linkNode.Attributes["code"].Value;
                    link.Title = linkNode.Attributes["title"].Value;
                    link.Href = linkNode.Attributes["href"].Value;
                    menu.Links.Add(link);
                }
                menus.Add(menu);
            }
            return menus;
    }
    //Write a program, which extract from the file catalog.xml
    //the prices for all albums, published 5 years ago or earlier. Use XPath query.
    static void Main()
    {
        string fileLocation = @"..\..\catalogue.xml";
        XmlDocument doc = new XmlDocument();
        doc.Load(fileLocation);
        Console.WriteLine("Document Loaded");

        string xPathQuery = "/Catalogue/Artist/Album";

        XmlNodeList artistList = doc.SelectNodes(xPathQuery);
        Dictionary<string, int> albumsDic = new Dictionary<string, int>();

        foreach (XmlNode node  in artistList)
        {
            var albumName = node.Attributes["name"].Value;
            int year = int.Parse(node["Year"].InnerText);
            int currentYear = DateTime.Now.Year;

            if ((currentYear - year) <= 5)
            {
                var price = node["Price"].InnerText;
                Console.WriteLine("The Album: {0} price is {1}",albumName,price);
            }
        }
    }
    static void Main()
    {
        XmlDocument xml = new XmlDocument();
        xml.Load("../../../xml/catalogue.xml");

        string artistsQuery = "/albums/album/artist";

        XmlNodeList artistList = xml.SelectNodes(artistsQuery);

        var artistMap = new Dictionary<string, int>();

        foreach (XmlNode artist in artistList)
        {
            var name = artist.InnerText;
            if (!artistMap.ContainsKey(name))
            {
                artistMap.Add(name, 1);
            }
            else
            {
                artistMap[name]++;
            }
        }

        foreach (var artist in artistMap)
        {
            Console.WriteLine("{0} --> {1}", artist.Key, artist.Value);
        }
    }
    protected void btnHashkirjaudu_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(Server.MapPath("~/App_Data/Tunnukset.xml"));
        String hash = txtHashkayttaja.Text + txtHashsala.Text;
        var md5 = MD5.Create();
        byte[] hashed = md5.ComputeHash(Encoding.UTF8.GetBytes(hash));

        //create new instance of StringBuilder to save hashed data
        StringBuilder returnValue = new StringBuilder();

        //loop for each byte and add it to StringBuilder
        for (int i = 0; i < hashed.Length; i++)
        {
            returnValue.Append(hashed[i].ToString());
        }

        // return hexadecimal string
        var  hashash = returnValue.ToString();
        foreach (XmlNode node in doc.SelectNodes("//Tunnukset"))
        {
            String username = node.SelectSingleNode("//kayttaja").InnerText;
            String password = node.SelectSingleNode("//sala").InnerText;

            if(username == txtHashkayttaja.Text && password == hashash)
            {
                Response.Redirect("G2559_WanhatAutotMuokkaus.aspx");
            }
            else
            {
                lblHashkirjautuminen.Text = "Invalid login details. Please try again.";
            }
        }
    }
Example #28
0
    public override void LoadWidget()
    {
        StringDictionary settings = GetSettings();
        XmlDocument doc = new XmlDocument();

        if (settings["content"] != null)
          doc.InnerXml = settings["content"];

        XmlNodeList links = doc.SelectNodes("//link");

        if (links.Count == 0)
        {
            ulLinks.Visible = false;
        }
        else
        {
            foreach (XmlNode node in links)
            {
                HtmlAnchor a = new HtmlAnchor();

                if (node.Attributes["url"] != null)
                    a.HRef = node.Attributes["url"].InnerText;

                if (node.Attributes["title"] != null)
                    a.InnerText = node.Attributes["title"].InnerText;

                if (node.Attributes["newwindow"] != null && node.Attributes["newwindow"].InnerText.Equals("true", StringComparison.OrdinalIgnoreCase))
                    a.Target = "_blank";

                HtmlGenericControl li = new HtmlGenericControl("li");
                li.Controls.Add(a);
                ulLinks.Controls.Add(li);
            }
        }
    }
    static void Main()
    {
        //Open xml file
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("../../simple-books.xml");

        //Create query to xml file
        string xPathQuery = "/catalog/book";
        XmlNodeList bookList = xmlDoc.SelectNodes(xPathQuery);
        foreach (XmlNode bookNode in bookList)
        {
            //Read inforamtion from xml file for each book
            string author = bookNode.GetChildText("author");
            ArgumentExceptionThrower(author, "author");

            string title = bookNode.GetChildText("title");
            ArgumentExceptionThrower(title, "title");

            string isbnAsString = bookNode.GetChildText("isbn");
            long? isbn = (isbnAsString != null) ? long.Parse(isbnAsString) : (long?)null;
            string priceAsString = bookNode.GetChildText("price");
            decimal? price = (priceAsString != null) ? decimal.Parse(priceAsString) : (decimal?)null;

            //Save the book in Bookstore database
            BookstoreDAL.AddBook(title, author, isbn, price);
        }
    }
        internal async Task <Dictionary <uint, string> > GetOwnedGames()
        {
            if (!await RefreshSessionIfNeeded().ConfigureAwait(false))
            {
                return(null);
            }

            string request = SteamCommunityURL + "/my/games/?xml=1";

            XmlDocument response = await WebBrowser.UrlGetToXMLRetry(request).ConfigureAwait(false);

            XmlNodeList xmlNodeList = response?.SelectNodes("gamesList/games/game");

            if ((xmlNodeList == null) || (xmlNodeList.Count == 0))
            {
                return(null);
            }

            Dictionary <uint, string> result = new Dictionary <uint, string>(xmlNodeList.Count);

            foreach (XmlNode xmlNode in xmlNodeList)
            {
                XmlNode appNode = xmlNode.SelectSingleNode("appID");
                if (appNode == null)
                {
                    Logging.LogNullError(nameof(appNode), Bot.BotName);
                    return(null);
                }

                uint appID;
                if (!uint.TryParse(appNode.InnerText, out appID))
                {
                    Logging.LogNullError(nameof(appID), Bot.BotName);
                    return(null);
                }

                XmlNode nameNode = xmlNode.SelectSingleNode("name");
                if (nameNode == null)
                {
                    Logging.LogNullError(nameof(nameNode), Bot.BotName);
                    return(null);
                }

                result[appID] = nameNode.InnerText;
            }

            return(result);
        }
Example #31
0
        public bool ParseNext()
        {
            try
            {
                if (DocumentProperties == null)
                {
                    DocumentProperties = ItemFactory.CreateDocumentProperties();
                }
                Output.Initialize(DocumentProperties);

                var fileInfo = ItemFactory.CreateFileProperties();
                fileInfo.FileConversionProperties = _fileProperties.FileConversionProperties;
                Output.SetFileProperties(fileInfo);

                var segNodes = _trgDocument?.SelectNodes("//Seg");
                if (segNodes != null)
                {
                    var totalUnitCount   = segNodes.Count;
                    var currentUnitCount = 0;

                    foreach (XmlNode item in segNodes)
                    {
                        var dataAttribute = item.SelectSingleNode("./@Data")?.InnerText;
                        if (dataAttribute != null)
                        {
                            var dataAttributeHexCode = _fileService.ConvertStringToHex(dataAttribute, Encoding.Unicode);
                            if (_fileService.IsValidNode(dataAttributeHexCode))
                            {
                                Output.ProcessParagraphUnit(CreateParagraphUnit(item, dataAttributeHexCode));
                            }
                        }
                        // update the progress report
                        currentUnitCount++;
                        OnProgress(Convert.ToByte(Math.Round(100 * ((decimal)currentUnitCount / totalUnitCount), 0)));
                    }
                }

                Output.FileComplete();
                Output.Complete();
            }
            catch (Exception ex)
            {
                _logger.Error($"{ex.Message}\n {ex.StackTrace}");
            }
            return(false);
        }
Example #32
0
        public static XmlNodeList GetXrefAddNodes(Type t, string xrefId)
        {
            if (t == null)
            {
                return(null);
            }
            if (string.IsNullOrWhiteSpace(xrefId))
            {
                return(null);
            }
            var asmOfT = t.Assembly;

            XrefXml = XrefXml ?? GetEmbeddedXmlDoc(XREF_XML_DATA_FILE, asmOfT);
            return
                (XrefXml?.SelectNodes(
                     $"//{X_REF_GROUP}[@{DATA_TYPE}='{t.FullName}']//{X_REF_ID}[text()='{xrefId}']/../../{ADD}"));
        }
Example #33
0
        protected void GetEmploymentSectorData(XmlDocument xml = null)
        {
            const string SECTOR           = "sector";
            const string CATEGORY_ID      = "category-ID";
            const string PERCENT_EMPLOYED = "percent-employed";

            if (string.IsNullOrWhiteSpace(_stateName))
            {
                return;
            }
            xml = UsStateDataXml ??
                  Core.XmlDocXrefIdentifier.GetEmbeddedXmlDoc(US_STATES_DATA,
                                                              Assembly.GetExecutingAssembly());
            var econDataNodes = xml?.SelectNodes($"//{_nodeName}[@{NAME}='{_stateName}']//{SECTOR}");

            if (econDataNodes == null)
            {
                return;
            }
            for (var i = 0; i < econDataNodes.Count; i++)
            {
                var emplyData = econDataNodes.Item(i) as XmlElement;
                if (emplyData?.Attributes?[PERCENT_EMPLOYED]?.Value == null)
                {
                    continue;
                }
                var strPercent = emplyData.Attributes[PERCENT_EMPLOYED].Value;
                if (!double.TryParse(strPercent, out var percent))
                {
                    continue;
                }
                var description = emplyData.Attributes[CATEGORY_ID]?.Value ?? "";
                if (string.IsNullOrWhiteSpace(description))
                {
                    continue;
                }

                EmploymentSectors.Add(new Tuple <string, double>(description, percent));
            }
        }
Example #34
0
        public string GetXML(string BillingPeriodId, string busUnit)
        {
            string DBConnection = Properties.Settings.Default.DBConnection;
            string connStr      = ConfigurationManager.ConnectionStrings[DBConnection].ConnectionString;
            // Create our DB connection.
            SqlConnection conn = new SqlConnection(connStr);


            SqlCommand cmd = new SqlCommand("[dbo].[generateInvoicesByBillingPeriod]", conn);

            cmd.CommandTimeout = 300;
            DataSet ds = new DataSet();

            SqlDataAdapter a  = new SqlDataAdapter();
            DataTable      dt = new DataTable();


            cmd.Parameters.Add(new SqlParameter("@BillingPeriodId", BillingPeriodId));
            cmd.Parameters.Add(new SqlParameter("@BusUnit", busUnit));
            cmd.CommandType = CommandType.StoredProcedure;
            a.SelectCommand = cmd;
            string responseText = "";

            // Use a DataAdapter to fill the dataset with four tables at once
            //SqlDataAdapter a = new SqlDataAdapter(cmd);
            a.Fill(ds);
            //for testing

            /*using (var stringWriter = new StringWriter())
             * using (var xmlTextWriter = XmlWriter.Create(stringWriter))
             * {
             *  ds.DataSetName = "Transaction";
             *  ds.Tables[0].TableName = "N_DLAR_JRNL_HDR";
             *  ds.WriteXml(xmlTextWriter);
             *  xmlTextWriter.Close();
             *
             *  XmlDocument doc = new XmlDocument();
             *
             *  string dsXML = ds.GetXml();
             *
             * }*/

            // These tables are returned from our stored proc
            DataTable tblHeaders = ds.Tables[0];

            tblHeaders.TableName = "JournalHeaders";
            DataTable tblItems = ds.Tables[1];

            tblItems.TableName = "JournalLineItems";

            /*if (ds.Tables[1].Rows.Count == 0)
             * {
             *  return "No Journal Sent!";
             *  //throw new SoapException("No Journals Sent.", SoapException.ServerFaultCode);
             * }*/
            //RELATE BILLING PERIOD

            /*DataRelation relHeaderItems = new DataRelation(
             * "relHeaderItems",                          // relation name
             * tblHeaders.Columns["JournalHeaderId"],     // parent column
             * tblItems.Columns["HeaderId"]); // child column
             * */
            DataRelation relHeaderItems = new DataRelation(
                "relHeaderItems",                        // relation name
                tblHeaders.Columns["Billing_Period_Id"], // parent column
                tblItems.Columns["Billing_Period_Id"]);  // child column

            // Set the "Nested" property on all the relations we created

            //no more check  box, always true.....
            //relHeaderItems.Nested = cbNestedRelation.Checked;
            relHeaderItems.Nested = true;

            // Lastly, add the relations to the dataset
            ds.Relations.Add(relHeaderItems);

            using (var stringWriter = new StringWriter())
                using (var xmlTextWriter = XmlWriter.Create(stringWriter))
                {
                    ds.DataSetName         = "Transaction";
                    ds.Tables[0].TableName = "N_DLAR_JRNL_HDR";
                    ds.WriteXml(xmlTextWriter);
                    xmlTextWriter.Close();

                    XmlDocument doc = new XmlDocument();

                    string dsXML = ds.GetXml();

                    doc.LoadXml(dsXML);
                    XmlDocument tempDoc = new XmlDocument();

                    var headers = doc.SelectNodes("//N_DLAR_JRNL_HDR");//count headers in ds, alway 1 in this case

                    /*
                     * tempDoc.Load("c:\\DLAR_JOURNAL_TEMP.xml");//load psoft xml file
                     *
                     * var tempHeader = tempDoc.SelectSingleNode("//N_DLAR_JRNL_HDR");
                     * var tempJournalLine = tempDoc.SelectSingleNode("//N_DLAR_JRNL_LIN ");
                     * */

                    //Deal with the dataset
                    //Journal Headers variable for both ds xml and template
                    var businessUnit = doc.SelectNodes("//BUSINESS_UNIT");
                    //var tempBusinessUnit = tempDoc.SelectNodes("//BUSINESS_UNIT");//BUSINESS_UNIT FROM TEMPLATE
                    var journalDate = doc.SelectNodes("//JOURNAL_DATE");
                    //var tempJournalDate = tempDoc.SelectNodes("//JOURNAL_DATE");
                    var ledgerGroup = doc.SelectNodes("//LEDGER_GROUP");
                    //var tempLedgerGroup = tempDoc.SelectNodes("//LEDGER_GROUP");
                    var ledger = doc.SelectNodes("//LEDGER");
                    //var tempLedger = tempDoc.SelectNodes("//LEDGER");
                    var descr = doc.SelectNodes("//DESCR");
                    //var tempDescr = tempDoc.SelectNodes("//DESCR");
                    string[] headersString = new string[headers.Count];
                    //hard coded business unit

                    string[] journalDateString = new string[headers.Count];
                    string[] ledgerGroupString = new string[headers.Count];
                    string[] ledgerString      = new string[headers.Count];
                    string[] descrString       = new string[headers.Count];

                    /*tempDoc.Load("c:\\DLAR_JOURNAL_TEMP.xml");//load psoft xml file
                     *
                     * var tempHeader = tempDoc.SelectSingleNode("//N_DLAR_JRNL_HDR");
                     * var tempJournalLine = tempDoc.SelectSingleNode("//N_DLAR_JRNL_LIN ");
                     * XmlDocument header = new XmlDocument();
                     *
                     * String headerOuterXml = headers[0].OuterXml;
                     *
                     * header.LoadXml(headerOuterXml);*/
                    //see if there is HOS01 in the dataset
                    //string[] businessUnitString = new string[2] { "SOM01", "HOS01" };
                    //ArrayList businessUnitString = new ArrayList();
                    //only one business unit is allowed at once for pSoft
                    //List<string> businessUnitString = new List<string>{"HOS01"};
                    List <string> businessUnitString = new List <string> {
                        busUnit
                    };
                    XMLToString xmlToString = new XMLToString();

                    /*bool hasHOS01 = false;
                     * for (int c= 0; c < businessUnit.Count; c++)
                     * {
                     *
                     *
                     *  if (businessUnit[c].InnerXml == "HOS01")
                     *  {
                     *      hasHOS01 = true;
                     *      //break;
                     *  }
                     *
                     * }
                     * if (hasHOS01 == true)
                     * {
                     *  businessUnitString = new List<string>(new string[] { "SOM01", "HOS01" });
                     * }
                     */
                    //for (int i = 0; i < headers.Count; i++)

                    //string responseText = "";
                    for (int i = 0; i < businessUnitString.Count; i++)

                    {
                        tempDoc.Load("c:\\SendVouchers\\DLAR_JOURNAL_TEMP.xml");//load psoft xml file

                        var         tempHeader      = tempDoc.SelectSingleNode("//N_DLAR_JRNL_HDR");
                        var         tempJournalLine = tempDoc.SelectSingleNode("//N_DLAR_JRNL_LIN ");
                        XmlDocument header          = new XmlDocument();
                        if (headers[i].InnerXml == "")
                        {
                            responseText = "No journals sent.";
                            return(responseText);
                        }
                        String headerOuterXml = headers[i].OuterXml;

                        header.LoadXml(headerOuterXml);

                        //Insert Journal Header values to the template
                        //tempDoc.SelectSingleNode("//BUSINESS_UNIT").InnerXml = businessUnit[i].InnerXml;
                        //Now hard coded Business Unit for the header

                        tempDoc.SelectSingleNode("//BUSINESS_UNIT").InnerXml = businessUnitString[i];
                        if (journalDate.Count != 0)
                        {
                            tempDoc.SelectSingleNode("//JOURNAL_DATE").InnerXml = journalDate[0].InnerXml;
                        }
                        else
                        {
                            tempDoc.SelectSingleNode("//JOURNAL_DATE").InnerXml = "";
                        }
                        if (ledgerGroup.Count != 0)
                        {
                            tempDoc.SelectSingleNode("//LEDGER_GROUP").InnerXml = ledgerGroup[0].InnerXml;
                        }
                        else
                        {
                            tempDoc.SelectSingleNode("//LEDGER_GROUP").InnerXml = "";
                        }
                        if (ledger.Count != 0)
                        {
                            tempDoc.SelectSingleNode("//LEDGER").InnerXml = ledger[0].InnerXml;
                        }
                        else
                        {
                            tempDoc.SelectSingleNode("//LEDGER").InnerXml = "";
                        }
                        if (descr.Count != 0)
                        {
                            tempDoc.SelectSingleNode("//DESCR").InnerXml = descr[0].InnerXml;
                        }
                        else
                        {
                            tempDoc.SelectSingleNode("//DESCR").InnerXml = "";
                        }
                        //}//if (businessUnitString.Length < 1)

                        //Journal Items
                        var businessUnits = header.SelectNodes("//BUSINESS_UNIT");
                        //ACCOUNTS NOW SHOULD BE COUNTED BY CHART STRINGS TO GET ACCURATE COUNT
                        var accounts       = header.SelectNodes("//ACCOUNT");
                        var glaccounts     = header.SelectNodes("//glAccount");
                        var deptIds        = header.SelectNodes("//DEPTID");
                        var operatingUnits = header.SelectNodes("//OPERATING_UNIT");
                        var fundCodes      = header.SelectNodes("//FUND_CODE");
                        var programCodes   = header.SelectNodes("//PROGRAM_CODE");
                        var projectIds     = header.SelectNodes("//PROJECT_ID");
                        var amounts        = header.SelectNodes("//MONETARY_AMOUNT");
                        var lines          = header.SelectNodes("//LINE_DESCR");
                        //NO MORE CURRENCY ADN LINE DESCRIPTION
                        //var currencies = header.SelectNodes("//CURRENCY_CD");
                        //var lineDescrs = header.SelectNodes("//LINE_DESCR");
                        string[] accountsString       = new string[accounts.Count];
                        string[] deptIdsString        = new string[deptIds.Count];
                        string[] operatingUnitsString = new string[operatingUnits.Count];
                        string[] fundCodesString      = new string[fundCodes.Count];
                        string[] programCodesString   = new string[programCodes.Count];
                        string[] projectIdsString     = new string[projectIds.Count];
                        string[] amountsString        = new string[amounts.Count];
                        //string[] currenciesString = new string[currencies.Count];
                        //string[] lineDescrsString = new string[lineDescrs.Count];
                        //we have to know how many headers to clone in the tempDoc
                        //and append ADDITIONAL journal line items to temp
                        var      tempAccounts       = header.SelectNodes("//ACCOUNT");
                        string[] tempAccountsString = new string[tempAccounts.Count];
                        //Append line items!!!!

                        XmlDocument soapRequest = new XmlDocument();
                        //XMLToString xmlToString = new XMLToString();
                        var headerNodes = doc.SelectNodes("//N_DLAR_JRNL_HDR");
                        // traditional approach
                        string[] transactions = new string[headerNodes.Count];
                        string[] responses    = new string[headerNodes.Count];
                        for (int y = 0; y < glaccounts.Count; y++)
                        {
                            if (businessUnits[y].InnerXml == businessUnitString[i])
                            {
                                //accountsString[y] = accounts[y].InnerXml;
                                //tempAccounts[y].InnerXml = accounts[y].InnerXml;
                                var accountInLine = tempJournalLine.SelectSingleNode("//ACCOUNT");
                                if (accounts.Count != 0)
                                {
                                    accountInLine.InnerXml = accounts[y].InnerXml;
                                }
                                else
                                {
                                    accountInLine.InnerXml = "";
                                }
                                var deptIdInLine = tempJournalLine.SelectSingleNode("//DEPTID");
                                if (deptIds.Count != 0)
                                {
                                    deptIdInLine.InnerXml = deptIds[y].InnerXml;
                                }
                                else
                                {
                                    deptIdInLine.InnerXml = "";
                                }

                                var operatingUnitInLine = tempJournalLine.SelectSingleNode("//OPERATING_UNIT");
                                if (operatingUnits.Count != 0)
                                {
                                    operatingUnitInLine.InnerXml = operatingUnits[y].InnerXml;
                                }
                                else
                                {
                                    operatingUnitInLine.InnerXml = "";
                                }

                                var fundCodeInLine = tempJournalLine.SelectSingleNode("//FUND_CODE");
                                if (fundCodes.Count != 0)
                                {
                                    fundCodeInLine.InnerXml = fundCodes[y].InnerXml;
                                }
                                else
                                {
                                    fundCodeInLine.InnerXml = "";
                                }
                                var programCodeInLine = tempJournalLine.SelectSingleNode("//PROGRAM_CODE");
                                if (programCodes.Count != 0)
                                {
                                    programCodeInLine.InnerXml = programCodes[y].InnerXml;
                                }
                                else
                                {
                                    programCodeInLine.InnerXml = "";
                                }
                                var projectIdInLine = tempJournalLine.SelectSingleNode("//PROJECT_ID");
                                if (projectIds.Count != 0)
                                {
                                    projectIdInLine.InnerXml = projectIds[y].InnerXml;
                                }
                                else
                                {
                                    projectIdInLine.InnerXml = "";
                                }
                                var amountInLine = tempJournalLine.SelectSingleNode("//MONETARY_AMOUNT");
                                if (amounts.Count != 0)
                                {
                                    amountInLine.InnerXml = amounts[y].InnerXml;
                                }
                                else
                                {
                                    amountInLine.InnerXml = "";
                                }
                                var currencyInLine = tempJournalLine.SelectSingleNode("//CURRENCY_CD");
                                //hard coded for currency and Line Description
                                //currencyInLine.InnerXml = currencies[y].InnerXml;
                                currencyInLine.InnerXml = "USD";
                                var lineDescrInLine = tempJournalLine.SelectSingleNode("//LINE_DESCR");
                                if (lines.Count != 0)
                                {
                                    lineDescrInLine.InnerXml = lines[y].InnerXml;
                                }
                                else
                                {
                                    lineDescrInLine.InnerXml = "";
                                }
                                //lineDescrInLine.InnerXml = lineDescrs[y].InnerXml;
                                //lineDescrInLine.InnerXml = "Line Description";
                                var cloneJournalLineNode = tempJournalLine.Clone();
                                tempHeader.AppendChild(cloneJournalLineNode);
                            }//if (businessUnits[y].InnerXml == businessUnitString[i])
                        }

                        var journalLinesInTemp = tempDoc.SelectNodes("//N_DLAR_JRNL_LIN");

                        //VERY IMPORTEANT:REMOVE THE VERY FIRST LINE IN tempDoc!!!!
                        for (int z = 0; z < journalLinesInTemp.Count; z++)
                        {
                            if (z == 0)
                            {
                                journalLinesInTemp[0].ParentNode.RemoveChild(journalLinesInTemp[0]);
                            }
                        }
                        //Now we have the temp xml doc ready we can insert the values from the string arrays above to
                        //the corresponding nodes in the temp xml doc

                        //Now we have to know how many items to append to each header


                        tempDoc.Save("c:\\SendVouchers\\DLAR_JOURNAL_MSG.xml");
                        soapRequest.Load("c:\\SendVouchers\\DLAR_JOURNAL_MSG.xml");
                        transactions[i] = headerNodes[i].ParentNode.InnerXml;
                        //soapRequest.GetElementsByTagName("Transaction").Item(0).InnerXml = doc.GetElementsByTagName("Transaction").Item(0).InnerXml;
                        soapRequest.GetElementsByTagName("Transaction").Item(0).InnerXml = transactions[i];
                        //soapRequest.GetElementsByTagName("N_DLAR_JRNL_HDR").Item(0).InnerXml = headerNodes[i].InnerXml;
                        //soapRequest.Save(@"c:\\DLAR_JOURNAL.xml");
                        //Now we can send the soap request transaction by transaction
                        XmlDocument XMLResponse = new XmlDocument();
                        string      xmlRequest  = xmlToString.GetXMLAsString(soapRequest);
                        //LogMessageToFile(xmlRequest);
                        //Log Sent Soap Message to file
                        string msg  = xmlRequest;
                        string path = ("C:\\SendVouchers\\");
                        //System.IO.StreamWriter sw = System.IO.File.AppendText(
                        //GetTempPath() + "My Log File.txt");
                        System.IO.StreamWriter sw = System.IO.File.AppendText(
                            path + "Send Journals Message Log File.txt");
                        try
                        {
                            string logLine = System.String.Format(
                                "{0:G}: {1}.", System.DateTime.Now, msg);
                            sw.WriteLine(logLine);
                        }
                        finally
                        {
                            sw.Close();
                        }
                        //EndPoint
                        string endPoint = Properties.Settings.Default.EndPoint;

                        //string endPointUrl = ConfigurationManager.ConnectionStrings[devType].ConnectionString;
                        string endPointUrl = ConfigurationManager.AppSettings[endPoint];
                        PsoftGetSoapXmlResponse psoftGetSoapXmlResponse = new PsoftGetSoapXmlResponse();
                        //XMLResponse = PsoftGetSoapXmlResponse.PostXMLTransaction("http://pfwlcdcdvm003.nyumc.org:7710/PSIGW/PeopleSoftServiceListeningConnector", "N_DLAR_JOURNAL.v1", "c:\\DLAR_JOURNAL_MSG.xml");
                        //NEW UAT
                        //XMLResponse = PsoftGetSoapXmlResponse.PostXMLTransaction("http://peoplesoftfscmuat.nyumc.org:8115/PSIGW/PeopleSoftServiceListeningConnector", "N_DLAR_JOURNAL.v1", "c:\\DLAR_JOURNAL_MSG.xml");
                        XMLResponse = PsoftGetSoapXmlResponse.PostXMLTransaction(endPointUrl, "N_DLAR_JOURNAL.v1", "c:\\SendVouchers\\DLAR_JOURNAL_MSG.xml");

                        //Now traverse through the Response Document to get the message we need

                        if (XMLResponse != null)
                        {
                            XmlNodeList node = XMLResponse.GetElementsByTagName("MsgData");

                            XmlNodeList ComboValidFalgNodes = XMLResponse.GetElementsByTagName("DESCR20");//Returns "Journal Received"
                            if (ComboValidFalgNodes.Count == 0)
                            {
                                responseText = "Peoplesoft service is down. Please try again later.";
                                return(responseText);
                            }
                            //responses[i] = ComboValidFalgNodes[1].InnerText;
                            responseText = ComboValidFalgNodes[1].InnerText;
                            //int x = i + 1;
                            //txtOutput.Text = ComboValidFalgNodes[1].InnerText;
                            //txtOutput.Text = i+1 + " " + ComboValidFalgNodes[1].InnerText;
                            //txtOutput.Text = responses[i] + "\r\n" + i + 1 + " Journal Entries Received.";
                            //txtOutput.AppendText (ComboValidFalgNodes[1].InnerText);

                            //NO OUTPUT, BELOW IS FOR WIN FORM APP
                            //txtOutput.AppendText(x + " " + responses[i] + "\r\n");
                            //save the response in log?????
                            string responseMsg  = responseText;
                            string responsePath = ("C:\\SendVouchers\\");
                            //System.IO.StreamWriter sw = System.IO.File.AppendText(
                            //GetTempPath() + "My Log File.txt");
                            System.IO.StreamWriter swR = System.IO.File.AppendText(
                                responsePath + "Journal Response Message Log File.txt");
                            try
                            {
                                string logLine = System.String.Format(
                                    "{0:G}: {1}.", System.DateTime.Now, responseMsg);
                                swR.WriteLine(logLine);
                            }
                            finally
                            {
                                swR.Close();
                            }
                        }
                        else
                        {
                            //ResultText.Text = "no value";
                            throw new ApplicationException("Something wrong happened while writing the XML content to the request stream: ");
                        }
                    }//for (int i = 0; i < businessUnitString.Length; i++)
                    //NO OUTPUT, BELOW IS FOR WIN FORM APP
                    //txtOutput.AppendText("Total " + headers.Count + " Journal Entries Received.");
                    return(responseText);
                }// using (var xmlTextWriter = XmlWriter.Create(stringWriter))
        }//end GetXML
Example #35
0
        private Project GetProjectObject(string projXml)
        {
            Logger.Info("Entering GetProjectObject");
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(projXml);
            var nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("mml", "http://macmillanlearning.com/");
            nsmgr.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");

            Project proj = new Project();

            proj.SystemId   = doc.SelectSingleNode("/mml:cmsDocument/mml:metadata/mml:cmsCore/mml:administrative/mml:systemID", nsmgr).InnerText;
            proj.ProjectURL = doc.SelectSingleNode("/mml:cmsDocument/mml:metadata/mml:cmsCore/mml:administrative/mml:uri", nsmgr).InnerText;

            string dateCrtd = doc.SelectSingleNode("/mml:cmsDocument/mml:metadata/mml:cmsCore/mml:administrative/mml:dateCreated", nsmgr).InnerText;

            if (!string.IsNullOrEmpty(dateCrtd))
            {
                proj.DateCreated = Convert.ToDateTime(dateCrtd);
            }

            proj.CreatedBy = doc.SelectSingleNode("/mml:cmsDocument/mml:metadata/mml:cmsCore/mml:administrative/mml:createdBy", nsmgr).InnerText;

            string dateModfd = doc.SelectSingleNode("/mml:cmsDocument/mml:metadata/mml:cmsCore/mml:administrative/mml:dateLastModified", nsmgr).InnerText;

            if (!string.IsNullOrEmpty(dateModfd))
            {
                proj.DateModified = Convert.ToDateTime(dateModfd);
            }

            proj.ModifiedBy = doc.SelectSingleNode("/mml:cmsDocument/mml:metadata/mml:cmsCore/mml:administrative/mml:modifiedBy", nsmgr).InnerText;

            proj.Title       = doc.SelectSingleNode("/mml:cmsDocument/mml:metadata/mml:cmsCore/mml:descriptive/dc:title", nsmgr).InnerText;
            proj.Description = doc.SelectSingleNode("/mml:cmsDocument/mml:metadata/mml:cmsCore/mml:descriptive/dc:description", nsmgr).InnerText;

            XmlNodeList subjectHeadings = doc.SelectNodes("/mml:cmsDocument/mml:metadata/mml:cmsCore/mml:semantic/mml:subjectHeadings/mml:subjectHeading", nsmgr);

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

            for (int i = 0; i < subjectHeadings.Count; i++)
            {
                subjects.Add(subjectHeadings[i].InnerText);
            }

            proj.SubjectHeadings = subjects.ToArray();

            XmlNodeList subjectKeywords = doc.SelectNodes("/mml:cmsDocument/mml:metadata/mml:cmsCore/mml:semantic/mml:subjectKeywords/mml:subjectKeyword", nsmgr);

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

            for (int i = 0; i < subjectKeywords.Count; i++)
            {
                keywords.Add(subjectKeywords[i].InnerText);
            }

            proj.SubjectKeywords = keywords.ToArray();

            proj.ProjectState = doc.SelectSingleNode("/mml:cmsDocument/mml:metadata/mml:project/mml:descriptive/mml:projectState", nsmgr).InnerText;
            Logger.Info("Exiting GetProjectObject");
            return(proj);
        }
Example #36
0
        protected void Page_Load(object sender, EventArgs e)
        {
            //redirect to home if there is no querystring
            if (string.IsNullOrWhiteSpace(Request.QueryString["queryID"]))
            {
                Response.Redirect("~/");
            }

            FourthProjectLogic.Movie themovie = new FourthProjectLogic.Movie(Int32.Parse(Request.QueryString["queryID"])); //get movie object via id, fetching db info for it

            themovie.IncrementViewcount();                                                                                 //what it says on the tin, this is how we track views

            //get movie name from object and show in label - thats not the movies f*****g name, how about asking me about shit instead of commenting methods out?
            LabelMessages.Text = themovie.title;                                               // .ToString();

            string result = FourthProjectLogic.OmdbAPI.NameAPI(themovie.title, themovie.year); //add year to make sure we get correct results?

            File.WriteAllText(Server.MapPath("~/MyFiles/Latestresult.xml"), result);
            XmlDocument doc = new XmlDocument();

            doc.LoadXml(result);

            if (doc.SelectSingleNode("/root/@response").InnerText == "True")
            {
                XmlNodeList nodelist = doc.SelectNodes("/root/movie");
                foreach (XmlNode node in nodelist)
                {
                    string poster = node.SelectSingleNode("@poster").InnerText;
                    if (poster == "N/A" || poster == "FAIL")
                    {
                        ImagePoster.ImageUrl = "/Myfiles/default-img.jpg";
                    }
                    else
                    {
                        ImagePoster.ImageUrl = poster;
                    }
                }
                LabelResultTitle.Text       = "Title: " + nodelist[0].SelectSingleNode("@title").InnerText;
                LabelResultRating.Text      = "Rating: " + nodelist[0].SelectSingleNode("@imdbRating").InnerText;
                LabelResultYear.Text        = "Year: " + nodelist[0].SelectSingleNode("@year").InnerText;
                LabelResultActors.Text      = "Actors: " + nodelist[0].SelectSingleNode("@actors").InnerText;
                LabelResultDescription.Text = "Description: " + nodelist[0].SelectSingleNode("@plot").InnerText;
                LabelResultChildRating.Text = "Child Rating: " + nodelist[0].SelectSingleNode("@rated").InnerText;

                MagicPanel.Visible = true;
            }
            else
            {
                MagicPanel.Visible    = false;
                LabelMessages.Text    = "Movie not found";
                ImagePoster.ImageUrl  = "/Myfiles/default-img.jpg";
                LabelResultTitle.Text = "no Results";
            }

            //top 10
            Repeater1.DataSource = FourthProjectLogic.Movie.MovieTableAdapter.MoviesTop10();
            Repeater1.DataBind();

            // COMMERCIAL
            // run the logic for commercial stat tracking - reading and modifying the xml to increment viewcount for the random commercial and passing the commercials id/rowindex/"position"
            int randomcommercialToDisplayPosition = FourthProjectLogic.Commercials.StatTracker();

            DataSet ds = new DataSet();

            ds.ReadXml(MapPath("/xml/commercialsTransformed.xml"));
            rpMyRepeater.DataSource = ds;
            rpMyRepeater.DataBind();

            foreach (RepeaterItem item in rpMyRepeater.Items)
            {
                if (item.ItemIndex != randomcommercialToDisplayPosition)
                {
                    item.Visible = false;
                }
            }
        }
Example #37
0
        public ContentInfo(string path, Node parent)
        {
            try
            {
                _metaDataPath = path;
                _attachments  = new List <string>();

                string directoryName = Path.GetDirectoryName(path);
                _name = Path.GetFileName(path);
                string extension = Path.GetExtension(_name);
                if (extension.ToLower() == ".content")
                {
                    var fileInfo = new FileInfo(path);
                    IsHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;

                    _xmlDoc = new XmlDocument();
                    _xmlDoc.Load(path);

                    XmlNode nameNode = _xmlDoc.SelectSingleNode("/ContentMetaData/ContentName");
                    _name = nameNode == null?Path.GetFileNameWithoutExtension(_name) : nameNode.InnerText;

                    _contentTypeName = _xmlDoc.SelectSingleNode("/ContentMetaData/ContentType").InnerText;

                    ClearPermissions    = _xmlDoc.SelectSingleNode("/ContentMetaData/Permissions/Clear") != null;
                    HasBreakPermissions = _xmlDoc.SelectSingleNode("/ContentMetaData/Permissions/Break") != null;
                    HasPermissions      = _xmlDoc.SelectNodes("/ContentMetaData/Permissions/Identity").Count > 0;

                    // /ContentMetaData/Properties/*/@attachment
                    foreach (XmlAttribute attachmentAttr in _xmlDoc.SelectNodes("/ContentMetaData/Fields/*/@attachment"))
                    {
                        string attachment = attachmentAttr.Value;
                        _attachments.Add(attachment);
                        bool isFolder = Directory.Exists(Path.Combine(directoryName, attachment));
                        if (isFolder)
                        {
                            if (_isFolder)
                            {
                                throw new ApplicationException(String.Concat("Two or more attachment folder is not enabled. ContentName: ", _name));
                            }
                            _isFolder       = true;
                            _childrenFolder = Path.Combine(directoryName, attachment);
                        }
                    }
                    //-- default attachment
                    var defaultAttachmentPath = Path.Combine(directoryName, _name);
                    if (!_attachments.Contains(_name))
                    {
                        string[] paths;
                        if (Directory.Exists(defaultAttachmentPath))
                        {
                            paths = new string[] { defaultAttachmentPath }
                        }
                        ;
                        else
                        {
                            paths = new string[0];
                        }

                        //string[] paths = Directory.GetDirectories(directoryName, _name);
                        if (paths.Length == 1)
                        {
                            if (_isFolder)
                            {
                                throw new ApplicationException(String.Concat("Two or more attachment folder is not enabled. ContentName: ", _name));
                            }
                            _isFolder       = true;
                            _childrenFolder = defaultAttachmentPath;
                            _attachments.Add(_name);
                        }
                        else
                        {
                            if (System.IO.File.Exists(defaultAttachmentPath))
                            {
                                _attachments.Add(_name);
                            }
                        }
                    }
                }
                else
                {
                    _isFolder = Directory.Exists(path);
                    if (_isFolder)
                    {
                        var dirInfo = new DirectoryInfo(path);
                        IsHidden = (dirInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;

                        _contentTypeName = GetParentAllowedContentTypeName(path, parent, "Folder");
                        _childrenFolder  = path;
                    }
                    else
                    {
                        var fileInfo = new FileInfo(path);
                        IsHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden;

                        _xmlDoc          = new XmlDocument();
                        _contentTypeName = GetContentTypeName(path) ?? GetParentAllowedContentTypeName(path, parent, "File");

                        var contentMetaData = String.Concat("<ContentMetaData><ContentType>{0}</ContentType><Fields><Binary attachment='", _name.Replace("'", "&apos;"), "' /></Fields></ContentMetaData>");
                        _xmlDoc.LoadXml(String.Format(contentMetaData, _contentTypeName));
                        _attachments.Add(_name);
                    }
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException("Cannot create a ContentInfo. Path: " + path, e);
            }
        }
Example #38
0
        /// <summary>
        /// Gets the list of sub-folders inside a folder
        /// </summary>
        /// <param name="FolderGuid">Edge drive folder guid</param>
        /// <returns>array of sub-folder details</returns>
        public FolderData[] BrowseFolders(string FolderGuid, out string errorMessage)
        {
            const string function = "CVAPI::BrowseFolders";

            FolderData[] result = null;
            errorMessage = string.Empty;
            try
            {
                // Get the client details
                if (_clientDetails.ClientID == null)
                {
                    GetEdgeClientID(out _clientDetails);
                }

                if (string.IsNullOrEmpty(_clientDetails.ClientID))
                {
                    errorMessage = "Server is not responding. Please try again later.";
                }
                else
                {
                    string requestBody = string.Format(browseRequestBody, _clientDetails.ClientID, _clientDetails.InstanceID, _clientDetails.SubClientID, _clientDetails.ApplicationID, _userGuid, "",
                                                       string.IsNullOrEmpty(FolderGuid) ? _clientDetails.RootWebFolderID : FolderGuid + Path.DirectorySeparatorChar.ToString());

                    HttpWebResponse ClientResp = SendRequest(ServiceURI.Replace("api/", "") + browseFolderURI, post, _authToken, requestBody);
                    if (null != ClientResp && ClientResp.StatusCode == HttpStatusCode.OK)
                    {
                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.Load(ClientResp.GetResponseStream());
                        XmlNodeList attrList = xmlDoc.SelectNodes("//databrowse_BrowseResponseWrapper/browseResponse/browseResult/dataResultSet/@displayName");
                        if (null != attrList)
                        {
                            XmlNode guidNode;
                            result = new FolderData[attrList.Count];
                            for (int i = 0; i < attrList.Count; i++)
                            {
                                result[i]            = new FolderData();
                                result[i].FolderName = attrList[i].Value;
                                guidNode             = xmlDoc.SelectSingleNode(string.Format("//dataResultSet[@displayName=\"{0}\"]/@path", attrList[i].Value));
                                if (null != guidNode)
                                {
                                    result[i].FolderGuid = guidNode.Value;
                                }
                                else
                                {
                                    Logger.Error("Folder guid attribute not found", function);
                                    result = null;
                                    break;
                                }
                            }
                        }
                    }
                    else if (ClientResp != null)
                    {
                        if (ClientResp.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            RenewToken(out errorMessage);
                        }
                        else
                        {
                            errorMessage = "Server is not responding. Please try again later.";
                            Logger.Error(string.Format("{0}:{1}", Convert.ChangeType(ClientResp.StatusCode, ClientResp.StatusCode.GetTypeCode()), ClientResp.StatusDescription), function);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, function);
            }
            return(result);
        }
        public string GetBlogImagesAlbum(string albumName)
        {
            const string FEED_REL      = "http://schemas.google.com/g/2005#feed";
            const string GPHOTO_NS_URI = "http://schemas.google.com/photos/2007";

            Uri picasaUri = new Uri("https://picasaweb.google.com/data/feed/api/user/default");

            try
            {
                Uri         reqUri       = picasaUri;
                XmlDocument albumListDoc = AtomClient.xmlRestRequestHelper.Get(ref reqUri, CreateAuthorizationFilter(), "kind", "album");
                foreach (XmlElement entryEl in albumListDoc.SelectNodes(@"/atom:feed/atom:entry", _nsMgr))
                {
                    XmlElement titleNode = entryEl.SelectSingleNode(@"atom:title", _nsMgr) as XmlElement;
                    if (titleNode != null)
                    {
                        string titleText = AtomProtocolVersion.V10DraftBlogger.TextNodeToPlaintext(titleNode);
                        if (titleText == albumName)
                        {
                            XmlNamespaceManager nsMgr2 = new XmlNamespaceManager(new NameTable());
                            nsMgr2.AddNamespace("gphoto", "http://schemas.google.com/photos/2007");
                            XmlNode numPhotosRemainingNode = entryEl.SelectSingleNode("gphoto:numphotosremaining/text()", nsMgr2);
                            if (numPhotosRemainingNode != null)
                            {
                                int numPhotosRemaining;
                                if (int.TryParse(numPhotosRemainingNode.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out numPhotosRemaining))
                                {
                                    if (numPhotosRemaining < 1)
                                    {
                                        continue;
                                    }
                                }
                            }
                            string selfHref = AtomEntry.GetLink(entryEl, _nsMgr, FEED_REL, "application/atom+xml", null, reqUri);
                            if (selfHref.Length > 1)
                            {
                                return(selfHref);
                            }
                        }
                    }
                }
            }
            catch (WebException we)
            {
                HttpWebResponse httpWebResponse = we.Response as HttpWebResponse;
                if (httpWebResponse != null)
                {
                    HttpRequestHelper.DumpResponse(httpWebResponse);
                    if (httpWebResponse.StatusCode == HttpStatusCode.NotFound)
                    {
                        throw new BlogClientOperationCancelledException();
                    }
                }
                throw;
            }

            XmlDocument newDoc     = new XmlDocument();
            XmlElement  newEntryEl = newDoc.CreateElement("atom", "entry", AtomProtocolVersion.V10DraftBlogger.NamespaceUri);

            newDoc.AppendChild(newEntryEl);

            XmlElement newTitleEl = newDoc.CreateElement("atom", "title", AtomProtocolVersion.V10DraftBlogger.NamespaceUri);

            newTitleEl.SetAttribute("type", "text");
            newTitleEl.InnerText = albumName;
            newEntryEl.AppendChild(newTitleEl);

            XmlElement newSummaryEl = newDoc.CreateElement("atom", "summary", AtomProtocolVersion.V10DraftBlogger.NamespaceUri);

            newSummaryEl.SetAttribute("type", "text");
            newSummaryEl.InnerText = Res.Get(StringId.BloggerImageAlbumDescription);
            newEntryEl.AppendChild(newSummaryEl);

            XmlElement newAccessEl = newDoc.CreateElement("gphoto", "access", GPHOTO_NS_URI);

            newAccessEl.InnerText = "private";
            newEntryEl.AppendChild(newAccessEl);

            XmlElement newCategoryEl = newDoc.CreateElement("atom", "category", AtomProtocolVersion.V10DraftBlogger.NamespaceUri);

            newCategoryEl.SetAttribute("scheme", "http://schemas.google.com/g/2005#kind");
            newCategoryEl.SetAttribute("term", "http://schemas.google.com/photos/2007#album");
            newEntryEl.AppendChild(newCategoryEl);

            Uri         postUri               = picasaUri;
            XmlDocument newAlbumResult        = AtomClient.xmlRestRequestHelper.Post(ref postUri, CreateAuthorizationFilter(), "application/atom+xml", newDoc, null);
            XmlElement  newAlbumResultEntryEl = newAlbumResult.SelectSingleNode("/atom:entry", _nsMgr) as XmlElement;

            Debug.Assert(newAlbumResultEntryEl != null);
            return(AtomEntry.GetLink(newAlbumResultEntryEl, _nsMgr, FEED_REL, "application/atom+xml", null, postUri));
        }
Example #40
0
        private void getDataTemperatureXml(decimal temperature, int sensorId)
        {
            string msg;

            if (File.Exists(path))
            {
                doc.Load(path);

                XmlNodeList nodeListAlerts = doc.SelectNodes("/alerts/alert");
                foreach (XmlNode alert in nodeListAlerts)
                {
                    //Console.WriteLine(alert.InnerText);
                    if (alert.SelectSingleNode("state").InnerText.ToUpper() == "True".ToUpper())
                    {
                        int id = Int32.Parse(alert.SelectSingleNode("id").InnerText);

                        if (alert.SelectSingleNode("type").InnerText.ToUpper() == "Temperature".ToUpper())
                        {
                            string condition = alert.SelectSingleNode("condition").InnerText;

                            switch (condition)
                            {
                            case "between":
                                decimal valueMax = Convert.ToDecimal(alert.SelectSingleNode("valueMax").InnerText);
                                decimal valueMin = Convert.ToDecimal(alert.SelectSingleNode("value").InnerText);
                                if (temperature > valueMin - 1 && temperature < valueMax + 1)
                                {
                                    msg = "Sensor ID = " + sensorId + "! Temperature between " + valueMin + " and " + valueMax + "! Alert with id = " + id;
                                    listBoxAlertTimeCurrent.Items.Add(msg);
                                    mClient.Publish("alerts", Encoding.UTF8.GetBytes(msg), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
                                }
                                break;

                            case "<":
                                decimal value = Convert.ToDecimal(alert.SelectSingleNode("value").InnerText);
                                if (temperature < value)
                                {
                                    msg = "Sensor ID = " + sensorId + "! Temperature lesser than " + value + "! Alert with id = " + id;
                                    listBoxAlertTimeCurrent.Items.Add(msg);
                                    mClient.Publish("alerts", Encoding.UTF8.GetBytes(msg), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
                                }
                                break;

                            case ">":
                                value = Convert.ToDecimal(alert.SelectSingleNode("value").InnerText);
                                if (temperature > value)
                                {
                                    msg = "Sensor ID = " + sensorId + "! Temperature greater than " + value + "! Alert with id = " + id;
                                    listBoxAlertTimeCurrent.Items.Add(msg);
                                    mClient.Publish("alerts", Encoding.UTF8.GetBytes(msg), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
                                }
                                break;

                            case "=":
                                value = Convert.ToDecimal(alert.SelectSingleNode("value").InnerText);
                                if (temperature == value)
                                {
                                    msg = "Sensor ID = " + sensorId + "! Temperature equal " + value + "! Alert with id = " + id;
                                    listBoxAlertTimeCurrent.Items.Add(msg);
                                    mClient.Publish("alerts", Encoding.UTF8.GetBytes(msg), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
                                }
                                break;

                            default:
                                break;
                            }
                        }
                    }
                }
            }
        }
Example #41
0
        private void CommonSetup()
        {
            try
            {
                _namespaceMgr = new XmlNamespaceManager(_testCaseDoc.NameTable);
                _namespaceMgr.AddNamespace("SsisUnit", "http://tempuri.org/SsisUnit.xsd");

                var xmlPackageReferences = _testCaseDoc.SelectNodes("SsisUnit:TestSuite/SsisUnit:PackageList/SsisUnit:Package", _namespaceMgr);

                if (xmlPackageReferences != null)
                {
                    foreach (XmlNode pkgRef in xmlPackageReferences)
                    {
                        if (pkgRef.Attributes == null)
                        {
                            continue;
                        }

                        PackageList.Add(pkgRef.Attributes["name"].Value, new PackageRef(pkgRef));
                    }
                }

                ConnectionList = _testCaseDoc.DocumentElement != null?LoadConnectionRefs(_testCaseDoc.DocumentElement["ConnectionList"]) : new Dictionary <string, ConnectionRef>();

                var xmlDatasets = _testCaseDoc.SelectNodes("SsisUnit:TestSuite/SsisUnit:DatasetList/SsisUnit:Dataset", _namespaceMgr);

                if (xmlDatasets != null)
                {
                    foreach (XmlNode xmlDataset in xmlDatasets)
                    {
                        if (xmlDataset.Attributes == null)
                        {
                            continue;
                        }

                        Datasets.Add(xmlDataset.Attributes["name"].Value, new Dataset(this, xmlDataset));
                    }
                }

                TestSuiteSetup    = _testCaseDoc.DocumentElement != null ? new CommandSet("Test Suite Setup", this, _testCaseDoc.DocumentElement["TestSuiteSetup"]) : new CommandSet(this);
                TestSuiteTeardown = _testCaseDoc.DocumentElement != null ? new CommandSet("Test Suite Teardown", this, _testCaseDoc.DocumentElement["TestSuiteTeardown"]) : new CommandSet(this);
                SetupCommands     = _testCaseDoc.DocumentElement != null ? new CommandSet("Unit Test Setup", this, _testCaseDoc.DocumentElement["Setup"]) : new CommandSet(this);
                TeardownCommands  = _testCaseDoc.DocumentElement != null ? new CommandSet("Unit Test Teardown", this, _testCaseDoc.DocumentElement["Teardown"]) : new CommandSet(this);

                var xmlTests = _testCaseDoc.SelectNodes("SsisUnit:TestSuite/SsisUnit:Tests/SsisUnit:Test", _namespaceMgr);

                if (xmlTests != null)
                {
                    foreach (XmlNode test in xmlTests)
                    {
                        if (test.Attributes == null)
                        {
                            continue;
                        }

                        Test newTest = new Test(this, test);

                        newTest.CommandCompleted += OnRaiseCommandCompleted;
                        newTest.CommandFailed    += OnRaiseCommandFailed;
                        newTest.CommandStarted   += OnRaiseCommandStarted;

                        Tests.Add(test.Attributes["name"].Value, newTest);
                    }
                }

                var xmlTestReferences = _testCaseDoc.SelectNodes("SsisUnit:TestSuite/SsisUnit:Tests/SsisUnit:TestRef", _namespaceMgr);

                if (xmlTestReferences != null)
                {
                    foreach (XmlNode testRef in xmlTestReferences)
                    {
                        if (testRef.Attributes == null)
                        {
                            continue;
                        }

                        TestRefs.Add(testRef.Attributes["path"].Value, new TestRef(this, testRef));
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException(string.Format("The unit test file is malformed or corrupt. Please verify that the file format conforms to the ssisUnit schema, provided in the SsisUnit.xsd file."), ex);
            }
        }
Example #42
0
        private void frmSelectWeapon_Load(object sender, EventArgs e)
        {
            DataGridViewCellStyle dataGridViewNuyenCellStyle = new DataGridViewCellStyle
            {
                Alignment = DataGridViewContentAlignment.TopRight,
                Format    = _objCharacter.Options.NuyenFormat + '¥',
                NullValue = null
            };

            dgvc_Cost.DefaultCellStyle = dataGridViewNuyenCellStyle;

            if (_objCharacter.Created)
            {
                chkHideOverAvailLimit.Visible = false;
                chkHideOverAvailLimit.Checked = false;
            }
            else
            {
                chkHideOverAvailLimit.Text    = string.Format(GlobalOptions.CultureInfo, chkHideOverAvailLimit.Text, _objCharacter.MaximumAvailability.ToString(GlobalOptions.CultureInfo));
                chkHideOverAvailLimit.Checked = _objCharacter.Options.HideItemsOverAvailLimit;
            }

            // Populate the Weapon Category list.
            // Populate the Category list.
            using (XmlNodeList xmlCategoryList = _objXmlDocument.SelectNodes("/chummer/categories/category"))
            {
                if (xmlCategoryList != null)
                {
                    foreach (XmlNode objXmlCategory in xmlCategoryList)
                    {
                        string strInnerText = objXmlCategory.InnerText;
                        if (_hashLimitToCategories.Count == 0 || _hashLimitToCategories.Contains(strInnerText))
                        {
                            _lstCategory.Add(new ListItem(strInnerText, objXmlCategory.Attributes?["translate"]?.InnerText ?? strInnerText));
                        }
                    }
                }
            }

            _lstCategory.Sort(CompareListItems.CompareNames);

            if (_lstCategory.Count > 0)
            {
                _lstCategory.Insert(0, new ListItem("Show All", LanguageManager.GetString("String_ShowAll")));
            }

            cboCategory.BeginUpdate();
            cboCategory.ValueMember   = "Value";
            cboCategory.DisplayMember = "Name";
            cboCategory.DataSource    = _lstCategory;

            chkBlackMarketDiscount.Visible = _objCharacter.BlackMarketDiscount;

            // Select the first Category in the list.
            if (string.IsNullOrEmpty(s_StrSelectCategory))
            {
                cboCategory.SelectedIndex = 0;
            }
            else
            {
                cboCategory.SelectedValue = s_StrSelectCategory;
            }

            if (cboCategory.SelectedIndex == -1)
            {
                cboCategory.SelectedIndex = 0;
            }
            cboCategory.EndUpdate();

            _blnLoading = false;
            RefreshList();
        }
Example #43
0
        public override void LoadSubtitle(Subtitle subtitle, List <string> lines, string fileName)
        {
            _errorCount = 0;
            FrameRate   = Configuration.Settings.General.CurrentFrameRate;

            var sb = new StringBuilder();

            lines.ForEach(line => sb.AppendLine(line));
            string x = sb.ToString();

            if (!x.Contains("<fcpxml version=\"1.4\">"))
            {
                return;
            }

            var xml = new XmlDocument();

            try
            {
                xml.LoadXml(x.Trim());

                if (subtitle.Paragraphs.Count == 0)
                {
                    var textNodes = xml.SelectNodes("//project/sequence/spine/title/text");
                    if (textNodes.Count == 0)
                    {
                        textNodes = xml.SelectNodes("//project/sequence/spine/gap/title/text");
                    }
                    foreach (XmlNode node in textNodes)
                    {
                        try
                        {
                            string text = node.ParentNode.InnerText;
                            var    p    = new Paragraph();
                            p.Text      = text.Trim();
                            p.StartTime = DecodeTime(node.ParentNode.Attributes["offset"]);
                            p.EndTime.TotalMilliseconds = p.StartTime.TotalMilliseconds + DecodeTime(node.ParentNode.Attributes["duration"]).TotalMilliseconds;
                            bool add = true;
                            if (subtitle.Paragraphs.Count > 0)
                            {
                                var prev = subtitle.Paragraphs[subtitle.Paragraphs.Count - 1];
                                if (prev.Text == p.Text && prev.StartTime.TotalMilliseconds == p.StartTime.TotalMilliseconds)
                                {
                                    add = false;
                                }
                            }
                            if (add)
                            {
                                subtitle.Paragraphs.Add(p);
                            }
                        }
                        catch
                        {
                            _errorCount++;
                        }
                    }
                }
                subtitle.Renumber();
            }
            catch
            {
                _errorCount = 1;
            }
        }
Example #44
0
        private string ImportFile(string name, string xml, List <WorklistAsset> sources, string sourcePath, List <WorklistAsset> targets, string targetPath)
        {
            ShowStatus("Importing " + name + " ...");

            var           error = "";
            WorklistAsset asset;

            var sourceId = int.Parse(name.Split(".-".ToCharArray()).FirstOrDefault());
            var source   = sources.FirstOrDefault(a => a.id == sourceId && a.FullPath.StartsWith(sourcePath));

            if (source == null)
            {
                try
                {
                    _cms.Asset.Read(sourceId, out asset);
                }
                catch
                {
                    asset = null;
                }
                if (asset != null && asset.id == sourceId && asset.branchId > 0)
                {
                    source = sources.FirstOrDefault(a => a.branchId == asset.branchId && a.FullPath.StartsWith(sourcePath));
                }
                if (source == null)
                {
                    // Try again with the first field, which contains branchid and path
                    var xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(xml);
                    var xnm = new XmlNamespaceManager(xmlDoc.NameTable);
                    xnm.AddNamespace("xtm", xmlDoc.DocumentElement.NamespaceURI);
                    var firstField = xmlDoc.SelectSingleNode("//xtm:field", xnm);
                    if (firstField != null)
                    {
                        var key   = System.Net.WebUtility.HtmlDecode(GetNodeValue(firstField.SelectSingleNode("xtm:_key", xnm)));
                        var value = GetNodeValue(firstField.SelectSingleNode("xtm:value", xnm));
                        if (value == "" && key.IndexOf("/") > 0)
                        {
                            var branchId = int.Parse(key.Substring(0, key.IndexOf("/")));
                            source = sources.FirstOrDefault(a => a.branchId == branchId && a.FullPath.StartsWith(sourcePath));
                            if (source == null)
                            {
                                var path = key.Substring(key.IndexOf("/"));
                                source = sources.FirstOrDefault(a => a.FullPath == path && a.FullPath.StartsWith(sourcePath));
                            }
                        }
                    }
                }
            }

            if (source == null)
            {
                error = "Source not found for " + sourceId;
            }
            else
            {
                var destPath = targetPath + source.FullPath.Substring(sourcePath.Length);
                var target   = targets.FirstOrDefault(a => a.FullPath == destPath);
                if (target == null)
                {
                    error = "Target not found for " + sourceId + ", " + source.FullPath;
                }
                else
                {
                    var xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(xml);
                    var xnm = new XmlNamespaceManager(xmlDoc.NameTable);
                    xnm.AddNamespace("xtm", xmlDoc.DocumentElement.NamespaceURI);
                    var fields       = xmlDoc.SelectNodes("//xtm:field", xnm).Cast <XmlNode>().ToArray();
                    var fieldsToSave = fields.Where(f => !string.IsNullOrEmpty(GetNodeValue(f.SelectSingleNode("xtm:value", xnm)))).ToDictionary(f => GetNodeValue(f.SelectSingleNode("xtm:_key", xnm)), f => GetNodeValue(f.SelectSingleNode("xtm:value", xnm)));
                    if (fieldsToSave.Any())
                    {
                        ShowStatus("Updating " + target.FullPath + " ...");
                        _cms.Asset.Update(target.id, fieldsToSave, out asset);
                    }
                }
            }

            if (!string.IsNullOrEmpty(error))
            {
                Console.Write(error);
            }

            return(error);
        }
Example #45
0
        public HttpResponseMessage GetSecurityBulletins()
        {
            try
            {
                var    plartformVersion = System.Reflection.Assembly.LoadFrom(Globals.ApplicationMapPath + @"\bin\DotNetNuke.dll").GetName().Version;
                string sRequest         = string.Format("http://update.dotnetnuke.com/security.aspx?type={0}&name={1}&version={2}",
                                                        DotNetNukeContext.Current.Application.Type,
                                                        "DNNCORP.CE",
                                                        Globals.FormatVersion(plartformVersion, "00", 3, ""));

                //format for display with "." delimiter
                string sVersion = Globals.FormatVersion(plartformVersion, "00", 3, ".");

                // make remote request
                Stream oStream = null;
                try
                {
                    HttpWebRequest oRequest = Globals.GetExternalRequest(sRequest);
                    oRequest.Timeout = 10000; // 10 seconds
                    WebResponse oResponse = oRequest.GetResponse();
                    oStream = oResponse.GetResponseStream();
                }
                catch (Exception oExc)
                {
                    // connectivity issues
                    if (PortalSecurity.IsInRoles(PortalSettings.AdministratorRoleId.ToString()))
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format(Localization.GetString("RequestFailed_Admin.Text", Components.Constants.LocalResourcesFile), sRequest)));
                    }
                    else
                    {
                        return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, Localization.GetString("RequestFailed_User.Text", Components.Constants.LocalResourcesFile) + oExc.Message));
                    }
                }

                // load XML document
                StreamReader oReader = new StreamReader(oStream);
                XmlDocument  oDoc    = new XmlDocument {
                    XmlResolver = null
                };
                oDoc.LoadXml(oReader.ReadToEnd());

                List <object> items = new List <object>();
                foreach (XmlNode selectNode in oDoc.SelectNodes(BULLETIN_XMLNODE_PATH))
                {
                    items.Add(new
                    {
                        Title       = selectNode.SelectSingleNode("title") != null ? selectNode.SelectSingleNode("title").InnerText : "",
                        Link        = selectNode.SelectSingleNode("link") != null ? selectNode.SelectSingleNode("link").InnerText : "",
                        Description = selectNode.SelectSingleNode("description") != null ? selectNode.SelectSingleNode("description").InnerText : "",
                        Author      = selectNode.SelectSingleNode("author") != null ? selectNode.SelectSingleNode("author").InnerText : "",
                        PubDate     = selectNode.SelectSingleNode("pubDate") != null ? selectNode.SelectSingleNode("pubDate").InnerText.Split(' ')[0] : ""
                    });
                }

                var response = new
                {
                    Success = true,
                    Results = new
                    {
                        PlatformVersion   = sVersion,
                        SecurityBulletins = items
                    }
                };

                return(Request.CreateResponse(HttpStatusCode.OK, response));
            }
            catch (Exception exc)
            {
                Logger.Error(exc);
                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc));
            }
        }
        //======================================================================
        // Import user settings
        //======================================================================
        public static void Import()
        {
            OpenFileDialog openFile = new OpenFileDialog();

            openFile.Filter   = "XML File (*.xml)|*.xml";
            openFile.FileName = "RWC Settings.xml";

            DialogResult result = openFile.ShowDialog();

            if (result == DialogResult.OK)
            {
                string selectedFile = openFile.FileName;
                string version      = Assembly.GetEntryAssembly().GetName().Version.ToString();

                XmlDocument doc = new XmlDocument();
                doc.Load(selectedFile);
                XmlNodeList xnList = doc.SelectNodes("/RWC-Settings");
                foreach (XmlNode xn in xnList)
                {
                    try
                    {
                        string xmlVersion = xn["Version"].InnerText;

                        // Version check? Can't decide if needed or not...
                        if (xmlVersion != version)
                        {
                            //    MessageBox.Show("Unable to import settings as they have been exported from a previous version.\r\n\r\n" +
                            //        "XML Version: " + xmlVersion + "\r\n" +
                            //        "RWC Version: " + version + "\r\n\r\n" +
                            //        "Please configure Reddit Wallpaper Changer manually, or re-export the settings form an application running on version " + version + ".", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            //    return;
                        }

                        Properties.Settings.Default.wallpaperGrabType    = Int32.Parse(xn["GrabType"].InnerText);
                        Properties.Settings.Default.subredditsUsed       = xn["Subreddits"].InnerText;
                        Properties.Settings.Default.searchQuery          = xn["SearchQuery"].InnerText;
                        Properties.Settings.Default.changeTimeValue      = Int32.Parse(xn["ChangeTimerValue"].InnerText);
                        Properties.Settings.Default.changeTimeType       = Int32.Parse(xn["ChangeTimerType"].InnerText);
                        Properties.Settings.Default.startInTray          = Boolean.Parse(xn["StartInTray"].InnerText);
                        Properties.Settings.Default.autoStart            = Boolean.Parse(xn["AutoStart"].InnerText);
                        Properties.Settings.Default.useProxy             = Boolean.Parse(xn["UseProxy"].InnerText);
                        Properties.Settings.Default.proxyAddress         = xn["ProxyServer"].InnerText;
                        Properties.Settings.Default.proxyAuth            = Boolean.Parse(xn["ProxyAuthentication"].InnerText);
                        Properties.Settings.Default.defaultSaveLocation  = xn["DefaultSaveLocation"].InnerText;
                        Properties.Settings.Default.autoSave             = Boolean.Parse(xn["AutoSave"].InnerText);
                        Properties.Settings.Default.wallpaperFade        = Boolean.Parse(xn["WallpaperFade"].InnerText);
                        Properties.Settings.Default.disableNotifications = Boolean.Parse(xn["DisableNotifications"].InnerText);
                        Properties.Settings.Default.Save();

                        Logging.LogMessageToFile("Settings have been successfully imported. Restarting RWC.");
                        MessageBox.Show("Settings file imported successfully.\r\n\r\n" +
                                        "Note: If a proxy is specified that requires authentication, you must manually enter the credentials.\r\n\r\n" +
                                        "RWC will now restart so the new settings take effect.", "Settings Imported", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        // Close and re-launch RWC to apply changes.
                        System.Diagnostics.Process.Start(System.Reflection.Assembly.GetExecutingAssembly().Location);
                        System.Environment.Exit(0);
                    }
                    catch (Exception ex)
                    {
                        Logging.LogMessageToFile("Unexpected error importing settings file: " + ex.Message);
                        MessageBox.Show("Unexpected error importing settings from XML: " + ex.Message, "Error Importing!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
Example #47
0
		static void Main (string [] args)
		{
			foreach (string arg in args) {
				if (arg.IndexOfAny ("*?".ToCharArray ()) != -1) {
					FileInfo [] infos = new DirectoryInfo (Environment.CurrentDirectory).GetFiles (arg);

					foreach (FileInfo info in infos) {
						XmlDocument doc = new XmlDocument ();

						doc.Load (info.FullName);
						string name = doc.SelectSingleNode ("//Identification/ShortName").InnerText;
                        string version = doc.SelectSingleNode ("//Identification/Version").InnerText;

						if (!name.Equals ("FpML Set of Coding Schemes"))
							codeLists [name+ "-" + version] = doc;
					}
				}
				else {
					XmlDocument doc = new XmlDocument ();

					doc.Load (arg);
					string name = doc.SelectSingleNode ("//Identification/ShortName").InnerText;

					if (!name.Equals ("FpML Set of Coding Schemes"))
						codeLists [name] = doc;
				}
			}

            Console.OutputEncoding = Encoding.UTF8;
			Console.Out.WriteLine ("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
			Console.Out.WriteLine ("<schemeDefinitions>");
			foreach (string name in codeLists.Keys) {
				XmlDocument doc = codeLists [name];
				string uri = doc.SelectSingleNode ("//Identification/CanonicalVersionUri").InnerText;
				string canonicalUri = doc.SelectSingleNode ("//Identification/CanonicalUri").InnerText;

				Console.Out.WriteLine ("\t<scheme uri=\"" + uri
					+ "\" canonicalUri=\"" + canonicalUri
					+ "\" name=\"" + name + "\">");
				Console.Out.WriteLine ("\t\t<schemeValues>");

				int codeIndex = -1;
				int sourceIndex = -1;
				int descIndex = -1;

				int count = 1;
				foreach (XmlNode node in doc.SelectNodes ("//ColumnSet/Column")) {
					string text = node ["ShortName"].InnerText;

					if (text.Equals ("Code")) codeIndex = count;
					if (text.Equals ("Source")) sourceIndex = count;
					if (text.Equals ("Description")) descIndex = count;

					++count;
				}

				if ((codeIndex == -1) || (sourceIndex == -1) || (descIndex == -1)) {
					Console.Error.WriteLine ("A required column is not present in code list for " + name);
					continue;
				}

				foreach (XmlNode node in doc.SelectNodes ("//SimpleCodeList/Row")) {
					string code = Escape (node.SelectSingleNode ("Value[" + codeIndex + "]/SimpleValue").InnerText);
					string source = Escape (node.SelectSingleNode ("Value[" + sourceIndex + "]/SimpleValue").InnerText);
					string desc = Escape (node.SelectSingleNode ("Value[" + descIndex + "]/SimpleValue").InnerText.Trim ());

					Console.Out.WriteLine ("\t\t\t<schemeValue schemeValueSource=\"" + source + "\" name=\"" + code + "\">");
					if (desc.Length > 0)
						Console.Out.WriteLine ("\t\t\t\t<paragraph>" + desc + "</paragraph>");
					Console.Out.WriteLine ("\t\t\t</schemeValue>");
				}

				Console.Out.WriteLine ("\t\t</schemeValues>");
				Console.Out.WriteLine ("\t</scheme>");
			}
			Console.Out.WriteLine ("</schemeDefinitions>");
		}
Example #48
0
        private List <Appointment> ParseAppointmentResultSetXml(XmlDocument doc)
        {
            List <Appointment> result = new List <Appointment>();
            XPathNavigator     nav    = doc.CreateNavigator();
            bool active = nav.MoveToFirstChild();

            XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                result.Add(appt);
            }

            return(result);
        }
Example #49
0
        /// <summary>
        /// Checks the minimum supported webserver version
        /// </summary>
        /// <returns>Returns true if it is supported</returns>
        public bool IsSupportedVersion()
        {
            bool         success  = false;
            const string function = "CVAPI::GetVersionInfo";

            try
            {
                // Get the min supported version in format 10.9.2
                string[] suportedVersion = AppSettingsReader.Instance.GetSettingValue("MinSupportedServerVersion").Split(new char[] { '.' });
                Logger.Info(string.Format("Supported version: {0}", AppSettingsReader.Instance.GetSettingValue("MinSupportedServerVersion")), function);

                HttpWebResponse ClientResp = SendRequest(ServiceURI + getVersionURI, get, _authToken, null);
                if (ClientResp.StatusCode == HttpStatusCode.OK)
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.Load(ClientResp.GetResponseStream());
                    Logger.Info("Server returned version: " + xmlDoc.InnerXml, function);
                    XmlNodeList nameAttrList  = xmlDoc.SelectNodes("/App_GetVersionInfoResponse/WSVersionInfo/attributes/@name");
                    XmlNodeList valueAttrList = xmlDoc.SelectNodes("/App_GetVersionInfoResponse/WSVersionInfo/attributes/@value");
                    if (null != nameAttrList && null != valueAttrList && nameAttrList.Count == valueAttrList.Count)
                    {
                        // parse the response xml to get the version info
                        Dictionary <string, int> versionInfoDic = new Dictionary <string, int>();
                        for (int i = 0; i < nameAttrList.Count; i++)
                        {
                            versionInfoDic.Add(nameAttrList[i].Value.ToLower(), Convert.ToInt32(valueAttrList[i].Value));
                        }

                        // Compare w/ the supported version
                        if (versionInfoDic.ContainsKey("release") && versionInfoDic.ContainsKey("highestsp") && versionInfoDic.ContainsKey("spminorversion"))
                        {
                            if (versionInfoDic["release"] > Convert.ToInt32(suportedVersion[0])) // Release is greater than supported, no need to check further
                            {
                                return(true);
                            }
                            else if (versionInfoDic["release"] == Convert.ToInt32(suportedVersion[0]))
                            {
                                if (versionInfoDic["highestsp"] > Convert.ToInt32(suportedVersion[1])) // Highest SP is greater than supported, no need to check further
                                {
                                    return(true);
                                }
                                else if (versionInfoDic["highestsp"] == Convert.ToInt32(suportedVersion[1]))
                                {
                                    if (versionInfoDic["spminorversion"] >= Convert.ToInt32(suportedVersion[2])) // Minor version is supported
                                    {
                                        return(true);
                                    }
                                }
                                else // release is supported but highest SP is lower than supported
                                {
                                    return(false);
                                }
                            }
                            else // release is lower than supported
                            {
                                return(false);
                            }
                        }
                        else
                        {
                            Logger.Error("API did not return attributes node in required format:" + xmlDoc.InnerText, function);
                        }
                    }
                    else
                    {
                        Logger.Error("API did not return attributes node in required format:" + xmlDoc.InnerText, function);
                    }
                }
                else
                {
                    Logger.Error("GetVersionInfo api call failed.", function);
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, function);
            }
            return(success);
        }
Example #50
0
        public override void control(bot ircbot, ref IRCConfig conf, int module_id, string[] line, string command, int nick_access, string nick, string channel, bool bot_command, string type)
        {
            string module_name = ircbot.conf.module_config[module_id][0];

            if (type.Equals("channel") && bot_command == false)
            {
                string text = "";
                if (line.GetUpperBound(0) > 3)
                {
                    text = line[3] + " " + line[4];
                }
                else
                {
                    text = line[3];
                }
                try
                {
                    Regex regex = new Regex("(((https?|ftp|file)://|www\\.)([A-Z0-9.-:]{1,})\\.[0-9A-Z?;~&#=\\-_\\./]{2,})", RegexOptions.Compiled | RegexOptions.IgnoreCase);

                    //get the first match
                    MatchCollection matches = regex.Matches(text);

                    foreach (Match match in matches)
                    {
                        string testMatch = match.Value.ToString();
                        if (!testMatch.Contains("://"))
                        {
                            testMatch = "http://" + testMatch;
                        }
                        Uri url     = new Uri(testMatch);
                        var request = WebRequest.Create(url);
                        request.Timeout = 5000;
                        using (var response = request.GetResponse())
                        {
                            string[] content_type = response.ContentType.Split('/');
                            switch (content_type[0])
                            {
                            case "text":
                                WebClient       x             = new WebClient();
                                string          source        = x.DownloadString(url.OriginalString);
                                string          title_regex   = @"(?<=<title.*>)(.*?)(?=</title>)";
                                Regex           title_ex      = new Regex(title_regex, RegexOptions.IgnoreCase);
                                MatchCollection title_matches = title_ex.Matches(source);
                                string          title         = title_matches[0].Value.Trim();
                                if (url.OriginalString.Contains("youtube.com/watch?") && ircbot.conf.module_config[module_id][4].Equals("True"))
                                {
                                    string YouTubeVideoID             = ExtractYouTubeVideoIDFromUrl(url.OriginalString);
                                    Uri    videoEntryUrl              = new Uri(string.Format("https://gdata.youtube.com/feeds/api/videos/{0}", YouTubeVideoID));
                                    YouTubeRequestSettings settings   = new YouTubeRequestSettings("YouTube Video Duration Sample App", developerKey);
                                    YouTubeRequest         yt_request = new YouTubeRequest(settings);
                                    Video    video          = yt_request.Retrieve <Video>(videoEntryUrl);
                                    int      duration       = int.Parse(video.Contents.First().Duration);
                                    string   yt_title       = video.Title;
                                    int      views          = video.ViewCount;
                                    double   rateavg        = video.RatingAverage;
                                    string   uploader       = video.Uploader;
                                    DateTime date           = video.Updated;
                                    string   total_duration = "";
                                    TimeSpan t = TimeSpan.FromSeconds(duration);
                                    if (t.Hours > 0)
                                    {
                                        total_duration += t.Hours.ToString() + "h ";
                                    }
                                    if (t.Minutes > 0)
                                    {
                                        total_duration += t.Minutes.ToString() + "m ";
                                    }
                                    if (t.Seconds > 0)
                                    {
                                        total_duration += t.Seconds.ToString() + "s ";
                                    }
                                    ircbot.sendData("PRIVMSG", channel + " :[Youtube] Title: " + HttpUtility.HtmlDecode(yt_title) + " | Length: " + total_duration.TrimEnd(' ') + " | Views: " + string.Format("{0:#,###0}", views) + " | Rated: " + Math.Round(rateavg, 2).ToString() + "/5.0 | Uploaded By: " + uploader + " on " + date.ToString("yyyy-MM-dd"));
                                }
                                else if (url.OriginalString.Contains("youtu.be") && ircbot.conf.module_config[module_id][4].Equals("True"))
                                {
                                    string[] url_parsed               = url.OriginalString.Split('/');
                                    string   YouTubeVideoID           = url_parsed[url_parsed.GetUpperBound(0)];
                                    Uri      videoEntryUrl            = new Uri(string.Format("https://gdata.youtube.com/feeds/api/videos/{0}", YouTubeVideoID));
                                    YouTubeRequestSettings settings   = new YouTubeRequestSettings("YouTube Video Duration Sample App", developerKey);
                                    YouTubeRequest         yt_request = new YouTubeRequest(settings);
                                    Video    video          = yt_request.Retrieve <Video>(videoEntryUrl);
                                    int      duration       = int.Parse(video.Contents.First().Duration);
                                    string   yt_title       = video.Title;
                                    int      views          = video.ViewCount;
                                    double   rateavg        = video.RatingAverage;
                                    string   uploader       = video.Uploader;
                                    DateTime date           = video.Updated;
                                    string   total_duration = "";
                                    TimeSpan t = TimeSpan.FromSeconds(duration);
                                    if (t.Hours > 0)
                                    {
                                        total_duration += t.Hours.ToString() + "h ";
                                    }
                                    if (t.Minutes > 0)
                                    {
                                        total_duration += t.Minutes.ToString() + "m ";
                                    }
                                    if (t.Seconds > 0)
                                    {
                                        total_duration += t.Seconds.ToString() + "s ";
                                    }
                                    ircbot.sendData("PRIVMSG", channel + " :[Youtube] Title: " + HttpUtility.HtmlDecode(yt_title) + " | Length: " + total_duration.TrimEnd(' ') + " | Views: " + string.Format("{0:#,###0}", views) + " | Rated: " + Math.Round(rateavg, 2).ToString() + "/5.0 | Uploaded By: " + uploader + " on " + date.ToString("yyyy-MM-dd"));
                                }
                                else if ((url.OriginalString.Contains("boards.4chan.org") && url.Segments.GetUpperBound(0) > 2) && ircbot.conf.module_config[module_id][5].Equals("True"))
                                {
                                    string    board     = url.Segments[1].TrimEnd('/');
                                    string    uri       = "https://api.4chan.org/" + board + "/res/" + url.Segments[3] + ".json";
                                    WebClient chan      = new WebClient();
                                    var       json_data = string.Empty;
                                    json_data = chan.DownloadString(uri);
                                    XmlDocument xmlDoc    = JsonConvert.DeserializeXmlNode(json_data, board + "-" + url.Segments[3]);
                                    XmlNodeList post_list = xmlDoc.SelectNodes(board + "-" + url.Segments[3] + "/posts");
                                    string      thread    = "";
                                    if (!url.Fragment.Equals(string.Empty))
                                    {
                                        thread = url.Fragment.TrimStart('#').TrimStart('p');
                                    }
                                    else
                                    {
                                        thread = url.Segments[3];
                                    }
                                    foreach (XmlNode post in post_list)
                                    {
                                        string post_num = post["no"].InnerText;
                                        if (post_num.Equals(thread))
                                        {
                                            string   date        = post["now"].InnerText;
                                            string   parsed_date = date.Split('(')[0] + " " + date.Split(')')[1];
                                            DateTime post_date   = DateTime.Parse(parsed_date);
                                            TimeSpan difference  = DateTime.UtcNow - post_date;
                                            difference = difference.Subtract(TimeSpan.FromHours(4));
                                            string   total_duration = "";
                                            TimeSpan t = TimeSpan.FromSeconds(difference.TotalSeconds);
                                            if (t.Hours > 0)
                                            {
                                                total_duration += t.Hours.ToString() + "h ";
                                            }
                                            if (t.Minutes > 0)
                                            {
                                                total_duration += t.Minutes.ToString() + "m ";
                                            }
                                            if (t.Seconds > 0)
                                            {
                                                total_duration += t.Seconds.ToString() + "s ";
                                            }
                                            string post_name = "", post_comment = "", tripcode = "", ID = "", email = "", subject = "", replies = "", images = "", image_ext = "", image_name = "", image_width = "", image_height = "";
                                            try
                                            {
                                                post_name = post["name"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                post_comment = post["com"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                tripcode = post["trip"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                ID = post["id"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                email = post["email"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                subject = post["sub"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                replies = post["replies"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                images = post["images"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                image_ext = post["ext"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                image_name = post["tim"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                image_width = post["w"].InnerText;
                                            }
                                            catch { }
                                            try
                                            {
                                                image_height = post["h"].InnerText;
                                            }
                                            catch { }

                                            if (!ID.Trim().Equals(string.Empty))
                                            {
                                                ID = "[" + ID + "]";
                                            }

                                            string post_message = "";
                                            if (!subject.Equals(string.Empty))
                                            {
                                                post_message += "Subject: " + subject + " | ";
                                            }
                                            string[] words = post_comment.Split(' ');
                                            if (words.GetUpperBound(0) > 10)
                                            {
                                                post_message += " Comment: ";
                                                for (int i = 0; i < 15; i++)
                                                {
                                                    post_message += words[i] + " ";
                                                }
                                                post_message += "...";
                                            }
                                            else if (!post_comment.Equals(string.Empty))
                                            {
                                                post_message += " Comment: " + post_comment;
                                            }

                                            string[] tmp_post = Regex.Split(post_message, "<br>");
                                            post_message = "";
                                            foreach (string tmp in tmp_post)
                                            {
                                                if (!tmp.Trim().Equals(string.Empty))
                                                {
                                                    post_message += HttpUtility.HtmlDecode(tmp) + " | ";
                                                }
                                            }

                                            string image_url = "";
                                            if (!image_name.Equals(string.Empty))
                                            {
                                                image_url = "http://images.4chan.org/" + board + "/src/" + image_name + image_ext;
                                            }

                                            if (!image_url.Equals(string.Empty))
                                            {
                                                image_url = " | Posted Image: " + image_url + " (" + image_width + "x" + image_height + ")";
                                            }

                                            if (!replies.Equals(string.Empty))
                                            {
                                                replies = " | Replies: " + replies;
                                            }

                                            if (!images.Equals(string.Empty))
                                            {
                                                images = " | Images: " + images;
                                            }

                                            ircbot.sendData("PRIVMSG", channel + " :[4chan] /" + board + "/ | Posted by: " + post_name + tripcode + ID + " " + total_duration.Trim() + " ago" + replies + images + image_url);
                                            string re = @"<a [^>]+>(.*?)<\/a>(.*?)";
                                            if (!post_message.Equals(string.Empty))
                                            {
                                                ircbot.sendData("PRIVMSG", channel + " :" + Regex.Replace(post_message.Trim().TrimEnd('|').Trim(), re, "$1"));
                                            }
                                            break;
                                        }
                                    }
                                }
                                else if (ircbot.conf.module_config[module_id][3].Equals("True"))
                                {
                                    ircbot.sendData("PRIVMSG", channel + " :[URL] " + HttpUtility.HtmlDecode(title) + " (" + url.Host.ToLower() + ")");
                                }
                                break;

                            case "image":
                                if (ircbot.conf.module_config[module_id][6].Equals("True"))
                                {
                                    Image _image = null;
                                    _image = DownloadImage(url.OriginalString);
                                    if (_image != null)
                                    {
                                        ircbot.sendData("PRIVMSG", channel + " :[" + response.ContentType + "] Size: " + ToFileSize(response.ContentLength) + " | Width: " + _image.Width.ToString() + "px | Height: " + _image.Height.ToString() + "px");
                                    }
                                }
                                break;

                            case "video":
                                if (ircbot.conf.module_config[module_id][7].Equals("True"))
                                {
                                    ircbot.sendData("PRIVMSG", channel + " :[Video] Type: " + content_type[1] + " | Size: " + ToFileSize(response.ContentLength));
                                }
                                break;

                            case "application":
                                if (ircbot.conf.module_config[module_id][8].Equals("True"))
                                {
                                    ircbot.sendData("PRIVMSG", channel + " :[Application] Type: " + content_type[1] + " | Size: " + ToFileSize(response.ContentLength));
                                }
                                break;

                            case "audio":
                                if (ircbot.conf.module_config[module_id][9].Equals("True"))
                                {
                                    ircbot.sendData("PRIVMSG", channel + " :[Audio] Type: " + content_type[1] + " | Size: " + ToFileSize(response.ContentLength));
                                }
                                break;

                            default:
                                if (ircbot.conf.module_config[module_id][10].Equals("True"))
                                {
                                    ircbot.sendData("PRIVMSG", channel + " :[URL] " + HttpUtility.HtmlDecode(response.ContentType) + " (" + url.Host.ToLower() + ")");
                                }
                                break;
                            }
                        }
                    }
                }
                catch
                {
                }
            }
        }
Example #51
0
 XmlNodeList IXmlOriginalDocumentService.SelectNodes(string xpath, XmlNamespaceManager nsmgr) => _xmlOriginal?.SelectNodes(xpath, nsmgr);
Example #52
0
        private void cmdSearch_Click(object sender, EventArgs e)
        {
            omaeSoapClient objService = _objOmaeHelper.GetOmaeService();

            // Clear the current contents of the Omae Panel. Detach the events before clearing it.
            foreach (OmaeRecord objRecord in panOmae.Controls.OfType <OmaeRecord>())
            {
                objRecord.OmaeDownloadClicked   -= objRecord_OmaeDownloadClicked;
                objRecord.OmaePostUpdateClicked -= objRecord_OmaePostUpdateClicked;
                objRecord.OmaeDeleteClicked     -= objRecord_OmaeDeleteClicked;
            }
            panOmae.Controls.Clear();

            // Set the current operating mode.
            switch (cboCharacterTypes.SelectedValue.ToString())
            {
            case "data":
                _objMode = OmaeMode.Data;
                break;

            case "sheets":
                _objMode = OmaeMode.Sheets;
                break;

            default:
                _objMode = OmaeMode.Character;
                break;
            }

            // Search for characters.
            if (_objMode == OmaeMode.Character)
            {
                try
                {
                    MemoryStream  objStream = new MemoryStream();
                    XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8);

                    objService.FetchCharacters153(Convert.ToInt32(cboCharacterTypes.SelectedValue),
                                                  Convert.ToInt32(cboSortOrder.SelectedValue), cboFilterMetatype.Text,
                                                  cboFilterMetavariant.Text, Convert.ToInt32(cboFilterMode.SelectedValue),
                                                  txtFilterUser.Text, cboFilterQuality1.Text, cboFilterQuality2.Text,
                                                  cboFilterQuality3.Text).WriteTo(objWriter);
                    // Flush the output.
                    objWriter.Flush();
                    objStream.Flush();

                    XmlDocument objXmlDocument = _objOmaeHelper.XmlDocumentFromStream(objStream);

                    // Close everything now that we're done.
                    objWriter.Close();
                    objStream.Close();

                    if (objXmlDocument.SelectNodes("/characters/character").Count == 0)
                    {
                        Label lblResults = new Label();
                        lblResults.Text  = LanguageManager.Instance.GetString("String_Omae_NoCharacters");
                        lblResults.Width = 200;
                        panOmae.Controls.Add(lblResults);
                    }
                    else
                    {
                        int intCounter = -1;
                        foreach (XmlNode objNode in objXmlDocument.SelectNodes("/characters/character"))
                        {
                            intCounter++;
                            OmaeRecord objRecord = new OmaeRecord(objNode, Convert.ToInt32(cboCharacterTypes.SelectedValue), OmaeMode.Character);
                            objRecord.OmaeDownloadClicked   += objRecord_OmaeDownloadClicked;
                            objRecord.OmaePostUpdateClicked += objRecord_OmaePostUpdateClicked;
                            objRecord.OmaeDeleteClicked     += objRecord_OmaeDeleteClicked;
                            if ((objRecord.UserName == txtUserName.Text || txtUserName.Text == "Nebular") && _blnLoggedIn)
                            {
                                objRecord.OwnedByUser = true;
                            }
                            objRecord.Top = intCounter * 88;
                            panOmae.Controls.Add(objRecord);
                        }
                    }
                    objService.Close();
                }
                catch (EndpointNotFoundException)
                {
                    MessageBox.Show(NO_CONNECTION_MESSAGE, NO_CONNECTION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            // Search for data.
            if (_objMode == OmaeMode.Data)
            {
                try
                {
                    MemoryStream  objStream = new MemoryStream();
                    XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8);

                    objService.FetchDataFiles(Convert.ToInt32(cboSortOrder.SelectedValue), "", txtFilterUser.Text).WriteTo(objWriter);
                    // Flush the output.
                    objWriter.Flush();
                    objStream.Flush();

                    XmlDocument objXmlDocument = _objOmaeHelper.XmlDocumentFromStream(objStream);

                    // Close everything now that we're done.
                    objWriter.Close();
                    objStream.Close();

                    if (objXmlDocument.SelectNodes("/datas/data").Count == 0)
                    {
                        Label lblResults = new Label();
                        lblResults.Text  = LanguageManager.Instance.GetString("String_Omae_NoData");
                        lblResults.Width = 200;
                        panOmae.Controls.Add(lblResults);
                    }
                    else
                    {
                        int intCounter = -1;
                        foreach (XmlNode objNode in objXmlDocument.SelectNodes("/datas/data"))
                        {
                            intCounter++;
                            OmaeRecord objRecord = new OmaeRecord(objNode, 0, OmaeMode.Data);
                            objRecord.OmaeDownloadClicked   += objRecord_OmaeDownloadClicked;
                            objRecord.OmaePostUpdateClicked += objRecord_OmaePostUpdateClicked;
                            objRecord.OmaeDeleteClicked     += objRecord_OmaeDeleteClicked;
                            if ((objRecord.UserName == txtUserName.Text || txtUserName.Text == "Nebular") && _blnLoggedIn)
                            {
                                objRecord.OwnedByUser = true;
                            }
                            objRecord.Top = intCounter * 88;
                            panOmae.Controls.Add(objRecord);
                        }
                    }
                    objService.Close();
                }
                catch (EndpointNotFoundException)
                {
                    MessageBox.Show(NO_CONNECTION_MESSAGE, NO_CONNECTION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }

            // Search for character sheets.
            if (_objMode == OmaeMode.Sheets)
            {
                try
                {
                    MemoryStream  objStream = new MemoryStream();
                    XmlTextWriter objWriter = new XmlTextWriter(objStream, Encoding.UTF8);

                    objService.FetchSheets(Convert.ToInt32(cboSortOrder.SelectedValue), txtFilterUser.Text).WriteTo(objWriter);
                    // Flush the output.
                    objWriter.Flush();
                    objStream.Flush();

                    XmlDocument objXmlDocument = _objOmaeHelper.XmlDocumentFromStream(objStream);

                    // Close everything now that we're done.
                    objWriter.Close();
                    objStream.Close();

                    if (objXmlDocument.SelectNodes("/sheets/sheet").Count == 0)
                    {
                        Label lblResults = new Label();
                        lblResults.Text  = LanguageManager.Instance.GetString("String_Omae_NoSheets");
                        lblResults.Width = 200;
                        panOmae.Controls.Add(lblResults);
                    }
                    else
                    {
                        int intCounter = -1;
                        foreach (XmlNode objNode in objXmlDocument.SelectNodes("/sheets/sheet"))
                        {
                            intCounter++;
                            OmaeRecord objRecord = new OmaeRecord(objNode, 0, OmaeMode.Sheets);
                            objRecord.OmaeDownloadClicked   += objRecord_OmaeDownloadClicked;
                            objRecord.OmaePostUpdateClicked += objRecord_OmaePostUpdateClicked;
                            objRecord.OmaeDeleteClicked     += objRecord_OmaeDeleteClicked;
                            if ((objRecord.UserName == txtUserName.Text || txtUserName.Text == "Nebular") && _blnLoggedIn)
                            {
                                objRecord.OwnedByUser = true;
                            }
                            objRecord.Top = intCounter * 88;
                            panOmae.Controls.Add(objRecord);
                        }
                    }
                    objService.Close();
                }
                catch (EndpointNotFoundException)
                {
                    MessageBox.Show(NO_CONNECTION_MESSAGE, NO_CONNECTION_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Example #53
0
    // Update is called once per frame
    void LoadMap()
    {
        //Loading the map
        currentPrefab = null;
        nodeList      = xmlDoc.SelectNodes("//level/map/row");

        for (int i = 0; i < nodeList.Count; i++)
        {
            currentNode = nodeList[i];
            for (int j = 0; j < currentNode.InnerText.Length; j++)
            {
                switch (currentNode.InnerText[j])
                {
                case 'A':
                    currentPrefab = Grass1;
                    break;

                case 'B':
                    currentPrefab = Grass2;
                    break;

                case 'C':
                    currentPrefab = Tree;
                    break;

                case 'D':
                    currentPrefab = RoadCross;
                    break;

                case 'E':
                    currentPrefab = RoadEndHor2;
                    break;

                case 'F':
                    currentPrefab = RoadEndHor2Left;
                    break;

                case 'G':
                    currentPrefab = RoadEndVer2;
                    break;

                case 'H':
                    currentPrefab = RoadEndVer2Down;
                    break;

                case 'I':
                    currentPrefab = RoadMiddleHor;
                    break;

                case 'J':
                    currentPrefab = RoaddMiddleVer1;
                    break;
                }

                currentPrefab = Instantiate(currentPrefab, new Vector3(j, -i),
                                            Quaternion.identity);

                currentPrefab.transform.SetParent(cellsConstainer);
            }
        }

        //Loading characters:

        LoadCharacters();
    }
Example #54
0
        public void update()
        {
            logging.AddToLog("Starting Update", false);
            try
            {
                string zipcode = OSAEObjectPropertyManager.GetObjectPropertyValue(pName, "Zipcode").Value;
                logging.AddToLog("ZipCode: " + zipcode, false);
                if (zipcode != "")
                {
                    List <ObservationStation> stationList = new List <ObservationStation>();
                    PointF             pt        = GetLatLonFromZip(zipcode);
                    ObservationStation myStation = new ObservationStation();
                    feedUrl = OSAEObjectPropertyManager.GetObjectPropertyValue(pName, "Feed URL").Value;
                    logging.AddToLog("pt.X: " + pt.X.ToString(), false);
                    logging.AddToLog("pt.Y: " + pt.Y.ToString(), false);
                    if (pt.X != 0 || pt.Y != 0)
                    {
                        logging.AddToLog("Enter Update", false);
                        logging.AddToLog("feedUrl: " + feedUrl, false);

                        if (feedUrl == "")
                        {
                            WebClient webClient = new WebClient();
                            string    strSource = webClient.DownloadString("http://www.weather.gov/xml/current_obs/index.xml");
                            webClient.Dispose();

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

                            XmlNodeList xnList = xml.SelectNodes("/wx_station_index/station");
                            foreach (XmlNode xn in xnList)
                            {
                                ObservationStation obs = new ObservationStation(xn);
                                stationList.Add(obs);
                            }

                            logging.AddToLog("lat: " + pt.X.ToString(), false);
                            logging.AddToLog("lon: " + pt.Y.ToString(), false);
                            logging.AddToLog("# of stations: " + stationList.Count.ToString(), false);
                            myStation = GetClosest((decimal)pt.Y, (decimal)pt.X, stationList);
                            feedUrl   = myStation.CurrentObsXmlUrl;
                            logging.AddToLog("Found feed: " + feedUrl, false);
                        }

                        if (feedUrl != "")
                        {
                            #region current conditions
                            WebClient webClient = new WebClient();
                            string    strSource = webClient.DownloadString(feedUrl);
                            webClient.Dispose();

                            XmlDocument xml = new XmlDocument();
                            xml.LoadXml(strSource);
                            //logging.AddToLog(strSource);

                            //update all the weather variables
                            try
                            {
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Temp", xml.SelectSingleNode("//temp_f").InnerText, "Weather");
                                logging.AddToLog("Found Temp: " + xml.SelectSingleNode("//temp_f").InnerText, false);
                            }
                            catch
                            {
                                logging.AddToLog("Error getting Temp", false);
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Temp", "", "Weather");
                            }

                            try
                            {
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Conditions", xml.SelectSingleNode("//weather").InnerText, "Weather");
                                logging.AddToLog("Found Conditions: " + xml.SelectSingleNode("//weather").InnerText, false);
                            }
                            catch
                            {
                                logging.AddToLog("Error getting Conditions", false);
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Conditions", "", "Weather");
                            }

                            try
                            {
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Wind Speed", xml.SelectSingleNode("//wind_mph").InnerText, "Weather");
                                logging.AddToLog("Found Wind Speed: " + xml.SelectSingleNode("//wind_mph").InnerText, false);
                            }
                            catch
                            {
                                logging.AddToLog("Error getting Wind Speed", false);
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Wind Speed", "", "Weather");
                            }

                            try
                            {
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Wind Direction", xml.SelectSingleNode("//wind_dir").InnerText, "Weather");
                                logging.AddToLog("Found Wind Direction: " + xml.SelectSingleNode("//wind_dir").InnerText, false);
                            }
                            catch
                            {
                                logging.AddToLog("Error getting Wind Direction", false);
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Wind Direction", "", "Weather");
                            }

                            try
                            {
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Humidity", xml.SelectSingleNode("//relative_humidity").InnerText, "Weather");
                                logging.AddToLog("Found Humidity: " + xml.SelectSingleNode("//relative_humidity").InnerText, false);
                            }
                            catch
                            {
                                logging.AddToLog("Error getting Humidity", false);
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Humidity", "", "Weather");
                            }

                            try
                            {
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Pressure", xml.SelectSingleNode("//pressure_in").InnerText, "Weather");
                                logging.AddToLog("Found Pressure: " + xml.SelectSingleNode("//pressure_in").InnerText, false);
                            }
                            catch
                            {
                                logging.AddToLog("Error getting Pressure", false);
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Pressure", "", "Weather");
                            }

                            try
                            {
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Dewpoint", xml.SelectSingleNode("//dewpoint_f").InnerText, "Weather");
                                logging.AddToLog("Found Dewpoint: " + xml.SelectSingleNode("//dewpoint_f").InnerText, false);
                            }
                            catch
                            {
                                logging.AddToLog("Error getting Dewpoint", false);
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Dewpoint", "", "Weather");
                            }

                            try
                            {
                                string curpath = @"\Images\Weather\" + xml.SelectSingleNode("//icon_url_name").InnerText;
                                if (!File.Exists(Common.ApiPath + @"\Images\Weather\" + xml.SelectSingleNode("//icon_url_name").InnerText))
                                {
                                    DownloadImage di = new DownloadImage(xml.SelectSingleNode("//icon_url_base").InnerText + xml.SelectSingleNode("//icon_url_name").InnerText);

                                    logging.AddToLog("Saving image: " + curpath, false);
                                    di.Download();
                                    di.SaveImage(Common.ApiPath + curpath, ImageFormat.Jpeg);
                                }

                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Image", curpath, "Weather");
                                logging.AddToLog("Found Image: " + curpath, false);
                            }
                            catch
                            {
                                logging.AddToLog("Error getting Image", false);
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Image", "", "Weather");
                            }

                            try
                            {
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Visibility", xml.SelectSingleNode("//visibility_mi").InnerText, "Weather");
                                logging.AddToLog("Found Visibility: " + xml.SelectSingleNode("//visibility_mi").InnerText, false);
                            }
                            catch
                            {
                                logging.AddToLog("Error getting Visibility", false);
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Visibility", "", "Weather");
                            }

                            try
                            {
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Windchill", xml.SelectSingleNode("//windchill_f").InnerText, "Weather");
                                logging.AddToLog("Found Windchill: " + xml.SelectSingleNode("//windchill_f").InnerText, false);
                            }
                            catch
                            {
                                logging.AddToLog("Error getting Windchill", false);
                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Windchill", "", "Weather");
                            }

                            #endregion
                        }

                        #region Forecasts
                        try
                        {
                            WebClient webClientForcast = new WebClient();
                            string    strSourceForcast = webClientForcast.DownloadString("http://forecast.weather.gov/MapClick.php?lat=" + pt.X.ToString() + "&lon=" + pt.Y.ToString() + "&FcstType=dwml");
                            webClientForcast.Dispose();
                            logging.AddToLog("Forecast XML: " + "http://forecast.weather.gov/MapClick.php?lat=" + pt.X.ToString() + "&lon=" + pt.Y.ToString() + "&FcstType=dwml", false);

                            XmlDocument xmlForcast = new XmlDocument();
                            xmlForcast.LoadXml(strSourceForcast);

                            XmlNode     temp     = null;
                            XmlNodeList tempList = xmlForcast.SelectNodes("//time-layout");
                            foreach (XmlNode xn in tempList)
                            {
                                logging.AddToLog("nodes: " + xn.ChildNodes.Count.ToString(), false);
                                if (xn.ChildNodes.Count > 10)
                                {
                                    temp = xn;
                                    break;
                                }
                            }

                            int day   = 2;
                            int today = 0;
                            try
                            {
                                foreach (XmlNode xn in temp.ChildNodes)
                                {
                                    if (xn.Name == "start-valid-time")
                                    {
                                        if (xn.Attributes["period-name"].Value == "Today" || xn.Attributes["period-name"].Value == "This Afternoon")
                                        {
                                            today = 1;
                                        }
                                        if (xn.Attributes["period-name"].Value != "Today" && xn.Attributes["period-name"].Value != "Tonight" && xn.Attributes["period-name"].Value != "Overnight")
                                        {
                                            if (day % 2 == 0)
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Day" + (day / 2).ToString() + " Label", xn.Attributes["period-name"].Value, "Weather");
                                                logging.AddToLog("Day" + (day / 2).ToString() + " Label: " + xn.Attributes["period-name"].Value, false);
                                            }
                                            else
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Night" + (day / 2).ToString() + " Label", xn.Attributes["period-name"].Value, "Weather");
                                                logging.AddToLog("Night" + (day / 2).ToString() + " Label: " + xn.Attributes["period-name"].Value, false);
                                            }
                                            day++;
                                        }
                                    }
                                }
                            }
                            catch { }

                            try
                            {
                                temp = xmlForcast.SelectSingleNode("//temperature[@type='maximum']");
                                day  = 1;
                                foreach (XmlNode xn in temp.ChildNodes)
                                {
                                    if (xn.Name == "value")
                                    {
                                        if (today == 1 && day == 1)
                                        {
                                            OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Today High", xn.InnerText, "Weather");
                                            logging.AddToLog("Found Today High: " + xn.InnerText, false);
                                        }
                                        else
                                        {
                                            OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Day" + (day - today).ToString() + " High", xn.InnerText, "Weather");
                                            logging.AddToLog("Found Day" + (day - today).ToString() + " High: " + xn.InnerText, false);
                                        }
                                        day++;
                                    }
                                }
                            }
                            catch { }

                            try
                            {
                                temp = xmlForcast.SelectSingleNode("//temperature[@type='minimum']");
                                day  = 1;
                                foreach (XmlNode xn in temp.ChildNodes)
                                {
                                    if (xn.Name == "value")
                                    {
                                        if (day == 1)
                                        {
                                            OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Tonight Low", xn.InnerText, "Weather");
                                            logging.AddToLog("Found Tonight Low: " + xn.InnerText, false);
                                        }
                                        else
                                        {
                                            OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Night" + (day - 1).ToString() + " Low", xn.InnerText, "Weather");
                                            logging.AddToLog("Found Night" + (day - 1).ToString() + " Low: " + xn.InnerText, false);
                                        }
                                        day++;
                                    }
                                }
                            }
                            catch { }

                            try
                            {
                                temp = xmlForcast.SelectSingleNode("//probability-of-precipitation");
                                day  = 2;
                                foreach (XmlNode xn in temp.ChildNodes)
                                {
                                    if (xn.Name == "value")
                                    {
                                        if (day % 2 == today)
                                        {
                                            if ((today == 0 && day == 2) || (today == 1 && day == 3))
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Tonight Precip", xn.InnerText, "Weather");
                                                logging.AddToLog("Tonight Precip: " + xn.InnerText, false);
                                            }
                                            else
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Night" + ((day / 2) - 1).ToString() + " Precip", xn.InnerText, "Weather");
                                                logging.AddToLog("Night" + ((day / 2) - 1).ToString() + " Precip: " + xn.InnerText, false);
                                            }
                                        }
                                        else
                                        {
                                            if (today == 1 && day == 2)
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Today Precip", xn.InnerText, "Weather");
                                                logging.AddToLog("Today Precip: " + xn.InnerText, false);
                                            }
                                            else
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Day" + ((day / 2) - today).ToString() + " Precip", xn.InnerText, "Weather");
                                                logging.AddToLog("Day" + ((day / 2) - today).ToString() + " Precip: " + xn.InnerText, false);
                                            }
                                        }
                                        day++;
                                    }
                                }
                            }
                            catch { }

                            try
                            {
                                temp = xmlForcast.SelectSingleNode("//weather");
                                day  = 2;
                                foreach (XmlNode xn in temp.ChildNodes)
                                {
                                    if (xn.Name == "weather-conditions")
                                    {
                                        if (day % 2 == today)
                                        {
                                            if ((today == 0 && day == 2) || (today == 1 && day == 3))
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Tonight Forecast", xn.Attributes["weather-summary"].Value, "Weather");
                                                logging.AddToLog("Tonight Forecast: " + xn.Attributes["weather-summary"].Value, false);
                                            }
                                            else
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Night" + ((day / 2) - 1).ToString() + " Forecast", xn.Attributes["weather-summary"].Value, "Weather");
                                                logging.AddToLog("Night" + ((day / 2) - 1).ToString() + " Forecast: " + xn.Attributes["weather-summary"].Value, false);
                                            }
                                        }
                                        else
                                        {
                                            if (today == 1 && day == 2)
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Today Forecast", xn.Attributes["weather-summary"].Value, "Weather");
                                                logging.AddToLog("Today Forecast: " + xn.Attributes["weather-summary"].Value, false);
                                            }
                                            else
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Day" + ((day / 2) - today).ToString() + " Forecast", xn.Attributes["weather-summary"].Value, "Weather");
                                                logging.AddToLog("Day" + ((day / 2) - today).ToString() + " Forecast: " + xn.Attributes["weather-summary"].Value, false);
                                            }
                                        }
                                        day++;
                                    }
                                }
                            }
                            catch { }

                            try
                            {
                                temp = xmlForcast.SelectSingleNode("//conditions-icon");
                                string path = "";
                                day = 2;
                                foreach (XmlNode xn in temp.ChildNodes)
                                {
                                    if (xn.Name == "icon-link")
                                    {
                                        path = @"\Images\Weather\" + xn.SelectSingleNode("//icon_url_name").InnerText;
                                        if (!File.Exists(Common.ApiPath + @"\Images\Weather\" + xn.SelectSingleNode("//icon_url_name").InnerText))
                                        {
                                            DownloadImage di = new DownloadImage(xn.InnerText);

                                            logging.AddToLog("Saving image: " + path, false);
                                            di.Download();
                                            di.SaveImage(Common.ApiPath + path, ImageFormat.Jpeg);
                                        }
                                        if (day % 2 == today)
                                        {
                                            if ((today == 0 && day == 2) || (today == 1 && day == 3))
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Tonight Image", path, "Weather");
                                                logging.AddToLog("Tonight Image: " + xn.InnerText, false);
                                            }
                                            else
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Night" + ((day / 2) - 1).ToString() + " Image", path, "Weather");
                                                logging.AddToLog("Night" + ((day / 2) - 1).ToString() + " Image: " + xn.InnerText, false);
                                            }
                                        }
                                        else
                                        {
                                            if (today == 1 && day == 2)
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Today Image", path, "Weather");
                                                logging.AddToLog("Today Image: " + xn.InnerText, false);
                                            }
                                            else
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Day" + ((day / 2) - today).ToString() + " Image", path, "Weather");
                                                logging.AddToLog("Day" + ((day / 2) - today).ToString() + " Image: " + xn.InnerText, false);
                                            }
                                        }
                                        day++;
                                    }
                                }
                            }
                            catch {  }

                            try
                            {
                                temp = xmlForcast.SelectSingleNode("//wordedForecast");
                                day  = 2;
                                foreach (XmlNode xn in temp.ChildNodes)
                                {
                                    if (xn.Name == "text")
                                    {
                                        if (day % 2 == today)
                                        {
                                            if ((today == 0 && day == 2) || (today == 1 && day == 3))
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Tonight Summary", xn.InnerText, "Weather");
                                                logging.AddToLog("Tonight Summary: " + xn.InnerText, false);
                                            }
                                            else
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Night" + ((day / 2) - 1).ToString() + " Summary", xn.InnerText, "Weather");
                                                logging.AddToLog("Night" + ((day / 2) - 1).ToString() + " Summary: " + xn.InnerText, false);
                                            }
                                        }
                                        else
                                        {
                                            if (today == 1 && day == 2)
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Today Summary", xn.InnerText, "Weather");
                                                logging.AddToLog("Today Summary: " + xn.InnerText, false);
                                            }
                                            else
                                            {
                                                OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Day" + ((day / 2) - today).ToString() + " Summary", xn.InnerText, "Weather");
                                                logging.AddToLog("Day" + ((day / 2) - today).ToString() + " Summary: " + xn.InnerText, false);
                                            }
                                        }
                                        day++;
                                    }
                                }
                            }
                            catch { }
                        }
                        catch (Exception ex)
                        {
                            logging.AddToLog("Error Forecast XML: " + ex.Message, true);
                        }
                        #endregion


                        OSAEObjectStateManager.ObjectStateSet("Weather Data", "ON", pName);
                        OSAEObjectPropertyManager.ObjectPropertySet("Weather Data", "Last Updated", DateTime.Now.ToString(), pName);
                    }
                }
            }
            catch (Exception ex)
            {
                logging.AddToLog("Error updating weather - " + ex.Message, true);
            }
        }
Example #55
0
    // Update is called once per frame
    void LoadMap()
    {
        //Loading the map
        currentPrefab = null;
        nodeList      = xmlDoc.SelectNodes("//level/map/row");

        for (int i = 0; i < nodeList.Count; i++)
        {
            currentNode = nodeList[i];
            for (int j = 0; j < currentNode.InnerText.Length; j++)
            {
                switch (currentNode.InnerText[j])
                {
                case 'A':
                    currentPrefab = Grass1;
                    break;

                case 'B':
                    currentPrefab = Grass2;
                    break;

                case 'C':
                    currentPrefab = Grass3;
                    break;

                case 'E':
                    currentPrefab = Tree1;
                    break;

                case 'F':
                    currentPrefab = Tree2;
                    break;

                case 'G':
                    currentPrefab = Rock;
                    break;

                case 'J':
                    currentPrefab = Obstacle1;
                    break;

                case 'K':
                    currentPrefab = Obstacle2;
                    break;

                case 'L':
                    currentPrefab = Obstacle3;
                    break;
                }

                currentPrefab = Instantiate(currentPrefab, new Vector3(j, -i),
                                            Quaternion.identity);

                currentPrefab.transform.SetParent(cellsConstainer);
            }
        }

        //Loading characters:

        LoadCharacters();
    }
Example #56
0
        public static async Task <List <ServerSideEvent> > GetEvents(string eventLogPath)
        {
            var events = new List <ServerSideEvent>();

            if (!File.Exists(eventLogPath))
            {
                return(events);
            }

            InitializeKnownResourceTypes();

            string fileText = string.Empty;
            await RetryHelper.RetryOnExceptionAsync <IOException>(10, TimeSpan.FromSeconds(1), async() =>
            {
                fileText = await FileSystemHelpers.ReadAllTextFromFileAsync(eventLogPath);
            });

            if (string.IsNullOrWhiteSpace(fileText))
            {
                return(events);
            }

            XmlDocument dom = new XmlDocument();

            dom.LoadXml(fileText);

            XmlNodeList xmlList = dom.SelectNodes("/Events/Event");

            for (int i = (xmlList.Count - 1); i >= 0; i--)
            {
                var     serverSideEvent = new ServerSideEvent();
                XmlNode eventNode       = xmlList[i];
                var     systemNode      = eventNode.SelectSingleNode("System");
                var     eventDataNode   = eventNode.SelectSingleNode("EventData");

                string strProvider = systemNode["Provider"].GetAttribute("Name");
                serverSideEvent.Source = strProvider;
                string dateTimeString = systemNode["TimeCreated"].GetAttribute("SystemTime");

                bool booValidDateFound = false;

                if (dateTimeString.Contains("T") && dateTimeString.Contains("Z"))
                {
                    if (DateTime.TryParse(dateTimeString, out DateTime resultDateTime))
                    {
                        serverSideEvent.DateAndTime = resultDateTime;
                        booValidDateFound           = true;
                    }
                    else
                    {
                        if (DateTime.TryParse(systemNode["TimeCreated"].GetAttribute("SystemTime"), out resultDateTime))
                        {
                            serverSideEvent.DateAndTime = resultDateTime;
                            booValidDateFound           = true;
                        }
                    }
                }
                else
                {
                    if (DateTime.TryParse(systemNode["TimeCreated"].GetAttribute("SystemTime"), out DateTime resultDateTime))
                    {
                        serverSideEvent.DateAndTime = resultDateTime;
                        booValidDateFound           = true;
                    }
                }

                serverSideEvent.EventID       = systemNode["EventID"].InnerText;
                serverSideEvent.TaskCategory  = systemNode["Task"].InnerText;
                serverSideEvent.EventRecordID = systemNode["EventRecordID"].InnerText;
                serverSideEvent.Computer      = systemNode["Computer"].InnerText;

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

                foreach (XmlNode datanode in eventDataNode.ChildNodes)
                {
                    arrayOfdata.Add(datanode.InnerText);
                }

                string[] args    = arrayOfdata.ToArray();
                int      eventId = Convert.ToInt32(systemNode["EventID"].InnerText);

                string strLevel = systemNode["Level"].InnerText;

                int intLevel = -1;
                int.TryParse(strLevel, out intLevel);


                if (strProvider.StartsWith("ASP.NET"))
                {
                    int level = MapEventTypeToWebEngineEventType(intLevel);
                    var aspnetResourceType = ResourceTypes.Values.Where(x => x.SourceStartsWith.StartsWith("ASP.NET"));
                    if (aspnetResourceType != null)
                    {
                        serverSideEvent.Description = GetDescriptionForEvent(aspnetResourceType.FirstOrDefault().PtrHandle, eventId, intLevel, eventDataNode, args);
                    }
                    if (!booValidDateFound)
                    {
                        if (ExtractDateTimeFromFormattedEvent(serverSideEvent.Description, out DateTime parsedDateTime))
                        {
                            serverSideEvent.DateAndTime = parsedDateTime;
                        }
                        else
                        {
                            if (DateTime.TryParse(systemNode["TimeCreated"].GetAttribute("SystemTime"), out DateTime resultDateTime))
                            {
                                serverSideEvent.DateAndTime = resultDateTime;
                            }
                        }
                    }
                }
                else
                {
                    foreach (var item in ResourceTypes)
                    {
                        if (strProvider.StartsWith(item.Value.SourceStartsWith))
                        {
                            serverSideEvent.Description  = GetDescriptionForEvent(item.Value.PtrHandle, eventId, intLevel, eventDataNode, args);
                            serverSideEvent.Description += Environment.NewLine + string.Join(Environment.NewLine, args);
                            break;
                        }
                    }
                }

                if (string.IsNullOrWhiteSpace(serverSideEvent.Description))
                {
                    serverSideEvent.Description = string.Join(Environment.NewLine, args);
                }

                serverSideEvent.Level = systemNode["Level"].InnerText;
                events.Add(serverSideEvent);
            }



            return(events);
        }
Example #57
0
        public async Task <MovieVM> CreateMovie(MovieVM movieVM)
        {
            string  Text = "";
            decimal start = -1; decimal end = 0;
            string  txt = "";

            try
            {
                movieVM.Movie.Subtitles = new List <Subtitle>();

                movieVM.Movie.Text = movieVM.Movie.Text.ToLower();
                movieVM.Movie.Text = movieVM.Movie.Text.Replace("<?xml version=\"1.0\" encoding=\"utf-8\" ?>", "");

                XmlDocument xml = new XmlDocument();
                xml.LoadXml(movieVM.Movie.Text);

                XmlNodeList xnList = xml.SelectNodes("/transcript/text");
                foreach (XmlNode xn in xnList)
                {
                    if (string.IsNullOrEmpty(xn.InnerText) || xn.Attributes["start"] == null || xn.Attributes["dur"] == null)
                    {
                        continue;
                    }

                    xn.InnerText = Reformat(xn.InnerText);

                    if (txt == "")
                    {
                        start = Convert.ToDecimal(xn.Attributes["start"].Value);
                    }
                    if (txt != "")
                    {
                        txt += " ";
                    }
                    txt += xn.InnerText;

                    if (txt.Length < 99)
                    {
                        continue;
                    }

                    end = Convert.ToDecimal(xn.Attributes["start"].Value) + Convert.ToDecimal(xn.Attributes["dur"].Value);

                    movieVM.Movie.Subtitles.Add(new pro_Models.Models.Subtitle
                    {
                        Text         = txt,
                        StartTime    = start,
                        EndtTime     = end,
                        VocSubtitles = await GetVocSubtitles(txt)
                    });
                    txt = "";
                }

                var result = await appDbContext.Movies.AddAsync(movieVM.Movie);

                await appDbContext.SaveChangesAsync();

                movieVM.Movie           = result.Entity;
                movieVM.Movie.Subtitles = null;
                movieVM.Movie.Text      = null;
            }
            catch (Exception ex)
            {
            }

            return(movieVM);
        }
        private SpecificInfo SpecificInfoDeserialize(string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return(null);
            }

            SpecificInfo info = null;

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(new StringReader(xml));

                info = new SpecificInfo();

                string  streamFormat    = "";
                XmlNode xmlStreamFormat = doc.SelectSingleNode("/Basler/StreamFormat");
                if (xmlStreamFormat != null)
                {
                    streamFormat = xmlStreamFormat.InnerText;
                }

                Bayer8Conversion bayer8Conversion    = Bayer8Conversion.Color;
                XmlNode          xmlBayer8Conversion = doc.SelectSingleNode("/Basler/Bayer8Conversion");
                if (xmlBayer8Conversion != null)
                {
                    bayer8Conversion = (Bayer8Conversion)Enum.Parse(typeof(Bayer8Conversion), xmlBayer8Conversion.InnerText);
                }

                Dictionary <string, CameraProperty> cameraProperties = new Dictionary <string, CameraProperty>();

                XmlNodeList props = doc.SelectNodes("/Basler/CameraProperties/CameraProperty");
                foreach (XmlNode node in props)
                {
                    XmlAttribute keyAttribute = node.Attributes["key"];
                    if (keyAttribute == null)
                    {
                        continue;
                    }

                    string         key      = keyAttribute.Value;
                    CameraProperty property = new CameraProperty();

                    string  xpath            = string.Format("/Basler/CameraProperties/CameraProperty[@key='{0}']", key);
                    XmlNode xmlPropertyValue = doc.SelectSingleNode(xpath + "/Value");
                    if (xmlPropertyValue != null)
                    {
                        property.CurrentValue = xmlPropertyValue.InnerText;
                    }
                    else
                    {
                        property.Supported = false;
                    }

                    XmlNode xmlPropertyAuto = doc.SelectSingleNode(xpath + "/Auto");
                    if (xmlPropertyAuto != null)
                    {
                        property.Automatic = XmlHelper.ParseBoolean(xmlPropertyAuto.InnerText);
                    }
                    else
                    {
                        property.Supported = false;
                    }

                    cameraProperties.Add(key, property);
                }

                info.StreamFormat     = streamFormat;
                info.Bayer8Conversion = bayer8Conversion;
                info.CameraProperties = cameraProperties;
            }
            catch (Exception e)
            {
                log.ErrorFormat(e.Message);
            }

            return(info);
        }
        //public static Score GetScore(string filename)
        public static Score GetScore(string _data)
        {
            var document = new XmlDocument();

            document.XmlResolver = null;
            document.LoadXml(_data);

            //document = GetXmlDocument(filename);

            var score = new Score();

            var movementTitleNode = document.SelectSingleNode("score-partwise/movement-title");

            if (movementTitleNode != null)
            {
                score.MovementTitle = movementTitleNode.InnerText;
            }

            score.Identification = GetIdentification(document);

            var partNodes = document.SelectNodes("score-partwise/part-list/score-part");

            if (partNodes != null)
            {
                foreach (XmlNode partNode in partNodes)
                {
                    var part = new Part();
                    score.Parts.Add(part);

                    if (partNode.Attributes != null)
                    {
                        part.Id = partNode.Attributes["id"].InnerText;
                    }

                    var partNameNode = partNode.SelectSingleNode("part-name");

                    if (partNameNode != null)
                    {
                        part.Name = partNameNode.InnerText;
                    }

                    var measuresXpath = string.Format("//part[@id='{0}']/measure", part.Id);

                    var measureNodes = partNode.SelectNodes(measuresXpath);

                    if (measureNodes != null)
                    {
                        foreach (XmlNode measureNode in measureNodes)
                        {
                            var measure = new Measure();

                            if (measureNode.Attributes != null)
                            {
                                var     measureWidthAttribute = measureNode.Attributes["width"];
                                decimal w;
                                if (measureWidthAttribute != null && decimal.TryParse(measureWidthAttribute.InnerText, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out w))
                                {
                                    measure.Width = w;
                                }
                            }

                            var attributesNode = measureNode.SelectSingleNode("attributes");

                            if (attributesNode != null)
                            {
                                measure.Attributes = new MeasureAttributes();

                                var divisionsNode = attributesNode.SelectSingleNode("divisions");
                                if (divisionsNode != null)
                                {
                                    measure.Attributes.Divisions = Convert.ToInt32(divisionsNode.InnerText);
                                }

                                var keyNode = attributesNode.SelectSingleNode("key");

                                if (keyNode != null)
                                {
                                    measure.Attributes.Key = new Key();

                                    var fifthsNode = keyNode.SelectSingleNode("fifths");
                                    if (fifthsNode != null)
                                    {
                                        measure.Attributes.Key.Fifths = Convert.ToInt32(fifthsNode.InnerText);
                                    }

                                    var modeNode = keyNode.SelectSingleNode("mode");
                                    if (modeNode != null)
                                    {
                                        measure.Attributes.Key.Mode = modeNode.InnerText;
                                    }
                                }

                                measure.Attributes.Time = GetTime(attributesNode);

                                measure.Attributes.Clef = GetClef(attributesNode);
                            }

                            var childNodes = measureNode.ChildNodes;

                            foreach (XmlNode node in childNodes)
                            {
                                MeasureElement measureElement = null;

                                if (node.Name == "note")
                                {
                                    var newNote = GetNote(node);
                                    measureElement = new MeasureElement {
                                        Type = MeasureElementType.Note, Element = newNote
                                    };
                                }
                                else if (node.Name == "backup")
                                {
                                    measureElement = new MeasureElement {
                                        Type = MeasureElementType.Backup, Element = GetBackupElement(node)
                                    };
                                }
                                else if (node.Name == "forward")
                                {
                                    measureElement = new MeasureElement {
                                        Type = MeasureElementType.Forward, Element = GetForwardElement(node)
                                    };
                                }

                                if (measureElement != null)
                                {
                                    measure.MeasureElements.Add(measureElement);
                                }
                            }

                            part.Measures.Add(measure);
                        }
                    }
                }
            }

            return(score);
        }
    static void Main()
    {
        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.Load("../../catalogue.xml");
        string xPathQuery = "/catalog/album";

        XmlNodeList ArtistsList = xmlDoc.SelectNodes(xPathQuery);
        Dictionary<string, int> artistsAndAlbumsCount = new Dictionary<string, int>();

        foreach (XmlNode ArtistNode in ArtistsList)
        {
            string authorName = ArtistNode.SelectSingleNode("artist").InnerText;
            if (artistsAndAlbumsCount.ContainsKey(authorName))
            {
                artistsAndAlbumsCount[authorName]++;
            }
            else
            {
                artistsAndAlbumsCount.Add(authorName, 1);
            }
        }

        foreach (var artist in artistsAndAlbumsCount)
        {
            Console.WriteLine("Artist: {0}", artist.Key);
            Console.WriteLine("Albums count: {0}", artist.Value);
            Console.WriteLine();
        }
    }