Search Results

Search found 314 results on 13 pages for 'xmldocument'.

Page 9/13 | < Previous Page | 5 6 7 8 9 10 11 12 13  | Next Page >

  • Blocking problem, C#, .net, Deserializing XML to object problem

    - by fernando
    Hi I have a blocking problem I have XML file under some url http://myserver/mywebApp/myXML.xml In the below code which I run in Console Application, bookcollection has null Books field :( <books> <book id="5352"> <date>1986-05-05</date> <title> Alice in chains </title> </book> <book id="4334"> <date>1986-05-05</date> <title> 1000 ways to heaven </title> </book> <book id="1111"> <date>1986-05-05</date> <title> Kitchen and me </title> </book> </books> XmlDocument doc = new XmlDocument(); doc.Load("http://myserver/mywebapp/myXML.xml"); BookCollection books = new BookCollection(); XmlNodeReader reader2 = new XmlNodeReader(doc.DocumentElement); XmlSerializer ser2 = new XmlSerializer(books.GetType()); object obj = ser2.Deserialize(reader2); BookCollection books2= (BookCollection)obj; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { [Serializable()] public class Book { [System.Xml.Serialization.XmlAttribute("id")] public string id { get; set; } [System.Xml.Serialization.XmlElement("date")] public string date { get; set; } [System.Xml.Serialization.XmlElement("title")] public string title { get; set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; namespace ConsoleApplication1 { [Serializable()] [System.Xml.Serialization.XmlRootAttribute("books", Namespace = "", IsNullable = false)] public class BookCollection { [XmlArray("books")] [XmlArrayItem("book", typeof(Book))] public Book[] Books { get; set; } } }

    Read the article

  • Edit very large xml files

    - by Matt
    I would like to create a text box which loads xml files and let users edit them. However, I cannot use XmlDocument to load since the files can be very large. I am looking for options to stream/load the xml document in chunks so that I do not get out of memory errors -- at the same time, performance is important too. Could you let me know what would be good options?

    Read the article

  • c# Counter requires 2 button clicks to update

    - by marko.ivanovski.nz
    Hi, I have a problem that has been bugging me all day. In my code I have the following: private int rowCount { get { return (int)ViewState["rowCount"]; } set { ViewState["rowCount"] = value; } } and a button event protected void addRow_Click(object sender, EventArgs e) { rowCount = rowCount + 1; } Then on Page_Load I read that value and create controls accordingly. I understand the button event fires AFTER the Page_Load fires so the value isn't updated until the next postback. Real nightmare. Here's the entire code: protected void Page_Load(object sender, EventArgs e) { string xmlValue = ""; //To read a value from a database if (xmlValue.Length > 0) { if (!Page.IsPostBack) { DataSet ds = XMLToDataSet(xmlValue); Table dimensionsTable = DataSetToTable(ds); tablePanel.Controls.Add(dimensionsTable); DataTable dt = ds.Tables["Dimensions"]; rowCount = dt.Rows.Count; colCount = dt.Columns.Count; } else { tablePanel.Controls.Add(DataSetToTable(DefaultDataSet(rowCount, colCount))); } } else { if (!Page.IsPostBack) { rowCount = 2; colCount = 4; } tablePanel.Controls.Add(DataSetToTable(DefaultDataSet(rowCount, colCount))); } } protected void submit_Click(object sender, EventArgs e) { resultsLabel.Text = Server.HtmlEncode(DataSetToStringXML(TableToDataSet((Table)tablePanel.Controls[0]))); } protected void addColumn_Click(object sender, EventArgs e) { colCount = colCount + 1; } protected void addRow_Click(object sender, EventArgs e) { rowCount = rowCount + 1; } public DataSet TableToDataSet(Table table) { DataSet ds = new DataSet(); DataTable dt = new DataTable("Dimensions"); ds.Tables.Add(dt); //Add headers for (int i = 0; i < table.Rows[0].Cells.Count; i++) { DataColumn col = new DataColumn(); TextBox headerTxtBox = (TextBox)table.Rows[0].Cells[i].Controls[0]; col.ColumnName = headerTxtBox.Text; col.Caption = headerTxtBox.Text; dt.Columns.Add(col); } for (int i = 0; i < table.Rows.Count; i++) { DataRow valueRow = dt.NewRow(); for (int x = 0; x < table.Rows[i].Cells.Count; x++) { TextBox valueTextBox = (TextBox)table.Rows[i].Cells[x].Controls[0]; valueRow[x] = valueTextBox.Text; } dt.Rows.Add(valueRow); } return ds; } public Table DataSetToTable(DataSet ds) { DataTable dt = ds.Tables["Dimensions"]; Table newTable = new Table(); //Add headers TableRow headerRow = new TableRow(); for (int i = 0; i < dt.Columns.Count; i++) { TableCell headerCell = new TableCell(); TextBox headerTxtBox = new TextBox(); headerTxtBox.ID = "HeadersTxtBox" + i.ToString(); headerTxtBox.Font.Bold = true; headerTxtBox.Text = dt.Columns[i].ColumnName; headerCell.Controls.Add(headerTxtBox); headerRow.Cells.Add(headerCell); } newTable.Rows.Add(headerRow); //Add value rows for (int i = 0; i < dt.Rows.Count; i++) { TableRow valueRow = new TableRow(); for (int x = 0; x < dt.Columns.Count; x++) { TableCell valueCell = new TableCell(); TextBox valueTxtBox = new TextBox(); valueTxtBox.ID = "ValueTxtBox" + i.ToString() + i + x + x.ToString(); valueTxtBox.Text = dt.Rows[i][x].ToString(); valueCell.Controls.Add(valueTxtBox); valueRow.Cells.Add(valueCell); } newTable.Rows.Add(valueRow); } return newTable; } public DataSet DefaultDataSet(int rows, int cols) { DataSet ds = new DataSet(); DataTable dt = new DataTable("Dimensions"); ds.Tables.Add(dt); DataColumn nameCol = new DataColumn(); nameCol.Caption = "Name"; nameCol.ColumnName = "Name"; nameCol.DataType = System.Type.GetType("System.String"); dt.Columns.Add(nameCol); DataColumn widthCol = new DataColumn(); widthCol.Caption = "Width"; widthCol.ColumnName = "Width"; widthCol.DataType = System.Type.GetType("System.String"); dt.Columns.Add(widthCol); if (cols > 2) { DataColumn heightCol = new DataColumn(); heightCol.Caption = "Height"; heightCol.ColumnName = "Height"; heightCol.DataType = System.Type.GetType("System.String"); dt.Columns.Add(heightCol); } if (cols > 3) { DataColumn depthCol = new DataColumn(); depthCol.Caption = "Depth"; depthCol.ColumnName = "Depth"; depthCol.DataType = System.Type.GetType("System.String"); dt.Columns.Add(depthCol); } if (cols > 4) { int newColCount = cols - 4; for (int i = 0; i < newColCount; i++) { DataColumn newCol = new DataColumn(); newCol.Caption = "New " + i.ToString(); newCol.ColumnName = "New " + i.ToString(); newCol.DataType = System.Type.GetType("System.String"); dt.Columns.Add(newCol); } } for (int i = 0; i < rows; i++) { DataRow newRow = dt.NewRow(); newRow["Name"] = "Name " + i.ToString(); newRow["Width"] = "Width " + i.ToString(); if (cols > 2) { newRow["Height"] = "Height " + i.ToString(); } if (cols > 3) { newRow["Depth"] = "Depth " + i.ToString(); } dt.Rows.Add(newRow); } return ds; } public DataSet XMLToDataSet(string xml) { StringReader sr = new StringReader(xml); DataSet ds = new DataSet(); ds.ReadXml(sr); return ds; } public string DataSetToStringXML(DataSet ds) { XmlDocument _XMLDoc = new XmlDocument(); _XMLDoc.LoadXml(ds.GetXml()); StringWriter sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter(sw); XmlDocument xml = _XMLDoc; xml.WriteTo(xw); return sw.ToString(); } private int rowCount { get { return (int)ViewState["rowCount"]; } set { ViewState["rowCount"] = value; } } private int colCount { get { return (int)ViewState["colCount"]; } set { ViewState["colCount"] = value; } } Thanks in advance, Marko

    Read the article

  • C# Parsing html for general use?

    - by Wardy
    What is the best way to take a string of html and turn it in to something useful? Essentially if i take a url and go get the html from that url in .net i get a response but this would come in the form of either a file or stream or string. What if i want an actual document or something I can crawl like an xmldocument object? I have some thoughts and an already implemented solution on this but I am interested to see what the community thinks about this.

    Read the article

  • Validate an Xml file against a DTD with a proxy. C# 2.0

    - by Chris Dunaway
    I have looked at many examples for validating an XML file against a DTD, but have not found one that allows me to use a proxy. I have a cXml file as follows (abbreviated for display) which I wish to validate: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.018/InvoiceDetail.dtd"> <cXML payloadID="123456" timestamp="2009-12-10T10:05:30-06:00"> <!-- content snipped --> </cXML> I am trying to create a simple C# program to validate the xml against the DTD. I have tried code such as the following but cannot figure out how to get it to use a proxy: private static bool isValid = false; static void Main(string[] args) { try { XmlTextReader r = new XmlTextReader(args[0]); XmlReaderSettings settings = new XmlReaderSettings(); XmlDocument doc = new XmlDocument(); settings.ProhibitDtd = false; settings.ValidationType = ValidationType.DTD; settings.ValidationEventHandler += new ValidationEventHandler(v_ValidationEventHandler); XmlReader validator = XmlReader.Create(r, settings); while (validator.Read()) ; validator.Close(); // Check whether the document is valid or invalid. if (isValid) Console.WriteLine("Document is valid"); else Console.WriteLine("Document is invalid"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } static void v_ValidationEventHandler(object sender, ValidationEventArgs e) { isValid = false; Console.WriteLine("Validation event\n" + e.Message); } The exception I receive is System.Net.WebException: The remote server returned an error: (407) Proxy Authentication Required. which occurs on the line while (validator.Read()) ; I know I can validate against a DTD locally, but I don't want to change the xml DOCTYPE since that is what the final form needs to be (this app is solely for diagnostic purposes). For more information about the cXML spec, you can go to cxml.org. I appreciate any assistance. Thanks

    Read the article

  • how to filter data from xml file for displaying only selected as nodes in treeview

    - by michale
    I have an xml file named "books.xml" provided in the link "http://msdn.microsoft.com/en-us/library/windows/desktop/ms762271(v=vs.85).aspx". What my requirement was to disaplay only the <title> from xml information as nodes in tree view. But when i did the following coding its displaying all the values as nodes like "catalog" as rootnode, book as parent node for all then author,title,genre etc as nodes but i want only root node catalogue and title as nodes not even book. Can any body guide me what modification i need to do in the exisitng logic for displaying title as nodes OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Open XML document"; dlg.Filter = "XML Files (*.xml)|*.xml"; dlg.FileName = Application.StartupPath + "\\..\\..\\Sample.xml"; if (dlg.ShowDialog() == DialogResult.OK) { try { //Just a good practice -- change the cursor to a //wait cursor while the nodes populate this.Cursor = Cursors.WaitCursor; //First, we'll load the Xml document XmlDocument xDoc = new XmlDocument(); xDoc.Load(dlg.FileName); //Now, clear out the treeview, //and add the first (root) node treeView1.Nodes.Clear(); treeView1.Nodes.Add(new TreeNode(xDoc.DocumentElement.Name)); TreeNode tNode = new TreeNode(); tNode = (TreeNode)treeView1.Nodes[0]; //We make a call to addTreeNode, //where we'll add all of our nodes addTreeNode(xDoc.DocumentElement, tNode); //Expand the treeview to show all nodes treeView1.ExpandAll(); } catch (XmlException xExc) //Exception is thrown is there is an error in the Xml { MessageBox.Show(xExc.Message); } catch (Exception ex) //General exception { MessageBox.Show(ex.Message); } finally { this.Cursor = Cursors.Default; //Change the cursor back } }} //This function is called recursively until all nodes are loaded private void addTreeNode(XmlNode xmlNode, TreeNode treeNode) { XmlNode xNode; TreeNode tNode; XmlNodeList xNodeList; if (xmlNode.HasChildNodes) //The current node has children { xNodeList = xmlNode.ChildNodes; for (int x = 0; x <= xNodeList.Count - 1; x++) //Loop through the child nodes { xNode = xmlNode.ChildNodes[x]; treeNode.Nodes.Add(new TreeNode(xNode.Name)); tNode = treeNode.Nodes[x]; addTreeNode(xNode, tNode); } } else //No children, so add the outer xml (trimming off whitespace) treeNode.Text = xmlNode.OuterXml.Trim(); }

    Read the article

  • Edit very large xml files in c#

    - by Matt
    Hi I would like to create a text box which loads xml files and let users edit them. However, I cannot use XmlDocument to load since the files can be very large. I am looking for options to stream/load the xml document in chunks so that I do not get out of memory errors -- at the same time, performance is important too. Could you let me know what would be good options? Thanks in advance for your help! Matt

    Read the article

  • How to replace HEX character in an xml document?

    - by Nalum
    I'm trying to import an xml file into vb.net XmlDocument but am getting the error: '.', hexadecimal value 0x00, is an invalid character. Line 94, position 1. I'm wondering if there is a way to replace the hex character 0x00 The following are lines 92,93,94 the file ends on line 94 92 | </request> 93 |</rpc> <!-- XML Finishes here --> 94 | Thanks for any help.

    Read the article

  • Blocking problem Deserializing XML to object problem

    - by fernando
    I have a blocking problem I have XML file under some url http://myserver/mywebApp/myXML.xml In the below code which I run in Console Application, bookcollection has null Books field :( <books> <book id="5352"> <date>1986-05-05</date> <title> Alice in chains </title> </book> <book id="4334"> <date>1986-05-05</date> <title> 1000 ways to heaven </title> </book> <book id="1111"> <date>1986-05-05</date> <title> Kitchen and me </title> </book> </books> XmlDocument doc = new XmlDocument(); doc.Load("http://myserver/mywebapp/myXML.xml"); BookCollection books = new BookCollection(); XmlNodeReader reader2 = new XmlNodeReader(doc.DocumentElement); XmlSerializer ser2 = new XmlSerializer(books.GetType()); object obj = ser2.Deserialize(reader2); BookCollection books2= (BookCollection)obj; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { [Serializable()] public class Book { [System.Xml.Serialization.XmlAttribute("id")] public string id { get; set; } [System.Xml.Serialization.XmlElement("date")] public string date { get; set; } [System.Xml.Serialization.XmlElement("title")] public string title { get; set; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; namespace ConsoleApplication1 { [Serializable()] [System.Xml.Serialization.XmlRootAttribute("books", Namespace = "", IsNullable = false)] public class BookCollection { [XmlArray("books")] [XmlArrayItem("book", typeof(Book))] public Book[] Books { get; set; } } }

    Read the article

  • Exception showing a erroneous web page in a WPF frame

    - by H4mm3rHead
    I have a small application where i need to navigate to an url, I use this method to get the Frame: public override System.Windows.UIElement GetPage(System.Windows.UIElement container) { XmlDocument doc = new XmlDocument(); doc.Load(Location); string webSiteUrl = doc.SelectSingleNode("website").InnerText; Frame newFrame = new Frame(); if (!webSiteUrl.StartsWith("http://")) { webSiteUrl = "http://" + webSiteUrl; } newFrame.Source = new Uri(webSiteUrl); return newFrame; } My problem is now that the page im trying to show generates a error (or so i think), when i load the page in a browser it never fully loads, keeps saying "loading1 element" in the load bar and the green progress line (IE 8) keeps showing. When i attach my debugger i get this error: System.ArgumentException was unhandled Message="Parameter and value pair is not valid. Expected form is parameter=value." Source="WindowsBase" StackTrace: at MS.Internal.ContentType.ParseParameterAndValue(String parameterAndValue) at MS.Internal.ContentType..ctor(String contentType) at MS.Internal.WpfWebRequestHelper.GetContentType(WebResponse response) at System.Windows.Navigation.NavigationService.GetObjectFromResponse(WebRequest request, WebResponse response, Uri destinationUri, Object navState) at System.Windows.Navigation.NavigationService.HandleWebResponse(IAsyncResult ar) at System.Windows.Navigation.NavigationService.<>c__DisplayClassc.<HandleWebResponseOnRightDispatcher>b__8(Object unused) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) at System.Windows.Threading.DispatcherOperation.InvokeImpl() at System.Threading.ExecutionContext.runTryCode(Object userData) at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Windows.Threading.DispatcherOperation.Invoke() at System.Windows.Threading.Dispatcher.ProcessQueue() at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled) at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o) at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter) at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler) ved System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter) at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage(MSG& msg) at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame) at System.Windows.Application.RunInternal(Window window) at GreenWebPlayerWPF.App.Main() i C:\Development\Hvarregaard\GWDS\GreenWeb\GreenWebPlayerWPF\obj\Debug\App.g.cs:linje 0 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: Anyone? Or any way to capture it and respond to it, tried a try/catch around my code, but its not caught - seems something deep inside the guts of the CLR is failing.

    Read the article

  • help with selecting nodes with xpath

    - by fayer
    my xml structure looks like this: <entity id="1000070"> <name>apple</name> <type>category</type> <entities> <entity id="7002870"> <name>mac</name> <type>category</type> <entities> <entity id="7002907"> <name>leopard</name> <type>sub-category</type> <entities> <entity id="7024080"> <name>safari</name> <type>subject</type> </entity> <entity id="7024701"> <name>finder</name> <type>subject</type> </entity> </entities> </entity> </entities> </entity> <entity id="7024080"> <name>iphone</name> <type>category</type> <entities> <entity id="7024080"> <name>3g</name> <type>sub-category</type> </entity> <entity id="7024701"> <name>3gs</name> <type>sub-category</type> </entity> </entities> </entity> <entity id="7024080"> <name>ipad</name> <type>category</type> </entity> </entities> </entity> currently i have selected all entities with type node that is not category. $xmlDocument-removeNodes("//entity[not(type='category')]") i wonder how i could select all nodes that dont contain type=category OR type=sub-category. i have tried with: $xmlDocument->removeNodes("//entity[not(type='category')] | //entity[not(type='sub-category')]") but it doesnt work!

    Read the article

  • Bind Config section to DataTable using c#

    - by srk
    I have the following config section in my app.config file and the code to iterate through config section to retrieve the values. But i want to save the values of config section to a datatable in a proper structure. How ? I want to show all the values in datagridview with appropriate columns. <configSections> <section name="ServerInfo" type="System.Configuration.IConfigurationSectionHandler" /> </configSections> <ServerInfo> <Server id="1"> <Name>SRUAV1</Name> <key> 1 </key> <IP>10.1.150.110</IP> <Port>7901</Port> </Server> <Server id="2"> <Name>SRUAV2</Name> <key> 4 </key> <IP>10.1.150.110</IP> <Port>7902</Port> </Server> <Server id="3"> <Name>SRUAV3</Name> <key> 6 </key> <IP>10.1.150.110</IP> <Port>7904</Port> </Server> </ServerInfo> Code : public void GetServerValues(string strSelectedServer) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigurationSection section = config.GetSection("ServerInfo"); XmlDocument xml = new XmlDocument(); xml.LoadXml(section.SectionInformation.GetRawXml()); string temp = ""; XmlNodeList applicationList = xml.DocumentElement.SelectNodes("Server"); for (int i = 0; i < applicationList.Count; i++) { object objAppId = applicationList[i].Attributes["id"]; int iAppId = 0; if (objAppId != null) { iAppId = Convert.ToInt32(applicationList[i].Attributes["id"].Value); } temp = BuildServerValues(applicationList[i]); } } public string BuildServerValues(XmlNode applicationNode) { for (int i = 0; i < applicationNode.ChildNodes.Count; i++) { if (applicationNode.ChildNodes.Item(i).Name.ToString().Equals("Name")) { strServerName = applicationNode.ChildNodes.Item(i).InnerXml.ToString(); } if (applicationNode.ChildNodes.Item(i).Name.ToString().Equals("IP")) { strIP = applicationNode.ChildNodes.Item(i).InnerXml.ToString(); } if (applicationNode.ChildNodes.Item(i).Name.ToString().Equals("Port")) { strPort = applicationNode.ChildNodes.Item(i).InnerXml.ToString(); } } return strServerName; }

    Read the article

  • '--' is an unexpected token. The expected token is '>'. Line 81, position 5.

    - by vamsivanka
    I am trying to get the html for this link http://slashdot.org/firehose.pl?op=rss&content_type=rss&orderby=createtime&fhfilter="home:vamsivanka" Dim myRequest As WebRequest Dim myResponse As WebResponse Try myRequest = System.Net.WebRequest.Create(url) myRequest.Timeout = 10000 myResponse = myRequest.GetResponse() Dim rssStream As Stream = myResponse.GetResponseStream() Dim rssDoc As New XmlDocument() rssDoc.Load(rssStream) Catch ex As Exception End Try But the rssDoc.Load is giving me an error '--' is an unexpected token. The expected token is ''. Line 81, position 5. Please Let me know your suggestions.

    Read the article

  • C# xml Class to substitute ini files

    - by Eduardo
    Hi guys, I am learning Windows Forms in C#.NET 2008 and i want to build a class to work with SIMPLE xml files (config file like INI files), but i just need a simple class (open, getvalue, setvalue, creategroup, save and close functions), to substitute of ini files. I already did something and it is working but I am having trouble when I need to create different groups, something like this: <?xml version="1.0" encoding="utf-8"?> <CONFIG> <General> <Field1>192.168.0.2</Field1> </General> <Data> <Field1>Joseph</Field1> <Field2>Locked</Field2> </Data> </CONFIG> how can i specify that i want to read the field1 of [data] group? note that i have same field name in both groups (Field1)! I am using System.Linq, something like this: To open document: XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(FilePath); To save document: xmlDoc.Save(FilePath); To get value: public string getValue(string Field) { string result = ""; try { XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field); if (xmlComum.Item(0) == null) result = ""; else result = xmlComum.Item(0).InnerText; } catch (Exception ex) { return ""; } return result; } To set value: public void setValue(string Group, string Field, string FieldValue) { try { XmlNodeList xmlComum = xmlDoc.GetElementsByTagName(Field); if (xmlComum.Item(0) == null) { xmlComum = xmlDoc.GetElementsByTagName(Group); if (xmlComum.Item(0) == null) { // create group createGroup(Group); xmlComum = xmlDoc.GetElementsByTagName(Group); } XmlElement xmlE = xmlDoc.CreateElement(Field); XmlText xmlT = xmlDoc.CreateTextNode(FieldValue); xmlE.AppendChild(xmlT); xmlComum.Item(0).AppendChild(xmlE); } else { // item already exists, just change its value xmlComum.Item(0).InnerText = Value; } xmlDoc.Save(FilePath); } catch (Exception ex) { } } The CreateGroup code: public void createGroup(string Group) { try { XmlElement xmlComum = xmlDoc.CreateElement(Group); xmlDoc.DocumentElement.AppendChild(xmlComum); xmlDoc.Save(FilePath); } catch (Exception ex) { } } Thank You!

    Read the article

  • C#, how to create an XML document from an object?

    - by JL
    I have the following variable that accepts a file name: var xtr = new XmlTextReader(xmlFileName) { WhitespaceHandling = WhitespaceHandling.None }; var xd = new XmlDocument(); xd.Load(xtr); I would like to change it so that I can pass in an object. I don't want to have to serialize the object to file first. Is this possible?

    Read the article

  • Getting full path for Windows Service

    - by Samuel Kim
    How can I find out the folder where the windows service .exe file is installed dynamically? Path.GetFullPath(relativePath); returns a path based on C:\WINDOWS\system32 directory. However, the XmlDocument.Load(string filename) method appears to be working against relative path inside the directory where the service .exe file is installed to.

    Read the article

  • XMLReader : how to catch syntax errors in the xml file ?

    - by mishal153
    Hi, I have an XML file with syntax errors. eg. <Viewport thisisbad Left="0" Top="0" Width="1280" Height="720" > When i create an XML reader it does not throw any errors. I there a way to do syntax checking automatically, like XMLDocument does ? I have tried setting various XmlReaderSettings flags but found nothing useful.

    Read the article

  • C# ApplicationContext usage

    - by rd42
    Apologies if my terminology is off, I'm new to C#. I'm trying to use an ApplicationContext file to store mysql conn values, like dbname, username, password. The class with mysql conn string is "using" the namespace for the ApplicationContext, but when I print out the connection string, the values are making it. A friend said, "I'm not initializing it" but couldn't stay to expand on what "it" was. and the "Console.WriteLine("1");" in ApplicationContext.cs never shows up. Do I need to create an ApplicationContext object and the call Initialize() on that object? Thanks for any help. ApplicationContext.cs: namespace NewApplication.Context { class ApplicationContext { public static string serverName; public static string username; public static string password; public static void Initialize() { //need to read through config here try { Console.WriteLine("1"); XmlDocument xDoc = new XmlDocument(); xDoc.Load(".\\Settings.xml"); XmlNodeList serverNodeList = xDoc.GetElementsByTagName("DatabaseServer"); XmlNodeList usernameNodeList = xDoc.GetElementsByTagName("UserName"); XmlNodeList passwordNodeList = xDoc.GetElementsByTagName("Password"); } catch (Exception ex) { // MessageBox.Show(ex.ToString()); //TODO: Future write to log file username = "user"; password = "password"; serverName = "localhost"; } } } } MySQLManager.cs: note: dbname is the same as the username as you'll see in the code, I copied this from a friend who does that. using System; using System.Collections.Generic; using System.Linq; using System.Text; using MySql.Data; using MySql.Data.MySqlClient; using NewApplication.Context; namespace NewApplication.DAO { class MySQLManager { private static MySqlConnection conn; public static MySqlConnection getConnection() { if (conn == null || conn.State == System.Data.ConnectionState.Closed) { string connStr = "server=" + ApplicationContext.serverName + ";user=" + ApplicationContext.username + ";database=" + ApplicationContext.username + ";port=3306;password=" + ApplicationContext.password + ";"; conn = new MySqlConnection(connStr); try { Console.WriteLine("Connecting to MySQL... "); Console.WriteLine("Connection string: " + connStr + "\n"); conn.Open(); // Perform databse operations // conn.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } return conn; } } } and, thanks for still reading, this is the code that uses the two previous files: class LogDAO { MySqlConnection conn; public LogDAO() { conn = MySQLManager.getConnection(); } Thank you, rd42

    Read the article

  • Accesing server control from withing app_code class

    - by OverSeven
    My question is about how to acces a server control (listbox) that is located in default.aspx. I wish to acces this control in Functions.cs (this class is located in the App_Code folder). My page structures: - 1 masterpage with 1 content holder - Default.aspx (all the controls are within the content place holder) - Functions.cs (located in App_Code) Now when i try to fill up the listbox elements i get the error "object reference not set to an instance of an object." What i have tried to gain acces to this control: (this code is located in Functions.cs in App_Code). This is basicly showing some items in the listbox that are located in the xml file private static string file = HttpContext.Current.Server.MapPath("~/App_Data/Questions.xml"); public static void ListItems() { XmlDocument XMLDoc = new XmlDocument(); XMLDoc.Load(file); XPathNavigator nav = XMLDoc.CreateNavigator(); XPathExpression expr; expr = nav.Compile("/root/file/naam"); XPathNodeIterator iterator = nav.Select(expr); //ATTEMPT to get acces to ServerControl(listbox) Page page = (Page)HttpContext.Current.Handler; ListBox test = (ListBox)page.FindControl("lbTest"); //control is called lbTest in Default.aspx test.Items.Clear(); while (iterator.MoveNext()) { test.Items.Add(iterator.Current.Value); } } Code from the default.apx file <%@ Page Title="" Language="C#" MasterPageFile="~/MasterFile.master" AutoEventWireup="true" CodeFile="default.aspx.cs" Inherits="default" Debug="true" %> <%@ MasterType TypeName="Master" %> <asp:Content ID="Content1" ContentPlaceHolderID="cphContent" Runat="Server" > <asp:MultiView ID="mvTest" runat="server" > <asp:View ID="vCollection" runat="server"> <asp:ListBox ID="lbTest" runat="server" CssClass="listbox" ></asp:ListBox> </asp:View> </asp:MultiView> </asp:Content> The masterfile itself just has 1 placeholder. Then i call upon the funcion ListItems in the Default.aspx.cs file protected void Page_Load(object sender, EventArgs e) { Functions.ListItems(); } Regards.

    Read the article

  • Generating text file from database

    - by Goldmember
    I have a requirement to hand-code an text file from data residing in a SQL table. Just wondering if there are any best practices here. Should I write it as an XMLDocument first and transform using XSL or just use Streamwriter and skip transformation altogether? The generated text file will be in EDIFACT format, so layout is very specific.

    Read the article

  • Should the argument be passed by reference in this .net example?

    - by Hamish Grubijan
    I have used Java, C++, .Net. (in that order). When asked about by-value vs. by-ref on interviews, I have always done well on that question ... perhaps because nobody went in-depth on it. Now I know that I do not see the whole picture. I was looking at this section of code written by someone else: XmlDocument doc = new XmlDocument(); AppendX(doc); // Real name of the function is different AppendY(doc); // ditto When I saw this code, I thought: wait a minute, should not I use a ref in front of doc variable (and modify AppendX/Y accordingly? it works as written, but made me question whether I actually understand the ref keyword in C#. As I thought about this more, I recalled early Java days (college intro language). A friend of mine looked at some code I have written and he had a mental block - he kept asking me which things are passed in by reference and when by value. My ignorant response was something like: Dude, there is only one kind of arg passing in Java and I forgot which one it is :). Chill, do not over-think and just code. Java still does not have a ref does it? Yet, Java hackers seem to be productive. Anyhow, coding in C++ exposed me to this whole by reference business, and now I am confused. Should ref be used in the example above? I am guessing that when ref is applied to value types: primitives, enums, structures (is there anything else in this list?) it makes a big difference. And ... when applied to objects it does not because it is all by reference. If things were so simple, then why would not the compiler restrict the usage of ref keyword to a subset of types. When it comes to objects, does ref serve as a comment sort of? Well, I do remember that there can be problems with null and ref is also useful for initializing multiple elements within a method (since you cannot return multiple things with the same easy as you would do in Python). Thanks.

    Read the article

  • Writing to XML issue Unity3D C#

    - by N0xus
    I'm trying to create a tool using Unity to generate an XML file for use in another project. Now, please, before someone suggests I do it in something, the reason I am using Unity is that it allows me to easily port this to an iPad or other device with next to no extra development. So please. Don't suggest to use something else. At the moment, I am using the following code to write to my XML file. public void WriteXMLFile() { string _filePath = Application.dataPath + @"/Data/HV_DarkRideSettings.xml"; XmlDocument _xmlDoc = new XmlDocument(); if (File.Exists(_filePath)) { _xmlDoc.Load(_filePath); XmlNode rootNode = _xmlDoc.CreateElement("Settings"); // _xmlDoc.AppendChild(rootNode); rootNode.RemoveAll(); XmlElement _cornerNode = _xmlDoc.CreateElement("Screen_Corners"); _xmlDoc.DocumentElement.PrependChild(_cornerNode); #region Top Left Corners XYZ Values // indent top left corner value to screen corners XmlElement _topLeftNode = _xmlDoc.CreateElement("Top_Left"); _cornerNode.AppendChild(_topLeftNode); // set the XYZ of the top left values XmlElement _topLeftXNode = _xmlDoc.CreateElement("TopLeftX"); XmlElement _topLeftYNode = _xmlDoc.CreateElement("TopLeftY"); XmlElement _topLeftZNode = _xmlDoc.CreateElement("TopLeftZ"); // indent these values to the top_left value in XML _topLeftNode.AppendChild(_topLeftXNode); _topLeftNode.AppendChild(_topLeftYNode); _topLeftNode.AppendChild(_topLeftZNode); #endregion #region Bottom Left Corners XYZ Values // indent top left corner value to screen corners XmlElement _bottomLeftNode = _xmlDoc.CreateElement("Bottom_Left"); _cornerNode.AppendChild(_bottomLeftNode); // set the XYZ of the top left values XmlElement _bottomLeftXNode = _xmlDoc.CreateElement("BottomLeftX"); XmlElement _bottomLeftYNode = _xmlDoc.CreateElement("BottomLeftY"); XmlElement _bottomLeftZNode = _xmlDoc.CreateElement("BottomLeftZ"); // indent these values to the top_left value in XML _bottomLeftNode.AppendChild(_bottomLeftXNode); _bottomLeftNode.AppendChild(_bottomLeftYNode); _bottomLeftNode.AppendChild(_bottomLeftZNode); #endregion #region Bottom Left Corners XYZ Values // indent top left corner value to screen corners XmlElement _bottomRightNode = _xmlDoc.CreateElement("Bottom_Right"); _cornerNode.AppendChild(_bottomRightNode); // set the XYZ of the top left values XmlElement _bottomRightXNode = _xmlDoc.CreateElement("BottomRightX"); XmlElement _bottomRightYNode = _xmlDoc.CreateElement("BottomRightY"); XmlElement _bottomRightZNode = _xmlDoc.CreateElement("BottomRightZ"); // indent these values to the top_left value in XML _bottomRightNode.AppendChild(_bottomRightXNode); _bottomRightNode.AppendChild(_bottomRightYNode); _bottomRightNode.AppendChild(_bottomRightZNode); #endregion _xmlDoc.Save(_filePath); } } This generates the following XML file: <Settings> <Screen_Corners> <Top_Left> <TopLeftX /> <TopLeftY /> <TopLeftZ /> </Top_Left> <Bottom_Left> <BottomLeftX /> <BottomLeftY /> <BottomLeftZ /> </Bottom_Left> <Bottom_Right> <BottomRightX /> <BottomRightY /> <BottomRightZ /> </Bottom_Right> </Screen_Corners> </Settings> Which is exactly what I want. However, each time I press the button that has the WriteXMLFile() method attached to it, it's write the entire lot again. Like so: <Settings> <Screen_Corners> <Top_Left> <TopLeftX /> <TopLeftY /> <TopLeftZ /> </Top_Left> <Bottom_Left> <BottomLeftX /> <BottomLeftY /> <BottomLeftZ /> </Bottom_Left> <Bottom_Right> <BottomRightX /> <BottomRightY /> <BottomRightZ /> </Bottom_Right> </Screen_Corners> <Screen_Corners> <Top_Left> <TopLeftX /> <TopLeftY /> <TopLeftZ /> </Top_Left> <Bottom_Left> <BottomLeftX /> <BottomLeftY /> <BottomLeftZ /> </Bottom_Left> <Bottom_Right> <BottomRightX /> <BottomRightY /> <BottomRightZ /> </Bottom_Right> </Screen_Corners> <Screen_Corners> <Top_Left> <TopLeftX /> <TopLeftY /> <TopLeftZ /> </Top_Left> <Bottom_Left> <BottomLeftX /> <BottomLeftY /> <BottomLeftZ /> </Bottom_Left> <Bottom_Right> <BottomRightX /> <BottomRightY /> <BottomRightZ /> </Bottom_Right> </Screen_Corners> </Settings> Now, I've written XML files before using winforms, and the WriteXMLFile function is exactly the same. However, in my winform, no matter how much I press the WriteXMLFile button, it doesn't write the whole lot again. Is there something that I'm doing wrong or should change to stop this from happening?

    Read the article

  • Retrieving a list of eBay categories using the .NET SDK and GetCategoriesCall

    - by Bill Osuch
    eBay offers a .Net SDK for its Trading API - this post will show you the basics of making an API call and retrieving a list of current categories. You'll need the category ID(s) for any apps that post or search eBay. To start, download the latest SDK from https://www.x.com/developers/ebay/documentation-tools/sdks/dotnet and create a new console app project. Add a reference to the eBay.Service DLL, and a few using statements: using eBay.Service.Call; using eBay.Service.Core.Sdk; using eBay.Service.Core.Soap; I'm assuming at this point you've already joined the eBay Developer Network and gotten your app IDs and user tokens. If not: Join the developer program Generate tokens Next, add an app.config file that looks like this: <?xml version="1.0"?> <configuration>   <appSettings>     <add key="Environment.ApiServerUrl" value="https://api.ebay.com/wsapi"/>     <add key="UserAccount.ApiToken" value="YourBigLongToken"/>   </appSettings> </configuration> And then add the code to get the xml list of categories: ApiContext apiContext = GetApiContext(); GetCategoriesCall apiCall = new GetCategoriesCall(apiContext); apiCall.CategorySiteID = "0"; //Leave this commented out to retrieve all category levels (all the way down): //apiCall.LevelLimit = 4; //Uncomment this to begin at a specific parent category: //StringCollection parentCategories = new StringCollection(); //parentCategories.Add("63"); //apiCall.CategoryParent = parentCategories; apiCall.DetailLevelList.Add(DetailLevelCodeType.ReturnAll); CategoryTypeCollection cats = apiCall.GetCategories(); using (StreamWriter outfile = new StreamWriter(@"C:\Temp\EbayCategories.xml")) {    outfile.Write(apiCall.SoapResponse); } GetApiContext() (provided in the sample apps in the SDK) is required for any call:         static ApiContext GetApiContext()         {             //apiContext is a singleton,             //to avoid duplicate configuration reading             if (apiContext != null)             {                 return apiContext;             }             else             {                 apiContext = new ApiContext();                 //set Api Server Url                 apiContext.SoapApiServerUrl = ConfigurationManager.AppSettings["Environment.ApiServerUrl"];                 //set Api Token to access eBay Api Server                 ApiCredential apiCredential = new ApiCredential();                 apiCredential.eBayToken = ConfigurationManager.AppSettings["UserAccount.ApiToken"];                 apiContext.ApiCredential = apiCredential;                 //set eBay Site target to US                 apiContext.Site = SiteCodeType.US;                 return apiContext;             }         } Running this will give you a large (4 or 5 megs) XML file that looks something like this: <soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">    <soapenv:Body>       <GetCategoriesResponse >          <Timestamp>2012-06-06T16:03:46.158Z</Timestamp>          <Ack>Success</Ack>          <CorrelationID>d02dd9e3-295a-4268-9ea5-554eeb2e0e18</CorrelationID>          <Version>775</Version>          <Build>E775_CORE_BUNDLED_14891042_R1</Build> -          <CategoryArray>             <Category>                <BestOfferEnabled>true</BestOfferEnabled>                <AutoPayEnabled>true</AutoPayEnabled>                <CategoryID>20081</CategoryID>                <CategoryLevel>1</CategoryLevel>                <CategoryName>Antiques</CategoryName>                <CategoryParentID>20081</CategoryParentID>             </Category>             <Category>                <BestOfferEnabled>true</BestOfferEnabled>                <AutoPayEnabled>true</AutoPayEnabled>                <CategoryID>37903</CategoryID>                <CategoryLevel>2</CategoryLevel>                <CategoryName>Antiquities</CategoryName>                <CategoryParentID>20081</CategoryParentID>             </Category> (etc.) You could work with this, but I wanted a nicely nested view, like this: <CategoryArray>    <Category Name='Antiques' ID='20081' Level='1'>       <Category Name='Antiquities' ID='37903' Level='2'/> </CategoryArray> ...so I transformed the xml: private void TransformXML(CategoryTypeCollection cats)         {             XmlElement topLevelElement = null;             XmlElement childLevelElement = null;             XmlNode parentNode = null;             string categoryString = "";             XmlDocument returnDoc = new XmlDocument();             XmlElement root = returnDoc.CreateElement("CategoryArray");             returnDoc.AppendChild(root);             XmlNode rootNode = returnDoc.SelectSingleNode("/CategoryArray");             //Loop through CategoryTypeCollection             foreach (CategoryType category in cats)             {                 if (category.CategoryLevel == 1)                 {                     //Top-level category, so we know we can just add it                     topLevelElement = returnDoc.CreateElement("Category");                     topLevelElement.SetAttribute("Name", category.CategoryName);                     topLevelElement.SetAttribute("ID", category.CategoryID);                     rootNode.AppendChild(topLevelElement);                 }                 else                 {                     // Level number will determine how many Category nodes we are deep                     categoryString = "";                     for (int x = 1; x < category.CategoryLevel; x++)                     {                         categoryString += "/Category";                     }                     parentNode = returnDoc.SelectSingleNode("/CategoryArray" + categoryString + "[@ID='" + category.CategoryParentID[0] + "']");                     childLevelElement = returnDoc.CreateElement("Category");                     childLevelElement.SetAttribute("Name", category.CategoryName);                     childLevelElement.SetAttribute("ID", category.CategoryID);                     parentNode.AppendChild(childLevelElement);                 }             }             returnDoc.Save(@"C:\Temp\EbayCategories-Modified.xml");         } Yes, there are probably much cleaner ways of dealing with it, but I'm not an xml expert… Keep in mind, eBay categories do not change on a regular basis, so you should be able to cache this data (either in a file or database) for some time. The xml returns a CategoryVersion node that you can use to determine if the category list has changed. Technorati Tags: Csharp, eBay

    Read the article

  • XNA Xbox 360 Content Manager Thread freezing Draw Thread

    - by Alikar
    I currently have a game that takes in large images, easily bigger than 1MB, to serve as backgrounds. I know exactly when this transition is supposed to take place, so I made a loader class to handle loading these large images in the background, but when I load the images it still freezes the main thread where the drawing takes place. Since this code runs on the 360 I move the thread to the 4th hardware thread, but that doesn't seem to help. Below is the class I am using. Any thoughts as to why my new content manager which should be in its own thread is interrupting the draw in my main thread would be appreciated. namespace FileSystem { /// <summary> /// This is used to reference how many objects reference this texture. /// Everytime someone references a texture we increase the iNumberOfReferences. /// When a class calls remove on a specific texture we check to see if anything /// else is referencing the class, if it is we don't remove it. If there isn't /// anything referencing the texture its safe to dispose of. /// </summary> class TextureContainer { public uint uiNumberOfReferences = 0; public Texture2D texture; } /// <summary> /// This class loads all the files from the Content. /// </summary> static class FileManager { static Microsoft.Xna.Framework.Content.ContentManager Content; static EventWaitHandle wh = new AutoResetEvent(false); static Dictionary<string, TextureContainer> Texture2DResourceDictionary; static List<Texture2D> TexturesToDispose; static List<String> TexturesToLoad; static int iProcessor = 4; private static object threadMutex = new object(); private static object Texture2DMutex = new object(); private static object loadingMutex = new object(); private static bool bLoadingTextures = false; /// <summary> /// Returns if we are loading textures or not. /// </summary> public static bool LoadingTexture { get { lock (loadingMutex) { return bLoadingTextures; } } } /// <summary> /// Since this is an static class. This is the constructor for the file loadeder. This is the version /// for the Xbox 360. /// </summary> /// <param name="_Content"></param> public static void Initalize(IServiceProvider serviceProvider, string rootDirectory, int _iProcessor ) { Content = new Microsoft.Xna.Framework.Content.ContentManager(serviceProvider, rootDirectory); Texture2DResourceDictionary = new Dictionary<string, TextureContainer>(); TexturesToDispose = new List<Texture2D>(); iProcessor = _iProcessor; CreateThread(); } /// <summary> /// Since this is an static class. This is the constructor for the file loadeder. /// </summary> /// <param name="_Content"></param> public static void Initalize(IServiceProvider serviceProvider, string rootDirectory) { Content = new Microsoft.Xna.Framework.Content.ContentManager(serviceProvider, rootDirectory); Texture2DResourceDictionary = new Dictionary<string, TextureContainer>(); TexturesToDispose = new List<Texture2D>(); CreateThread(); } /// <summary> /// Creates the thread incase we wanted to set up some parameters /// Outside of the constructor. /// </summary> static public void CreateThread() { Thread t = new Thread(new ThreadStart(StartThread)); t.Start(); } // This is the function that we thread. static public void StartThread() { //BBSThreadClass BBSTC = (BBSThreadClass)_oData; FileManager.Execute(); } /// <summary> /// This thread shouldn't be called by the outside world. /// It allows the File Manager to loop. /// </summary> static private void Execute() { // Make sure our thread is on the correct processor on the XBox 360. #if WINDOWS #else Thread.CurrentThread.SetProcessorAffinity(new int[] { iProcessor }); Thread.CurrentThread.IsBackground = true; #endif // This loop will load textures into ram for us away from the main thread. while (true) { wh.WaitOne(); // Locking down our data while we process it. lock (threadMutex) { lock (loadingMutex) { bLoadingTextures = true; } bool bContainsKey = false; for (int con = 0; con < TexturesToLoad.Count; con++) { // If we have already loaded the texture into memory reference // the one in the dictionary. lock (Texture2DMutex) { bContainsKey = Texture2DResourceDictionary.ContainsKey(TexturesToLoad[con]); } if (bContainsKey) { // Do nothing } // Otherwise load it into the dictionary and then reference the // copy in the dictionary else { TextureContainer TC = new TextureContainer(); TC.uiNumberOfReferences = 1; // We start out with 1 referece. // Loading the texture into memory. try { TC.texture = Content.Load<Texture2D>(TexturesToLoad[con]); // This is passed into the dictionary, thus there is only one copy of // the texture in memory. // There is an issue with Sprite Batch and disposing textures. // This will have to wait until its figured out. lock (Texture2DMutex) { bContainsKey = Texture2DResourceDictionary.ContainsKey(TexturesToLoad[con]); Texture2DResourceDictionary.Add(TexturesToLoad[con], TC); } // We don't have the find the reference to the container since we // already have it. } // Occasionally our texture will already by loaded by another thread while // this thread is operating. This mainly happens on the first level. catch (Exception e) { // If this happens we don't worry about it since this thread only loads // texture data and if its already there we don't need to load it. } } Thread.Sleep(100); } } lock (loadingMutex) { bLoadingTextures = false; } } } static public void LoadTextureList(List<string> _textureList) { // Ensuring that we can't creating threading problems. lock (threadMutex) { TexturesToLoad = _textureList; } wh.Set(); } /// <summary> /// This loads a 2D texture which represents a 2D grid of Texels. /// </summary> /// <param name="_textureName">The name of the picture you wish to load.</param> /// <returns>Holds the image data.</returns> public static Texture2D LoadTexture2D( string _textureName ) { TextureContainer temp; lock (Texture2DMutex) { bool bContainsKey = false; // If we have already loaded the texture into memory reference // the one in the dictionary. lock (Texture2DMutex) { bContainsKey = Texture2DResourceDictionary.ContainsKey(_textureName); if (bContainsKey) { temp = Texture2DResourceDictionary[_textureName]; temp.uiNumberOfReferences++; // Incrementing the number of references } // Otherwise load it into the dictionary and then reference the // copy in the dictionary else { TextureContainer TC = new TextureContainer(); TC.uiNumberOfReferences = 1; // We start out with 1 referece. // Loading the texture into memory. try { TC.texture = Content.Load<Texture2D>(_textureName); // This is passed into the dictionary, thus there is only one copy of // the texture in memory. } // Occasionally our texture will already by loaded by another thread while // this thread is operating. This mainly happens on the first level. catch(Exception e) { temp = Texture2DResourceDictionary[_textureName]; temp.uiNumberOfReferences++; // Incrementing the number of references } // There is an issue with Sprite Batch and disposing textures. // This will have to wait until its figured out. Texture2DResourceDictionary.Add(_textureName, TC); // We don't have the find the reference to the container since we // already have it. temp = TC; } } } // Return a reference to the texture return temp.texture; } /// <summary> /// Go through our dictionary and remove any references to the /// texture passed in. /// </summary> /// <param name="texture">Texture to remove from texture dictionary.</param> public static void RemoveTexture2D(Texture2D texture) { foreach (KeyValuePair<string, TextureContainer> pair in Texture2DResourceDictionary) { // Do our references match? if (pair.Value.texture == texture) { // Only one object or less holds a reference to the // texture. Logically it should be safe to remove. if (pair.Value.uiNumberOfReferences <= 1) { // Grabing referenc to texture TexturesToDispose.Add(pair.Value.texture); // We are about to release the memory of the texture, // thus we make sure no one else can call this member // in the dictionary. Texture2DResourceDictionary.Remove(pair.Key); // Once we have removed the texture we don't want to create an exception. // So we will stop looking in the list since it has changed. break; } // More than one Object has a reference to this texture. // So we will not be removing it from memory and instead // simply marking down the number of references by 1. else { pair.Value.uiNumberOfReferences--; } } } } /*public static void DisposeTextures() { int Count = TexturesToDispose.Count; // If there are any textures to dispose of. if (Count > 0) { for (int con = 0; con < TexturesToDispose.Count; con++) { // =!THIS REMOVES THE TEXTURE FROM MEMORY!= // This is not like a normal dispose. This will actually // remove the object from memory. Texture2D is inherited // from GraphicsResource which removes it self from // memory on dispose. Very nice for game efficency, // but "dangerous" in managed land. Texture2D Temp = TexturesToDispose[con]; Temp.Dispose(); } // Remove textures we've already disposed of. TexturesToDispose.Clear(); } }*/ /// <summary> /// This loads a 2D texture which represnets a font. /// </summary> /// <param name="_textureName">The name of the font you wish to load.</param> /// <returns>Holds the font data.</returns> public static SpriteFont LoadFont( string _fontName ) { SpriteFont temp = Content.Load<SpriteFont>( _fontName ); return temp; } /// <summary> /// This loads an XML document. /// </summary> /// <param name="_textureName">The name of the XML document you wish to load.</param> /// <returns>Holds the XML data.</returns> public static XmlDocument LoadXML( string _fileName ) { XmlDocument temp = Content.Load<XmlDocument>( _fileName ); return temp; } /// <summary> /// This loads a sound file. /// </summary> /// <param name="_fileName"></param> /// <returns></returns> public static SoundEffect LoadSound( string _fileName ) { SoundEffect temp = Content.Load<SoundEffect>(_fileName); return temp; } } }

    Read the article

< Previous Page | 5 6 7 8 9 10 11 12 13  | Next Page >