Get web methods dynamically for an asmx service - dynamic

We have number of asmx services. I want to give an user a page with a textbox to input service url like http://abc.win.com/myservice/customerdata.asmx. When user hit "Load" button, dynamically I add all the web methods to the dropdown. I need some pointers:
1. How to dynamically get all the methods?
2. How can I get the SOAP request for the method selected? So that, we can replace the parameter values with actual values?
Appreciate your help.

Kuul13 : You need to modify your webservice URL like http://abc.win.com/myservice/customerdata.asmx?wsdl when user clicks on load button. then you can use we "ServiceDescription" class to get wsdl description and then iterate that to get method names in 'WebMethodInfoCollection' class.
To get SOAP request you need to use SOAPExtension class.This will give you SOAP Request and Response XML.Refere this link for that : http://blog.encoresystems.net/articles/how-to-capture-soap-envelopes-when-consuming-a-web-service.aspx?www.microsoft.com
For dynamically calling webservice look a this V.Good article
http://www.codeproject.com/KB/webservices/webservice_.aspx
Please reply me for any comment.

System.Net.WebClient client = new System.Net.WebClient();
System.IO.Stream stream = client.OpenRead("http://www.webservicex.net/globalweather.asmx?wsdl");
ServiceDescription description = ServiceDescription.Read(stream);
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12";
importer.AddServiceDescription(description, null, null);
importer.Style = ServiceDescriptionImportStyle.Client;
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
CodeNamespace nmspace = new CodeNamespace();
CodeCompileUnit unit1 = new CodeCompileUnit();
unit1.Namespaces.Add(nmspace);
ServiceDescriptionImportWarnings warning = importer.Import(nmspace, unit1);
if (warning == 0)
{
CodeDomProvider provider1 = CodeDomProvider.CreateProvider("CSharp");
string[] assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
CompilerParameters parms = new CompilerParameters(assemblyReferences);
CompilerResults results = provider1.CompileAssemblyFromDom(parms, unit1);
object[] args = new object[1];
args[0] = "India";
object wsvcClass = results.CompiledAssembly.CreateInstance("GlobalWeather");
MethodInfo mi = wsvcClass.GetType().GetMethod("GetCitiesByCountry");
RegExpForCountryCity(mi.Invoke(wsvcClass, args).ToString());
}
else
{
Console.WriteLine("Warning: " + warning);
}
void RegExpForCountryCity(string strHTML)
{
Regex qariRegex = new Regex(#"<Table>\s*<Country>(?<Country>[\s\S]*?)</Country>\s*<City>(?<City>[\s\S]*?)</City>\s*</Table>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
MatchCollection mc = qariRegex.Matches(strHTML);
string strCountryCity = "";
for (int i = 0; i < mc.Count; i++)
{
if (string.IsNullOrEmpty(strCountryCity))
strCountryCity = "Country: " + "<b>" + mc[i].Groups["Country"].Value + "</b>" + " " + "City: " + "<b>" + mc[i].Groups["City"].Value + "</b>" + "</br>";
else
strCountryCity += "</br>" + "Country: " + "<b>" + mc[i].Groups["Country"].Value + "</b>" + " " + "City: " + "<b>" + mc[i].Groups["City"].Value + "</b>" + "</br>";
}
Response.Write(strCountryCity);
}

Related

RDLC report Index was outside the bounds of the array asp net core

I got Index was outside the bounds of the array error when use debug mode in asp net core mvc, but its ok when run in non-debug mode (Shift+F5).
Here details of error description :
An unhandled exception occurred while processing the request.
IndexOutOfRangeException: Index was outside the bounds of the array.
AspNetCore.ReportingServices.RdlExpressions.ExpressionHostObjectModel.RemoteArrayWrapper.get_Item(int
index)
ReportProcessingException: An unexpected error occurred in Report
Processing. Index was outside the bounds of the array.
AspNetCore.ReportingServices.ReportProcessing.Execution.RenderReport.Execute(IRenderingExtension
newRenderer)
LocalProcessingException: An error occurred during local report
processing.;An unexpected error occurred in Report Processing. Index
was outside the bounds of the array.
AspNetCore.Reporting.InternalLocalReport.InternalRender(string format,
bool allowInternalRenderers, string deviceInfo, PageCountMode
pageCountMode, CreateAndRegisterStream createStreamCallback, out
Warning[] warnings)
Here my export to pdf code :
int extension = 1;
var path = $"{this._webHostEnvironment.WebRootPath}\\Report\\RptDO2.rdlc";
Dictionary<string, string> parameters = new Dictionary<string, string>();
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding.GetEncoding("windows-1252");
parameters.Add("txtto", inv.Quotation.CustomerContact.Customer.CompanyName);
parameters.Add("txtaddress_detail", inv.Quotation.CustomerContact.Customer.Address1 + "\r\n"
+ inv.Quotation.CustomerContact.Customer.Address2 + "- "
+ inv.Quotation.CustomerContact.Customer.City + "- "
+ inv.Quotation.CustomerContact.Customer.State + " ("
+ inv.Quotation.CustomerContact.Customer.Zip + ")\r\n"
+ "Phone : " + inv.Quotation.CustomerContact.Customer.PhoneNumber
+ ", Email : " + inv.Quotation.CustomerContact.Customer.Email);
parameters.Add("txtdo_no", inv.Id.Replace("INV", "DO"));
parameters.Add("txtdate", inv.Quotation.CreatedAt.ToShortDateString());
parameters.Add("txtrefnum", inv.QuotationId);
parameters.Add("txtfrom", us.FirstName + " " + us.LastName);
parameters.Add("txtUP", TextUp);
parameters.Add("kop_nama", c.CpName);
parameters.Add("kop_alamat", c.CpStreetAddress);
parameters.Add("kop_alamat2", c.CpCity + " " + c.CpState + " (" + c.CpZip + ")");
parameters.Add("kop_contact", c.CpPhone);
parameters.Add("kop_email", c.CpEmail);
parameters.Add("kop_logo", Convert.ToBase64String(c.CpFoto));
parameters.Add("txtjabatan", us.Designation);
parameters.Add("txtPrintedBy", lgnuser.FirstName + " " + lgnuser.LastName);
List<vwQuotationDetail> vwQuotationDetails = new List<vwQuotationDetail>();
foreach (TblquotationDetail quos in inv.Quotation.TblquotationDetail.OrderBy(o => o.Id))
{
vwQuotationDetail quotationDetail = new vwQuotationDetail
{
id = quos.Id,
quotation_id = quos.QuotationId,
order_number = quos.OrderNumber,
product_name = quos.Product.ProductName,
product_id = quos.ProductId,
product_comments = string.IsNullOrEmpty(quos.ProductComments) ? "" : quos.ProductComments,
quantity = quos.Quantity,
unit_price = quos.UnitPrice,
unit_name = quos.Product.Unit.UnitName,
sub_total = quos.SubTotal,
product_desc = quos.Product.ProductDesc,
category_name = quos.Product.Category.CategoryName
};
vwQuotationDetails.Add(quotationDetail);
}
LocalReport localReport = new LocalReport(path);
localReport.AddDataSource("dsDO", vwQuotationDetails.ToArray());
//var result = localReport.Execute(RenderType.Pdf, extension, parameters, mimtype);
var result = localReport.Execute(RenderType.Pdf, extension, parameters);
return File(result.MainStream, "application/pdf");
Any suggestion will appreciated, thanks in advance.
Just Dont Pass extension as 1 in:
var result = localReport.Execute(RenderType.Pdf, extension, parameters);
The Solution is:
int ext = (int)(DateTime.Now.Ticks >> 10);
var result = localReport.Execute(RenderType.Pdf, ext, param);
In other words, Extension should not be same for every report.

Selenium File upload on chrome from android phone

I am trying to upload file in a selenium test that is run on chrome browser on an android phone. The usual element.sendkeys(path) is not working.
Are there any known alternatives for android ?
It may help to upload the file:
public CorePage UploadHack(string fileInputId, string contentType, string fileContent, string fileName, string angularScopeVar)
{
UploadFile(_filePath);
var uploadHack =
"(function(){" +
"function convert(base64){" +
"var raw = atob(base64);" +
"var arr = new Uint8Array(new ArrayBuffer(raw.length));" +
"for (var i = 0; i < raw.length; i++){" +
"arr[i] = raw.charCodeAt(i);" +
"}" +
"return arr; " +
"}" +
$"var file = new Blob([convert('{fileContent}')], {{'type':'{contentType}'}}); " +
$"file.name = '{fileName}'; " +
$"angular.element('#{fileInputId}').scope().{angularScopeVar} = file;" +
"})()";
Driver.ExecuteJavaScript(uploadHack);
return this;
}

getting "415:Media not supported" Error when passing pdf to IBM watson in Salesforce

I am planning to integrate the IBM Watson Document Conversion service
with Salesforce.
From there I am unable to send my pdf file directly to Watson and I'm getting Media Type not supported.
I am also getting this error:
{
"code" : 500 ,
"error" : "Server Error" ,
"description" : "2017-07-18T06:02:19-04:00, Error WATSNGWERR-0x0113001c occurred when accessing https://gateway.watsonplatform.net/document-conversion/api/v1/convert_document?version=2015-12-15&config="{"conversion_target":"answer_units"}", Tran-Id: gateway-dp02-1967135880 - Watson Gateway Error"
}
Here is the code I'm using:
public class Resume {
String boundary = '----------------------------741e90d31eff';
public string id{get;set;}
public string content{get;set;}
Transient public Attachment att{set;get;}
public Resume(ApexPages.StandardController controller) {
id=ApexPages.currentPage().getParameters().get('id');
att=new Attachment();
att=[Select Id,ParentId, Name,body,ContentType From Attachment where ParentId=:id limit 1];
content=String.valueOf(att.body);
System.debug('---->' + content);
String header = '--' + boundary + '\nContent-Disposition: form-data; name="att"; filename="'+att.name+'";\nContent-Type: application/pdf';
String footer = '--' + boundary + '--';
String headerEncoded =
EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
String bodyEncoded = EncodingUtil.base64Encode(att.body);
Blob bodyBlob = null;
String last4Bytes =
bodyEncoded.substring(bodyEncoded.length() - 4, bodyEncoded.length());
while (headerEncoded.endsWith('=')){
header+=' ';
headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
}
if (last4Bytes.endsWith('==')) {
last4Bytes = last4Bytes.substring(0,2) + '0K';
bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded + bodyEncoded + footerEncoded);
} else if (last4Bytes.endsWith('=')) {
last4Bytes = last4Bytes.substring(0,3) + 'N';
bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;
footer = '\n' + footer;
String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded + bodyEncoded + footerEncoded);
} else {
footer = '\r\n' + footer;
String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded + bodyEncoded + footerEncoded);
}
String configAsString ='\"conversion_target:answer_units\"';
Http h = new Http();
HttpRequest request = new HttpRequest();
request.setMethod('POST');
request.setHeader('Content-Type','multipart/form-data; boundary=' + boundary);
String username= 'DOCUMENT-CONVERSION-USERNAME';
String password= 'DOCUMENT-CONVERSION-PASSWORD';
request.setHeader('Authorization', 'Basic ' + EncodingUtil.base64Encode(blob.valueOf(username + ':' + password)));
request.setEndpoint('https://gateway.watsonplatform.net/document-conversion/api/v1/convert_document?version=2015-12-15&config='+configAsString);
request.setBodyAsBlob(bodyBlob);
request.setCompressed(true);
HttpResponse response = h.send(request);
System.debug(response.getBody());
}
}
You are sending the config as a query parameter, but it should be in the body.
Here is the curl command that makes what you are trying to do:
curl -X POST \
-u "{username}":"{password}" \
-F config="{\"conversion_target\":\"answer_units\"}" \
-F "file=#sample.pdf;type=application/pdf" \
"https://gateway.watsonplatform.net/document-conversion/api/v1/convert_document?version=2015-12-15"
I also think there is an error in the way you are creating the body. My team built an SDK to use the Watson APIs in the Salesforce environment. I would suggest you take a look.
If you can't deploy the SDK to your Salesforce organization (It's a lot of code), copy the code from the IBMWatsonMultipartBody.cls class. It will help you encode an Attachment as base64 so that you can end it to Watson.
UPDATE: The Document Conversion service was deprecated but the features from that service were enhanced and migrated to the Discovery service

Signature did not match. String to sign used was r

Trying to Construct a Shared Access Signature URI for a Blob access in a container
BlobHelper BlobHelper = new BlobHelper(StorageAccount, StorageKey);
string signature = "";
string signedstart = DateTime.UtcNow.AddMinutes(-1).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
string signedexpiry = DateTime.UtcNow.AddMinutes(2).ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
//// SET CONTAINER LEVEL ACCESS POLICY
string accessPolicyXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<SignedIdentifiers>\n" +
" <SignedIdentifier>\n" +
" <Id>twominutepolicy</Id>\n" +
" <AccessPolicy>\n" +
" <Start>" + signedstart + "</Start>\n" +
" <Expiry>" + signedexpiry + "</Expiry>\n" +
" <Permission>r</Permission>\n" +
" </AccessPolicy>\n" +
" </SignedIdentifier>\n" +
"</SignedIdentifiers>\n";
BlobHelper.SetContainerAccessPolicy("xxxxxxx", "container", accessPolicyXml));
string canonicalizedresource = "/xxxxxxx/501362787";
string StringToSign = String.Format("{0}\n{1}\n{2}\n{3}\n{4}\n{5}\n{6}\n{7}\n{8}\n{9}\n{10}",
"r",
signedstart,
signedexpiry,
canonicalizedresource,
"twominutepolicy",
"2013-08-15",
"rscc",
"rscd",
"rsce",
"rscl",
"rsct"
);
using (HMACSHA256 hmacSha256 = new HMACSHA256(Convert.FromBase64String(StorageKey)))
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(StringToSign);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
StringBuilder sasToken = new StringBuilder();
sasToken.Append(BlobHelper.DecodeFrom64(e.Item.ToolTip).ToString().Replace("http","https") + "?");
//signedversion
sasToken.Append("sv=2013-08-15&");
sasToken.Append("sr=b&");
//
sasToken.Append("si=twominutepolicy&");
sasToken.Append("sig=" + signature + "&");
//
sasToken.Append("st=" + HttpUtility.UrlEncode(signedstart).ToUpper() + "&");
//
sasToken.Append("se=" + HttpUtility.UrlEncode(signedexpiry).ToUpper() + "&");
//
sasToken.Append("sp=r");
string url = sasToken.ToString();
I am getting the following exception below
<Error>
<Code>AuthenticationFailed</Code>
<Message>Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature. RequestId:e424e1ac-fd96-4557-866a-992fc8c41841 Time:2014-05-22T18:46:15.3436786Z</Message>
<AuthenticationErrorDetail>Signature did not match. String to sign used was r 2014-05-22T18:45:06Z 2014-05-22T18:48:06Z /xxxxxxx/501362787/State.SearchResults.pdf twominutepolicy 2013-08-15 </AuthenticationErrorDetail>
</Error>
rscc, rscd, rsce, rscl, rsct are placeholders for overridden response headers. Your sasToken variable does not seem to override response headers, so you should just use empty strings with a new-line character when signing them. Moreover, it looks like your canonicalized resource also does not match the server's resource.
By the way, did you look at Azure Storage Client Library to create Shared Access Signature tokens? It provides lots of features and is the official SDK to access Microsoft Azure Storage.

Embedded Signing api docusign

I'm using DocuSign to add eSignature to my requests and everything's working well. Right now I send my signature requests,by using Embedded method- to initiate my workflows immediately by navigating to a URL.
After login,and execute the bellow code,i get the (Embedded View: https://demo.docusign.net/Member/StartInSession.aspx?StartConsole=1&t=32598057-5a59-4d0b-bad8-a8ff8f2407f6&DocuEnvelope=168bc155-e013-4ffd-abb4-7608b56647f8&send=1), but whene i paste the url to try signing document in navigate, but will redirect me to an other url is(http://www.docusign.com/?event=Send&envelopeId=168bc155-e013-4ffd-abb4-7608b56647f8),
how can'i start wotkflow process to sign my enveloppe ?? i can't see my enveloppe to sign it.
// STEP 2 - Create an envelope with one recipient, document, and tab and send
//
String jsonBody = "{\"emailBlurb\":\"partail\"," +
"\"emailSubject\":\"API Call for adding signature request to document and sending\"," +
"\"documents\":[{" +
"\"documentId\":\"1\"," +
"\"name\":\"test.pdf\"}]," +
"\"recipients\":{" +
"\"signers\":[{" +
"\"email\":\"" + EmailRecipients + "\"," +
"\"name\":\"name\"," +
"\"recipientId\":\"1\"," +
"\"routingOrder\":\"1\","+
"\"clientUserId\":\"1000\","+
"\"tabs\":{" +
"\"signHereTabs\":[{" +
"\"xPosition\":\"300\"," +
"\"yPosition\":\"600\"," +
"\"documentId\":\"1\"," +
"\"pageNumber\":\"1\"" + "}]}}]}," +
"\"status\":\"sent\"}";
//DemandeSign.getenvelope();
File file = new File("D:/test.pdf");
InputStream inputStream = new FileInputStream(file);
byte[] bytes = new byte[(int) file.length()];
inputStream.read(bytes);
inputStream.close();
String requestBody = "\r\n\r\n--BOUNDARY\r\n" +
"Content-Type: application/json\r\n" +
"Content-Disposition: form-data\r\n" +
"\r\n" +
jsonBody + "\r\n\r\n--BOUNDARY\r\n" + // our json formatted request body
"Content-Type: application/pdf\r\n" +
"Content-Disposition: file; filename=\"test.pdf\"; documentId=1\r\n" +
"\r\n";
// we break this up into two string since the PDF doc bytes go here and are not in string format.
// see further below where we write to the outputstream...
String reqBody2 = "\r\n" + "--BOUNDARY--\r\n\r\n";
// append "/envelopes" to the baseUrl and use in the request
conn = (HttpURLConnection)new URL(baseURL + "/envelopes").openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=BOUNDARY");
conn.setRequestProperty("Content-Length", Integer.toString(requestBody.toString().length()));
conn.setRequestProperty("Accept", "application/xml");
// write the body of the request...
DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(requestBody.toString());
dos.write(bytes);
dos.writeBytes(reqBody2.toString());
dos.flush(); dos.close();
status = conn.getResponseCode(); // triggers the request
if( status != 201 ) // 201 = Created
{
System.out.println("Error calling webservice, status is: " + status);
InputStreamReader isr = new InputStreamReader( conn.getErrorStream() );
br = new BufferedReader(isr);
StringBuilder error_response = new StringBuilder();
while ( (line = br.readLine()) != null)
error_response.append(line);
System.out.println("Error response is " + error_response.toString() );
System.exit(-1);
}
// Read the response
InputStreamReader isr = new InputStreamReader( conn.getInputStream() );
br = new BufferedReader(isr);
StringBuilder response2 = new StringBuilder();
while ( (line = br.readLine()) != null)
response2.append(line);
//token1 = "//*[1]/*[local-name()='envelopeId']";
//String envelopeId = xPath.evaluate(token1, new InputSource(new StringReader(response2.toString())));
//--- display results
//System.out.println("Document sent! envelopeId is " + envelopeId );//envelopeId is e4c0659a-9d01-4ac3-a45f-02a80fd6bd96 at 04/07/2013 17:24
token1 = "//*[1]/*[local-name()='uri']";
String uri = xPath.evaluate(token1, new InputSource(new StringReader(response2.toString())));
//--- display results
System.out.println("uri = " + uri );
/// Step3
// construct another outgoing XML request body
String reqBody = "<returnUrlRequest xmlns=\"http://www.docusign.com/restapi\">" +
"<authenticationMethod>email</authenticationMethod>" +
"<email>***test#gmail.com***</email>" +
"<returnUrl>http://www.docusign.com</returnUrl>" +
"<userName>name</userName>" +
"<clientUserId>1000</clientUserId>" +
"</returnUrlRequest>";
// append uri + "/views/sender" to the baseUrl and use in the request
conn = (HttpURLConnection)new URL(baseURL + uri + "/views/sender").openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("X-DocuSign-Authentication", authenticateStr);
conn.setRequestProperty("Content-Type", "application/xml");
conn.setRequestProperty("Content-Length", Integer.toString(reqBody.length()));
conn.setRequestProperty("Accept", "application/xml");
// write the body of the request...
dos = new DataOutputStream( conn.getOutputStream() );
dos.writeBytes(reqBody); dos.flush(); dos.close();
status = conn.getResponseCode(); // triggers the request
if( status != 201 ) // 201 = Created
{
System.out.println("Error calling webservice, status is: " + status);
System.exit(-1);
}
// Read the response
isr = new InputStreamReader( conn.getInputStream() );
br = new BufferedReader(isr);
StringBuilder response3 = new StringBuilder();
while ( (line = br.readLine()) != null)
response3.append(line);
token1 = "//*[1]/*[local-name()='url']";
//--- display results
System.out.println("Embedded View: " + xPath.evaluate(token1, new InputSource(new StringReader(response3.toString()))));`
Are you trying to access the URL immediately or are you waiting at all? Once you generate a URL token to access a given envelope it has a TTL (time to life) of 5 mins, meaning it expires after 5 minutes and you then need to generate a new one.
If that's not it, your problem might be related to how you are identifying your recipient. A recipient in DocuSign is identified by the unique combination of their name, email, recipientId, and in the case of embedding, the clientUserId. You seem to be setting all of those, however whatever the combination is when you first create the envelope, you need to refer to the same combination when you are requesting the Embedded URL token.
When you create your envelope I see you are setting the name literally to "name" and that you are setting the email through a variable called "EmailRecipients". But when you request the URL token you are using email "test#gmail.com", that might be causing your issue too.