I'm trying to create an XML document to return through a web service, and am quite stumped. I'm still pretty new at XML itself, so I'm trying to learn as I go. The error I'm getting is
object reference not set to an
instance of an object.
The code works by calling a constructor, taking in the request document and parsing it to the response. I have the format of both the request and the response, and just need to be able to send it back.
Code:
XmlTextReader xml_read = new XmlTextReader(HttpContext.Current.Request.MapPath("/ap/aitcXMLConfirmationRequest.xml"));
XmlDocument xml_doc = new XmlDocument();
xml_doc.Load(xml_read);
xml_read.Close();
//Do some stuff.
int int_dtl = 1;
//Builds the list of Confirmation items.
XmlNodeList nodelst_cnfrm = p_transdoc.SelectNodes("//Request/OrderRequest/ItemOut");
foreach (XmlNode node in nodelst_cnfrm)
{
XmlNode node_cnfrm_itm = this.CreateElement("ConfirmationItem");
//Do some other stuff here
}
xml_doc.ImportNode(node_cnfrm_itm,true);
root.AppendChild(xml_doc); //Error generated here.
this.AppendChild(root);
But it's giving me the aforementioned error. Can anyone help out? I'm not understanding how there is no instance of an object, if I have been manipulating it before the AppendChild request.
Any ideas?
With respect to NullReferenceExceptions in general, you should just put a break point (typically F9) on that line and start the Debugger. Once that line is hit, inspect the variables and confirm that one is in fact null.
In your case, it should be pretty obvious that root is null (given the code successfully uses xml_doc). At that point, find the places where root is supposed to be set and investigate why that isn't happening.
Related
I found a question posted here that had something interesting i wanted to implement in my application.
Previous question(this is using HtmlAgilityPack):
Pulling data from a webpage, parsing it for specific pieces, and displaying it
I've done pretty much what they are doing their and i'm getting an error stating object reference not set to an instance of an object. i'm fairly new to programming in general and while I've seen this error message hundreds of times i never seem to understand the cause or how to fix it. Can someone assist with this?
Code:
public void Page_Load()
{
string Url = "myPrivateURL";
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load(Url);
//Both below strings are getting a null reference exception.
string DeskOncallPhone = doc.DocumentNode.SelectNodes("//*[#id=\"content\"]/div/section/section/div[4]/div[1]/div[1]/div[2]/div/div/div[1]/span")[0].InnerText;
string DeskOncallName = doc.DocumentNode.SelectNodes("//*[#id=\"content\"]/div/section/section/div[4]/div[1]/div[1]/div[2]/div/a[1]")[0].InnerText;
}
Error:
The host property of a familyInstance returns a RevitLinkInstance when the host is placed within a linked document. I there a way to get the real Element (or its ID) instead of the RevitLinkInstance?
I was hoping that the stableREpresentation could give me more information, but unfortunatly, it doesn't.
Reference hostFaceReference = instance.HostFace;
string stableRepresentation = hostFaceReference.ConvertToStableRepresentation(instance.Document);
this would give "ac669fa6-4686-4f47-b1d0-5d7de6a40550-000a6a4a:0:RVTLINK:234297:0:218" where 234297 is the ID of the referenced element, in this case, still the RevitLinkInstance.
Have you tried this?
ElementId hostFaceReferenceId = instance.HostFace.LinkedElementId;
You could then try getting the Element via the linkedDocument.
Document LinkedDoc = RevitLinkInstance01.GetLinkDocument();
Element linkedEl = LinkedDoc.GetElement(hostFaceReferenceId);
Depending on the host you may have to go about it a few ways. For example, with a wall you could try the following (this is using LINQ by the way):
// filter the Host's document's items
FilteredElementCollector linkdocfec = new FilteredElementCollector(elem_inst.Host.Document);
// establish the host's type
linkdocfec.OfClass(elem_inst.Host.GetType());
// find the host in the list by comparing the UNIQUEIDS
Element hostwallinlinkedfile = (from posshost in linkdocfec
where posshost.UniqueId.ToString().Equals(elem_inst.Host.UniqueId.ToString())
select posshost).First();
// check the different faces of the host (wall in this case) and select the exterior one
Reference linkrefface = HostObjectUtils.GetSideFaces((hostwallinlinkedfile as HostObject), ShellLayerType.Exterior).First<Reference>();
// create a reference to the linked face in the the CURRENT document (not the linked document)
Reference linkref = linkrefface.CreateLinkReference(rvtlink_other);
Ultimately, according to the docs anyway, you're supposed to utilize the CreateReferenceInLink method to get your item.
So I'm using Amazon MWS and I was finally able to parse through the ListOrder response, but I have a problem. If there are over 100 orders, it will put a "NextToken" element in the 3rd level. I keep trying to find it, but whenever I run my code, it shows up null even though I know it's there (by looking at the actual XML generated in the response). To clear things up, here's an XML sample (irrelevant Elements redacted) and the code I'm using to read it.
<ListOrdersResponse xmlns="https://mws.amazonservices.com/Orders/2011-01-01">
<ListOrdersResult>
<NextToken>let's just pretend this is a nice token :)</NextToken>
</ListOrdersResult>
</ListOrdersResponse>
And the code:
XElement nextToken = null;
XDocument responseXMLDoc = XDocument.Parse(responseXml);
XNamespace ns = "http://mws.amazonservices.com/schema/Products/2011-10-01";
nextToken = responseXMLDoc.Root.Element(ns + "NextToken");
if (nextToken != null)
{
hasNext = true;
}
else
{
Console.WriteLine("No more pages!");
System.Threading.Thread.Sleep(20000);
}
Every time I run this, even though is always there, I receive a null. I actually have to define the XElement in a parent scope so I can use it later.
Some things I've tried:
Removed "root" from responseXMLDoc.Root.Element
Didn't use the namespace in (ns + "NextToken)
There will only ever be one NextToken element in a request, and I just need the token from it so I can call the request again with the token - and keep repeating until there is no "NextToken".
Update: I'm certain I am getting the syntax wrong, I just can't seem to put my finger on the problem. With the same sample, trying
XElement listOrdersResult = responseXMLDoc.Root.Element(ns + "ListOrdersResult");
will also return a null value! I've read a bunch of questions on the Linq/XML topics here, and that's where I learned most of the syntax. Still not getting any results.
Update 2: Thanks to Brad Cunningham for the answer!
To fix the namespace issue I changed the following [the root node always has the xmlns attribute (and only that attribute):
String docNameSpace = responseXMLDoc.Root.FirstAttribute.Value.ToString();
XNamespace ns = docNameSpace;
And changing the following gives me the element I'm looking for:
nextToken = responseXMLDoc.Root.Descendants(ns + "NextToken").FirstOrDefault();
Your namespace is incorrect in your example (maybe a copy and paste error just for the example)
NextToken has a namespace of
https://mws.amazonservices.com/Orders/2011-01-01
However you are looking for a namespace of
http://mws.amazonservices.com/schema/Products/2011-10-01
Also using Element will only return the element if it is a immediate child of the parent element.
You should use Descendants if you don't know what level the node will be at
This works for me
XDocument responseXMLDoc = XDocument.Parse(responseXml);
XNamespace ns = "https://mws.amazonservices.com/Orders/2011-01-01";
XElement nextToken = responseXMLDoc.Root.Descendants(ns + "NextToken").FirstOrDefault();
I started with the solution here http://social.technet.microsoft.com/wiki/contents/articles/20547.biztalk-server-dynamic-schema-resolver-real-scenario.aspx
which matches my scenario perfectly except for the send port, but that isn't necessary. I need the receive port to choose the file and apply a schema to disassemble. From their the orchestration does the mapping, some of it custom, etc.
I've done everything in the tutorial but I keep getting the following error.
"There was a failure executing the receive pipeline... The body part is NULL"
The things I don't get from the tutorial but don't believe they should be an issue are:
I created a new solution and project to make the custompipeline component (reference figure 19) and thus the dll file. Meaning it is on it's own namespace. However, it looks like from the tutorial they created the project within the main biztalk solution (ie the one with the pipeline and the orchestration) and thus the namespace has "TechNetWiki.SchemaResolver." in it. Should I make the custompipeline component have the namespace of my main solution? I'm assuming this shouldn't matter because I should be able to use this component in other solutions as it is meant to be generic to the business rules that are associated with the biztalk application.
The other piece I don't have is Figure 15 under the "THEN Action" they have it equal the destination schema they would like to disassemble to but then they put #Src1 at the end of "http://TechNetWiki.SchemaResolver.Schemas.SRC1_FF#Src1". What is the #Src1 for?
In the sample you've linked to, the probe method of the pipeline component is pushing the first 4 characters from the filename into a typed message that is then passed into the rules engine. Its those 4 characters that match the "SRC1" in the example.
string srcFileName = pInMsg.Context.Read("ReceivedFileName", "http://schemas.microsoft.com/BizTalk/2003/file-properties This link is external to TechNet Wiki. It will open in a new window. ").ToString();
srcFileName = Path.GetFileName(srcFileName);
//Substring the first four digits to take source code to use to call BRE API
string customerCode = srcFileName.Substring(0, 4);
//create an instance of the XML object
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(string.Format(#"<ns0:Root xmlns:ns0='http://TechNetWiki.SchemaResolver.Schemas.SchemaResolverBRE This link is external to TechNet Wiki. It will open in a new window. '>
<SrcCode>{0}</SrcCode>
<MessageType></MessageType>
</ns0:Root>", customerCode));
//retreive source code in case in our cache dictionary
if (cachedSources.ContainsKey(customerCode))
{
messageType = cachedSources[customerCode];
}
else
{
TypedXmlDocument typedXmlDocument = new TypedXmlDocument("TechNetWiki.SchemaResolver.Schemas.SchemaResolverBRE", xmlDoc);
Microsoft.RuleEngine.Policy policy = new Microsoft.RuleEngine.Policy("SchemaResolverPolicy");
policy.Execute(typedXmlDocument);
So the matching rule is based on the 1st 4 characters of the filename. If one isn't matched, the probe returns a false - i.e. unrecognised.
The final part is that the message type is pushed into the returned message - this is made up of the namespace and the root schema node with a # separator - so your #src1 is the root node.
You need to implement IProbeMessage near to class
I forgot to add IProbeMessage in the code of article. It is updated now.
but it is there in sample source code
Src1 is the the root node name of schema. I mentioned that in article that message type is TargetNamespace#Root
I recommend to download the sample code
I hope this will help you
When I deploy an Infopath 2007 form to the SharePoint server, the SelectSingleNode always returns null but always works locally. Here is an example of the following code that is failing:
XPathNavigator vendor = payeeDS.SelectSingleNode(
"/dfs:myFields/dfs:dataFields/tns:GetVendorsResponse/tns:GetVendorsResult/NewDataSet/Vendor s[Name='"
+ payeeTypedName + "']", NamespaceManager);
I'm writing to the event viewer so I can confirm that the code is actually hit. The form is Administrator approved and has Full Trust.
Any ideas on what could be causing this issue?
Thanks
XPathNavigator behavior doesn't change based on environment. I'm not certain, but you likely have one of two problems.
Either the payeeDS isn't loading as a valid XML file and cannot be read, or more likely,
Sharepoint has added some NameSpacing to the XML file, and you need to change your navigation.
Verify your node path.("/dfs:myFields/dfs:dataFields/tns:GetVendorsResponse/tns:GetVendorsResult/)
The first part of the path is in one name space(dfs:) and other part is in other name space(tns:).
You can do two things
1.Set the name space of the tns: with your web service
IXMLDOMDocument2 domXml = (IXMLDOMDocument2)xDocument.DataObjects[dataSource].DOM;
string selectionNamespaceValue = string.Empty;
public const string SELECTION_NAMESPACE_VALUE =
"xmlns:dfs='http://schemas.microsoft.com/office/infopath/2003/dataFormSolution' xmlns:ns1='{0}'";
selectionNamespaceValue = string.Format(CultureInfo.CurrentCulture, Constants.SELECTION_NAMESPACE_VALUE,Constants.DEFAULT_WEB_SERVICE);
domXml.setProperty("SelectionNamespaces", selectionNamespaceValue);
You can access the node by either like this.
payeeDS.SelectSingleNode("/dfs:myFields/dfs:dataFields)..firstChild.firstChild;