Search Results

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

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

  • problem in getting value of the object attribute in flex

    - by madanmohan
    i have an xml which contains 'interface' sub tag, iam converting xml to object using SampleXmlDecoder. compiler did not allow me to access the value of the 'inteface' attrible of the resultobject. var xml:XML = event.result as XML; var xmlDoc : XMLDocument = new XMLDocument(xml.toString()); var decoder : SimpleXMLDecoder = new SimpleXMLDecoder(true) var resultObj : Object = decoder.decodeXML(xmlDoc); var o:Object = new Object(); o.someprop = resultObj.maintag.item.interface; its treating interface as keyword. can anyone tell me the solution for this. Thanks in advance

    Read the article

  • Insert line in xml doc

    - by phenevo
    Hi, I wanna insert in second line : <?mso-application progid="Excel.Sheet"?> but I'm started to think that it is impossible. Here is my base code: XmlDocument doc = new XmlDocument(); XmlReader reader = cmd.ExecuteXmlReader(); doc.LoadXml("<results></results>"); XmlNode newNode = doc.ReadNode(reader); while (newNode != null) { doc.DocumentElement.AppendChild(newNode); newNode = doc.ReadNode(reader); }

    Read the article

  • Anyone saw a worst written function than this? [closed]

    - by fvoncina
    string sUrl = "http://www.ipinfodb.com/ip_query.php?ip=" + ip + "&output=xml"; StringBuilder oBuilder = new StringBuilder(); StringWriter oStringWriter = new StringWriter(oBuilder); XmlTextReader oXmlReader = new XmlTextReader(sUrl); XmlTextWriter oXmlWriter = new XmlTextWriter(oStringWriter); while (oXmlReader.Read()) { oXmlWriter.WriteNode(oXmlReader, true); } oXmlReader.Close(); oXmlWriter.Close(); // richTextBox1.Text = oBuilder.ToString(); XmlDocument doc = new XmlDocument(); doc.LoadXml(oBuilder.ToString()); doc.Save(System.Web.HttpContext.Current.Server.MapPath(".") + "data.xml"); DataSet ds = new DataSet(); ds.ReadXml(System.Web.HttpContext.Current.Server.MapPath(".") + "data.xml"); string strcountry = "India"; if (ds.Tables[0].Rows.Count > 0) { strcountry = ds.Tables[0].Rows[0]["CountryName"].ToString(); }

    Read the article

  • Merging XMLTextReaders in C#

    - by smithchelluk
    I have a website that needs to pull information from two diffferent XML data sources. Originally I only need to get the data from one source so I was building a URL in the backend that went and retrieved the data from the XML site and then parsed and rendered it in the front end of the website. Now I have to use a 2nd data source and merge the result sets (which are identically structured XML) into one result set. Here is the code I am currently using to get one XML feed. sUrl = sbUrl.ToString(); //The URL for the XML feed XmlDocument xDoc = new XmlDocument(); StringBuilder oBuilder = new StringBuilder(); //The parsed HTML output XmlTextReader oXmlReader = new XmlTextReader(sUrl); oXmlReader.Read(); xDoc.Load(oXmlReader); XmlNodeList List = xDoc.GetElementsByTagName("result"); foreach (XmlNode node in List) { XmlElement key = (XmlElement)node; //BUILD THE OUTPUT HERE } Thanks in advance for your help.

    Read the article

  • c# xml function to check whether a string is equal to a xml attribute, to add selected combobox item

    - by fuch
    i want to check the combobox.selecteditem.tostring() on combobox select in a given xml with several nodes, where each one has an attribute called "name" private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { try { textBox1.AppendText(nameAttributeCheck(comboBox1.SelectedItem.ToString())); } catch { } } private string nameAttributeCheck(string a) { XmlDocument doc = new XmlDocument(); doc.Load("armor.xml"); XmlElement root = doc.DocumentElement; XmlNodeList items = root.SelectNodes("/items"); String result = null; try { foreach (XmlNode item in items) { if (string.Equals(a, item.Attributes["name"].InnerText.ToString())) { result += item.Attributes["picture"].InnerText.ToString(); } } } catch { } return result; } each time i try it, nothing happens

    Read the article

  • Correct syntax in stored procedure and method using MsSqlProvider.ExecProcedure? [migrated]

    - by Dudi
    I have problem with ASP.net and database prcedure My procedure in mssql base USE [dbase] GO SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ALTER PROCEDURE [dbo].[top1000] @Published datetime output, @Title nvarchar(100) output, @Url nvarchar(1000) output, @Count INT output AS SET @Published = (SELECT TOP 1000 dbo.vst_download_files.dfl_date_public FROM dbo.vst_download_files ORDER BY dbo.vst_download_files.dfl_download_count DESC ) SET @Title = (SELECT TOP 1000 dbo.vst_download_files.dfl_name FROM dbo.vst_download_files ORDER BY dbo.vst_download_files.dfl_download_count DESC) SET @Url = (SELECT TOP 1000 dbo.vst_download_files.dfl_source_url FROM dbo.vst_download_files ORDER BY dbo.vst_download_files.dfl_download_count DESC) SET @Count = (SELECT TOP 1000 dbo.vst_download_files.dfl_download_count FROM dbo.vst_download_files ORDER BY dbo.vst_download_files.dfl_download_count DESC) And my proceduer in website project public static void Top1000() { List<DownloadFile> List = new List<DownloadFile>(); SqlDataReader dbReader; SqlParameter published = new SqlParameter("@Published", SqlDbType.DateTime2); published.Direction = ParameterDirection.Output; SqlParameter title = new SqlParameter("@Title", SqlDbType.NVarChar); title.Direction = ParameterDirection.Output; SqlParameter url = new SqlParameter("@Url", SqlDbType.NVarChar); url.Direction = ParameterDirection.Output; SqlParameter count = new SqlParameter("@Count", SqlDbType.Int); count.Direction = ParameterDirection.Output; SqlParameter[] parm = {published, title, count}; dbReader = MsSqlProvider.ExecProcedure("top1000", parm); try { while (dbReader.Read()) { DownloadFile df = new DownloadFile(); //df.AddDate = dbReader["dfl_date_public"]; df.Name = dbReader["dlf_name"].ToString(); df.SourceUrl = dbReader["dlf_source_url"].ToString(); df.DownloadCount = Convert.ToInt32(dbReader["dlf_download_count"]); List.Add(df); } XmlDocument top1000Xml = new XmlDocument(); XmlNode XMLNode = top1000Xml.CreateElement("products"); foreach (DownloadFile df in List) { XmlNode productNode = top1000Xml.CreateElement("product"); XmlNode publishedNode = top1000Xml.CreateElement("published"); publishedNode.InnerText = "data dodania"; XMLNode.AppendChild(publishedNode); XmlNode titleNode = top1000Xml.CreateElement("title"); titleNode.InnerText = df.Name; XMLNode.AppendChild(titleNode); } top1000Xml.AppendChild(XMLNode); top1000Xml.Save("\\pages\\test.xml"); } catch { } finally { dbReader.Close(); } } And if I made to MsSqlProvider.ExecProcedure("top1000", parm); I got String[1]: property Size has invalid size of 0. Where I shoudl look for solution? Procedure or method?

    Read the article

  • Weblogic 10.0: SAMLSignedObject.verify() failed to validate signature value

    - by joshea
    I've been having this problem for a while and it's driving me nuts. I'm trying to create a client (in C# .NET 2.0) that will use SAML 1.1 to sign on to a WebLogic 10.0 server (i.e., a Single Sign-On scenario, using browser/post profile). The client is on a WinXP machine and the WebLogic server is on a RHEL 5 box. I based my client largely on code in the example here: http://www.codeproject.com/KB/aspnet/DotNetSamlPost.aspx (the source has a section for SAML 1.1). I set up WebLogic based on instructions for SAML Destination Site from here:http://www.oracle.com/technology/pub/articles/dev2arch/2006/12/sso-with-saml4.html I created a certificate using makecert that came with VS 2005. makecert -r -pe -n "CN=whatever" -b 01/01/2010 -e 01/01/2011 -sky exchange whatever.cer -sv whatever.pvk pvk2pfx.exe -pvk whatever.pvk -spc whatever.cer -pfx whatever.pfx Then I installed the .pfx to my personal certificate directory, and installed the .cer into the WebLogic SAML Identity Asserter V2. I read on another site that formatting the response to be readable (ie, adding whitespace) to the response after signing would cause this problem, so I tried various combinations of turning on/off .Indent XMLWriterSettings and turning on/off .PreserveWhiteSpace when loading the XML document, and none of it made any difference. I've printed the SignatureValue both before the message is is encoded/sent and after it arrives/gets decoded, and they are the same. So, to be clear: the Response appears to be formed, encoded, sent, and decoded fine (I see the full Response in the WebLogic logs). WebLogic finds the certificate I want it to use, verifies that a key was supplied, gets the signed info, and then fails to validate the signature. Code: public string createResponse(Dictionary<string, string> attributes){ ResponseType response = new ResponseType(); // Create Response response.ResponseID = "_" + Guid.NewGuid().ToString(); response.MajorVersion = "1"; response.MinorVersion = "1"; response.IssueInstant = System.DateTime.UtcNow; response.Recipient = "http://theWLServer/samlacs/acs"; StatusType status = new StatusType(); status.StatusCode = new StatusCodeType(); status.StatusCode.Value = new XmlQualifiedName("Success", "urn:oasis:names:tc:SAML:1.0:protocol"); response.Status = status; // Create Assertion AssertionType assertionType = CreateSaml11Assertion(attributes); response.Assertion = new AssertionType[] {assertionType}; //Serialize XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("samlp", "urn:oasis:names:tc:SAML:1.0:protocol"); ns.Add("saml", "urn:oasis:names:tc:SAML:1.0:assertion"); XmlSerializer responseSerializer = new XmlSerializer(response.GetType()); StringWriter stringWriter = new StringWriter(); XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = false;//I've tried both ways, for the fun of it settings.Encoding = Encoding.UTF8; XmlWriter responseWriter = XmlTextWriter.Create(stringWriter, settings); responseSerializer.Serialize(responseWriter, response, ns); responseWriter.Close(); string samlString = stringWriter.ToString(); stringWriter.Close(); // Sign the document XmlDocument doc = new XmlDocument(); doc.PreserveWhiteSpace = true; //also tried this both ways to no avail doc.LoadXml(samlString); X509Certificate2 cert = null; X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); X509Certificate2Collection coll = store.Certificates.Find(X509FindType.FindBySubjectDistinguishedName, "distName", true); if (coll.Count < 1) { throw new ArgumentException("Unable to locate certificate"); } cert = coll[0]; store.Close(); //this special SignDoc just overrides a function in SignedXml so //it knows to look for ResponseID rather than ID XmlElement signature = SamlHelper.SignDoc( doc, cert, "ResponseID", response.ResponseID); doc.DocumentElement.InsertBefore(signature, doc.DocumentElement.ChildNodes[0]); // Base64Encode and URL Encode byte[] base64EncodedBytes = Encoding.UTF8.GetBytes(doc.OuterXml); string returnValue = System.Convert.ToBase64String( base64EncodedBytes); return returnValue; } private AssertionType CreateSaml11Assertion(Dictionary<string, string> attributes){ AssertionType assertion = new AssertionType(); assertion.AssertionID = "_" + Guid.NewGuid().ToString(); assertion.Issuer = "madeUpValue"; assertion.MajorVersion = "1"; assertion.MinorVersion = "1"; assertion.IssueInstant = System.DateTime.UtcNow; //Not before, not after conditions ConditionsType conditions = new ConditionsType(); conditions.NotBefore = DateTime.UtcNow; conditions.NotBeforeSpecified = true; conditions.NotOnOrAfter = DateTime.UtcNow.AddMinutes(10); conditions.NotOnOrAfterSpecified = true; //Name Identifier to be used in Saml Subject NameIdentifierType nameIdentifier = new NameIdentifierType(); nameIdentifier.NameQualifier = domain.Trim(); nameIdentifier.Value = subject.Trim(); SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType(); subjectConfirmation.ConfirmationMethod = new string[] { "urn:oasis:names:tc:SAML:1.0:cm:bearer" }; // // Create some SAML subject. SubjectType samlSubject = new SubjectType(); AttributeStatementType attrStatement = new AttributeStatementType(); AuthenticationStatementType authStatement = new AuthenticationStatementType(); authStatement.AuthenticationMethod = "urn:oasis:names:tc:SAML:1.0:am:password"; authStatement.AuthenticationInstant = System.DateTime.UtcNow; samlSubject.Items = new object[] { nameIdentifier, subjectConfirmation}; attrStatement.Subject = samlSubject; authStatement.Subject = samlSubject; IPHostEntry ipEntry = Dns.GetHostEntry(System.Environment.MachineName); SubjectLocalityType subjectLocality = new SubjectLocalityType(); subjectLocality.IPAddress = ipEntry.AddressList[0].ToString(); authStatement.SubjectLocality = subjectLocality; attrStatement.Attribute = new AttributeType[attributes.Count]; int i=0; // Create SAML attributes. foreach (KeyValuePair<string, string> attribute in attributes) { AttributeType attr = new AttributeType(); attr.AttributeName = attribute.Key; attr.AttributeNamespace= domain; attr.AttributeValue = new object[] {attribute.Value}; attrStatement.Attribute[i] = attr; i++; } assertion.Conditions = conditions; assertion.Items = new StatementAbstractType[] {authStatement, attrStatement}; return assertion; } private static XmlElement SignDoc(XmlDocument doc, X509Certificate2 cert2, string referenceId, string referenceValue) { // Use our own implementation of SignedXml SamlSignedXml sig = new SamlSignedXml(doc, referenceId); // Add the key to the SignedXml xmlDocument. sig.SigningKey = cert2.PrivateKey; // Create a reference to be signed. Reference reference = new Reference(); reference.Uri= String.Empty; reference.Uri = "#" + referenceValue; // Add an enveloped transformation to the reference. XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform(); reference.AddTransform(env); // Add the reference to the SignedXml object. sig.AddReference(reference); // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate). KeyInfo keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(cert2)); sig.KeyInfo = keyInfo; // Compute the signature. sig.ComputeSignature(); // Get the XML representation of the signature and save // it to an XmlElement object. XmlElement xmlDigitalSignature = sig.GetXml(); return xmlDigitalSignature; } To open the page in my client app, string postData = String.Format("SAMLResponse={0}&APID=ap_00001&TARGET={1}", System.Web.HttpUtility.UrlEncode(builder.buildResponse("http://theWLServer/samlacs/acs",attributes)), "http://desiredURL"); webBrowser.Navigate("http://theWLServer/samlacs/acs", "_self", Encoding.UTF8.GetBytes(postData), "Content-Type: application/x-www-form-urlencoded");

    Read the article

  • Building a better mouse-trap &ndash; Improving the creation of XML Message Requests using Reflection, XML &amp; XSLT

    - by paulschapman
    Introduction The way I previously created messages to send to the GovTalk service I used the XMLDocument to create the request. While this worked it left a number of problems; not least that for every message a special function would need to created. This is OK for the short term but the biggest cost in any software project is maintenance and this would be a headache to maintain. So the following is a somewhat better way of achieving the same thing. For the purposes of this article I am going to be using the CompanyNumberSearch request of the GovTalk service – although this technique would work for any service that accepted XML. The C# functions which send and receive the messages remain the same. The magic sauce in this is the XSLT which defines the structure of the request, and the use of objects in conjunction with reflection to provide the content. It is a bit like Sweet Chilli Sauce added to Chicken on a bed of rice. So on to the Sweet Chilli Sauce The Sweet Chilli Sauce The request to search for a company based on it’s number is as follows; <GovTalkMessage xsi:schemaLocation="http://www.govtalk.gov.uk/CM/envelope http://xmlgw.companieshouse.gov.uk/v1-0/schema/Egov_ch-v2-0.xsd" xmlns="http://www.govtalk.gov.uk/CM/envelope" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:gt="http://www.govtalk.gov.uk/schemas/govtalk/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <EnvelopeVersion>1.0</EnvelopeVersion> <Header> <MessageDetails> <Class>NumberSearch</Class> <Qualifier>request</Qualifier> <TransactionID>1</TransactionID> </MessageDetails> <SenderDetails> <IDAuthentication> <SenderID>????????????????????????????????</SenderID> <Authentication> <Method>CHMD5</Method> <Value>????????????????????????????????</Value> </Authentication> </IDAuthentication> </SenderDetails> </Header> <GovTalkDetails> <Keys/> </GovTalkDetails> <Body> <NumberSearchRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlgw.companieshouse.gov.uk/v1-0/schema/NumberSearch.xsd"> <PartialCompanyNumber>99999999</PartialCompanyNumber> <DataSet>LIVE</DataSet> <SearchRows>1</SearchRows> </NumberSearchRequest> </Body> </GovTalkMessage> This is the XML that we send to the GovTalk Service and we get back a list of companies that match the criteria passed A message is structured in two parts; The envelope which identifies the person sending the request, with the name of the request, and the body which gives the detail of the company we are looking for. The Chilli What makes it possible is the use of XSLT to define the message – and serialization to convert each request object into XML. To start we need to create an object which will represent the contents of the message we are sending. However there is a common properties in all the messages that we send to Companies House. These properties are as follows SenderId – the id of the person sending the message SenderPassword – the password associated with Id TransactionId – Unique identifier for the message AuthenticationValue – authenticates the request Because these properties are unique to the Companies House message, and because they are shared with all messages they are perfect candidates for a base class. The class is as follows; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using Microsoft.WindowsAzure.ServiceRuntime; namespace CompanyHub.Services { public class GovTalkRequest { public GovTalkRequest() { try { SenderID = RoleEnvironment.GetConfigurationSettingValue("SenderId"); SenderPassword = RoleEnvironment.GetConfigurationSettingValue("SenderPassword"); TransactionId = DateTime.Now.Ticks.ToString(); AuthenticationValue = EncodePassword(String.Format("{0}{1}{2}", SenderID, SenderPassword, TransactionId)); } catch (System.Exception ex) { throw ex; } } /// <summary> /// returns the Sender ID to be used when communicating with the GovTalk Service /// </summary> public String SenderID { get; set; } /// <summary> /// return the password to be used when communicating with the GovTalk Service /// </summary> public String SenderPassword { get; set; } // end SenderPassword /// <summary> /// Transaction Id - uses the Time and Date converted to Ticks /// </summary> public String TransactionId { get; set; } // end TransactionId /// <summary> /// calculate the authentication value that will be used when /// communicating with /// </summary> public String AuthenticationValue { get; set; } // end AuthenticationValue property /// <summary> /// encodes password(s) using MD5 /// </summary> /// <param name="clearPassword"></param> /// <returns></returns> public static String EncodePassword(String clearPassword) { MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); byte[] hashedBytes; UTF32Encoding encoder = new UTF32Encoding(); hashedBytes = md5Hasher.ComputeHash(ASCIIEncoding.Default.GetBytes(clearPassword)); String result = Regex.Replace(BitConverter.ToString(hashedBytes), "-", "").ToLower(); return result; } } } There is nothing particularly clever here, except for the EncodePassword method which hashes the value made up of the SenderId, Password and Transaction id. Each message inherits from this object. So for the Company Number Search in addition to the properties above we need a partial number, which dataset to search – for the purposes of the project we only need to search the LIVE set so this can be set in the constructor and the SearchRows. Again all are set as properties. With the SearchRows and DataSet initialized in the constructor. public class CompanyNumberSearchRequest : GovTalkRequest, IDisposable { /// <summary> /// /// </summary> public CompanyNumberSearchRequest() : base() { DataSet = "LIVE"; SearchRows = 1; } /// <summary> /// Company Number to search against /// </summary> public String PartialCompanyNumber { get; set; } /// <summary> /// What DataSet should be searched for the company /// </summary> public String DataSet { get; set; } /// <summary> /// How many rows should be returned /// </summary> public int SearchRows { get; set; } public void Dispose() { DataSet = String.Empty; PartialCompanyNumber = String.Empty; DataSet = "LIVE"; SearchRows = 1; } } As well as inheriting from our base class, I have also inherited from IDisposable – not just because it is just plain good practice to dispose of objects when coding, but it gives also gives us more versatility when using the object. There are four stages in making a request and this is reflected in the four methods we execute in making a call to the Companies House service; Create a request Send a request Check the status If OK then get the results of the request I’ve implemented each of these stages within a static class called Toolbox – which also means I don’t need to create an instance of the class to use it. When making a request there are three stages; Get the template for the message Serialize the object representing the message Transform the serialized object using a predefined XSLT file. Each of my templates I have defined as an embedded resource. When retrieving a resource of this kind we have to include the full namespace to the resource. In making the code re-usable as much as possible I defined the full ‘path’ within the GetRequest method. requestFile = String.Format("CompanyHub.Services.Schemas.{0}", RequestFile); So we now have the full path of the file within the assembly. Now all we need do is retrieve the assembly and get the resource. asm = Assembly.GetExecutingAssembly(); sr = asm.GetManifestResourceStream(requestFile); Once retrieved  So this can be returned to the calling function and we now have a stream of XSLT to define the message. Time now to serialize the request to create the other side of this message. // Serialize object containing Request, Load into XML Document t = Obj.GetType(); ms = new MemoryStream(); serializer = new XmlSerializer(t); xmlTextWriter = new XmlTextWriter(ms, Encoding.ASCII); serializer.Serialize(xmlTextWriter, Obj); ms = (MemoryStream)xmlTextWriter.BaseStream; GovTalkRequest = Toolbox.ConvertByteArrayToString(ms.ToArray()); First off we need the type of the object so we make a call to the GetType method of the object containing the Message properties. Next we need a MemoryStream, XmlSerializer and an XMLTextWriter so these can be initialized. The object is serialized by making the call to the Serialize method of the serializer object. The result of that is then converted into a MemoryStream. That MemoryStream is then converted into a string. ConvertByteArrayToString This is a fairly simple function which uses an ASCIIEncoding object found within the System.Text namespace to convert an array of bytes into a string. public static String ConvertByteArrayToString(byte[] bytes) { System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); return enc.GetString(bytes); } I only put it into a function because I will be using this in various places. The Sauce When adding support for other messages outside of creating a new object to store the properties of the message, the C# components do not need to change. It is in the XSLT file that the versatility of the technique lies. The XSLT file determines the format of the message. For the CompanyNumberSearch the XSLT file is as follows; <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <GovTalkMessage xsi:schemaLocation="http://www.govtalk.gov.uk/CM/envelope http://xmlgw.companieshouse.gov.uk/v1-0/schema/Egov_ch-v2-0.xsd" xmlns="http://www.govtalk.gov.uk/CM/envelope" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:gt="http://www.govtalk.gov.uk/schemas/govtalk/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" > <EnvelopeVersion>1.0</EnvelopeVersion> <Header> <MessageDetails> <Class>NumberSearch</Class> <Qualifier>request</Qualifier> <TransactionID> <xsl:value-of select="CompanyNumberSearchRequest/TransactionId"/> </TransactionID> </MessageDetails> <SenderDetails> <IDAuthentication> <SenderID><xsl:value-of select="CompanyNumberSearchRequest/SenderID"/></SenderID> <Authentication> <Method>CHMD5</Method> <Value> <xsl:value-of select="CompanyNumberSearchRequest/AuthenticationValue"/> </Value> </Authentication> </IDAuthentication> </SenderDetails> </Header> <GovTalkDetails> <Keys/> </GovTalkDetails> <Body> <NumberSearchRequest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://xmlgw.companieshouse.gov.uk/v1-0/schema/NumberSearch.xsd"> <PartialCompanyNumber> <xsl:value-of select="CompanyNumberSearchRequest/PartialCompanyNumber"/> </PartialCompanyNumber> <DataSet> <xsl:value-of select="CompanyNumberSearchRequest/DataSet"/> </DataSet> <SearchRows> <xsl:value-of select="CompanyNumberSearchRequest/SearchRows"/> </SearchRows> </NumberSearchRequest> </Body> </GovTalkMessage> </xsl:template> </xsl:stylesheet> The outer two tags define that this is a XSLT stylesheet and the root tag from which the nodes are searched for. The GovTalkMessage is the format of the message that will be sent to Companies House. We first set up the XslCompiledTransform object which will transform the XSLT template and the serialized object into the request to Companies House. xslt = new XslCompiledTransform(); resultStream = new MemoryStream(); writer = new XmlTextWriter(resultStream, Encoding.ASCII); doc = new XmlDocument(); The Serialize method require XmlTextWriter to write the XML (writer) and a stream to place the transferred object into (writer). The XML will be loaded into an XMLDocument object (doc) prior to the transformation. // create XSLT Template xslTemplate = Toolbox.GetRequest(Template); xslTemplate.Seek(0, SeekOrigin.Begin); templateReader = XmlReader.Create(xslTemplate); xslt.Load(templateReader); I have stored all the templates as a series of Embedded Resources and the GetRequestCall takes the name of the template and extracts the relevent XSLT file. /// <summary> /// Gets the framwork XML which makes the request /// </summary> /// <param name="RequestFile"></param> /// <returns></returns> public static Stream GetRequest(String RequestFile) { String requestFile = String.Empty; Stream sr = null; Assembly asm = null; try { requestFile = String.Format("CompanyHub.Services.Schemas.{0}", RequestFile); asm = Assembly.GetExecutingAssembly(); sr = asm.GetManifestResourceStream(requestFile); } catch (Exception) { throw; } finally { asm = null; } return sr; } // end private static stream GetRequest We first take the template name and expand it to include the full namespace to the Embedded Resource I like to keep all my schemas in the same directory and so the namespace reflects this. The rest is the default namespace for the project. Then we get the currently executing assembly (which will contain the resources with the call to GetExecutingAssembly() ) Finally we get a stream which contains the XSLT file. We use this stream and then load an XmlReader with the contents of the template, and that is in turn loaded into the XslCompiledTransform object. We convert the object containing the message properties into Xml by serializing it; calling the Serialize() method of the XmlSerializer object. To set up the object we do the following; t = Obj.GetType(); ms = new MemoryStream(); serializer = new XmlSerializer(t); xmlTextWriter = new XmlTextWriter(ms, Encoding.ASCII); We first determine the type of the object being transferred by calling GetType() We create an XmlSerializer object by passing the type of the object being serialized. The serializer writes to a memory stream and that is linked to an XmlTextWriter. Next job is to serialize the object and load it into an XmlDocument. serializer.Serialize(xmlTextWriter, Obj); ms = (MemoryStream)xmlTextWriter.BaseStream; xmlRequest = new XmlTextReader(ms); GovTalkRequest = Toolbox.ConvertByteArrayToString(ms.ToArray()); doc.LoadXml(GovTalkRequest); Time to transform the XML to construct the full request. xslt.Transform(doc, writer); resultStream.Seek(0, SeekOrigin.Begin); request = Toolbox.ConvertByteArrayToString(resultStream.ToArray()); So that creates the full request to be sent  to Companies House. Sending the request So far we have a string with a request for the Companies House service. Now we need to send the request to the Companies House Service. Configuration within an Azure project There are entire blog entries written about configuration within an Azure project – most of this is out of scope for this article but the following is a summary. Configuration is defined in two files within the parent project *.csdef which contains the definition of configuration setting. <?xml version="1.0" encoding="utf-8"?> <ServiceDefinition name="OnlineCompanyHub" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition"> <WebRole name="CompanyHub.Host"> <InputEndpoints> <InputEndpoint name="HttpIn" protocol="http" port="80" /> </InputEndpoints> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" /> <Setting name="DataConnectionString" /> </ConfigurationSettings> </WebRole> <WebRole name="CompanyHub.Services"> <InputEndpoints> <InputEndpoint name="HttpIn" protocol="http" port="8080" /> </InputEndpoints> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" /> <Setting name="SenderId"/> <Setting name="SenderPassword" /> <Setting name="GovTalkUrl"/> </ConfigurationSettings> </WebRole> <WorkerRole name="CompanyHub.Worker"> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" /> </ConfigurationSettings> </WorkerRole> </ServiceDefinition>   Above is the configuration definition from the project. What we are interested in however is the ConfigurationSettings tag of the CompanyHub.Services WebRole. There are four configuration settings here, but at the moment we are interested in the second to forth settings; SenderId, SenderPassword and GovTalkUrl The value of these settings are defined in the ServiceDefinition.cscfg file; <?xml version="1.0"?> <ServiceConfiguration serviceName="OnlineCompanyHub" xmlns="http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"> <Role name="CompanyHub.Host"> <Instances count="2" /> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" value="UseDevelopmentStorage=true" /> <Setting name="DataConnectionString" value="UseDevelopmentStorage=true" /> </ConfigurationSettings> </Role> <Role name="CompanyHub.Services"> <Instances count="2" /> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" value="UseDevelopmentStorage=true" /> <Setting name="SenderId" value="UserID"/> <Setting name="SenderPassword" value="Password"/> <Setting name="GovTalkUrl" value="http://xmlgw.companieshouse.gov.uk/v1-0/xmlgw/Gateway"/> </ConfigurationSettings> </Role> <Role name="CompanyHub.Worker"> <Instances count="2" /> <ConfigurationSettings> <Setting name="DiagnosticsConnectionString" value="UseDevelopmentStorage=true" /> </ConfigurationSettings> </Role> </ServiceConfiguration>   Look for the Role tag that contains our project name (CompanyHub.Services). Having configured the parameters we can now transmit the request. This is done by ‘POST’ing a stream of XML to the Companies House servers. govTalkUrl = RoleEnvironment.GetConfigurationSettingValue("GovTalkUrl"); request = WebRequest.Create(govTalkUrl); request.Method = "POST"; request.ContentType = "text/xml"; writer = new StreamWriter(request.GetRequestStream()); writer.WriteLine(RequestMessage); writer.Close(); We use the WebRequest object to send the object. Set the method of sending to ‘POST’ and the type of data as text/xml. Once set up all we do is write the request to the writer – this sends the request to Companies House. Did the Request Work Part I – Getting the response Having sent a request – we now need the result of that request. response = request.GetResponse(); reader = response.GetResponseStream(); result = Toolbox.ConvertByteArrayToString(Toolbox.ReadFully(reader));   The WebRequest object has a GetResponse() method which allows us to get the response sent back. Like many of these calls the results come in the form of a stream which we convert into a string. Did the Request Work Part II – Translating the Response Much like XSLT and XML were used to create the original request, so it can be used to extract the response and by deserializing the result we create an object that contains the response. Did it work? It would be really great if everything worked all the time. Of course if it did then I don’t suppose people would pay me and others the big bucks so that our programmes do not a) Collapse in a heap (this is an area of memory) b) Blow every fuse in the place in a shower of sparks (this will probably not happen this being real life and not a Hollywood movie, but it was possible to blow the sound system of a BBC Model B with a poorly coded setting) c) Go nuts and trap everyone outside the airlock (this was from a movie, and unless NASA get a manned moon/mars mission set up unlikely to happen) d) Go nuts and take over the world (this was also from a movie, but please note life has a habit of being of exceeding the wildest imaginations of Hollywood writers (note writers – Hollywood executives have no imagination and judging by recent output of that town have turned plagiarism into an art form). e) Freeze in total confusion because the cleaner pulled the plug to the internet router (this has happened) So anyway – we need to check to see if our request actually worked. Within the GovTalk response there is a section that details the status of the message and a description of what went wrong (if anything did). I have defined an XSLT template which will extract these into an XML document. <?xml version="1.0"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ev="http://www.govtalk.gov.uk/CM/envelope" xmlns:gt="http://www.govtalk.gov.uk/schemas/govtalk/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <xsl:template match="/"> <GovTalkStatus xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <Status> <xsl:value-of select="ev:GovTalkMessage/ev:Header/ev:MessageDetails/ev:Qualifier"/> </Status> <Text> <xsl:value-of select="ev:GovTalkMessage/ev:GovTalkDetails/ev:GovTalkErrors/ev:Error/ev:Text"/> </Text> <Location> <xsl:value-of select="ev:GovTalkMessage/ev:GovTalkDetails/ev:GovTalkErrors/ev:Error/ev:Location"/> </Location> <Number> <xsl:value-of select="ev:GovTalkMessage/ev:GovTalkDetails/ev:GovTalkErrors/ev:Error/ev:Number"/> </Number> <Type> <xsl:value-of select="ev:GovTalkMessage/ev:GovTalkDetails/ev:GovTalkErrors/ev:Error/ev:Type"/> </Type> </GovTalkStatus> </xsl:template> </xsl:stylesheet>   Only thing different about previous XSL files is the references to two namespaces ev & gt. These are defined in the GovTalk response at the top of the response; xsi:schemaLocation="http://www.govtalk.gov.uk/CM/envelope http://xmlgw.companieshouse.gov.uk/v1-0/schema/Egov_ch-v2-0.xsd" xmlns="http://www.govtalk.gov.uk/CM/envelope" xmlns:dsig="http://www.w3.org/2000/09/xmldsig#" xmlns:gt="http://www.govtalk.gov.uk/schemas/govtalk/core" If we do not put these references into the XSLT template then  the XslCompiledTransform object will not be able to find the relevant tags. Deserialization is a fairly simple activity. encoder = new ASCIIEncoding(); ms = new MemoryStream(encoder.GetBytes(statusXML)); serializer = new XmlSerializer(typeof(GovTalkStatus)); xmlTextWriter = new XmlTextWriter(ms, Encoding.ASCII); messageStatus = (GovTalkStatus)serializer.Deserialize(ms);   We set up a serialization object using the object type containing the error state and pass to it the results of a transformation between the XSLT above and the GovTalk response. Now we have an object containing any error state, and the error message. All we need to do is check the status. If there is an error then we can flag an error. If not then  we extract the results and pass that as an object back to the calling function. We go this by guess what – defining an XSLT template for the result and using that to create an Xml Stream which can be deserialized into a .Net object. In this instance the XSLT to create the result of a Company Number Search is; <?xml version="1.0" encoding="us-ascii"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ev="http://www.govtalk.gov.uk/CM/envelope" xmlns:sch="http://xmlgw.companieshouse.gov.uk/v1-0/schema" exclude-result-prefixes="ev"> <xsl:template match="/"> <CompanySearchResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <CompanyNumber> <xsl:value-of select="ev:GovTalkMessage/ev:Body/sch:NumberSearch/sch:CoSearchItem/sch:CompanyNumber"/> </CompanyNumber> <CompanyName> <xsl:value-of select="ev:GovTalkMessage/ev:Body/sch:NumberSearch/sch:CoSearchItem/sch:CompanyName"/> </CompanyName> </CompanySearchResult> </xsl:template> </xsl:stylesheet> and the object definition is; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace CompanyHub.Services { public class CompanySearchResult { public CompanySearchResult() { CompanyNumber = String.Empty; CompanyName = String.Empty; } public String CompanyNumber { get; set; } public String CompanyName { get; set; } } } Our entire code to make calls to send a request, and interpret the results are; String request = String.Empty; String response = String.Empty; GovTalkStatus status = null; fault = null; try { using (CompanyNumberSearchRequest requestObj = new CompanyNumberSearchRequest()) { requestObj.PartialCompanyNumber = CompanyNumber; request = Toolbox.CreateRequest(requestObj, "CompanyNumberSearch.xsl"); response = Toolbox.SendGovTalkRequest(request); status = Toolbox.GetMessageStatus(response); if (status.Status.ToLower() == "error") { fault = new HubFault() { Message = status.Text }; } else { Object obj = Toolbox.GetGovTalkResponse(response, "CompanyNumberSearchResult.xsl", typeof(CompanySearchResult)); } } } catch (FaultException<ArgumentException> ex) { fault = new HubFault() { FaultType = ex.Detail.GetType().FullName, Message = ex.Detail.Message }; } catch (System.Exception ex) { fault = new HubFault() { FaultType = ex.GetType().FullName, Message = ex.Message }; } finally { } Wrap up So there we have it – a reusable set of functions to send and interpret XML results from an internet based service. The code is reusable with a little change with any service which uses XML as a transport mechanism – and as for the Companies House GovTalk service all I need to do is create various objects for the result and message sent and the relevent XSLT files. I might need minor changes for other services but something like 70-90% will be exactly the same.

    Read the article

  • Parsing JSON into XML using Windows Phone

    - by Henry Edwards
    I have this code, but can't get it all working. I am trying to get a json string into xml. So that I can get a list of items when i parse the data. Is there a better way to parse json into xml. If so what's the best way to do it, and if possible could you give me a working example? The URL that is in the code is not the URL that i am using using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using Microsoft.Phone.Controls; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Bson; using System.Xml; using System.Xml.Serialization; using System.Xml.Linq; using System.Xml.Linq.XDocument; using System.IO; namespace WindowsPhonePanoramaApplication3 { public partial class Page2 : PhoneApplicationPage { public Page2() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e1) { /* because the origional JSON string has multiple root's this needs to be added */ string json = "{BFBC2_GlobalStats:"; json += DownlodUrl("http://api.bfbcs.com/api/xbox360?globalstats"); json += "}"; XmlDocument doc = (XmlDocument)JsonConvert.DeserializeObject(json); textBox1.Text = GetXmlString(doc); } private string GetXmlString() { throw new NotImplementedException(); } private string DownlodUrl(string url) { string result = null; try { WebClient client = new WebClient(); result = client.DownloadString(url); } catch (Exception ex) { // handle error result = ex.Message; } return result; } private string GetXmlString(XmlDocument xmlDoc) { sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter(sw); xw.Formatting = System.Xml.Formatting.Indented; xmlDoc.WriteTo(xw); return sw.ToString(); } } } The URL outputs the following code: {"StopName":"Race Hill", "stopId":7553, "NaptanCode":"bridwja", "LongName":"Race Hill", "OperatorsCode1":" 5", "OperatorsCode2":" ", "OperatorsCode3":" ", "OperatorsCode4":"bridwja", "Departures":[ { "ServiceName":"", "Destination":"", "DepartureTimeAsString":"", "DepartureTime":"30/01/2012 00:00:00", "Notes":""}` Thanks for your responses. So Should i just leave the data a json and then view the data via that??? Is this a way to show the data from a json string. public void Load() { // form the URI UriBuilder uri = new UriBuilder("http://mysite.com/events.json"); WebClient proxy = new WebClient(); proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted); proxy.OpenReadAsync(uri.Uri); } void OnReadCompleted(object sender, OpenReadCompletedEventArgs e) { if (e.Error == null) { var serializer = new DataContractJsonSerializer(typeof(EventList)); var events = (EventList)serializer.ReadObject(e.Result); foreach (var ev in events) { Items.Add(ev); } } } public ObservableCollection<EventDetails> Items { get; private set; } Edit: Have now kept the url as json and have now got it working by using the json way.

    Read the article

  • 407 Proxy Authentication Required

    - by Hemant Kothiyal
    I am working on a website, in which I am retrieving XML data from an external URL, using the following code WebRequest req = WebRequest.Create("External server url"); req.Proxy = new System.Net.WebProxy("proxyUrl:8080", true); req.Proxy.Credentials = CredentialCache.DefaultCredentials; WebResponse resp = req.GetResponse(); StreamReader textReader = new StreamReader(resp.GetResponseStream()); XmlTextReader xmlReader = new XmlTextReader(textReader); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlReader); This code is working fine on my development PC (Windows XP with .Net 3.5) But when I deploy this code to IIS (Both at Windows XP and at Windows Server 2003) it's giving me following error "The remote server returned an error: (407) Proxy Authentication Required." Sometimes it gives me "The remote server returned an error: (502) Bad Gateway." Following code is from my web.config <system.net> <defaultProxy> <proxy usesystemdefault="False" proxyaddress ="http://172.16.12.12:8080" bypassonlocal ="True" /> </defaultProxy> </system.net> Please help me ? [Edit] Even when i run the website for devlopment PC but through IIS it gives me error "The remote server returned an error: (407) Proxy Authentication Required." But when i run website from Microsoft Devlopment server, it is running fine

    Read the article

  • Serializing java objects with respect to xml schema loaded at runtime

    - by kohomologie
    I call an XML document three-layered if its structure is laid out as following: the root element contains some container elements (I'll call them entities), each of them has some simpleType elements inside (I'll call them properties). Something like that: <data> <spaceship> <number>1024</number> <name>KTHX</name> </spaceship> <spaceship> <number>1624</number> <name>LEXX</name> </spaceship> <knife> <length>10</length> </knife> </data> where spaceship is an entity, and number is a property. My problem is stated below: Given schema: an arbitrary xsd file describing a three-layered document, loaded at runtime. xmlDocument: an xml document conforming to the schema. Create A Map<String, Map <String, Object>> containing data from the xmlDocument, where first key corresponds to entity, second key correponds to this entity's property, and the value corresponds to this property's value, after casting it to a proper java type (for example, if the schema sets the property value to be xs:int, then it should be cast to Integer). What is the easiest way to achieve this result with existing libraries? P. S. JAXB is not really an option here. The schema might be arbitrary and unknown at compile-time. Also I wish to avoid an excessive use of reflection (associated with converting the beans to maps). I'm looking for something that would allow me to make the typecasts while xml is being parsed.

    Read the article

  • Avoid extra xmlns:xsi while adding an attribute to XML root

    - by Rakesh kumar
    I am creating an xml file using this code: XmlDocument d = new XmlDocument(); XmlDeclaration xmlDeclaration = d.CreateXmlDeclaration("1.0", "utf-8", null); d.InsertBefore(xmlDeclaration,d.DocumentElement); XmlElement root = d.CreateElement("ITRETURN","ITR","http://incometaxindiaefiling.gov.in/ITR1"); XmlAttribute xsiNs = d.CreateAttribute("xsi:schemaLocation", "http://www.w3.org/2001/XMLSchema-instance"); xsiNs.Value = "http://incometaxindiaefiling.gov.in/main ITRMain10.xsd"; root.SetAttributeNode(xsiNs); //root.SetAttribute("xsi:schemaLocation", "http://www.w3.org/2001/XMLSchema-instance"); root.SetAttribute("xmlns:ITR1FORM", "http://incometaxindiaefiling.gov.in/ITR1"); root.SetAttribute("xmlns:ITR2FORM", "http://incometaxindiaefiling.gov.in/ITR2"); root.SetAttribute("xmlns:ITR3FORM", "http://incometaxindiaefiling.gov.in/ITR3"); root.SetAttribute("xmlns:ITR4FORM", "http://incometaxindiaefiling.gov.in/ITR4"); d.AppendChild(root); d.Save("c://myxml.xml"); and I am getting an output like this <?xml version="1.0" encoding="utf-8" ?> - <!-- Sample XML file generated by XMLSpy v2007 sp2 (http://www.altova.com) --> - <ITRETURN:ITR xsi:schemaLocation="http://incometaxindiaefiling.gov.in/main ITRMain10.xsd" xmlns:ITR1FORM="http://incometaxindiaefiling.gov.in/ITR1" xmlns:ITR2FORM="http://incometaxindiaefiling.gov.in/ITR2" xmlns:ITR3FORM="http://incometaxindiaefiling.gov.in/ITR3" xmlns:ITR4FORM="http://incometaxindiaefiling.gov.in/ITR4" xmlns:xsi="http://incometaxindiaefiling.gov.in/main ITRMain10.xsd" xmlns:ITRETURN="http://incometaxindiaefiling.gov.in/ITR1"> <ITR1FORM:ITR1>root node</ITR1FORM:ITR1> </ITRETURN:ITR> But my requirement is like <ITRETURN:ITR xsi:schemaLocation="http://incometaxindiaefiling.gov.in/main ITRMain10.xsd" xmlns:ITR1FORM="http://incometaxindiaefiling.gov.in/ITR1" xmlns:ITR2FORM="http://incometaxindiaefiling.gov.in/ITR2" xmlns:ITR3FORM="http://incometaxindiaefiling.gov.in/ITR3" xmlns:ITR4FORM="http://incometaxindiaefiling.gov.in/ITR4" xmlns:ITRETURN="http://incometaxindiaefiling.gov.in/main" xmlns:ITRForm="http://incometaxindiaefiling.gov.in/master" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <ITR1FORM:ITR1>any value </ITR1FORM:ITR1> </ITRETURN:ITR> What do I need to change in my code to get the desired output?

    Read the article

  • How to catch a Microsoft.SharePoint.SoapServer.SoapServerException?

    - by JL
    I am a bit perplexed on how to catch a specific error type of Microsoft.SharePoint.SoapServer.SoapServerException, I'll explain why, and I've included a code sample below for you guys to see. As you know there are 2 ways to interact with MOSS. The object model (only runs on MOSS Server) Web Services (can be run on a remote machine querying the MOSS server) So as per code sample I'm using web services to query MOSS, because of this I don't have sharepoint installed on the remote server running these web services and without MOSS installed its impossible to reference the SharePoint DLL to get the specific error type : Microsoft.SharePoint.SoapServer.SoapServerException. If I can't reference the DLL then how the heck am I supposed to catch this specific error type? System.Xml.XmlNode ndListView = wsLists.GetListAndView(ListName, ""); string strListID = ndListView.ChildNodes[0].Attributes["Name"].Value; string strViewID = ndListView.ChildNodes[1].Attributes["Name"].Value; System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); System.Xml.XmlElement batchElement = doc.CreateElement("Batch"); batchElement.SetAttribute("OnError", "Continue"); batchElement.SetAttribute("ListVersion", "1"); batchElement.SetAttribute("ViewName", strViewID); batchElement.InnerXml = "<Method ID='1' Cmd='Update'>" + "<Field Name='DeliveryStatus'>" + newStatus.ToString() + "</Field>" + "<Where><Eq><FieldRef Name='ID' /><Value Type='Text'>" + id + "</Value></Eq></Where></Method>"; try { wsLists.UpdateListItems(strListID, batchElement); return true; } catch (Microsoft.SharePoint.SoapServer.SoapServerException ex) { }

    Read the article

  • How to update Properties of Uploaded Documents on Sharepoint using Web Services ? : c#

    - by Preeti
    Hi, I am trying to Update/Edit Properties of Uploaded Document on Sharepoint 2007. My code: Lists listService = new Lists(); listService.PreAuthenticate = true; listService.Credentials = new NetworkCredential(username,password); listService.Url = "http://myserver/SiteName/_vti_bin/lists.asmx"; string strBatch = "<Method ID='1' Cmd='Update'> " + " <Field Name='ID'>3</Field> " + " <Field Name='Name'>Preeti</Field> " + " </Method> "; XmlDocument xmlDoc = new System.Xml.XmlDocument(); System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch"); elBatch.SetAttribute("OnError", "Continue"); elBatch.SetAttributeNode("UserName", "Preeti"); elBatch.InnerXml = strBatch; XmlNode ndReturn = listService.UpdateListItems(ListName, elBatch); MessageBox.Show(ndReturn.OuterXml); Refering Link. Getting Error: "One or more field types are not installed properly. Go to the list settings page to delete these fields". Regards, Preeti

    Read the article

  • not able to Deserialize xml into object

    - by Ravisha
    I am having following peice of code ,where in i am trying to serialize and deserailize object of StringResource class. Please note Resource1.stringXml = its coming from resource file.If i pass strelemet.outerXMl i get the object from Deserialize object ,but if i pass Resource1.stringXml i am getting following exception {"< STRING xmlns='' was not expected."} System.Exception {System.InvalidOperationException} class Program { static void Main(string[] args) { StringResource str = new StringResource(); str.DELETE = "CanDelete"; str.ID= "23342"; XmlElement strelemet = SerializeObjectToXmlNode (str); StringResource strResourceObject = DeSerializeXmlNodeToObject<StringResource>(Resource1.stringXml); Console.ReadLine(); } public static T DeSerializeXmlNodeToObject<T>(string objectNodeOuterXml) { try { TextReader objStringsTextReader = new StringReader(objectNodeOuterXml); XmlSerializer stringResourceSerializer = new XmlSerializer(typeof(T),string.Empty); return (T)stringResourceSerializer.Deserialize(objStringsTextReader); } catch (Exception excep) { return default(T); } } public static XmlElement SerializeObjectToXmlNode(object obj) { using (MemoryStream memoryStream = new MemoryStream()) { try { XmlSerializerNamespaces xmlNameSpace = new XmlSerializerNamespaces(); xmlNameSpace.Add(string.Empty, string.Empty); XmlWriterSettings writerSettings = new XmlWriterSettings(); writerSettings.CloseOutput = false; writerSettings.Encoding = System.Text.Encoding.UTF8; writerSettings.Indent = false; writerSettings.OmitXmlDeclaration = true; XmlWriter writer = XmlWriter.Create(memoryStream, writerSettings); XmlSerializer xmlserializer = new XmlSerializer(obj.GetType()); xmlserializer.Serialize(writer, obj, xmlNameSpace); writer.Close(); memoryStream.Position = 0; XmlDocument serializeObjectDoc = new XmlDocument(); serializeObjectDoc.Load(memoryStream); return serializeObjectDoc.DocumentElement; } catch (Exception excep) { return null; } } } } public class StringResource { [XmlAttribute] public string DELETE; [XmlAttribute] public string ID; } < STRING ID="1" DELETE="True" /

    Read the article

  • ASP.Net menu databinding encoding problem

    - by WtFudgE
    Hi, I have a menu where I bind data through: XmlDataSource xmlData = new XmlDataSource(); xmlData.DataFile = String.Format(@"{0}{1}\Navigation.xml", getXmlPath(), getLanguage()); xmlData.XPath = @"/Items/Item"; TopNavigation.DataSource = xmlData; TopNavigation.DataBind(); The problem is when my xml has special characters, since I use a lot of french words. As an alternative I tried using a stream instead and using encoding to get the special characters, with the following code: StreamReader strm = new StreamReader(String.Format(@"{0}{1}\Navigation.xml", getXmlPath(), getLanguage()), Encoding.GetEncoding(1254)); XmlDocument xDoc = new XmlDocument(); xDoc.Load(strm); XmlDataSource xmlData = new XmlDataSource(); xmlData.ID = "TopNav"; xmlData.Data = xDoc.InnerXml; xmlData.XPath = @"/Items/Item"; TopNavigation.Items.Clear(); TopNavigation.DataSource = xmlData; TopNavigation.DataBind(); The problem I'm having now is that my data doesn't refresh when I change the path where the stream gets read. When I skip through the code it does, but not on my page. So the thing is either, how do I get the data te be refreshed? Or (which is actually preferred) how do I get the encoding right in the first piece of code? Help is highly apreciated!

    Read the article

  • best practice for directory polling

    - by Hieu Lam
    Hi all, I have to do batch processing to automate business process. I have to poll directory at regular interval to detect new files and do processing. While old files is being processed, new files can come in. For now, I use quartz scheduler and thread synchronization to ensure that only one thread can process files. Part of the code are: application-context.xml <bean id="methodInvokingJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean" <property name="targetObject" ref="documentProcessor" / <property name="targetMethod" value="processDocuments" / </bean DocumentProcessor ..... public void processDocuments() { LOG.info(Thread.currentThread().getName() + " attempt to run."); if (!processing) { synchronized (this) { try { processing = true; LOG.info(Thread.currentThread().getName() + " is processing"); List xmlDocuments = documentManager.getFileNamesFromFolder(incomingFolderPath); // loop over the files and processed unlock files. for (String xmlDocument : xmlDocuments) { processDocument(xmlDocument); } } finally { processing = false; } } } } For the current code, I have to prevent other thread to process files when one thread is processing. Is that a good idea ? or we support multi-threaded processing. In that case how can I know which files is being process and which files has just arrived ? Any idea is really appreciated.

    Read the article

  • Changing App.config at Runtime

    - by born to hula
    I'm writing a test winforms / C# / .NET 3.5 application for the system we're developing and we fell in the need to switch between .config files at runtime, but this is turning out to be a nightmare. Here's the scene: the Winforms application is aimed at testing a WebApp, divided into 5 subsystems. The test proccess works with messages being sent between the subsystems, and for this proccess to be sucessful each subsystem got to have its own .config file. For my Test Application I wrote 5 separate configuration files. I wish I was able to switch between these 5 files during runtime, but the problem is: I can programatically edit the application .config file inumerous times, but these changes will only take effect once. I've been searching a long time for a form to address this problem but I still wasn't sucessful. I know the problem definition may be a bit confusing but I would really appreciate it if someone helped me. Thanks in advance! --- UPDATE 01-06-10 --- There's something I didn't mention before. Originally, our system is a Web Application with WCF calls between each subsystem. For performance testing reasons (we're using ANTS 4), we had to create a local copy of the assemblies and reference them from the test project. It may sound a bit wrong, but we couldn't find a satisfying way to measure performance of a remote application. --- End Update --- Here's what I'm doing: public void UpdateAppSettings(string key, string value) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); foreach (XmlElement item in xmlDoc.DocumentElement) { foreach (XmlNode node in item.ChildNodes) { if (node.Name == key) { node.Attributes[0].Value = value; break; } } } xmlDoc.Save(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile); System.Configuration.ConfigurationManager.RefreshSection("section/subSection"); }

    Read the article

  • XmlNode.SelectNode with multiple attribute.

    - by kapil
    One of my nodes inmy xml file is as follows. <LOGIN_ID NAME="Kapil"> <SEARCH_ID>Kapil Koli</SEARCH_ID> <GUID>111</GUID> <FIRST_NAME>Kapil</FIRST_NAME> <LAST_NAME>Koli</LAST_NAME> <EMAIL_ID>[email protected]</EMAIL_ID> <PASSWORD>abc123**</PASSWORD> </LOGIN_ID> The code I am using is - XmlDocument document = new XmlDocument(); document.Load(_XmlFileName); nodeList = document.SelectNode."USERS/LOGIN_ID[contains(SEARCH_ID,'Kapil')"; nodeList = document.SelectNode."USERS/LOGIN_ID[contains(EMAIL_ID,'[email protected]')"; I want to use select node which will accept search_id and login_id as attributes to search? If either search_id or email_id is wrong, I want to return null. How could I do this? thanks. kapil.

    Read the article

  • Programmatically call webmethods in C#

    - by hancock
    I'm trying to write a function that can call a webmethod from a webserive given the method's name and URL of the webservice. I've found some code on a blog that does this just fine except for one detail. It requires that the request XML be provided as well. The goal here is to get the request XML template from the webservice itself. I'm sure this is possible somehow because I can see both the request and response XML templates if I access a webservice's URL in my browser. This is the code which calls the webmethod programmatically: XmlDocument doc = new XmlDocument(); //this is the problem. I need to get this automatically doc.Load("../../request.xml"); HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld"); req.ContentType = "text/xml;charset=\"utf-8\""; req.Accept = "text/xml"; req.Method = "POST"; Stream stm = req.GetRequestStream(); doc.Save(stm); stm.Close(); WebResponse resp = req.GetResponse(); stm = resp.GetResponseStream(); StreamReader r = new StreamReader(stm); Console.WriteLine(r.ReadToEnd());

    Read the article

  • How do you pass .net objects values around in F#?

    - by Russell
    I am currently learning F# and functional programming in general (from a C# background) and I have a question about using .net CLR objects during my processing. The best way to describe my problem will be to give an example: let xml = new XmlDocument() |> fun doc -> doc.Load("report.xml"); doc let xsl = new XslCompiledTransform() |> fun doc -> doc.Load("report.xsl"); doc let transformedXml = new MemoryStream() |> fun mem -> xsl.Transform(xml.CreateNavigator(), null, mem); mem This code transforms an XML document with an XSLT document using .net objects. Note XslCompiledTransform.Load works on an object, and returns void. Also the XslCompiledTransform.Transform requires a memorystream object and returns void. The above strategy used is to add the object at the end (the ; mem) to return a value and make functional programming work. When we want to do this one after another we have a function on each line with a return value at the end: let myFunc = new XmlDocument("doc") |> fun a -> a.Load("report.xml"); a |> fun a -> a.AppendChild(new XmlElement("Happy")); a Is there a more correct way (in terms of functional programming) to handle .net objects and objects that were created in a more OO environment? The way I returned the value at the end then had inline functions everywhere feels a bit like a hack and not the correct way to do this. Any help is greatly appreciated!

    Read the article

  • Data Contract Serialization Not Working For All Elements

    - by splatto
    I have an XML file that I'm trying to serialize into an object. Some elements are being ignored. My XML File: <?xml version="1.0" encoding="utf-8" ?> <License xmlns="http://schemas.datacontract.org/2004/07/MyApp.Domain"> <Guid>7FF07F74-CD5F-4369-8FC7-9BF50274A8E8</Guid> <Url>http://www.gmail.com</Url> <ValidKey>true</ValidKey> <CurrentDate>3/1/2010 9:39:28 PM</CurrentDate> <RegistrationDate>3/8/2010 9:39:28 PM</RegistrationDate> <ExpirationDate>3/8/2099 9:39:28 PM</ExpirationDate> </License> My class definition: [DataContract] public class License { [DataMember] public virtual int Id { get; set; } [DataMember] public virtual string Guid { get; set; } [DataMember] public virtual string ValidKey { get; set; } [DataMember] public virtual string Url { get; set; } [DataMember] public virtual string CurrentDate { get; set; } [DataMember] public virtual string RegistrationDate { get; set; } [DataMember] public virtual string ExpirationDate { get; set; } } And my Serialization attempt: XmlDocument Xmldoc = new XmlDocument(); Xmldoc.Load(string.Format(url)); string xml = Xmldoc.InnerXml; var serializer = new DataContractSerializer(typeof(License)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)); License license = (License)serializer.ReadObject(memoryStream); memoryStream.Close(); The following elements are serialized: Guid ValidKey The following elements are not serialized: Url CurrentDate RegistrationDate ExpirationDate Replacing the string dates in the xml file with "blah" doesn't work either. What gives?

    Read the article

  • XML Serialization Not Working For All Elements (C#)

    - by splatto
    I have an XML file that I'm trying to serialize into an object. Some elements are being ignored. My XML File: <?xml version="1.0" encoding="utf-8" ?> <License xmlns="http://schemas.datacontract.org/2004/07/MyApp.Domain"> <Guid>7FF07F74-CD5F-4369-8FC7-9BF50274A8E8</Guid> <Url>http://www.gmail.com</Url> <ValidKey>true</ValidKey> <CurrentDate>3/1/2010 9:39:28 PM</CurrentDate> <RegistrationDate>3/8/2010 9:39:28 PM</RegistrationDate> <ExpirationDate>3/8/2099 9:39:28 PM</ExpirationDate> </License> My class definition: [DataContract] public class License { [DataMember] public virtual int Id { get; set; } [DataMember] public virtual string Guid { get; set; } [DataMember] public virtual string ValidKey { get; set; } [DataMember] public virtual string Url { get; set; } [DataMember] public virtual string CurrentDate { get; set; } [DataMember] public virtual string RegistrationDate { get; set; } [DataMember] public virtual string ExpirationDate { get; set; } } And my Serialization attempt: XmlDocument Xmldoc = new XmlDocument(); Xmldoc.Load(string.Format(url)); string xml = Xmldoc.InnerXml; var serializer = new DataContractSerializer(typeof(License)); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)); License license = (License)serializer.ReadObject(memoryStream); memoryStream.Close(); The following elements are serialized: Guid ValidKey The following elements are not serialized: Url CurrentDate RegistrationDate ExpirationDate Replacing the string dates in the xml file with "blah" doesn't work either. What gives?

    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
    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

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