public void TestCanLoadXmlFromDiskWithUtf8BomInMemory() { Assert.DoesNotThrow(delegate() { XmlUtilities.CreateDocument(Resources.Utf8Bom); XmlUtilities.CreateDocument(Encoding.UTF8.GetBytes(Resources.Utf8Bom)); }); }
/// <summary> /// Parses the error response into an exception. /// </summary> /// <param name="exception">The original exception.</param> /// <param name="contents">The errors XML.</param> /// <returns>An AdWords Reports exception that represents the error.</returns> private AdWordsReportsException ParseException(Exception exception, string contents) { List <ReportDownloadError> errorList = new List <ReportDownloadError>(); try { XmlDocument xDoc = XmlUtilities.CreateDocument(contents); XmlNodeList errorNodes = xDoc.DocumentElement.SelectNodes("ApiError"); foreach (XmlElement errorNode in errorNodes) { ReportDownloadError downloadError = new ReportDownloadError(); downloadError.ErrorType = errorNode.SelectSingleNode("type").InnerText; downloadError.FieldPath = errorNode.SelectSingleNode("fieldPath").InnerText; downloadError.Trigger = errorNode.SelectSingleNode("trigger").InnerText; errorList.Add(downloadError); } } catch { } AdWordsReportsException retval = new AdWordsReportsException(this.reportVersion, AdWordsErrorMessages.ReportingExceptionOccurred, exception); retval.Errors = errorList.ToArray(); return(retval); }
/// <summary> /// Gets the summary request logs. /// </summary> /// <param name="soapRequest">The request xml for this SOAP call.</param> /// <returns>The summary request logs.</returns> protected override string GetSummaryRequestLogs(string soapRequest) { XmlDocument xDoc = XmlUtilities.CreateDocument(soapRequest); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); XmlNode methodNode = xDoc.SelectSingleNode("soap:Envelope/soap:Body/*", xmlns); string operators = "None"; if (methodNode.Name == "mutate") { StringBuilder builder = new StringBuilder(); foreach (XmlNode child in methodNode.ChildNodes) { if (child.Name == "operations") { foreach (XmlNode grandChild in child.ChildNodes) { if (grandChild.Name == "operator") { builder.Append(grandChild.InnerText + "|"); } } } } operators = builder.ToString().TrimEnd('|'); } return(string.Format(CultureInfo.InvariantCulture, "method={0},operator={1}", methodNode.Name, operators)); }
/// <summary> /// Masks the contents of the traced message. /// </summary> /// <param name="body">The message body.</param> /// <param name="keysToMask">The keys for which values should be masked /// in the message body.</param> /// <returns> /// The formatted message body. /// </returns> public override string MaskContents(string body, ISet <string> keysToMask) { if (keysToMask.Count == 0) { return(body); } XmlDocument xDoc = XmlUtilities.CreateDocument(body); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); foreach (string key in keysToMask) { string xPath = string.Format("soap:Envelope/descendant::*[local-name()='{0}']", key); XmlNodeList nodes = xDoc.SelectNodes(xPath, xmlns); foreach (XmlElement node in nodes) { node.InnerText = MASK_PATTERN; } } // Pretty-print the XML. StringBuilder sb = new StringBuilder(); using (XmlWriter xmlWriter = XmlWriter.Create(sb, XmlWriterSettings)) { xDoc.WriteContentTo(xmlWriter); } return(sb.ToString()); }
public void TestCallEntryExtractedFromXml() { AdWordsUser user = new AdWordsUser(); AdWordsSoapHeaderInspector inspector = new AdWordsSoapHeaderInspector() { User = user }; XmlDocument xDoc = XmlUtilities.CreateDocument(SoapMessages_v201708.UpdateCampaign); XmlElement xResponse = (XmlElement)xDoc.SelectSingleNode("/Example/SOAP/Response"); xDoc.LoadXml(xResponse.InnerText); this.response = Message.CreateMessage(new XmlNodeReader(xDoc), Int32.MaxValue, TestMessageVersion); inspector.AfterReceiveReply(ref this.response, null); // API no longer returns operation count. Assert.AreEqual(user.GetTotalOperationCount(), 0); Assert.AreEqual(user.GetOperationCountForLastCall(), 0); ApiCallEntry[] callEntries = user.GetCallDetails(); Assert.AreEqual(callEntries.Length, 1); ApiCallEntry callEntry = user.GetCallDetails()[0]; Assert.AreEqual(0, callEntry.OperationCount); Assert.AreEqual("mutate", callEntry.Method); Assert.AreEqual("CampaignService", callEntry.Service); }
public void TestHandleMessage() { try { ContextStore.AddKey("SoapMethod", "mutate"); XmlDocument xDoc = XmlUtilities.CreateDocument(SoapMessages_v201609.UpdateCampaign); XmlElement xRequest = (XmlElement)xDoc.SelectSingleNode("/Example/SOAP/Response"); xDoc.LoadXml(xRequest.InnerText); CampaignService service = (CampaignService)user.GetService( AdWordsService.v201609.CampaignService); AdWordsCallListener.Instance.HandleMessage(xDoc, service, SoapMessageDirection.IN); // API no longer returns operation count. Assert.AreEqual(user.GetTotalOperationCount(), 0); Assert.AreEqual(user.GetOperationCountForLastCall(), 0); ApiCallEntry[] callEntries = user.GetCallDetails(); Assert.AreEqual(callEntries.Length, 1); ApiCallEntry callEntry = user.GetCallDetails()[0]; // API no longer returns operation count. Assert.AreEqual(callEntry.OperationCount, 0); Assert.AreEqual(callEntry.Method, "mutate"); Assert.AreEqual(callEntry.Service.Signature.ServiceName, "CampaignService"); } finally { ContextStore.RemoveKey("SoapMethod"); } }
public void TestNoXxeTranslation() { XmlDocument xDoc = XmlUtilities.CreateDocument(Resources.XxeExample); string temp = xDoc.OuterXml; Assert.That(temp.Contains("file:///c:/boot.ini")); }
public void TestAdManagerApiExceptionForFault() { SoapFaultInspector <AdManagerApiException> inspector = new SoapFaultInspector <AdManagerApiException>() { ErrorType = typeof(AdManager.v202202.ApiException) }; XmlDocument xDoc = XmlUtilities.CreateDocument(fault_xml); Message message = Message.CreateMessage(new XmlNodeReader(xDoc), Int32.MaxValue, TestMessageVersion); AdManagerApiException exception = Assert.Throws <AdManagerApiException>( delegate() { inspector.AfterReceiveReply(ref message, this.channel); }, "No exception was thrown for a SOAP Fault response"); Assert.AreEqual(typeof(ApiException), exception.ApiException.GetType()); ApiException apiException = (ApiException)exception.ApiException; Assert.AreEqual(1, apiException.errors.Length); Assert.AreEqual(typeof(PublisherQueryLanguageContextError), apiException.errors[0].GetType()); PublisherQueryLanguageContextError error = (PublisherQueryLanguageContextError)apiException.errors[0]; Assert.AreEqual(PublisherQueryLanguageContextErrorReason.UNEXECUTABLE, error.reason); Assert.AreEqual("Mapping requested for unknown identifer", error.fieldPath); }
/// <summary> /// Verifies the SOAP headers. /// </summary> /// <param name="requestUri">The request URI.</param> /// <param name="requestBody">The request body.</param> protected void VerifySoapHeaders(Uri requestUri, string requestBody) { AdWordsAppConfig config = user.Config as AdWordsAppConfig; if (requestUri.AbsoluteUri.StartsWith(config.AdWordsApiServer)) { XmlDocument xDoc = XmlUtilities.CreateDocument(requestBody); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); XmlElement requestHeaders = (XmlElement)xDoc.SelectSingleNode("soap:Envelope/soap:Header/child::*", xmlns); Assert.NotNull(requestHeaders); Assert.AreEqual(requestHeaders.Name, "RequestHeader"); foreach (XmlElement childNode in requestHeaders.ChildNodes) { switch (childNode.Name) { case "developerToken": Assert.AreEqual(childNode.InnerText, config.DeveloperToken); break; case "clientCustomerId": Assert.AreEqual(childNode.InnerText, config.ClientCustomerId); break; case "userAgent": Assert.AreEqual(childNode.InnerText, config.GetUserAgent()); break; } } } }
public void TestMaskContents() { string maskedBody = new SoapTraceFormatter().MaskContents(Resources.SoapRequest, KEYS); XmlDocument xDoc = XmlUtilities.CreateDocument(maskedBody); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); xmlns.AddNamespace("cm", "https://adwords.google.com/api/adwords/cm/v201409"); // Test masking on header nodes. XmlNodeList childNodes = xDoc.SelectNodes( "soap:Envelope/soap:Header/cm:RequestHeader/child::*", xmlns); foreach (XmlElement childNode in childNodes) { if (KEYS.Contains(childNode.LocalName)) { Assert.AreEqual(childNode.InnerText, SoapTraceFormatter.MASK_PATTERN); } } // Test masking on body nodes. childNodes = xDoc.SelectNodes("soap:Envelope/soap:Body/cm:get/child::*", xmlns); foreach (XmlElement childNode in childNodes) { if (KEYS.Contains(childNode.LocalName)) { Assert.AreEqual(childNode.InnerText, SoapTraceFormatter.MASK_PATTERN); } } }
/// <summary> /// Deserialize the object from xml. /// </summary> /// <param name="reader">The xml reader for reading the /// serialized xml.</param> public virtual void ReadXml(XmlReader reader) { XmlDocument doc = XmlUtilities.CreateDocument(reader.ReadOuterXml()); XmlNameTable xmlnt = doc.NameTable; XmlElement root = doc.CreateElement(XmlElementName, XmlNamespace); XmlNodeList xmlNodes = doc.DocumentElement.SelectNodes("*"); foreach (XmlNode node in xmlNodes) { root.AppendChild(node); } doc.RemoveAll(); doc.AppendChild(root); string contents = doc.OuterXml; foreach (string key in placeHolders.Keys) { if (placeHolders[key] != null) { contents = contents.Replace(placeHolders[key], key); } } Stub = SerializationUtilities.DeserializeFromXmlText(contents, Stub.GetType()); }
public void TestAdWordsApiExceptionForFault() { SoapFaultInspector <AdWordsApiException> inspector = new SoapFaultInspector <AdWordsApiException>() { ErrorType = typeof(ApiException) }; foreach (string faultXml in faultXmls) { XmlDocument xDoc = XmlUtilities.CreateDocument(faultXml); Message message = Message.CreateMessage(new XmlNodeReader(xDoc), Int32.MaxValue, TestMessageVersion); AdWordsApiException exception = Assert.Throws <AdWordsApiException>( delegate() { inspector.AfterReceiveReply(ref message, this.channel); }, "No exception was thrown for a SOAP Fault response"); Assert.AreEqual(typeof(ApiException), exception.ApiException.GetType()); ApiException apiException = (ApiException)exception.ApiException; Assert.AreEqual(1, apiException.errors.Length); Assert.AreEqual(typeof(AuthenticationError), apiException.errors[0].GetType()); AuthenticationError error = (AuthenticationError)apiException.errors[0]; Assert.AreEqual(AuthenticationErrorReason.CUSTOMER_NOT_FOUND, error.reason); } }
/// <summary> /// Gets the summary request logs. /// </summary> /// <param name="soapRequest">The request xml for this SOAP call.</param> /// <returns>The summary request logs.</returns> protected override string GetSummaryRequestLogs(string soapRequest) { XmlDocument xDoc = XmlUtilities.CreateDocument(soapRequest); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); XmlNode methodNode = xDoc.SelectSingleNode("soap:Envelope/soap:Body/*", xmlns); return(string.Format("method={0}", methodNode.Name)); }
/// <summary> /// Converts the report definition to XML format. /// </summary> /// <param name="definition">The report definition.</param> /// <returns>The report definition serialized as an XML string.</returns> private string ConvertDefinitionToXml(IReportDefinition definition) { string xml = SerializationUtilities.SerializeAsXmlText(definition).Replace( "ReportDefinition", "reportDefinition"); XmlDocument doc = XmlUtilities.CreateDocument(xml); XmlNodeList xmlNodes = doc.SelectNodes("descendant::*"); foreach (XmlElement node in xmlNodes) { node.RemoveAllAttributes(); } return(doc.OuterXml); }
public void TestCanLoadXmlFromDiskWithUtf8Bom() { string path = Path.GetTempFileName(); using (FileStream fs = File.Create(path)) { fs.Write(Resources.Utf8Bom, 0, Resources.Utf8Bom.Length); } using (FileStream fs = File.OpenRead(path)) { Assert.DoesNotThrow(delegate() { XmlUtilities.CreateDocument(fs); }); } }
/// <summary> /// Parses the XML response from the server into a type object. /// </summary> /// <typeparam name="T">The type of the object.</typeparam> /// <param name="contents">The XML contents.</param> /// <returns>The parsed object</returns> protected T ParseResponse <T>(string contents) { XmlDocument xDoc = XmlUtilities.CreateDocument(contents); string wrappedXml = string.Format(@" <?xml version='1.0' encoding='UTF-8'?> <root xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'> {0} </root>", xDoc.DocumentElement.OuterXml).Trim(); return((T)SerializationUtilities.DeserializeFromXmlText(wrappedXml, typeof(T))); }
/// <summary> /// Parses the body of the request and populates fields in the request info. /// </summary> /// <param name="info">The request info for this SOAP call.</param> protected virtual void PopulateRequestInfo(ref RequestInfo info) { XmlDocument xDoc = XmlUtilities.CreateDocument(info.Body); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); // Retrieve method. XmlNode methodNode = xDoc.SelectSingleNode("soap:Envelope/soap:Body/*", xmlns); if (methodNode != null) { info.Method = methodNode.Name; } }
/// <summary> /// Loads the mock data for a code example. /// </summary> /// <param name="mockData">The mock data.</param> /// <returns>The parsed mock data.</returns> protected ExamplesMockData LoadMockData(string mockData) { List <HttpMessage> messages = new List <HttpMessage>(); XmlDocument xDoc = XmlUtilities.CreateDocument(mockData); XmlNodeList soapNodes = xDoc.SelectNodes("Example/SOAP"); foreach (XmlElement soapNode in soapNodes) { messages.Add(new HttpMessage(soapNode.SelectSingleNode("Request").InnerText, soapNode.SelectSingleNode("Response").InnerText, AdWordsRequestInterceptor.SOAP_RESPONSE_TYPE)); } return(new ExamplesMockData(messages.ToArray(), xDoc.SelectSingleNode("Example/Output"). InnerText)); }
/// <summary> /// Serialize the object into an xml. /// </summary> /// <param name="writer">The writer to which the serialized data /// should be written.</param> public virtual void WriteXml(XmlWriter writer) { string contents = SerializationUtilities.SerializeAsXmlText(Stub); foreach (string key in placeHolders.Keys) { if (placeHolders[key] != null) { contents = contents.Replace(key, placeHolders[key]); } } XmlDocument xDoc = XmlUtilities.CreateDocument(contents); writer.WriteRaw(xDoc.DocumentElement.InnerXml); }
/// <summary> /// Calls the listeners. /// </summary> /// <param name="direction">The direction of SOAP message.</param> private void CallListeners(SoapMessageDirection direction) { XmlDocument document = XmlUtilities.CreateDocument(Encoding.UTF8.GetString( newStream.ToArray())); AdsClient service = (AdsClient)ContextStore.GetValue("SoapService"); if (service != null) { service.User.CallListeners(document, service, direction); } byte[] bytes = Encoding.UTF8.GetBytes(document.OuterXml); newStream.SetLength(0); newStream.Write(bytes, 0, bytes.Length); newStream.Seek(0, SeekOrigin.Begin); }
/// <summary> /// Verifies whether UpdateCampaign example is serializing the request /// correctly. /// </summary> /// <param name="requestUri">The request URI.</param> /// <param name="headers">The headers.</param> /// <param name="body">The body.</param> private void VerifyUpdateCampaignRequest(Uri requestUri, WebHeaderCollection headers, string body) { XmlDocument doc = XmlUtilities.CreateDocument(body); XmlElement node = (XmlElement)doc.GetElementsByTagName("operations")[0]; CampaignOperation campaignOperation = (CampaignOperation)SerializationUtilities.DeserializeFromXmlTextCustomRootNs( node.OuterXml, typeof(CampaignOperation), "https://adwords.google.com/api/adwords/cm/v201605", "operations"); Assert.AreEqual(campaignOperation.@operator, Operator.SET); Campaign campaign = campaignOperation.operand; Assert.AreEqual(campaign.id, 12345); Assert.AreEqual(campaign.status, CampaignStatus.PAUSED); }
public void TestHandleMessageNoClient() { config.SetPropertyFieldForTests("MaskCredentials", true); listener = new MockTraceListener(config); XmlDocument xOutgoing = XmlUtilities.CreateDocument(Resources.XmlRequest); listener.HandleMessage(xOutgoing, null, SoapMessageDirection.OUT); Assert.AreEqual(xOutgoing.OuterXml, ContextStore.GetValue("SoapRequest")); XmlDocument xIncoming = XmlUtilities.CreateDocument(Resources.XmlResponse); listener.HandleMessage(xIncoming, null, SoapMessageDirection.IN); Assert.AreEqual(xIncoming.OuterXml, ContextStore.GetValue("SoapResponse")); Assert.IsNull(ContextStore.GetValue("FormattedSoapLog")); Assert.IsNull(ContextStore.GetValue("FormattedRequestLog")); }
/// <summary> /// Masks the contents of the traced message. /// </summary> /// <param name="body">The message body.</param> /// <param name="keysToMask">The keys for which values should be masked /// in the message body.</param> /// <returns> /// The formatted message body. /// </returns> public override string MaskContents(string body, ISet <string> keysToMask) { XmlDocument xDoc = XmlUtilities.CreateDocument(body); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); XmlNodeList nodes = xDoc.SelectNodes("soap:Envelope/soap:Header/descendant::*", xmlns); foreach (XmlElement node in nodes) { if (keysToMask.Contains(node.LocalName)) { node.InnerText = MASK_PATTERN; } } return(xDoc.OuterXml); }
public void TestHandleMessage() { config.SetPropertyFieldForTests("MaskCredentials", true); listener = new MockTraceListener(config); XmlDocument xOutgoing = XmlUtilities.CreateDocument(Resources.XmlRequest); listener.HandleMessage(xOutgoing, adsClient, SoapMessageDirection.OUT); Assert.AreEqual(xOutgoing.OuterXml, ContextStore.GetValue("SoapRequest")); XmlDocument xIncoming = XmlUtilities.CreateDocument(Resources.XmlResponse); listener.HandleMessage(xIncoming, adsClient, SoapMessageDirection.IN); Assert.AreEqual(xIncoming.OuterXml, ContextStore.GetValue("SoapResponse")); string expected = Resources.SoapLog.Replace("\r\n", "\n").Trim(); string actual = ((string)ContextStore.GetValue("FormattedSoapLog")). Replace("\r\n", "\n").Trim(); Assert.AreEqual(expected, actual); Assert.AreEqual(Resources.ResponseLog.Replace("\r\n", "\n"), ((string)ContextStore.GetValue("FormattedRequestLog")).Replace("\r\n", "\n")); }
/// <summary> /// Parses the body of the response and populates fields in the repsonse info. /// </summary> /// <param name="info">The response info for this SOAP call.</param> protected virtual void PopulateResponseInfo(ref ResponseInfo info) { XmlDocument xDoc = XmlUtilities.CreateDocument(info.Body); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); // Retrieve loggable headers. XmlNode headerNode = xDoc.SelectSingleNode("soap:Envelope/soap:Header/*", xmlns); if (headerNode != null && headerNode.Name == "ResponseHeader") { info.RequestId = RetrieveLoggableHeader(headerNode, "requestId"); long operations; if (long.TryParse(RetrieveLoggableHeader(headerNode, "operations"), out operations)) { info.OperationCount = operations; } long responseTime; if (long.TryParse(RetrieveLoggableHeader(headerNode, "responseTime"), out responseTime)) { info.ResponseTimeMs = responseTime; } } //Retrieve fault string (if one exists). XmlNode faultNode = xDoc.SelectSingleNode("soap:Envelope/soap:Body/soap:Fault/faultstring", xmlns); if (faultNode != null) { info.ErrorMessage = faultNode.InnerText; } }
/// <summary> /// Masks the contents of the traced message. /// </summary> /// <param name="body">The message body.</param> /// <param name="keysToMask">The keys for which values should be masked /// in the message body.</param> /// <returns> /// The formatted message body. /// </returns> public override string MaskContents(string body, ISet <string> keysToMask) { if (keysToMask.Count == 0) { return(body); } XmlDocument xDoc = XmlUtilities.CreateDocument(body); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); foreach (string key in keysToMask) { string xPath = string.Format("soap:Envelope/descendant::*[local-name()='{0}']", key); XmlNodeList nodes = xDoc.SelectNodes(xPath, xmlns); foreach (XmlElement node in nodes) { node.InnerText = MASK_PATTERN; } } return(xDoc.OuterXml); }
/// <summary> /// Gets the summary response logs. /// </summary> /// <param name="soapResponse">The response xml for this SOAP call.</param> /// <returns>The summary response logs.</returns> protected override string GetSummaryResponseLogs(string soapResponse) { XmlDocument xDoc = XmlUtilities.CreateDocument(soapResponse); XmlNamespaceManager xmlns = new XmlNamespaceManager(xDoc.NameTable); xmlns.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); XmlNodeList childNodes = xDoc.SelectNodes("soap:Envelope/soap:Header/*", xmlns); if (childNodes.Count == 1 && childNodes[0].Name == "ResponseHeader") { childNodes = childNodes[0].ChildNodes; } StringBuilder responseText = new StringBuilder(); foreach (XmlNode childNode in childNodes) { if (childNode is XmlElement) { responseText.AppendFormat("{0}={1},", childNode.Name, childNode.InnerText); } } return(responseText.ToString().TrimEnd(',')); }
public void TestNoXxeTranslation() { Assert.Throws <XmlException>(delegate() { XmlDocument xDoc = XmlUtilities.CreateDocument(Resources.XxeExample); }); }