How to specify the namespace when referencing a table in a dataset - asp.net

I'm loading data into a DataSet from an XML file using the ReadXml method. This results in two tables with the same name. One of the tables has a namespace and the other doesn't. I'm trying to reference the table with the namespace. Can anyone tell me how to do this?
Dim reader As XmlTextReader = New XmlTextReader(strURL)
Dim city as string = ""
Dim ds As DataSet = New DataSet()
ds.Namespace = "HomeAddress"
ds.ReadXml(reader)
city = ds.Tables("Address").Rows(0).Item(2).ToString()

From MSDN: DataSet.Namespace
The Namespace property is used when
reading and writing an XML document
into the DataSet using the ReadXml,
WriteXml, ReadXmlSchema, or
WriteXmlSchema methods.
The namespace of an XML document is
used to scope XML attributes and
elements when read into a DataSet. For
example, if a DataSet contains a
schema that was read from a document
with the namespace "myCompany," and an
attempt is made to read data only from
a document with a different namespace,
any data that does not correspond to
the existing schema is ignored.
The following example sets the Prefix
before calling the ReadXml method.
private void ReadData(DataSet thisDataSet)
{
thisDataSet.Namespace = "CorporationA";
thisDataSet.Prefix = "DivisionA";
// Read schema and data.
string fileName = "CorporationA_Schema.xml";
thisDataSet.ReadXmlSchema(fileName);
fileName = "DivisionA_Report.xml";
thisDataSet.ReadXml(fileName);
}
I cant see from the example you gave, but unless you set your prefix before you load, you wont be able to read data that doesn't correspond to the existing schema.

I found the answer. You can pass in the namespace as the second parameter. I guess I didn't notice this particular overload in Intellisense.
ds.Tables("Address", "HomeAddress").Rows(1).Item(2).ToString()

Related

Extracting userid from Inbound headers

I have to read element from Inbound Header...
I am assigning inbound header using WCF.InboundHeaders to a string....
now my problem is my inbounde header is looking like this
InboundHeaders
<headers><s:userid xmlns:s="http://www.w3.org/2003/05/soap-envelope">testuser</s:userid>
<s:applicationid xmlns:s="http://www.w3.org/2003/05/soap-envelope">assistworkerweb</s:applicationid>
<a:Action s:mustUnderstand="1" xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">http://Request</a:Action><a:To s:mustUnderstand="1" xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
Now i need to extract user id from it ..how to extract user id from it..
You haven't mentioned where or how your string is stored (that is populated with your WCF.InboundHeaders), however I would use a simple fragment of XPath to extract the UserId. If you were extracting this using a C# helper, you could do something along the lines of (note, this is untested, however its pretty much there):
XmlDocument doc = new XmlDocument();
doc.Load([WCF.InboundHeaders Xml Fragment]);
// Create an XmlNamespaceManager to add 'soap-envelope' namespace
XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
nsmgr.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope");
// Select the UserId
XmlNode userId = doc.SelectSingleNode("/headers/s:userid", nsmgr);
Console.WriteLine(userId.InnerXml);
You may also want to serialize the Xml fragment into a .Net object and retrieve the UserId in that manner.

How can i extract XML and use it as a datasource?

I am using asp.net VB and I have an XML file containing a set of data, I would like to use it in something like a datalist and where usually you would use a database i would like to use the XML file to produce the information.
Does anyone know how to do this, i have read about transform files but surely i will format the information in the control?
The file has multiple records so in some cases i would need to perform queries on the information through the datasource.
I would maybe look into XML serialization and de-serialization. Using de-serialization you could read your XML into a List(T) object containing a list of your own class objects and use that as a data source for your application.
Heres a link that you may find useful:
http://msdn.microsoft.com/en-us/library/ms731073.aspx
Hope this helps.
Dim ds As New DataSet()
ds.ReadXml(MapPath("data.xml"))
First you have to parse the XML and store that into custom C# object or you can directly pass the XML to your stored procedure and do the codding there for saving it into DB.
Passing the xml to stored procedure and manipulating it there is bit difficult so what I suggest is to parse it in C# and then get a custom object. Once you get it you can do whatever you want to.
Below is the sample code that parse a XML file and generate a custom C# object from it.
public CatSubCatList GenerateCategoryListFromProductFeedXML()
{
string path = System.Web.HttpContext.Current.Server.MapPath(_xmlFilePath);
XDocument xDoc = XDocument.Load(path);
XElement xElement = XElement.Parse(xDoc.ToString());
List<Category> lstCategory = xElement.Elements("Product").Select(d => new Category
{
Code = Convert.ToString(d.Element("CategoryCode").Value),
CategoryPath = d.Element("CategoryPath").Value,
Name = GetCateOrSubCategory(d.Element("CategoryPath").Value, 0), // Category
SubCategoryName = GetCateOrSubCategory(d.Element("CategoryPath").Value, 1) // Sub Category
}).GroupBy(x => new { x.Code, x.SubCategoryName }).Select(x => x.First()).ToList();
CatSubCatList catSubCatList = GetFinalCategoryListFromXML(lstCategory);
return catSubCatList;
}

XML validation error when updating Keyword metadata

Following on from my earlier question about creating Address Books (many thanks Peter!), I have a small throw-away console application doing just that and working great - but in addition I'm trying to update the metadata of a Keyword with the Item Id of the created Address Book.
Slightly shortened snippet ...
StaticAddressBook ab = new StaticAddressBook();
ab.Title = title;
ab.Key = key;
ab.Save();
// id is a correct Keyword TCM ID
Keyword k = tdse.GetObject(id, EnumOpenMode.OpenModeEdit);
if (k != null)
{
k.MetadataFields["addressbookid"].value[0] = ab.Id.ItemId;
k.Save(true);
}
I keep getting the following error on Save():
XML validation error. Reason: The element 'Metadata' in namespace
'uuid:2065d525-a365-4b45-b68e-bf45f0fba188' has invalid child element
'addressbookid' in namespace
'uuid:2065d525-a365-4b45-b68e-bf45f0fba188'. List of possible elements
expected: 'contact_us_email' in namespace
'uuid:2065d525-a365-4b45-b68e-bf45f0fba188'
But I know the Keyword has the correct Metadata assigned, (thats why I don't bother checking!). Shortened Tridion XML from a current keyword in question:
<tcm:Keyword>
<tcm:Data>
<tcm:MetadataSchemaxlink:type="simple"xlink:title="IP.Location.Metadata" xlink:href="tcm:49-2142-8" />
<tcm:Metadata>
<Metadata xmlns="uuid:2065d525-a365-4b45-b68e-bf45f0fba188">
<email>...</email>
<addressbookid>3</addressbookid>
<contact_us_email>...</contact_us_email>
<request_a_sample_email>...</request_a_sample_email>
<webinar_feedback_email>....</webinar_feedback_email>
</Metadata>
</tcm:Metadata>
<tcm:IsRoot>true</tcm:IsRoot>
</tcm:Data>
</tcm:Keyword>
Have I missed something can Keyword metadata not be updated in this way?
I guess I could look at the Core Service to update Keywords, but it seemed to to make sense to do everything within this application.
UPDATE
Order was key here, strangely!
The following code works:
ItemFields fields = k.MetadataFields;
System.Diagnostics.Debug.WriteLine(fields.Count);
string email = fields[1].value[1];
string contact = fields[3].value[1];
string request = fields[4].value[1];
string webinar = fields[5].value[1];
fields[1].value[1] = email;
fields[2].value[1] = ab.Id.ItemId;
fields[3].value[1] = contact;
fields[4].value[1] = request;
fields[5].value[1] = webinar;
k.Save(true);
Got caught out by the non-0-based index when getting/setting values and had to reassign existing fields back, in order.
Cheers
It seems that the order of the fields has changed in the Schema since that Component was created. At least the Schema expects contact_us_email in the position where you current have addressbookid.
There may be other changes, so I'd verify the order of fields in the Schema and make sure the Component(s) match, before you run your tool.

Read XML from String

I have data in XML format. I stored it in varchar datatype column. I have retrieved it by using Linq to sql in visual studio 2010. I got xml format data in string variable. now i need read it as a Xml. I need to take value in particular node.
for example,
<Sale>
<LTV>150</LTV>
<CLTV>350</CLTV>
<DLTV>600</DLTV>
</sale>
I NEED TO TAKE CLTV value.
This code should work for you:
using System.Xml;
...
string xmlStr = "<sale><LTV>150</LTV><CLTV>350</CLTV><DLTV>600</DLTV></sale>";
XmlDocument x = new XmlDocument();
x.LoadXml(xmlStr);
MessageBox.Show(x.GetElementsByTagName("CLTV")[0].InnerText);
var value = XDocument.parse("YOUR_XML_STRING").Root.Element("ELEMENT_NAME").Value;
try
var xml = XElement.Parse("your xml");
//Gives you the value of the CLTV node
xml.Descendants("CLTV").FirstOrDefault().Value;
To change the value
xml.Descendants("CLTV").FirstOrDefault().Value = "1";
//Save to disk
xml.Save({stream or file location});
//Get a string back
xml.ToString();
Descendants will give you a list of XElements that you can enumerate or by doing FirstOrDefault you will get the first one it finds or an empty Element.

dynamically generate ComboBox name

I have a script that parses some complex XML. When the XML element is of a certain type, it generates a comboBox using the XML element's children to populate the box. I then want to check all of the values of the all the generated ComboBoxes against their correct answers (which is also info stored in the XML file). When creating the ComboBoxes, I added an "id" property. However, it seems that I cannot them use:
dynamicQuestion.id.selectedItem.labelField
to check the answers. However, I am able to get the labelField if I know the variable name used to create the ComboBox.
dynamicQuestion.selectedItem.labelField
This indicates (to me) that I need to dynamically generate the variable name as I'm creating new instances of the ComboBox. But how do I dynamically generate a variable name? If I use
var thisBox:String = "box"+boxCount;
var newBox:ComboBox = thisBox as ComboBox;
I get an implicit coercion error. I also tried changing the creation statement to a function that accepted an argument, "thisBox," but this didn't work either. Conceptually, this seems quite simple, but I'm having a hard time putting it to practice. It seems that the comboBox's id is what is generated by created the box using script (e.g., var thisBox). How do I dynamically generate this name?
Use an array as Stefan suggested. If you must use string identifiers, you can create an object and use it as an associative array.
var combos:Object = {};
var boxCount:Number = 1;
var thisBox:String = "box"+boxCount;
//you can store comboboxes in the object using the following syntax
combos[thisBox] = new ComboBox();
//or
combos.box2 = new ComboBox();
//or
combos["box3"] = new ComboBox();
trace(combos.box1.selectedItem.labelField);
trace(combos.box2.selectedItem.labelField);
trace(combos.box3.selectedItem.labelField);
Why don't you store all your dynamically created combo boxes in an array? When you want to evaluate them you iterate over the array and access selectedItem.labelField.

Resources