DocuSign Connect Listener MVC5 Api - asp.net-mvc

I have the following MVC 5 Rest Controller:
namespace Rest4.Controllers
{
public class DocuSignController : ApiController
{
// POST api/docusign
public void Post([FromBody]DocuSignAPI.DocuSignEnvelopeInformation DocuSignEnvelopeInformation)
{
try
{
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(DocuSignAPI.DocuSignEnvelopeInformation));
XmlSerializer serializer = new XmlSerializer(typeof(DocuSignAPI.DocuSignEnvelopeInformation));
StringBuilder sb = new StringBuilder();
using (StringWriter writer = new StringWriter(sb))
{
serializer.Serialize(writer, DocuSignEnvelopeInformation);
}
string fileName = DateTime.Now.Ticks.ToString();
using (StreamWriter outputFile = new StreamWriter(string.Format(#"c:\clientuploads\{0}.xml", fileName)))
{
outputFile.WriteLine(sb.ToString());
outputFile.WriteLine("Nothing to see here");
}
}
catch { }
}
However, when I go to the DocuSign Connect Settings and try to send the same, all I get is:
<?xml version="1.0" encoding="utf-16"?>
<DocuSignEnvelopeInformation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xsi:nil="true" />
Nothing to see here
However, if I look at the logs on the DocuSign site:
1/28/2016 8:49:56 PM Connect send to: http://somewhere.com/Rest/api/DocuSign
1/28/2016 8:49:56 PM Envelope Data (documents were included):<?xml version="1.0" encoding="utf-8"?><DocuSignEnvelopeInformation xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.docusign.net/API/3.0"><EnvelopeStatus><RecipientStatuses><RecipientStatus><Type>Signer</Type><Email>someemailaddress</Email><UserName>somebody</UserName><RoutingOrder>1</RoutingOrder><Sent>2016-01-13T10:35:11.16</Sent>....<Sequence>4</Sequence></DocumentStatus></DocumentStatuses></EnvelopeStatus></DocuSignEnvelopeInformation>
So, why is the document I get from DocuSign empty? Is there a better way to capture the info? If I try Post([FromBody]string DocuSignEnvelopeInformation) instead, I get a 500 Error on the DocuSign site

Did you specify the default name space while initializing serializer as follows.
XmlSerializer serializer = new XmlSerializer(typeof(DocuSignEnvelopeInformation), "http://www.docusign.net/API/3.0");
DocuSignEnvelopeInformation envelopeInfo = serializer.Deserialize(reader) as DocuSignEnvelopeInformation;

Related

"Response status code does not indicate success: 500 (Internal Server Error)" while creating Test Suite through TFS Rest API

While trying to create a Test Suite using TFS 2017 REST API, I am getting the error:
System.Net.Http.HttpRequestException - Response status code does not
indicate success: 500 (Internal Server Error)
Code I tried:
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
string base64StringPat = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", Configs.Pat)));
AuthenticationHeaderValue authHeader = new AuthenticationHeaderValue("Basic", base64StringPat);
client.DefaultRequestHeaders.Authorization = authHeader;
string url = "http://vmctp-tl-mtm:8080/tfs/DefaultCollection/SgkProject/_apis/test/Plans/7/Suites/8?api-version=1.0";
var content = new StringContent("{\"suiteType\":\"StaticTestSuite\",\"name\":\"Module1\"}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.PostAsync(url, content).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
I have used this documentation from Microsoft to call the API: Create a test suite
Please guide me in fixing the issue.
HTTP code 500 means that this is an error on your server. The server threw an exception when trying to process this POST request.
So, this error has nothing to do with HttpClient. Just check your server first and see what causes the exception.
A possibility is that the specified content type is not expected by the server. POST a StringContent will set the content type to text/plain. You might find the server doesn't like that. In this case just try to find out what media type the server is expecting and set the Headers.ContentType of the StringContent instance.
Whatever, I can create the suite by below sample, you can have a try for that:
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace CreateTestSuite
{
class Program
{
public static void Main()
{
Task t = CreateTestSuite();
Task.WaitAll(new Task[] { t });
}
private static async Task CreateTestSuite()
{
try
{
var username = "username";
var password = "password";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
string url = "http://server:8080/tfs/DefaultCollection/LCScrum/_apis/test/plans/212/suites/408?api-version=1.0";
var content = new StringContent("{\"suiteType\":\"StaticTestSuite\",\"name\":\"Module3\"}", Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.PostAsync(url, content).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
}

Parse Error - When convering a xmlstring to a document

Been breaking my head to get this straight. Pretty simple though.. have not been able to figure out why. Any help would be very much appreciated.
Here my XML file
<?xml version="1.0" encoding="UTF-8"?>
<User mode="Retrieve" simCardNumber=“9602875089237652" softwareVersion=“9" phoneManufacturer=“Nokia" phoneModel="I747" deviceId=“562372389498734" networkOperator=“Blu">
<Errors>
<Error number="404"/>
</Errors>
</User>
private static Document convertStringToDocument(String xmlStr) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder =factory.newDocumentBuilder();
//The below statement fails and jumps to return null
//Document doc = builder.parse( new InputSource(new StringReader(xmlStr)));
//Adding replace method on the string to handle the strange looking double quote on the xml string. However I still get the same error.
Document doc = builder.parse( new InputSource(new StringReader(xmlStr.replace("“", "\'\""))));
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
check the quotes..
networkOperator=“Blu"
Don't know if it isn't a paste error but you used “ instead of " in your code. The first one if often used in rich text editors as a starting quote, you need to change it manually to let it be parseable.
Ok this solution works. Thanks everyone for your time and support.
Document doc = null;
try
{
DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xmlStr));
doc = db.parse(is);
} catch (Exception e) {
e.printStackTrace();
}
return doc;

Printer error (EX_TIMEOUT) Epson TM-T88V-I with epson.ePOSBuilder

Epson model TM-T88V-i.
Connected to LAN.
Ping response OK.
Printing status sheet OK.
I have access to printer configuration page.
http://192.168.x.x/PrinterConfigurationPage/
In configuration page - section devices raise error in test print button for the printer "local_printer", error: "EX_TIMEOUT A time-out ocurred".
reference (ePOS-Print API/XML):
https://download.epson-biz.com/modules/community/index.php?content_subject=ePOS-Print%20API/XML
simple test web site:
print.html
<script type="text/javascript" src="js/epos-print-3.0.0.js"></script>
code
function printTest() {
// open print dialog
$('#print').dialog('open');
//
// build print data
//
// create print data builder object
var builder = new epson.ePOSBuilder();
builder.addText('Test Print\n');
builder.addFeedLine(1);
// append paper cutting
builder.addCut();
//
// send print data
//
// create print object
var url = 'http://192.168.x.x/cgi-bin/epos/service.cgi?devid=local_printer&timeout=6000';
var epos = new epson.ePOSPrint(url);
// register callback function
epos.onreceive = function (res) {
// close print dialog
$('#print').dialog('close');
// print failure
if (!res.success) {
// show error message
$('#receive').dialog('open');
}
}
// register callback function
epos.onerror = function (err) {
// close print dialog
$('#print').dialog('close');
// show error message
$('#error').dialog('open');
}
// send
epos.send(builder.toString());
}
Request to service.cgi :
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<epos-print xmlns="http://www.epson-pos.com/schemas/2011/03/epos-print">
<text>Test Print!!
</text>
<feed line="1"/>
<cut/>
</epos-print>
</s:Body>
</s:Envelope>
Response: epson api manual (status: 0x00000001 = No response from the TM printer)
<?xml version="1.0" encoding="UTF-8" ?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
<soapenv:Body>
<response success="false" code="EX_TIMEOUT" status="1" xmlns="http://www.epson-pos.com/schemas/2011/03/epos-print" />
</soapenv:Body>
</soapenv:Envelope>
when i change the service url a other device
var url = 'http://192.168.x.x/cgi-bin/epos/service.cgi?devid=other_printer&timeout=6000';
Request correct
Sucess="False" code="DeviceNotFound" status="0"
Windows Application example the same response:
Public Class Form1
' URL of ePOS-Print supported TM printer
Private address As String = "http://192.168.x.x/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000"
' XML namespace
Private soap As XNamespace = "http://schemas.xmlsoap.org/soap/envelope/"
Private epos As XNamespace = "http://www.epson-pos.com/schemas/2011/03/epos-print"
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Create print document
Dim req As XElement = _
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<epos-print xmlns="http://www.epson-pos.com/schemas/2011/03/epos-print">
<text lang="en" smooth="true">Intelligent Printer
</text>
<cut/>
</epos-print>
</s:Body>
</s:Envelope>
' Send print document
Dim client As WebClient = New WebClient()
client.Headers.Set("Content-Type", "text/xml; charset=utf-8")
AddHandler client.UploadStringCompleted, AddressOf UploadStringCompletedEventHandler
client.UploadStringAsync(New Uri(address, UriKind.Absolute), req.ToString())
End Sub
' Receive response document
Private Sub UploadStringCompletedEventHandler(sender As Object, e As UploadStringCompletedEventArgs)
If (e.Error IsNot Nothing) Then
MessageBox.Show(e.Error.Message)
Else
'Parse response document
Dim res As XElement = XElement.Parse(e.Result)
Dim c = From el In res.Descendants(epos + "response") Select el.Attribute("success")
MessageBox.Show(c.First().Value)
End If
End Sub
End Class
Two possibilities:
Your printer has a device id that is different from local_printer - check the configuration page.
Or the ePOSPrint() function does not allow sending the url directly. What I have on my first test page (I'm working on building an app for the same printer right now) looks different than on yours:
var epos = new epson.ePOSPrint();
epos.address = 'http://192.168.0.1/cgi-bin/epos/services.cgi?devid=local_printer&timeout=6000';
Note the empty () and how the url is delivered after initialization.
After checking, it looks like some other test code I have does submit the url as parameter to the function like you have it, so my only guess is that the device id local_printer is incorrect.

Creating soap request with http build

Im trying to make a soap request using httpbuilder. I need to pass some authentication parameters in the head section.
My code is as follows
def String WSDL_URL = 'http://ws.tradetracker.com/soap/affiliate?wsdl'
def http = new HTTPBuilder( WSDL_URL , ContentType.TEXT )
String soapEnvelope =
"""<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap-env:Header>
<authenticate>
<customerID>id</customerID>
<passphrase>pass</passphrase>
<demo>true</demo>
</authenticate>
</soap-env:Header>
<soap12:Body>
<getConversionTransactions xmlns="xmlns':'http://schemas.xmlsoap.org/wsdl">
<affiliateSiteID>id</affiliateSiteID>
</getConversionTransactions>
</soap12:Body>
</soap12:Envelope>"""
http.request( Method.POST, ContentType.TEXT ) {
body = soapEnvelope
response.success = { resp, xml ->
String xm = xml.readLines()
println "XML was ${xm}"
def territories = new XmlSlurper().parseText(
'<?xml version="1.0" encoding="UTF-8"?> <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope" xmlns:ns1="urn:http://ws.webgains.com/aws.php" xmlns:enc="http://www.w3.org/2003/05/soap-encoding" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><env:Body xmlns:rpc="http://www.w3.org/2003/05/soap-rpc"><ns1:getFullUpdatedEarningsResponse env:encodingStyle="http://www.w3.org/2003/05/soap-encoding"><rpc:result>return</rpc:result><return enc:itemType="ns1:fullLinesArray" enc:arraySize="1" xsi:type="ns1:fullReportArray"><item xsi:type="ns1:fullLinesArray"><transactionID xsi:type="xsd:int">39367137</transactionID><affiliateID xsi:type="xsd:int">59987</affiliateID><campaignName xsi:type="xsd:string">www.tikcode.com</campaignName><campaignID xsi:type="xsd:int">136755</campaignID><date xsi:type="xsd:dateTime">2013-05-13T15:04:48</date><validationDate xsi:type="xsd:dateTime">2013-05-13T15:04:48</validationDate><delayedUntilDate xsi:type="xsd:string"></delayedUntilDate><programName xsi:type="xsd:string">Miniinthebox - US</programName><programID xsi:type="xsd:int">4611</programID><linkID xsi:type="xsd:string">95661</linkID><eventID xsi:type="xsd:int">7285</eventID><commission xsi:type="xsd:float">0.06</commission><saleValue xsi:type="xsd:float">0.8</saleValue><status xsi:type="xsd:string">confirmed</status><paymentStatus xsi:type="xsd:string">notcleared</paymentStatus><changeReason xsi:nil="true"/><clickRef xsi:nil="true"/><clickthroughTime xsi:type="xsd:dateTime">2013-05-13T14:58:33</clickthroughTime><landingPage xsi:type="xsd:string">http%3A%2F%2Fwww.lightinthebox.com%2Fes%2F%3Flitb_from%3Daffiliate_webgains</landingPage><country xsi:type="xsd:string">ES</country><referrer xsi:type="xsd:string">http%3A%2F%2Flocalhost%3A8080%2Fcom.publidirecta.widget%2Fpromocion%2FverPromocion%3Fpromocion%3D</referrer></item></return></ns1:getFullUpdatedEarningsResponse></env:Body></env:Envelope>').declareNamespace("ns1":"http://ws.webgains.com/aws.php")
println "aaaaaaaaaaaaaaaa"+ territories.Body.getFullUpdatedEarningsResponse.return.item.transactionID
}
response.failure = { resp, xml ->
println "pues peto, no se porque"+xml.readLines()
}
}
Im getting the following error and I dont have any clue wants wrong
<?xml version="1.0" encoding="UTF-8"?>, <env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"><env:Body><env:Fault><env:Code><env:Value>env:Sender</env:Value></env:Code><env:Reason><env:Text>Body must be present in a SOAP envelope</env:Text></env:Reason></env:Fault></env:Body></env:Envelope>
Namespace for Envelope and its corresponding Header element is mismatching.
<soap12:Envelope> should have <soap12:Header> instead you have <soap-env:Header>. The payload becomes invalid in the header element so body becomes unreachable.
Like #dmahapatro said you have a problem in your XML. Anyway checking your code I've noted that you are using HTTPBuilder directly. Maybe you can try to use groovy-wslite (https://github.com/jwagenleitner/groovy-wslite) to make SOAP requests. It's very simple to call and process the response. There is a plugin for Grails, despite I'm not using the plugin, but the groovy-wslite directly.
BuildConfig.groovy
dependencies {
compile 'com.github.groovy-wslite:groovy-wslite:0.7.2'
runtime 'com.github.groovy-wslite:groovy-wslite:0.7.2'
}
In a Grails Service for instance:
def cnpj = "999999999906"
def clientSOAP = new SOAPClient('https://www.soawebservices.com.br/webservices/producao/cdc/cdc.asmx')
def response = clientSOAP.send (SOAPVersion.V1_2,
"""<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<PessoaJuridicaNFe xmlns="SOAWebServices">
<Credenciais>
<Email>xxxxx</Email>
<Senha>xxxxx</Senha>
</Credenciais>
<Documento>${cnpj}</Documento>
</PessoaJuridicaNFe>
</soap12:Body>
</soap12:Envelope>"""
)
//processing the response (very simple...)
Client client = new Client()
client.webServiceMsg = response.PessoaJuridicaNFeResponse.PessoaJuridicaNFeResult.Mensagem.text()
client.nome = response.PessoaJuridicaNFeResponse.PessoaJuridicaNFeResult.RazaoSocial.text()
//etc...

Sharing IClaimsPrincipal/FedAuth Cookie between servers/apps ID1006

I have an ASP.NET app that uses Azure ACS (and indirectly ADFS) for Authentication - which all works fine. Now I've been asked to pass the SessionToken to another backend service where it can be verified and the claims extracted. [Long Story and not my choice]
I'm having fits on the decryption side, and I'm sure I'm missing something basic.
To set the stage, the error upon decryption is:
ID1006: The format of the data is incorrect. The encryption key length is negative: '-724221793'. The cookie may have been truncated.
The ASP.NET website uses the RSA wrapper ala:
void WSFederationAuthenticationModule_OnServiceConfigurationCreated(object sender, ServiceConfigurationCreatedEventArgs e)
{
string thumbprint = "BDE74A3EB573297C7EE79EB980B0727D73987B0D";
X509Certificate2 certificate = GetCertificate(thumbprint);
List<CookieTransform> sessionTransforms = new List<CookieTransform>(new CookieTransform[]
{
new DeflateCookieTransform(),
new RsaEncryptionCookieTransform(certificate),
new RsaSignatureCookieTransform(certificate)
});
SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
e.ServiceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler);
}
(the thumbprint is the same value as added by FedUtil in web.config.
I write the token with:
if (Microsoft.IdentityModel.Web.FederatedAuthentication.SessionAuthenticationModule.TryReadSessionTokenFromCookie(out token))
{
Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler th = new Microsoft.IdentityModel.Tokens.SessionSecurityTokenHandler();
byte[] results = th.WriteToken(token);
...
which gives me:
<?xml version="1.0" encoding="utf-8"?>
<SecurityContextToken p1:Id="_53382b9e-8c4b-490e-bfd5-de2e8c0f25fe-94C8D2D9079647B013081356972DE275"
xmlns:p1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
xmlns="http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512">
<Identifier>urn:uuid:54bd1bd7-1110-462b-847e-7f49c1043b32</Identifier>
<Instance>urn:uuid:0462b7d7-717e-4ce2-b942-b0d6a968355b</Instance>
<Cookie xmlns="http://schemas.microsoft.com/ws/2006/05/security">AQAAANCMnd blah blah 1048 bytes total
</Cookie>
</SecurityContextToken>
and, with the same Certificate on the other box (and the token read in as a file just for testing), I have:
public static void Attempt2(FileStream fileIn, X509Certificate2 certificate, out SecurityToken theToken)
{
List<CookieTransform> sessionTransforms = new List<CookieTransform>(new CookieTransform[]
{
new DeflateCookieTransform(),
new RsaSignatureCookieTransform(certificate),
new RsaEncryptionCookieTransform(certificate)
});
SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
// setup
SecurityTokenResolver resolver;
{
var token = new X509SecurityToken(certificate);
var tokens = new List<SecurityToken>() { token };
resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false);
}
sessionHandler.Configuration = new SecurityTokenHandlerConfiguration();
sessionHandler.Configuration.IssuerTokenResolver = resolver;
using (var reader = XmlReader.Create(fileIn))
{
theToken = sessionHandler.ReadToken(reader);
}
}
and then ReadToken throws a FormatException of
ID1006: The format of the data is incorrect. The encryption key length is negative: '-724221793'. The cookie may have been truncated.
At this point, I can't tell if my overall approach is flawed or if I'm just missing the proverbial "one-line" that fixes all of this.
Oh, and I'm using VS2010 SP1 for the website (.NET 4.0) and I've tried both VS2010SP1 .NET 4.0 and VS2012 .NET 4.5 on the decoding side.
Thanks!
Does your app pool account for the backend service have read access to the certificate? If not give your app pool account for the backend service read access to the certificate. I had problems in the past with encryption/decryption because of this.
This might help, this will turn your FedAuth cookies into a readable XML string like:
<?xml version="1.0" encoding="utf-8"?>
<SecurityContextToken p1:Id="_548a372e-1111-4df8-b610-1f9f618a5687-953155F0C35B4862A5BCE4D5D0C5ADF0" xmlns:p1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns="http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512">
<Identifier>urn:uuid:c9f9b733-1111-4b01-8af3-23c8af3e19a6</Identifier>
<Instance>urn:uuid:ee955207-1111-4498-afa3-4b184e97d0be</Instance>
<Cookie xmlns="http://schemas.microsoft.com/ws/2006/05/security">long_string==</Cookie>
</SecurityContextToken>
Code:
private string FedAuthToXmlString(string fedAuthCombinedString)
{
// fedAuthCombinedString is from FedAuth + FedAuth1 cookies: just combine the strings
byte[] authBytes = Convert.FromBase64String(fedAuthCombinedString);
string decodedString = Encoding.UTF8.GetString(authBytes);
var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
var thumbprint = "CERT_THUMBPRINT"; // from config
var cert = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, false)[0];
var sessionTransforms = new List<System.IdentityModel.CookieTransform>(new System.IdentityModel.CookieTransform[]
{
new System.IdentityModel.DeflateCookieTransform(),
new System.IdentityModel.RsaSignatureCookieTransform(cert),
new System.IdentityModel.RsaEncryptionCookieTransform(cert)
});
SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
SecurityTokenResolver resolver;
{
var token = new X509SecurityToken(cert);
var tokens = new List<SecurityToken>() { token };
resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false);
}
sessionHandler.Configuration = new SecurityTokenHandlerConfiguration();
sessionHandler.Configuration.IssuerTokenResolver = resolver;
var i = 0; // clear out invalid leading xml
while ((int)decodedString[i] != 60 && i < decodedString.Length - 1) i++; // while the first character is not <
store.Close();
return decodedString.Substring(i);
}

Resources