I am trying to send erc20 tokens using web3j , it always throw the protocol exception and transaction is always pending. Is there anything wrong i did in my code?
Code:
Web3j web3 = Web3j.build(new HttpService("https://ropsten.infura.io/v3/xxxxxxxxxxxx"));
Credentials creds = Credentials.create(privateKey);
String tokenAddress = "0x............."
ERC20 contract = ERC20.load(tokenAddress, web3, creds, new StaticGasProvider(new BigInteger('25000000000'), new BigInteger('5500000')));
String tokenName = contract.name().send()
String tokenSymbol = contract.symbol().send()
def balanceToken = contract.balanceOf(creds.address).send()
resp = contract.transfer("0xXXXX", new BigInteger('100')).send()
Exception:
org.web3j.protocol.exceptions.TransactionException: Transaction receipt was not generated after 600 seconds for transaction: 0x4e730fab8621396ef520d976b777db62ea79e30b7b402d6206dba47d59ccc2fc
at org.web3j.tx.response.PollingTransactionReceiptProcessor.getTransactionReceipt(PollingTransactionReceiptProcessor.java:61)
at org.web3j.tx.response.PollingTransactionReceiptProcessor.waitForTransactionReceipt(PollingTransactionReceiptProcessor.java:38)
at org.web3j.tx.TransactionManager.processResponse(TransactionManager.java:181)
at org.web3j.tx.TransactionManager.executeTransaction(TransactionManager.java:81)
at org.web3j.tx.ManagedTransaction.send(ManagedTransaction.java:128)
at org.web3j.tx.Contract.executeTransaction(Contract.java:367)
at org.web3j.tx.Contract.executeTransaction(Contract.java:350)
at org.web3j.tx.Contract.executeTransaction(Contract.java:344)
at org.web3j.tx.Contract.executeTransaction(Contract.java:339)
at org.web3j.tx.Contract.lambda$executeRemoteCallTransaction$3(Contract.java:410)
at org.web3j.protocol.core.RemoteCall.send(RemoteCall.java:42)
at org.web3j.protocol.core.RemoteCall$send.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
at com.elintegro.coinface.cft.BuyCftService.$tt__buyCFT(BuyCftService.groovy:246)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1426)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
This is how I fixed the problem.
The below code for transferring erc20 tokens using web3j works fine.
Web3j web3 = Web3j.build(new HttpService(https://ropsten.infura.io/)) // for ropsten test network
Credentials credentials = Credentials.create(privateKey);
EthGetTransactionCount ethGetTransactionCount = web3.ethGetTransactionCount(credentials.getAddress(), DefaultBlockParameterName.LATEST).send();
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
BigInteger amountToSend = new BigInteger(100); // you can provide yourself how much you want to send
Function function = new Function(
"transfer",
Arrays.asList(new Address(toAddress), new Uint256(amountToSend)),
Collections.singletonList(new TypeReference<Bool>() {
}));;
String encodedFunction = FunctionEncoder.encode(function);
BigInteger gasLimit = BigInteger.valueOf(71000); // you can customize these
BigInteger gasPrice = new BigInteger(100000); //
RawTransaction rawTransaction =
RawTransaction.createTransaction(
nonce, gasPrice, gasLimit, <contract_address_of_erc20_token>, encodedFunction);
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
EthSendTransaction ethSendTransaction = web3.ethSendRawTransaction(hexValue).sendAsync().get();
String transactionHash = ethSendTransaction.getTransactionHash();
Related
As per gimap documentation javamail new gimap doc, ImapMessage not casting to GmailMessage.
Doc code is:
GmailMessage gmsg = (GmailMessage)msg; System.out.println("Gmail message ID is " + gmsg.getMsgId()); String[] labels = gmsg.getLabels(); for (String s : labels) System.out.println("Gmail message label: " + s);
here msg is a object of ImapMessage.
Error is: java.lang.ClassCastException: com.sun.mail.imap.IMAPMessage cannot be cast to com.sun.mail.gimap.mailMessage
How to solve it?
My Imap connection code is:
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Folder;
String IMAP_PROTOCOL = "imap";
String IMAP_HOST = "imap.gmail.com";
String IMAP_PORT = "993";
private Store store;
private Folder folderInbox;
private Session session;
private Properties getServerProperties(String protocol, String host,
String port) {
Properties properties = new Properties();
// server setting
properties.put(String.format("mail.%s.host", protocol), host);
properties.put(String.format("mail.%s.port", protocol), port);
// SSL setting
properties.setProperty(
String.format("mail.%s.socketFactory.class", protocol),
"javax.net.ssl.SSLSocketFactory");
properties.setProperty(
String.format("mail.%s.socketFactory.fallback", protocol),
"false");
properties.setProperty(
String.format("mail.%s.socketFactory.port", protocol),
String.valueOf(port));
return properties;
}
//Now connect gmail with imap
Properties properties = getServerProperties(protocol, host, port);
session = Session.getDefaultInstance(properties);
store = session.getStore(protocol);
store.connect(userName, password);
// opens the inbox folder
folderInbox = store.getFolder(folderName);
folderInbox.open(Folder.READ_ONLY);
// fetches new messages from server
Message[] messages = folderInbox.getMessages();
for (Message msg: messages
) {
GmailMessage gmsg = (GmailMessage)msg;
System.out.println("Gmail message ID is " + gmsg.getMsgId());
String[] labels = gmsg.getLabels();
for (String s : labels)
System.out.println("Gmail message label: " + s);
}
I am trying to call a REST API with JSON payload using Grails and getting error below.
I have already converted the object to JSON earlier here and passing it in. Not sure what am I missing.
SpotifyService.groovy
#Transactional
class SpotifyService implements EventPublisher {
String spotifyServiceBaseUrl = 'http://localhost:9999'
String username = "abcd"
String password = "defg"
void createSoldOrder(ItemDetails itemDetails) {
println("into the createSoldOrder method......")
String orderId = "100-200-ABC"
String soldDate = itemDetails.order.orderDate
String partnerUniqueId = itemDetails.customer.billingAddress.email
def monthEndDate = new Date() + 30
String commitEndDate = monthEndDate.toString()
String product = "premium-month"
String soldMetadata = "Partner's metadata connected to the sold order"
String partnerDeals = "hardbundle*3,standalone"
NewOrder newOrder = new NewOrder(orderId: orderId, soldDate: soldDate, partnerUniqueId: partnerUniqueId,
commitEndDate: commitEndDate, product: product, soldMetadata: soldMetadata,
partnerDeals: partnerDeals)
println("newOrder: " + newOrder)
String newOrderJsonPayload = new JsonBuilder(newOrder).toPrettyString()
println("newOrderJsonPayload: " + newOrderJsonPayload)
placeSpotifyOrder(newOrderJsonPayload)
}
void placeSpotifyOrder(String newOrderJsonPayload) {
println("into the placeSpotifyOrder method........")
String restUrl = spotifyServiceBaseUrl + "/order-sold"
println restUrl
RestBuilder rest = new RestBuilder()
RestResponse restResponse = rest.post(restUrl) {
auth username, password
json {
newOrderJsonPayload
}
}
if (restResponse.statusCode.value()) {
println(restResponse.text)
}
null
}
}
Error:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '{
"product": "premium-month",
"orderId": "100-200-ABC",
"soldMetadata": "Partner's metadata connected to the sold order",
"partnerUniqueId": "success#simulator.amazonses.com",
"commitEndDate": "Sat Mar 24 16:51:37 EDT 2018",
"soldDate": "2017-08-03T20:07:27+0000",
"partnerDeals": "hardbundle*3,standalone"
}' with class 'java.lang.String' to class 'grails.converters.JSON'
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnSAM(DefaultTypeTransformation.java:405)
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.continueCastOnNumber(DefaultTypeTransformation.java:319)
at org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation.castToType(DefaultTypeTransformation.java:232)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.asType(DefaultGroovyMethods.java:15669)
at org.codehaus.groovy.runtime.StringGroovyMethods.asType(StringGroovyMethods.java:195)
at org.codehaus.groovy.runtime.dgm$1048.doMethodInvoke(Unknown Source)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1213)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
at org.codehaus.groovy.runtime.InvokerHelper.invokePojoMethod(InvokerHelper.java:913)
at org.codehaus.groovy.runtime.InvokerHelper.invokeMethod(InvokerHelper.java:904)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.invokeMethodN(ScriptBytecodeAdapter.java:168)
at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.asType(ScriptBytecodeAdapter.java:591)
at grails.web.JSONBuilder.build(JSONBuilder.groovy:42)
at grails.plugins.rest.client.RequestCustomizer.json(RequestCustomizer.groovy:195)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springsource.loaded.ri.ReflectiveInterceptor.jlrMethodInvoke(ReflectiveInterceptor.java:1433)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:93)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:325)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:384)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1022)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:69)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:154)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:166)
at com.synapsegroupinc.spotifyintegrator.SpotifyService$__tt__placeSpotifyOrder_closure4.doCall(SpotifyService.groovy:50)
Create a new class with all the properties you need in the json object. Create an instance of the class and populate its properties. Then use objInstance as JSON to covert it to json.
I think your problem connected with Method json{}. The method is overloaded. If you want to send payload as json string you should change your code in placeSpotifyOrder as following:
RestResponse restResponse = rest.post(restUrl) {
auth (username, password)
json (newOrderJsonPayload)
}
I am using Mockito for testing. Getting nullpointerexcpetion with message as null
TestMethod
// build request
RequestObject requestObject = new RequestObject();
String accountNumber = "12345628928";
String accountId = "dc23362e-f46f-4cce-b49a-cd10d737f483";
requestObject.setAccountId(accountId);
requestObject.setAccountNumber(accountNumber);
String firstName = "test";
String middlename = "test";
String lastName = "test";
String gender = "M";
String dob = "01-JUN-2016";
String emailaddress = "test#test.com";
String prefferedLanguageCode = "1";
String preffredname = "test";
String prefix = "Mr.";
String suffix = "Jr";
String minor = "1";
String deathDate = "09-SEP-2009";
String deathInformationDate = "14-OCT-2010";
Customer customer = new Customer();
customer.setFirstName(firstName);
customer.setMiddleName(middlename);
customer.setLastName(lastName);
customer.setGender(gender);
customer.setDob(dob);
customer.setEmail(emailaddress);
customer.setPreferredLanguageCode(prefferedLanguageCode);
customer.setPreferredName(preffredname);
customer.setPrefix(prefix);
customer.setSuffix(suffix);
customer.setMinor(minor);
customer.setDeathDate(deathDate);
customer.setDeathInformedDate(deathInformationDate);
requestObject.setCustomer(customer);
IdObject idObject = new IdObject();
idObject.setAccountId(UUID.fromString(accountId));
List<PersonAccount> personAccount = new ArrayList<PersonAccount>();
PersonAccount personAccount1 = new PersonAccount();
personAccount1.setFirstName("First name in testing");
personAccount.add(personAccount1);
// mock external call
when(sessionFactory.openSession()).thenReturn(session);
when(session.beginTransaction()).thenReturn(transaction);
when(session.createQuery(SQLConstants.FETCH_PERSON_ACCT)).thenReturn(query);
when(query.list()).thenReturn(personAccount);
when(query.executeUpdate()).thenReturn(1);
// Call the testing method
idObject = customerDAOImpl.updateCustomerRecord(requestObject);
//check the assertion
assertEquals("dc23362e-f46f-4cce-b49a-cd10d737f483", idObject.getAccountId().toString());
// verify the mock call
verify(customerDAOImpl, times(1)).updateCustomerRecord(requestObject);
and my
UpdateMethod
`
private void updateAccountInformation(RequestObject requestObject, Session session)
throws CustomerDataException{
try{
Query queryForPersonAccount = session.createQuery(SQLConstants.FETCH_PERSON_ACCT);
queryForPersonAccount.setParameter(Constants.ACCOUNTID, UUID.fromString(requestObject.getAccountId().toUpperCase()));
#SuppressWarnings("unchecked")
List<PersonAccount> listpersonAccount = (List<PersonAccount>) queryForPersonAccount.list();
if (CollectionUtils.isNotEmpty(listpersonAccount)) {
PersonAccount personAccount = listpersonAccount.get(0);
Query updateQuery = session.createQuery(SQLConstants.UPDATE_PERSON_ACCOUNT);
updateQuery.setParameter(Constants.ACCOUNTID,UUID.fromString(requestObject.getAccountId().toUpperCase()));
updateQuery.setParameter(Constants.UPDATED_BY_NAME, Constants.PCF);
updateQuery.setParameter(Constants.END_TIMESTAMP,DateUtil.dateDDMMMYY());
updateQuery.executeUpdate();
updatePersonAccount(session,personAccount, requestObject);
}else{
throw new CustomerDataException(MessageKeys.UPDATE_CUSTOMER_ERRROR_MESSAGE);
}
}catch(Exception ex)
{
LOGGER.error(Constants.PATIENT_FETCH_EXCEPTION, ex);
throw new CustomerDataException(MessageKeys.UPDATE_CUSTOMER_ERRROR_MESSAGE);
}
}`
I am getting nuppointerexception at line updateQuery.setParameter(Constants.ACCOUNTID,UUID.fromString(requestObject.getAccountId().toUpperCase())).
I can see the accountID is available in the requestObject when I debug.
Following is the stacktrace. Help is apprecited :)
ava.lang.NullPointerException: null
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateAccountInformation(CustomerDAOImpl.java:312)
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateCustomer(CustomerDAOImpl.java:285)
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateCustomerInformations(CustomerDAOImpl.java:180)
at com.cardinalhealth.chh.dao.CustomerDAOImpl.updateCustomerRecord(CustomerDAOImpl.java:141)
at com.cardinalhealth.chh.dao.CustomerDAOImplTest.testUpdateCustomerRecordforCustomerObject(CustomerDAOImplTest.java:452)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Your stubbing of session.createQuery:
when(session.createQuery(SQLConstants.FETCH_PERSON_ACCT)).thenReturn(query);
And what your code actually calls right before you get the exception:
Query updateQuery = session.createQuery(SQLConstants.UPDATE_PERSON_ACCOUNT);
So createQuery is stubbed to return a query when called with a different constant.
Meaning your production code will return null from createQuery and the next line then throws your NPE.
I have a SSIS package in which i use a WebService task to call a Spring WS.
The authentication is done by client certificate and username & password.
I have tried to do it like this a simple HttpConnection and a WebService task - Error 504 Gateway Timeout. When i edit the HttpConnection and click on Test Connection i get an error that states:
"The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel."
I have tried doing it with a script task and the same error.
I have even tried with a dummy console application and the same result.
I also have a java written app that actually does the job but i do not have access to it's code-behind. This basically proves that the problem is not from the server itself.
The java application has it's own keystore and the same certificates that i have installed on the server.
I opened a wireshark capture and i saw that when i used either of my apps the host made a DNS request for an address that i did not configure anywhere(it seems like a proxy address from the intranet), while the java app made a DNS request with the correct address.
I am stuck here, and i have no idea what the problem might be or what else i can do so that i would get a proper error.
Please advise!
Edit:
This is the code that calls the WS:
public static void CallWebService()
{
var _url = "https://<IP>/App/soap/DataService";
string action = "getData";
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("param1", "0");
parameters.Add("param2", "0");
parameters.Add("param3", "value");
XmlDocument soapEnvelopeXml = CreateSoapEnvelope(action, parameters);
HttpWebRequest webRequest = CreateWebRequest(_url);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
}
Console.WriteLine(soapResult);
}
private static HttpWebRequest CreateWebRequest(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
string thumbprint = "CERTIFICATE THUMBPRINT";
byte[] thumbprintArray = new byte[thumbprint.Split(new char[]{ ' ' }).Length];
string[] stringArray = thumbprint.Split(new char[] { ' ' });
for (int i = 0; i < thumbprintArray.Length; i++)
{
thumbprintArray[i] = Convert.ToByte(stringArray[i], 16);
}
X509Store localStore = new X509Store("My");
localStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCol = localStore.Certificates.Find(X509FindType.FindByTimeValid, DateTime.Now, true);
foreach (X509Certificate cert in certCol)
{
if (cert.GetCertHashString() == thumbprint)
{
webRequest.ClientCertificates.Add(cert);
break;
}
}
webRequest.UseDefaultCredentials = false;
webRequest.Credentials = new NetworkCredential("USER", "PASSWORD");
return webRequest;
}
private static XmlDocument CreateSoapEnvelope(string action, Dictionary<string, string> parameters)
{
string formatedParameters = string.Empty;
string paramFormat = "<{0}>{1}</{0}>";
foreach (string key in parameters.Keys)
{
formatedParameters += string.Format(paramFormat, key, parameters[key]);
}
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(string.Format(#"
<soapenv:Envelope xmlns:soap=""http://custom/soap/"" xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"">
<soapenv:Header/>
<soapenv:Body>
<soap:{0}>
{1}
</soap:{0}>
</soapenv:Body>
</soapenv:Envelope>", action, formatedParameters));
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
Iam calling a web service through my web service dynamically. I stored serviceName, MethodToCall, and array of parameters in my database table and execute these two methods to call a dynamic service url with .asmx extention and its method without adding its reference in my app. It works fine.
Following code is here.
public string ShowThirdParty(String strURL, String[] Params, String MethodToCall, String ServiceName)
{
String Result = String.Empty;
//Specify service Url without ?wsdl suffix.
//Reference urls for code help
///http://www.codeproject.com/KB/webservices/webservice_.aspx?msg=3197985#xx3197985xx
//http://www.codeproject.com/KB/cpp/CallWebServicesDynamic.aspx
//String WSUrl = "http://localhost/ThirdParty/WebService.asmx";
String WSUrl = strURL;
//Specify service name
String WSName = ServiceName;
//Specify method name to be called
String WSMethodName = MethodToCall;
//Parameters passed to the method
String[] WSMethodArguments = Params;
//WSMethodArguments[0] = "20500";
//Create and Call Service Wrapper
Object WSResults = CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);
if (WSResults != null)
{
//Decode Results
if (WSResults is DataSet)
{
Result += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
}
else if (WSResults is Boolean)
{
bool BooleanResult = (Boolean)WSResults;
if(BooleanResult)
Result += "Result: \r\n" + "Success";
else
Result += "Result: \r\n" + "Failure";
}
else if (WSResults.GetType().IsArray)
{
Object[] oa = (Object[])WSResults;
//Retrieve a property value withour reflection...
PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
foreach (Object oae in oa)
{
Result += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
}
}
else
{
Result += ("Result: \r\n" + WSResults.ToString());
}
}
return Result;
}
public Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
Uri objURI = new Uri(webServiceAsmxUrl);
//bool isProxy = client.Proxy.IsBypassed(objURI);
//objURI = client.Proxy.GetProxy(objURI);
//-Connect To the web service
// System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
string ccc = webServiceAsmxUrl + "?wsdl";// Connect To the web service System.IO.
//string wsdlContents = client.DownloadString(ccc);
string wsdlContents = client.DownloadString(ccc);
XmlDocument wsdlDoc = new XmlDocument();
wsdlDoc.InnerXml = wsdlContents;
System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(new XmlNodeReader(wsdlDoc));
//Read the WSDL file describing a service.
// System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream);
//Load the DOM
//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);
//--Generate a proxy client.
importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);
//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
if (warning == 0)
{
//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};
//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
//--Check For Errors
if (results.Errors.Count > 0)
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}
//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
Now the problem arraize when i have two different client servers. and calling a service from one server to the service deployed on other server. Follwing two kind of error log occurs. Cant find the exact reson for cope up this problem.
System.Net.WebException: The request failed with HTTP status 400: Bad Request.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at MarkUsageHistoryInSTJH.InsertUpdateIssueItemAditionalDetail(String csvBarcode, String csvName, String csvPMGSRN, String csvGLN, String csvMobile, String csvPhone, String csvAddressLine1, String csvAddressLine2, String csvAddressLine3, String csvIsHospital)
and
System.Net.Sockets.SocketException (0x80004005):
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.17.13.7:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
Please Carry Out Following Steps :
1) First of all try to access your service by adding reference of it.
It it works fine then we can say that there is no problem related to accessibility and permission.
2) If its not work then there is a problem with connection.
-->So Check Configuration in your service and try to set timeout for your web service.
(http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7-
333579a9f0fe/webservice-client-timeout)
3)Now try after setting the timeout.
it operation completes successfully after above change that means now you can check with your web client method(dymamic calling).
4) If still problem persists then this might be network latency issue. Check the n/w latency between your client and server.
it will helps you.