Search Results

Search found 83 results on 4 pages for 'selectnodes'.

Page 3/4 | < Previous Page | 1 2 3 4  | Next Page >

  • Code to update HyperV Export file

    - by Andy Schneider
    I am using the HyperV Module from Codeplex to do a "config only" export from a 2008R2 Hyper-V server. In order to import the configuration on another HyperV server, I need to edit the value of CopyVMStorage in the EXP file. This file is an XML file. I wrote the following code in PowerShell to do the update for me. The variable $existing is the existing exp file. $xml = [xml](get-content $existing) $xpath = '//PROPERTY[@NAME ="CopyVmStorage"]' foreach ($node in $xml.SelectNodes($xpath)) {$node.Value = 'TRUE'} $xml.Save($existing) This code makes the correct changes to the XML. However, when I go to import the file on the Hyper-V server, I get an error that says the file format is incorrect. I am wondering if the encoding of the file is incorrect or if there is something else going on. If I edit the file manually in wordpad, it imports without an issue. The filename is a GUID with a .exp extension, and it appears that the file name is too long for notepad to open. Notepad throws an error trying to open the file, which is why I went with WordPad. I have noticed that the file that is updated with PowerShell comes out formatted whereas the raw file is xml all bunched together with no whitespace. Any ideas on what "file format" means in this HyperV error message and how I might be able to use my code to automate this change in the XML without changing the file format?

    Read the article

  • HTML Agility Pack Screen Scraping XPATH isn't returning data

    - by Matthias Welsh
    I'm attempting to write a screen scraper for Digikey that will allow our company to keep accurate track of pricing, part availability and product replacements when a part is discontinued. There seems to be a discrepancy between the XPATH that I'm seeing in Chrome Devtools as well as Firebug on Firefox and what my C# program is seeing. The code I'm currently using is pretty quick and dirty... //This function retrieves data from the digikey private static List<string> ExtractProductInfo(HtmlDocument doc) { List<HtmlNode> m_unparsedProductInfoNodes = new List<HtmlNode>(); List<string> m_unparsedProductInfo = new List<string>(); //Base Node for part info string m_baseNode = @"//html[1]/body[1]/div[2]"; //Write part info to list m_unparsedProductInfoNodes.Add(doc.DocumentNode.SelectSingleNode(m_baseNode + @"/table[1]/tr[1]/td[1]/table[1]/tr[1]/td[1]")); //More lines of similar form will go here for more info //this retrieves digikey PN foreach(HtmlNode node in m_unparsedProductInfoNodes) { m_unparsedProductInfo.Add(node.InnerText); } return m_unparsedProductInfo; } Although the path I'm using appears to be "correct" I keep getting NULL when I look at the list "m_unparsedProductInfoNodes" Any idea what's going on here? I'll also add that if I do a "SelectNodes" on the baseNode it only returns a div... not sure what that indicates but it doesn't seem right.

    Read the article

  • TCL TDom: Looping through Objects

    - by pws5068
    Using TDom, I would like to cycle through a list of objects in the following format: <object> <type>Hardware</type> <name>System Name</name> <description>Basic Description of System.</description> <attributes> <vendor>Dell</vendor> <contract>MM/DD/YY</contract> <supportExpiration>MM/DD/YY</supportExpiration> <location>Building 123</location> <serial>xxx-xxx-xxxx</serial> <mac>some-mac-address</mac> </attributes> </object> <object> <type>Software</type> <name>Second Object</name> ... Then I use TDom to make a list of objects: set dom [dom parse $xml] set doc [$dom documentElement] set nodeList [$doc selectNodes /systems/object] So far I've done this to (theoretically) select every "Object" node from the list. How can I loop through them? Is it just: foreach node $nodeList { For each object, I need to retrieve the association of each attribute. From the example, I need to remember that the "name" is "System Name", "vendor" is "Dell", etc. I'm new to TCL but in other languages I would use an object or an associative list to store these. Is this possible? Can you show me an example of the syntax to select an attribute in this manner?

    Read the article

  • Save all xml nodes to db without looping through it

    - by AndreMiranda
    I have this xml: <Path> <Record> <ID>6534808</ID> <Distance>1.05553036073736</Distance> </Record> <Record> <ID>6542471</ID> <Distance>1.05553036073736</Distance> </Record> ... and about more 500 nodes </Path> And I'm using the code below to get all "Record" nodes: XmlNodeList paths = xDoc.SelectNodes("//Record"); And, after that, I save each record to database. But, the problem is that I'm using a foreach to loop through this nodes and the count of this nodes may be more than 500, sometimes it gets up to 1000 "Records" node. And this gets too long... Is there a way to save all of these nodes without looping through it? Thanks!!

    Read the article

  • Extract enumeration data from .XSD file

    - by Ram
    Hi, I am trying to read enum from a XSD file. The schema is as follows <xs:schema id="ShipReports-v1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" attributeFormDefault="unqualified" elementFormDefault="qualified" msdata:IsDataSet="true"> <xs:simpleType name="Type"> <xs:restriction base="xs:string"> <xs:enumeration value="Op1" /> <xs:enumeration value="Op2" /> <xs:enumeration value="Op3" /> </xs:restriction> </xs:simpleType> </xs:schema> I also tried using this but I am getting list item count as Zero. Following is the code I am using DataSet _sR = new DataSet(); _sR.ReadXmlSchema(assembly.GetManifestResourceStream("v1.xsd")); XmlDocument xDoc = new XmlDocument(); xDoc.LoadXml(_sR.GetXml()); XmlNamespaceManager xMan = new XmlNamespaceManager(xDoc.NameTable); xMan.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema"); XmlNodeList xNodeList = xDoc.SelectNodes( "//xs:schema/xs:simpleType[@name='Type']/xs:enumeration", xMan); string[] enumVal = new string[xNodeList.Count]; int ctr = 0; foreach (XmlNode xNode in xNodeList) { enumVal[ctr] = xNode.Attributes["value"].Value; ctr++; }

    Read the article

  • How to improve this piece of code

    - by user303518
    Can anyone help me on this. It may be very frustrating for you all. But I want you guys to take a moment to look at the code below and please tell me all the things that are wrong in the below piece of code. You can copy it into your visual studio to analyze this better. You don’t have to make this code compile. My task is to get the following things: Most obvious mistakes with this code All the things that are wrong/bad practices with the code below Modify/Write an optimized version of this code. Keep in mind, the code DOES NOT need to compile. Reduce the number of lines of code You should NEVER try to implement something like below: public List<ValidationErrorDto> ProcessEQuote(string eQuoteXml, long programUniversalID) { // Get Program Info. DataTable programs = GetAllPrograms(); DataRow[] programRows = programs.Select(string.Format("ProgramUniversalID = {0}", programUniversalID)); long programID = (long)programRows[0]["ProgramID"]; string programName = (string)programRows[0]["Description"]; // Get Config file values. string fromEmail = ConfigurationManager.AppSettings["eQuotesFromEmail"]; string technicalSupportPhone = ConfigurationManager.AppSettings["TechnicalSupportPhone"]; string fromEmailDisplayName = string.IsNullOrEmpty(ConfigurationManager.AppSettings["eQuotesFromDisplayName"]) ? null : string.Format(ConfigurationManager.AppSettings["eQuotesFromDisplayName"], programName); string itEmail = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["ITEmail"]) ? ConfigurationManager.AppSettings["ITEmail"] : string.Empty; string itName = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["ITName"]) ? ConfigurationManager.AppSettings["ITName"] : "IT"; try { List<ValidationErrorDto> allValidationErrors = new List<ValidationErrorDto>(); List<ValidationErrorDto> validationErrors = new List<ValidationErrorDto>(); if (validationErrors.Count == 0) { validationErrors.AddRange(ValidateEQuoteXmlAgainstSchema(eQuoteXml)); if (validationErrors.Count == 0) { XmlDocument eQuoteXmlDoc = new XmlDocument(); eQuoteXmlDoc.LoadXml(eQuoteXml); XmlElement rootElement = eQuoteXmlDoc.DocumentElement; XmlNodeList quotesList = rootElement.SelectNodes("Quote"); foreach (XmlNode node in quotesList) { // Each node should be a quote node but to be safe, check if (node.Name == "Quote") { string groupName = node.SelectSingleNode("Group/GroupName").InnerText; string groupCity = node.SelectSingleNode("Group/GroupCity").InnerText; string groupPostalCode = node.SelectSingleNode("Group/GroupZipCode").InnerText; string groupSicCode = node.SelectSingleNode("Group/GroupSIC").InnerText; string generalAgencyLicenseNumber = node.SelectSingleNode("Group/GALicenseNbr").InnerText; string brokerName = node.SelectSingleNode("Group/BrokerName").InnerText; string deliverToEmailAddress = node.SelectSingleNode("Group/ReturnEmailAddress").InnerText; string brokerEmail = node.SelectSingleNode("Group/BrokerEmail").InnerText; string groupEligibleEmployeeCountString = node.SelectSingleNode("Group/GroupNbrEmployees").InnerText; string quoteEffectiveDateString = node.SelectSingleNode("Group/QuoteEffectiveDate").InnerText; string salesRepName = node.SelectSingleNode("Group/SalesRepName").InnerText; string salesRepPhone = node.SelectSingleNode("Group/SalesRepPhone").InnerText; string salesRepEmail = node.SelectSingleNode("Group/SalesRepEmail").InnerText; string brokerLicenseNumber = node.SelectSingleNode("Group/BrokerLicenseNbr").InnerText; DateTime? quoteEffectiveDate = null; int eligibleEmployeeCount = int.Parse(groupEligibleEmployeeCountString); DateTime quoteEffectiveDateOut; if (!DateTime.TryParse(quoteEffectiveDateString, out quoteEffectiveDateOut)) validationErrors.Add(ValidationHelper.CreateValidationError((long)QuoteField.EffectiveDate, "Quote Effective Date", ValidationErrorDto.ValueOutOfRange, false, ValidationHelper.CreateValidationContext(Entity.QuoteDetail, "Quote"))); else quoteEffectiveDate = quoteEffectiveDateOut; Dictionary<string, string> replacementCodeValues = new Dictionary<string, string>(); if (string.IsNullOrEmpty(Resources.ParameterMessageKeys.ResourceManager.GetString("GroupName"))) throw new InvalidOperationException("GroupName key is not configured"); replacementCodeValues.Add(Resources.ParameterMessageKeys.GroupName, groupName); replacementCodeValues.Add(Resources.ParameterMessageKeys.ProgramName, programName); replacementCodeValues.Add(Resources.ParameterMessageKeys.SalesRepName, salesRepName); replacementCodeValues.Add(Resources.ParameterMessageKeys.SalesRepPhone, salesRepPhone); replacementCodeValues.Add(Resources.ParameterMessageKeys.SalesRepEmail, salesRepEmail); replacementCodeValues.Add(Resources.ParameterMessageKeys.TechnicalSupportPhone, technicalSupportPhone); replacementCodeValues.Add(Resources.ParameterMessageKeys.EligibleEmployeCount, eligibleEmployeeCount.ToString()); // Retrieve the CityID and StateID long? cityID = null; long? stateID = null; DataSet citiesAndStates = Addresses.GetCitiesAndStatesFromPostalCode(groupPostalCode); DataTable cities = citiesAndStates.Tables[0]; DataTable states = citiesAndStates.Tables[1]; DataRow[] cityRows = cities.Select(string.Format("Name = '{0}'", groupCity)); if (cityRows.Length > 0) { cityID = (long)cityRows[0]["CityID"]; DataRow[] stateRows = states.Select(string.Format("CityID = {0}", cityID)); if (stateRows.Length > 0) stateID = (long)stateRows[0]["StateID"]; } // If the StateID does not exist, then we cannot get the GeneralAgency, so set a validation error and do not contine. // Else, Continue and look for an General Agency. If a GA was found, look for or create a Broker. Then look for or create a Prospect Group // Then using the info, create a quote. if (!stateID.HasValue) validationErrors.Add(ValidationHelper.CreateValidationError((long)ProspectGroupField.State, "Prospect Group State", ValidationErrorDto.RequiredFieldMissing, false, ValidationHelper.CreateValidationContext(Entity.ProspectGroup, "Prospect Group"))); bool brokerValidationError = false; SalesRepDto salesRep = GetSalesRepByEmail(salesRepEmail, ref validationErrors); if (salesRep == null) { string exceptionMessage = "Sales Rep Not found in Opportunity System. Please make sure Sales Rep is present in the system by adding the sales rep in AWP SR Add Screen." + Environment.NewLine; exceptionMessage = exceptionMessage + " Sales Rep Name: " + salesRepName + Environment.NewLine; exceptionMessage = exceptionMessage + " Sales Rep Email: " + salesRepEmail + Environment.NewLine; exceptionMessage = exceptionMessage + " Module : E-Quote Service" + Environment.NewLine; throw new Exception(exceptionMessage); } if (validationErrors.Count == 0) { // Note that StateID and EffectiveDate should be valid at this point. If it weren't there would be validation errors. // Find General Agency long? generalAgencyID; validationErrors.AddRange(GetEQuoteGeneralAgency(generalAgencyLicenseNumber, stateID.Value, out generalAgencyID)); // If GA was found, check for Broker. if (validationErrors.Count == 0 && generalAgencyID.HasValue) { Dictionary<string, string> brokerNameParts = ContactHelper.GetNamePartsFromFullName(brokerName); long? brokerID; validationErrors.AddRange(CreateEQuoteBroker(brokerNameParts["FirstName"], brokerNameParts["LastName"], brokerEmail, brokerLicenseNumber, stateID.Value, generalAgencyID.Value, salesRep, programID, out brokerID)); // If Broker was found but had validation errors if (validationErrors.Count > 0) { DeliverEmailMessage(programID, quoteEffectiveDate.Value, fromEmail, fromEmailDisplayName, itEmail, DocumentType.EQuoteBrokerValidationFailureMessageEmail, replacementCodeValues); brokerValidationError = true; } // If Broker was found, check for Prospect Group if (validationErrors.Count == 0 && brokerID.HasValue) { long? prospectGroupID; validationErrors.AddRange(CreateEQuoteProspectGroup(groupName, cityID, stateID, groupPostalCode, groupSicCode, brokerID.Value, out prospectGroupID)); if (validationErrors.Count == 0 && prospectGroupID.HasValue) { if (validationErrors.Count == 0) { long? quoteID; validationErrors.AddRange(CreateEQuote(programID, prospectGroupID.Value, generalAgencyID.Value, quoteEffectiveDate.Value, eligibleEmployeeCount, deliverToEmailAddress, node.SelectNodes("Employees/Employee"), deliverToEmailAddress, out quoteID)); if (validationErrors.Count == 0 && quoteID.HasValue) { QuoteFromServiceDto quoteFromService = GetQuoteByQuoteID(quoteID.Value); // Generate Pre-Message replacementCodeValues.Add(Resources.ParameterMessageKeys.QuoteNumber, string.Format("{0}.{1}", quoteFromService.QuoteNumber, quoteFromService.QuoteVersion)); replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, brokerName); replacementCodeValues.Add(Resources.ParameterMessageKeys.LicenseNumbers, brokerLicenseNumber); DeliverEmailMessage(programID, quoteEffectiveDate.Value, fromEmail, fromEmailDisplayName, deliverToEmailAddress, DocumentType.EQuotePreMessageEmail, replacementCodeValues); bool quoteGenerated = false; try { quoteGenerated = GenerateAndDeliverInitialQuote(quoteID.Value); } catch (Exception exception) { TraceLogger.LogException(exception, LoggingCategory); if (replacementCodeValues.ContainsKey(Resources.ParameterMessageKeys.Name)) replacementCodeValues[Resources.ParameterMessageKeys.Name] = itName; else replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, itName); if (replacementCodeValues.ContainsKey(Resources.ParameterMessageKeys.Errors)) replacementCodeValues[Resources.ParameterMessageKeys.Errors] = string.Format("Errors:\r\n:{0}", exception); else replacementCodeValues.Add(Resources.ParameterMessageKeys.Errors, string.Format("Errors:\r\n:{0}", exception)); DeliverEmailMessage(programID, quoteEffectiveDate.Value, fromEmail, fromEmailDisplayName, itEmail, DocumentType.EQuoteSystemFailureMessageEmail, replacementCodeValues); } if (!quoteGenerated) { // Generate System Failure Message if (replacementCodeValues.ContainsKey(Resources.ParameterMessageKeys.Name)) replacementCodeValues[Resources.ParameterMessageKeys.Name] = brokerName; else replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, brokerName); if (replacementCodeValues.ContainsKey(Resources.ParameterMessageKeys.Errors)) replacementCodeValues[Resources.ParameterMessageKeys.Errors] = string.Empty; else replacementCodeValues.Add(Resources.ParameterMessageKeys.Errors, string.Empty); DeliverEmailMessage(programID, quoteEffectiveDate.Value, fromEmail, fromEmailDisplayName, itEmail, DocumentType.EQuoteSystemFailureMessageEmail, replacementCodeValues); } } } } } } } //if (validationErrors.Count > 0) // Per spec, if Broker Validation returned an error we already sent an email, don't send another generic one if (validationErrors.Count > 0 && (!brokerValidationError)) { StringBuilder errorString = new StringBuilder(); foreach (ValidationErrorDto validationError in validationErrors) errorString = errorString.AppendLine(string.Format(" - {0}", ValidationHelper.GetValidationErrorReason(validationError, true))); replacementCodeValues.Add(Resources.ParameterMessageKeys.Errors, errorString.ToString()); if (replacementCodeValues.ContainsKey(Resources.ParameterMessageKeys.Name)) replacementCodeValues[Resources.ParameterMessageKeys.Name] = brokerName; else replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, brokerName); // HACK: If there is no effective date, then use Today's date. Do we care about the effecitve dat on validation message? if (quoteEffectiveDate.HasValue) DeliverEmailMessage(programID, quoteEffectiveDate.Value, fromEmail, fromEmailDisplayName, itEmail, DocumentType.EQuoteValidationFailureMessageEmail, replacementCodeValues); else DeliverEmailMessage(programID, DateTime.Now, fromEmail, fromEmailDisplayName, itEmail, DocumentType.EQuoteValidationFailureMessageEmail, replacementCodeValues); } allValidationErrors.AddRange(validationErrors); validationErrors.Clear(); } } } else { // Use todays date as the effective date. Dictionary<string, string> replacementCodeValues = new Dictionary<string, string>(); StringBuilder errorString = new StringBuilder(); foreach (ValidationErrorDto validationError in validationErrors) errorString = errorString.AppendLine(string.Format(" - {0}", ValidationHelper.GetValidationErrorReason(validationError, true))); replacementCodeValues.Add(Resources.ParameterMessageKeys.Errors, string.Format("The following validation errors occurred: \r\n{0}", errorString)); replacementCodeValues.Add(Resources.ParameterMessageKeys.ProgramName, programName); replacementCodeValues.Add(Resources.ParameterMessageKeys.GroupName, "Group"); replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, itName); DeliverEmailMessage(programID, DateTime.Now, fromEmail, null, itEmail, DocumentType.EQuoteSystemFailureMessageEmail, replacementCodeValues); allValidationErrors.AddRange(validationErrors); validationErrors.Clear(); } } return allValidationErrors; } catch (Exception exception) { TraceLogger.LogException(exception, LoggingCategory); // Use todays date as the effective date. Dictionary<string, string> replacementCodeValues = new Dictionary<string, string>(); replacementCodeValues.Add(Resources.ParameterMessageKeys.ProgramName, programName); replacementCodeValues.Add(Resources.ParameterMessageKeys.GroupName, "Group"); replacementCodeValues.Add(Resources.ParameterMessageKeys.Name, itName); replacementCodeValues.Add(Resources.ParameterMessageKeys.Errors, string.Format("Errors:\r\n:{0}", exception)); DeliverEmailMessage(programID, DateTime.Now, fromEmail, null, itEmail, DocumentType.EQuoteSystemFailureMessageEmail, replacementCodeValues); throw new FaultException(exception.ToString()); } }

    Read the article

  • How to improve this piece of code

    - by user303518
    XmlDocument eQuoteXmlDoc = new XmlDocument(); eQuoteXmlDoc.LoadXml(eQuoteXml); XmlElement rootElement = eQuoteXmlDoc.DocumentElement; XmlNodeList quotesList = rootElement.SelectNodes("Quote"); foreach (XmlNode node in quotesList) { // Each node should be a quote node but to be safe, check if (node.Name == "Quote") { string groupName = node.SelectSingleNode("Group/GroupName").InnerText; string groupCity = node.SelectSingleNode("Group/GroupCity").InnerText; string groupPostalCode = node.SelectSingleNode("Group/GroupZipCode").InnerText; string groupSicCode = node.SelectSingleNode("Group/GroupSIC").InnerText; string generalAgencyLicenseNumber = node.SelectSingleNode("Group/GALicenseNbr").InnerText; string brokerName = node.SelectSingleNode("Group/BrokerName").InnerText; string deliverToEmailAddress = node.SelectSingleNode("Group/ReturnEmailAddress").InnerText; string brokerEmail = node.SelectSingleNode("Group/BrokerEmail").InnerText; string groupEligibleEmployeeCountString = node.SelectSingleNode("Group/GroupNbrEmployees").InnerText; string quoteEffectiveDateString = node.SelectSingleNode("Group/QuoteEffectiveDate").InnerText; string salesRepName = node.SelectSingleNode("Group/SalesRepName").InnerText; string salesRepPhone = node.SelectSingleNode("Group/SalesRepPhone").InnerText; string salesRepEmail = node.SelectSingleNode("Group/SalesRepEmail").InnerText; string brokerLicenseNumber = node.SelectSingleNode("Group/BrokerLicenseNbr").InnerText; } }

    Read the article

  • Select Table Rows by Grouping them Adjacent to each Other using XPath

    - by Adnan Yaseen
    I am not clear how to express my problem correctly in the question so forgive me if I am not able to properly convey my problem. I have following data. <tr class="header">Random Value 1</tr> <tr class="item">1</tr> <tr class="item">2</tr> <tr class="item">3</tr> <tr class="header">Random Value 2</tr> <tr class="item">4</tr> <tr class="item">5</tr> <tr class="item">6</tr> <tr class="header">Random Value 3</tr> <tr class="item">7</tr> <tr class="item">8</tr> <tr class="item">9</tr> What I want to acheive is that I want to select the with class header. I have achieved this by using the following line of code, HtmlNodeCollection headerNodes = doc.DocumentNode.SelectNodes("//tr[@class='header']"); Now I have all the header rows in the collection. Now I loop through all the header nodes and I want to get the table rows which are adjacent to the respective header rows. foreach (HtmlNode node in headerNodes) { HtmlNodeCollection itemNodes = ??? } My question is that what I should write here so that for header row with text "Random Value 1" I get the item rows 1,2 and 3. Similarly for header row with text "Random Value 2" I get the item row 4,5 and 6 and so on.

    Read the article

  • When NOT TO USE 'this' keyword?

    - by LifeH2O
    Sorry for asking it again, there are already 3 questions about this keyword. But all of them tell the purpose of 'this'. My question is when not to use 'this' keyword . OR Is it all right to use this keyword always in situation like the code class RssReader { private XmlTextReader _rssReader; private XmlDocument _rssDoc; private XmlNodeList _xn; protected XmlNodeList Item { get { return _xn; } } public int Count { get { return _count; } } public bool FetchFeed(String url) { this._rssReader = new XmlTextReader(url); this._rssDoc = new XmlDocument(); _rssDoc.Load(_rssReader); _xn = _rssDoc.SelectNodes("/rss/channel/item"); _count = _xn.Count; return true; } } here i have not used 'this' with "_xn" and "_count" also not with "_rssDoc.Load(_rssReader);" is it fine? Should i use "this" with all occurrences of class variables within the class?

    Read the article

  • Counting elements and reading attributes with .net2.0 ?

    - by Prix
    I have an application that is on .net 2.0 and I am having some difficult with it as I am more use to linq. The xml file look like this: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <updates> <files> <file url="files/filename.ext" checksum="06B9EEA618EEFF53D0E9B97C33C4D3DE3492E086" folder="bin" system="0" size="40448" /> <file url="files/filename.ext" checksum="CA8078D1FDCBD589D3769D293014154B8854D6A9" folder="" system="0" size="216" /> <file url="files/filename.ext" checksum="CA8078D1FDCBD589D3769D293014154B8854D6A9" folder="" system="0" size="216" /> </files> </updates> The file is downloaded and readed on the fly: XmlDocument readXML = new XmlDocument(); readXML.LoadXml(xmlData); Initially i was thinking it would go with something like this: XmlElement root = doc.DocumentElement; XmlNodeList nodes = root.SelectNodes("//files"); foreach (XmlNode node in nodes) { ... im reading it ... } But before reading them I need to know how many they are to use on my progress bar and I am also clueless on how to grab the attribute of the file element in this case. How could I count how many "file" ELEMENTS I have (count them before entering the foreach ofc) and read their attributes ? I need the count because it will be used to update the progress bar. Overall it is not reading my xml very well.

    Read the article

  • Trying to use RemoveChild() on XmlNodeList messes up my XmlNode collection

    - by user299090
    Hi there, I'm trying to remove a specific node from a XmlNodeList named listaWidths. This specific list has 5 items before I use RemoveChild(). But, after the RemoveChild() statement, the list stays only with 1 item. XmlNodeList listaWidths = xmlDoc.SelectNodes("/MsBuild:Report/MsBuild:Body/MsBuild:ReportItems/MsBuild:Tablix/MsBuild:TablixBody/MsBuild:TablixColumns/*", nsmgr); int indexEpoca = 0; //Remover época XmlNode node = listaWidths[indexEpoca]; XmlNode parent = listaWidths[indexEpoca].ParentNode; parent.RemoveChild(node); This is a RDL Reporting Services XML. The specific XML code is here: <Tablix Name="Tablix3"> <TablixBody> <TablixColumns> <TablixColumn> <Width>1.602in</Width> </TablixColumn> <TablixColumn> <Width>1.61in</Width> </TablixColumn> <TablixColumn> <Width>1.6323in</Width> </TablixColumn> <TablixColumn> <Width>1.6023in</Width> </TablixColumn> <TablixColumn> <Width>1.6033in</Width> </TablixColumn> </TablixColumns> (...) I've tried every combination possible, with no luck whatsoever. What am I doing wrong? Thank you.

    Read the article

  • Should I thread this?

    - by Psytronic
    I've got a "Loading Progress" WPF form which I instantiate when I start loading some results into my Main Window, and every time a result is loaded I want the progress bar to fill up by x amount (Based on the amount of results I'm loading). However what happens is that the Progress bar in the window stays blank the entire time, until the results have finished loading, then it will just display the full progress bar. Does this need threading to work properly? Or is it just to do with the way I'm trying to get it to work? //code snippet LoadingProgress lp = new LoadingProgress(feedCount); lp.Show(); foreach (FeedConfigGroup feed in _Feeds) { feed.insertFeeds(lp); } //part of insertFeeds(LoadingProgress lbBox) foreach (Feeds fd in _FeedSource) { lpBox.setText(fd.getName); XmlDocument feedResults = new XmlDocument(); feedResults.PreserveWhitespace = false; try { feedResults.Load(wc.OpenRead(fd.getURL)); } catch (WebException) { lpBox.addError(fd.getName); } foreach (XmlNode item in feedResults.SelectNodes("/rss/channel/item")) { //code for processing the nodes... } lpBox.progressIncrease(); } If more code is needed let me know.

    Read the article

  • How to compare dictonary key with xml attribute value in xml using LINQ in c #?

    - by Pramodh
    Dear all, i've a dictonary " dictSample " which contains 1 data1 2 data2 3 data3 4 data4 and an xml file"sample.xml" in the form of: <node> <element id="1" value="val1"/> <element id="2" value="val2"/> <element id="3" value="val3"/> <element id="4" value="val4"/> <element id="5" value="val5"/> <element id="6" value="val6"/> <element id="7" value="val7"/> </node> i need to match the dictonary keys with the xml attribute id and to insert the matching id and the value of attribute"value" into another dictonary now i'm using like: XmlDocument XDOC = new XmlDocument(); XDOC.Load("Sample.xml"); XmlNodeList NodeList = XDOC.SelectNodes("//element"); Dictionary<string, string> dictTwo = new Dictionary<string, string>(); foreach (string l_strIndex in dictSample .Keys) { foreach (XmlNode XNode in NodeList) { XmlElement XEle = (XmlElement)XNode; if (dictSample[l_strIndex] == XEle.GetAttribute("id")) dictTwo.Add(dictSample[l_strIndex], XEle.GetAttribute("value").ToString()); } } please help me to do this in a simple way using LINQ

    Read the article

  • Namespace Traversal

    - by RikSaunderson
    I am trying to parse the following sample piece of XML: <?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soapenv:Body> <d2LogicalModel modelBaseVersion="1.0" xmlns="http://datex2.eu/schema/1_0/1_0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://datex2.eu/schema/1_0/1_0 http://datex2.eu/schema/1_0/1_0/DATEXIISchema_1_0_1_0.xsd"> <payloadPublication xsi:type="PredefinedLocationsPublication" lang="en"> <predefinedLocationSet id="GUID-NTCC-VariableMessageSignLocations"> <predefinedLocation id="VMS30082775"> <predefinedLocationName> <value lang="en">VMS M60/9084B</value> </predefinedLocationName> </predefinedLocation> </predefinedLocationSet> </payloadPublication> </d2LogicalModel> </soapenv:Body> </soapenv:Envelope> I specifically need to get at the contents of the top-level predefinedLocation tag. By my calculations, the correct XPath should be /soapenv:Envelope/soapenv:Body/d2LogicalModel/payloadPublication/predefinedLocationSet/predefinedLocation I am using the following C# code to parse the XML: string filename = "content-sample.xml"; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(filename); XmlNamespaceManager nsmanager = new XmlNamespaceManager(xmlDoc.NameTable); nsmanager.AddNamespace("soapenv", "http://schemas.xmlsoap.org/soap/Envelope"); string xpath ="/soapenv:Envelope/soapenv:Body/d2LogicalModel/payloadPublication/predefinedLocationSet/predefinedLocation"; XmlNodeList itemNodes = xmlDoc.SelectNodes(xpath, nsmanager); However, this keeps coming up with no results. Can anyone shed any light on this, because I feel like I'm banging my head on a brick wall.

    Read the article

  • C# XML node with colon

    - by Sticky
    Hi, my code attempts to grab data from the RSS feed of a website. It grabs the nodes fine, but when attempting to grab the data from a node with a colon, it crashes and gives the error "Namespace Manager or XsltContext needed. This query has a prefix, variable, or user-defined function." The code is shown below: WebRequest request = WebRequest.Create("http://buypoe.com/external.php?type=RSS2&lastpost=true"); WebResponse response = request.GetResponse(); StringBuilder sb = new StringBuilder(""); System.IO.StreamReader rssStream = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8")); XmlDocument rssDoc = new XmlDocument(); rssDoc.Load(rssStream); XmlNodeList rssItems = rssDoc.SelectNodes("rss/channel/item"); for (int i = 0; i < 5; i++) { XmlNode rssDetail; rssDetail = rssItems.Item(i).SelectSingleNode("dc:creator"); if (rssDetail != null) { user = rssDetail.InnerText; } else { user = ""; } } I understand that I need to define the namespace, but am unsure how to do this. Help would be appreciated.

    Read the article

  • Find XmlNode where attribute value is contained in string

    - by bflemi3
    I have an xml file... <?xml version="1.0" encoding="UTF-8"?> <items defaultNode="1"> <default contentPlaceholderName="pageContent" template="" genericContentItemName="" /> <item urlSearchPattern="connections-learning" contentPlaceholderName="pageContent" template="Connections Learning Content Page" genericContentItemName="" /> <item urlSearchPattern="online-high-school" contentPlaceholderName="pageContent" template="" genericContentItemName="" /> </items> I am trying to find the first node where the urlSearchPattern attribute is contained in the string urlSearchPattern. Where I'm having trouble is finding the nodes where the attribute is contained in the string value instead of the string value be contained in the attribute. Here's my attempt so far. This will find the firstOrDefault node where the string value is contained in the attribute (I need the opposite)... string urlSearchPattern = Request.QueryString["aspxerrorpath"]; MissingPageSettingsXmlDocument missingPageSettingsXmlDocument = new MissingPageSettingsXmlDocument(); XmlNode missingPageItem = missingPageSettingsXmlDocument.SelectNodes(ITEM_XML_PATH).Cast<XmlNode>().Where(item => item.Attributes["urlSearchPattern"].ToString().ToLower().Contains(urlSearchPattern)).FirstOrDefault();

    Read the article

  • C# XPath Not Finding Anything

    - by ehdv
    I'm trying to use XPath to select the items which have a facet with Location values, but currently my attempts even to just select all items fail: The system happily reports that it found 0 items, then returns (instead the nodes should be processed by a foreach loop). I'd appreciate help either making my original query or just getting XPath to work at all. XML <?xml version="1.0" encoding="UTF-8" ?> <Collection Name="My Collection" SchemaVersion="1.0" xmlns="http://schemas.microsoft.com/collection/metadata/2009" xmlns:p="http://schemas.microsoft.com/livelabs/pivot/collection/2009" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <FacetCategories> <FacetCategory Name="Current Address" Type="Location"/> <FacetCategory Name="Previous Addresses" Type="Location" /> </FacetCategories> <Items> <Item Id="1" Name="John Doe"> <Facets> <Facet Name="Current Address"> <Location Value="101 America Rd, A Dorm Rm 000, Chapel Hill, NC 27514" /> </Facet> <Facet Name="Previous Addresses"> <Location Value="123 Anywhere Ln, Darien, CT 06820" /> <Location Value="000 Foobar Rd, Cary, NC 27519" /> </Facet> </Facets> </Item> </Items> </Collection> C# public void countItems(string fileName) { XmlDocument document = new XmlDocument(); document.Load(fileName); XmlNode root = document.DocumentElement; XmlNodeList xnl = root.SelectNodes("//Item"); Console.WriteLine(String.Format("Found {0} items" , xnl.Count)); } There's more to the method than this, but since this is all that gets run I'm assuming the problem lies here. Calling root.ChildNodes accurately returns FacetCategories and Items, so I am completely at a loss. Thanks for your help!

    Read the article

  • Parsing Web Service Response in Oracle 9i

    - by zechariahs
    I'm having trouble parsing an XML response from a web service. I have a feeling this is due to a namespace issue. But, after 4 hours of research, trial-and-error, and head-banging I haven't been able to resolve it. Please help. My goal is to get a dbms_xmldom.DOMNodeList that contains "ERRORS" nodes. XML Response: <?xml version="1.0" encoding="ISO-8859-1"?> <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <GetMailDataResponse xmlns="https://www.customnamespacehost.com/webservicename"> <GetMailDataResult> <Errors xmlns=""> <ErrorDetail>Access Credentials Invalid</ErrorDetail> </Errors> </GetMailDataResult> </GetMailDataResponse> </soap:Body> Code: Unfortunately this code compiles but doesn't work. Error: "ORA-31013: Invalid XPATH expression." I believe this is due to the multiple namespaces defined in L_NS variable. I tried setting L_XPATH: "/soap:Envelope/soap:Body" and L_NS: "xmlns:soap="http://schemas.xmlsoap.org/soap/envelope"" but L_NL_RESULTS ends up being null. -- Variable Declarations -- P_XML XMLTYPE; L_CODE_NAME VARCHAR2(1000) := 'PKG_CIS_WS.FNC_STAGE_DATA'; L_XML_DOC dbms_xmldom.DOMDocument; L_NL_RESULTS dbms_xmldom.DOMNodeList; L_NL_DONOR_SCREENING_RESULTS dbms_xmldom.DOMNodeList; L_N_RESULT dbms_xmldom.DOMNode; L_XPATH VARCHAR2(4000); L_NS VARCHAR2(4000); L_TEMP VARCHAR2(4000); -- Code Snippet -- L_XML_DOC := dbms_xmldom.newDOMDocument(P_XML); L_XPATH := '/soap:Envelope/soap:Body/a:GetMailDataResponse/GetMailDataResult'; L_NS := 'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope"' || 'xmlns:a="https://www.customnamespacehost.com/webservicename"'; L_NL_RESULTS := dbms_xslprocessor.selectNodes( dbms_xmldom.makeNode(L_XML_DOC) , L_XPATH , L_NS); if not DBMS_XMLDOM.ISNULL(L_NL_RESULTS) then FOR RESULTS_REC IN 0 .. dbms_xmldom.getLength(L_NL_RESULTS) - 1 LOOP L_N_RESULT := dbms_xmldom.item(L_NL_RESULTS, RESULTS_REC); L_TEMP := dbms_xmldom.GETNODENAME(L_N_RESULT); prc_bjm(L_CODE_NAME, 'L_TEMP = ' || L_TEMP, SQLCODE); dbms_xslprocessor.valueOf(L_N_RESULT, 'Errors/ErrorDetail/text()', L_TEMP); prc_bjm(L_CODE_NAME, 'L_TEMP = ' || L_TEMP, SQLCODE); END LOOP; else prc_bjm(L_CODE_NAME, 'No nodes for: ' || L_XPATH || '(' || L_NS || ')', SQLCODE); end if; -- if not DBMS_XMLDOM.ISNULL(L_NL_RESULTS)

    Read the article

  • How to access and work with XML from API in C#

    - by Jarek
    My goal is to pull XML data from the API and load it to a sql server database. The frist step I'm attempting here is to access the data and display it. Once I get this to work I'll loop through each row and insert the values into a sql server database. When I try to run the code below nothing happens and when I paste the url directly into the browser I get this error "2010-03-08 04:24:17 Wallet exhausted: retry after 2010-03-08 05:23:58. 2010-03-08 05:23:58" To me it seems that every iteration of the foreach loop makes a call to the site and I get blocked for an hour. Am I retrieving data from the API in an incorrect manner? Is there some way to load the data into memory or an array then loop through that? Here's the bit of code I hacked together. using System; using System.Data.SqlClient; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml; using System.Data; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { string userID = "123"; string apiKey = "abc456"; string characterID = "789"; string url = "http://api.eve-online.com/char/WalletTransactions.xml.aspx?userID=" + userID + "&apiKey=" + apiKey + "&characterID=" + characterID; XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(url); XmlNamespaceManager xnm1 = new XmlNamespaceManager(xmldoc.NameTable); XmlNodeList nList1 = xmldoc.SelectNodes("result/rowset/row", xnm1); foreach (XmlNode xNode in nList1) { Response.Write(xNode.InnerXml + "<br />"); } } catch (SqlException em) { Response.Write(em.Message); } } } Here's a sample of the xml <eveapi version="2"> <currentTime>2010-03-06 17:38:35</currentTime> <result> <rowset name="transactions" key="transactionID" columns="transactionDateTime,transactionID,quantity,typeName,typeID,price,clientID,clientName,stationID,stationName,transactionType,transactionFor"> <row transactionDateTime="2010-03-06 17:16:00" transactionID="1343566007" quantity="1" typeName="Co-Processor II" typeID="3888" price="1122999.00" clientID="1404318579" clientName="unseenstrike" stationID="60011572" stationName="Osmeden IX - Moon 6 - University of Caille School" transactionType="sell" transactionFor="personal" /> <row transactionDateTime="2010-03-06 17:15:00" transactionID="1343565894" quantity="1" typeName="Co-Processor II" typeID="3888" price="1150000.00" clientID="1404318579" clientName="unseenstrike" stationID="60011572" stationName="Osmeden IX - Moon 6 - University of Caille School" transactionType="sell" transactionFor="personal" /> </rowset> </result> <cachedUntil>2010-03-06 17:53:35</cachedUntil> </eveapi>

    Read the article

  • What Amazon S3 .NET Library is most useful and efficient?

    - by Geo
    There are two main open source .net Amazon S3 libraries. Three Sharp LitS3 I am currently using LitS3 in our MVC demo project, but there is some criticism about it. Has anyone here used both libraries so they can give an objective point of view. Below some sample calls using LitS3: On demo controller: private S3Service s3 = new S3Service() { AccessKeyID = "Thekey", SecretAccessKey = "testing" }; public ActionResult Index() { ViewData["Message"] = "Welcome to ASP.NET MVC!"; return View("Index",s3.GetAllBuckets()); } On demo view: <% foreach (var item in Model) { %> <p> <%= Html.Encode(item.Name) %> </p> <% } %> EDIT 1: Since I have to keep moving and there is no clear indication of what library is more effective and kept more up to date, I have implemented a repository pattern with an interface that will allow me to change library if I need to in the future. Below is a section of the S3Repository that I have created and will let me change libraries in case I need to: using LitS3; namespace S3Helper.Models { public class S3Repository : IS3Repository { private S3Service _repository; #region IS3Repository Members public IQueryable<Bucket> FindAllBuckets() { return _repository.GetAllBuckets().AsQueryable(); } public IQueryable<ListEntry> FindAllObjects(string BucketName) { return _repository.ListAllObjects(BucketName).AsQueryable(); } #endregion If you have any information about this question please let me know in a comment, and I will get back and edit the question. EDIT 2: Since this question is not getting attention, I integrated both libraries in my web app to see the differences in design, I know this is probably a waist of time, but I really want a good long run solution. Below you will see two samples of the same action with the two libraries, maybe this will motivate some of you to let me know your thoughts. WITH THREE SHARP LIBRARY: public IQueryable<T> FindAllBuckets<T>() { List<string> list = new List<string>(); using (BucketListRequest request = new BucketListRequest(null)) using (BucketListResponse response = service.BucketList(request)) { XmlDocument bucketXml = response.StreamResponseToXmlDocument(); XmlNodeList buckets = bucketXml.SelectNodes("//*[local-name()='Name']"); foreach (XmlNode bucket in buckets) { list.Add(bucket.InnerXml); } } return list.Cast<T>().AsQueryable(); } WITH LITS3 LIBRARY: public IQueryable<T> FindAllBuckets<T>() { return _repository.GetAllBuckets() .Cast<T>() .AsQueryable(); }

    Read the article

  • XML structure question

    - by Andrew Jahn
    I have a basic XML object that I'm working with. I can't figure out how to access the parts of it. EX:<br> <pre><code> < FacetsData> < Collection name="CDDLALL" type="Group"> < SubCollection name="CDDLALL" type="Row"> < Column name="DPDP_ID">D0230< /Column> < Column name="Count">9< /Column> < /SubCollection> < SubCollection name="CDDLALL" type="Row"> < Column name="DPDP_ID">D1110< /Column> < Column name="Count">9< /Column> < /SubCollection> < /Collection> < /FacetsData> (PS: I can't get this damn xml to format so people can read it) What I need to do is check each DPDP_ID and if its value is D0230 then I leave the Count alone, all else I change the Count to 1. What I have so far: node = doc.DocumentElement; nodeList = node.SelectNodes("/FacetsData/Collection/SubCollection"); for (int x = 0; x < nodeList.Count; x++) { if (nodeList[x].HasChildNodes) { for (int i = 0; i < nodeList[x].ChildNodes.Count; i++) { //This part I can't figure out how to get the name="" part of the xml //MessageBox.Show(oNodeList[x].ChildNodes[i].InnerText); get the "D0230","1" //part but not the "DPDP_ID","Count" part. } } }

    Read the article

  • XML - how to use namespace prefixes

    - by Asbie
    I have this XML at http://localhost/file.xml: <?xml version="1.0" encoding="utf-8"?> <val:Root xmlns:val="http://www.hw-group.com/XMLSchema/ste/values.xsd"> <Agent> <Version>2.0.3</Version> <XmlVer>1.01</XmlVer> <DeviceName>HWg-STE</DeviceName> <Model>33</Model> <vendor_id>0</vendor_id> <MAC>00:0A:DA:01:DA:DA</MAC> <IP>192.168.1.1</IP> <MASK>255.255.255.0</MASK> <sys_name>HWg-STE</sys_name> <sys_location/> <sys_contact> HWg-STE:For more information try http://www.hw-group.com </sys_contact> </Agent> <SenSet> <Entry> <ID>215</ID> <Name>Home</Name> <Units>C</Units> <Value>27.7</Value> <Min>10.0</Min> <Max>40.0</Max> <Hyst>0.0</Hyst> <EmailSMS>1</EmailSMS> <State>1</State> </Entry> </SenSet> </val:Root> I am trying to read this from my c# code: static void Main(string[] args) { var xmlDoc = new XmlDocument(); xmlDoc.Load("http://localhost/file.xml"); XmlElement root = xmlDoc.DocumentElement; // Create an XmlNamespaceManager to resolve the default namespace. XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable); nsmgr.AddNamespace("val", "http://www.hw-group.com/XMLSchema/ste/values.xsd"); XmlNodeList nodes = root.SelectNodes("/val:SenSet/val:Entry"); foreach (XmlNode node in nodes) { string name = node["Name"].InnerText; string value = node["Value"].InnerText; Console.Write("name\t{0}\value\t{1}", name, value); } Console.ReadKey(); } } Problem is that the node is empty. I understand this is a common newbie problem when reading XML, still not able to solve what I am doing wrong, probably something with the Namespace "val" ?

    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

  • VB.NET looping through XML to store in singleton

    - by rockinthesixstring
    I'm having a problem with looping through an XML file and storing the value in a singleton My XML looks like this <values> <value></value> <value>$1</value> <value>$5,000</value> <value>$10,000</value> <value>$15,000</value> <value>$25,000</value> <value>$50,000</value> <value>$75,000</value> <value>$100,000</value> <value>$250,000</value> <value>$500,000</value> <value>$750,000</value> <value>$1,000,000</value> <value>$1,250,000</value> <value>$1,500,000</value> <value>$1,750,000</value> <value>$2,000,000</value> <value>$2,500,000</value> <value>$3,000,000</value> <value>$4,000,000</value> <value>$5,000,000</value> <value>$7,500,000</value> <value>$10,000,000</value> <value>$15,000,000</value> <value>$25,000,000</value> <value>$50,000,000</value> <value>$100,000,000</value> <value>$100,000,000+</value> </values> And my function looks like this Public Class LoadValues Private Shared SearchValuesInstance As List(Of SearchValues) = Nothing Public Shared ReadOnly Property LoadSearchValues As List(Of SearchValues) Get Dim sv As New List(Of SearchValues) If SearchValuesInstance Is Nothing Then Dim objDoc As XmlDocument = New XmlDataDocument Dim objRdr As XmlTextReader = New XmlTextReader(HttpContext.Current.Server.MapPath("~/App_Data/Search-Values.xml")) objRdr.Read() objDoc.Load(objRdr) Dim root As XmlElement = objDoc.DocumentElement Dim itemNodes As XmlNodeList = root.SelectNodes("/values") For Each n As XmlNode In itemNodes sv.Add(New SearchValues(n("@value").InnerText, n("@value").InnerText)) Next SearchValuesInstance = sv Else : sv = SearchValuesInstance End If Return sv End Get End Property End Class My problem is that I'm getting an object not set to an instance of an object on the sv.Add(New SearchValues(n("@value").InnerText, n("@value").InnerText)) line.

    Read the article

  • SSIS: Deploying OLAP cubes using C# script tasks and AMO

    - by DrJohn
    As part of the continuing series on Building dynamic OLAP data marts on-the-fly, this blog entry will focus on how to automate the deployment of OLAP cubes using SQL Server Integration Services (SSIS) and Analysis Services Management Objects (AMO). OLAP cube deployment is usually done using the Analysis Services Deployment Wizard. However, this option was dismissed for a variety of reasons. Firstly, invoking external processes from SSIS is fraught with problems as (a) it is not always possible to ensure SSIS waits for the external program to terminate; (b) we cannot log the outcome properly and (c) it is not always possible to control the server's configuration to ensure the executable works correctly. Another reason for rejecting the Deployment Wizard is that it requires the 'answers' to be written into four XML files. These XML files record the three things we need to change: the name of the server, the name of the OLAP database and the connection string to the data mart. Although it would be reasonably straight forward to change the content of the XML files programmatically, this adds another set of complication and level of obscurity to the overall process. When I first investigated the possibility of using C# to deploy a cube, I was surprised to find that there are no other blog entries about the topic. I can only assume everyone else is happy with the Deployment Wizard! SSIS "forgets" assembly references If you build your script task from scratch, you will have to remember how to overcome one of the major annoyances of working with SSIS script tasks: the forgetful nature of SSIS when it comes to assembly references. Basically, you can go through the process of adding an assembly reference using the Add Reference dialog, but when you close the script window, SSIS "forgets" the assembly reference so the script will not compile. After repeating the operation several times, you will find that SSIS only remembers the assembly reference when you specifically press the Save All icon in the script window. This problem is not unique to the AMO assembly and has certainly been a "feature" since SQL Server 2005, so I am not amazed it is still present in SQL Server 2008 R2! Sample Package So let's take a look at the sample SSIS package I have provided which can be downloaded from here: DeployOlapCubeExample.zip  Below is a screenshot after a successful run. Connection Managers The package has three connection managers: AsDatabaseDefinitionFile is a file connection manager pointing to the .asdatabase file you wish to deploy. Note that this can be found in the bin directory of you OLAP database project once you have clicked the "Build" button in Visual Studio TargetOlapServerCS is an Analysis Services connection manager which identifies both the deployment server and the target database name. SourceDataMart is an OLEDB connection manager pointing to the data mart which is to act as the source of data for your cube. This will be used to replace the connection string found in your .asdatabase file Once you have configured the connection managers, the sample should run and deploy your OLAP database in a few seconds. Of course, in a production environment, these connection managers would be associated with package configurations or set at runtime. When you run the sample, you should see that the script logs its activity to the output screen (see screenshot above). If you configure logging for the package, then these messages will also appear in your SSIS logging. Sample Code Walkthrough Next let's walk through the code. The first step is to parse the connection string provided by the TargetOlapServerCS connection manager and obtain the name of both the target OLAP server and also the name of the OLAP database. Note that the target database does not have to exist to be referenced in an AS connection manager, so I am using this as a convenient way to define both properties. We now connect to the server and check for the existence of the OLAP database. If it exists, we drop the database so we can re-deploy. svr.Connect(olapServerName); if (svr.Connected) { // Drop the OLAP database if it already exists Database db = svr.Databases.FindByName(olapDatabaseName); if (db != null) { db.Drop(); } // rest of script } Next we start building the XMLA command that will actually perform the deployment. Basically this is a small chuck of XML which we need to wrap around the large .asdatabase file generated by the Visual Studio build process. // Start generating the main part of the XMLA command XmlDocument xmlaCommand = new XmlDocument(); xmlaCommand.LoadXml(string.Format("<Batch Transaction='false' xmlns='http://schemas.microsoft.com/analysisservices/2003/engine'><Alter AllowCreate='true' ObjectExpansion='ExpandFull'><Object><DatabaseID>{0}</DatabaseID></Object><ObjectDefinition/></Alter></Batch>", olapDatabaseName));  Next we need to merge two XML files which we can do by simply using setting the InnerXml property of the ObjectDefinition node as follows: // load OLAP Database definition from .asdatabase file identified by connection manager XmlDocument olapCubeDef = new XmlDocument(); olapCubeDef.Load(Dts.Connections["AsDatabaseDefinitionFile"].ConnectionString); // merge the two XML files by obtain a reference to the ObjectDefinition node oaRootNode.InnerXml = olapCubeDef.InnerXml;   One hurdle I had to overcome was removing detritus from the .asdabase file left by the Visual Studio build. Through an iterative process, I found I needed to remove several nodes as they caused the deployment to fail. The XMLA error message read "Cannot set read-only node: CreatedTimestamp" or similar. In comparing the XMLA generated with by the Deployment Wizard with that generated by my code, these read-only nodes were missing, so clearly I just needed to strip them out. This was easily achieved using XPath to find the relevant XML nodes, of which I show one example below: foreach (XmlNode node in rootNode.SelectNodes("//ns1:CreatedTimestamp", nsManager)) { node.ParentNode.RemoveChild(node); } Now we need to change the database name in both the ID and Name nodes using code such as: XmlNode databaseID = xmlaCommand.SelectSingleNode("//ns1:Database/ns1:ID", nsManager); if (databaseID != null) databaseID.InnerText = olapDatabaseName; Finally we need to change the connection string to point at the relevant data mart. Again this is easily achieved using XPath to search for the relevant nodes and then replace the content of the node with the new name or connection string. XmlNode connectionStringNode = xmlaCommand.SelectSingleNode("//ns1:DataSources/ns1:DataSource/ns1:ConnectionString", nsManager); if (connectionStringNode != null) { connectionStringNode.InnerText = Dts.Connections["SourceDataMart"].ConnectionString; } Finally we need to perform the deployment using the Execute XMLA command and check the returned XmlaResultCollection for errors before setting the Dts.TaskResult. XmlaResultCollection oResults = svr.Execute(xmlaCommand.InnerXml);  // check for errors during deployment foreach (Microsoft.AnalysisServices.XmlaResult oResult in oResults) { foreach (Microsoft.AnalysisServices.XmlaMessage oMessage in oResult.Messages) { if ((oMessage.GetType().Name == "XmlaError")) { FireError(oMessage.Description); HadError = true; } } } If you are not familiar with XML programming, all this may all seem a bit daunting, but perceiver as the sample code is pretty short. If you would like the script to process the OLAP database, simply uncomment the lines in the vicinity of Process method. Of course, you can extend the script to perform your own custom processing and to even synchronize the database to a front-end server. Personally, I like to keep the deployment and processing separate as the code can become overly complex for support staff.If you want to know more, come see my session at the forthcoming SQLBits conference.

    Read the article

< Previous Page | 1 2 3 4  | Next Page >