Consuming web services in android studio - ksoap2

I am trying to access a web service from android studio and generates an exeption when I make the call've read several tutorials've tried everything and nothing.
final String SOAP_ACTION = "http://www.maticlot.com/TestWS";
final String NAMESPACE = "http://www.maticlot.com/";
final String METHOD_NAME = "TestWS";
final String DIRURL = direccionIp + "/wsReportes.asmx";
SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
request.addProperty("Parametro","Pruebas");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.implicitTypes = true;
envelope.setAddAdornments(false);
envelope.setOutputSoapObject(request);
try {
HttpTransportSE transporte = new HttpTransportSE(DIRURL);
transporte.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
transporte.debug = true;
transporte.call(SOAP_ACTION,envelope);
SoapPrimitive resultadoXML = (SoapPrimitive)envelope.getResponse();
String resultado = resultadoXML.toString();
Mensaje = resultado;
textView03.setText("Paso Bien");
//Montrar la respuesta en un Toast
Toast.makeText(getBaseContext(),resultado+"",Toast.LENGTH_LONG).show();
}
catch (Exception e){
Toast.makeText(getBaseContext(),toString(),Toast.LENGTH_LONG).show();
}

Related

Using webforms with API - returns null values

Can anybody help me?
This code work fine with no parameter:
private void PopulateGridView()
{
string apiUrl = apiurl + "local_stud_listgrupmenu";
string inputJson = (new JavaScriptSerializer()).Serialize(input);
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Encoding = Encoding.UTF8;
string json2 = client.UploadString(apiUrl,"POST");
Response.Write("output:" + json2.ToString());
}
but this code below return null with post parameter, what wrong my code :)
private void crudinsert()
{
string data;
string apiUrl = apiurl + "ins_rec_crudparentmenu";
string x = "";
var vm = new { mod = "0", moduldesc ="test'", modulurl = "tesx.aspx", idparent= "0" };
using (var clien2 = new WebClient())
{
var dataString = (new JavaScriptSerializer()).Serialize(vm);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
x = client.UploadString(new Uri(apiUrl), "POST", dataString);
}
Response.Write("output:"+x);
}

Cannot refresh listview with observablecollection

I am trying to refresh my listview when an item is removed from it, but every time it gives me this error:
System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values.
Parameter name: index.
Before updating the ObservableCollection, I do this:
Groups = new ObservableCollection<RequestGroups>();
And then I fill it with this:
var temp = (JArray)resultJson["data"];
JArray jarr = temp;
foreach (JObject contents in jarr.Children<JObject>())
{
Requests obj = new Requests();
obj.Id = (int)contents["id"];
Client c = new Client();
c.address = contents["address"].ToString();
c.phone = contents["phone"].ToString();
c.name = contents["user"].ToString();
obj.Client = c;
obj.Date = contents["date"].ToString();
obj.Duration = contents["duration"].ToString();
obj.DurationText = "Duración: "+contents["duration"].ToString()+"h";
obj.Price = "$" + contents["price"].ToString();
String[] cDate = obj.Date.Split(' ');
String cHour = cDate[1]+" "+cDate[2];
obj.Hour = cHour;
String[] date = cDate[0].Split('-');
String title = months[date[1]] + " " + date[0];
obj.Title = title;
bool flag = false;
foreach(RequestGroups rqG in Groups){
if(rqG.Title.Equals(title)){
rqG.Add(obj);
flag = true;
}
}
if(!flag){
RequestGroups rq = new RequestGroups(title, date[1] + "-" + date[0]);
rq.Add(obj);
Device.BeginInvokeOnMainThread(() =>
{
Groups.Add(rq);
});
}
}
This is where I remove the items:
private async Task UpdateRequest(int status,int idEvent)
{
HttpClient hTTPClient = new HttpClient();
var client = new HttpClient();
client.Timeout = TimeSpan.FromSeconds(60);
client.BaseAddress = new Uri(Utils.baseUrl);
Dictionary<string, string> dataToSend = new Dictionary<string, string>();
dataToSend.Add("session", Utils.loginKey);
dataToSend.Add("eventId", idEvent+"");
dataToSend.Add("status", status.ToString());
string jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(dataToSend, new KeyValuePairConverter());
var contentVar = new StringContent(jsonData, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = await client.PostAsync("/UpdateEvent", contentVar);
var result = await response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
string contents = await response.Content.ReadAsStringAsync();
var resultJson = JObject.Parse(result);
if ((int)resultJson["status"] == 0)
{
await base.DisplayAlert((string)resultJson["msg"], "", "OK");
return;
}
else if ((int)resultJson["status"] == 1)
{
//I'm currently trying to reload the whole view, before this was calling the method above.
await this.mainPage.Navigation.PushAsync(new NavigationPage(new MasterMenu.MainPage()));
await getRequests();
}
else
{
await base.DisplayAlert("Error procesando la solicitud, intente más tarde", "", "Ok");
return;
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error update request: {0}", ex);
}
await Task.Delay(1);
}
If I leave it like that, UI will not update. Please help me, as I've been struggling with this issue for 2 days now. It happens exclusively on iOS.
The issue was fixed after updating iOS. The problem was caused because of a buggy iOS version that had problems indexing objects. After updating, everything ran as smoothly as usual. If anyone runs into this issue (exclusively on iOS), try updating both iOS and Xamarin Forms.

AcquireTokenByAuthorizationCodeAsync does not complete

Here is my code. It's been over a month I'm trying to add calendars in Outlook but nothing is working :( please help. The function AcquireTokenByAuthorizationCodeAsync never completes. And the token.Result is always null
string authority = ConfigurationManager.AppSettings["authority"];
string clientID = ConfigurationManager.AppSettings["clientID"];
Uri clientAppUri = new Uri(ConfigurationManager.AppSettings["clientAppUri"]);
string serverName = ConfigurationManager.AppSettings["serverName"];
var code = Request.Params["code"];
AuthenticationContext ac = new AuthenticationContext(authority, true);
ClientCredential clcred = new ClientCredential(clientid, secretkey);
//ac = ac.AcquireToken(serverName, clientID, clientAppUri, PromptBehavior.Auto);
//string to = ac.AcquireToken(serverName, clientID, clientAppUri, PromptBehavior.Auto).AccessToken;
var token = ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri("http://localhost:2694/GetAuthCode/Index/"), clcred, resource: "https://graph.microsoft.com/");
string newtoken = token.Result.AccessToken;
ExchangeService exchangeService = new ExchangeService(ExchangeVersion.Exchange2013);
exchangeService.Url = new Uri("https://outlook.office365.com/" + "ews/exchange.asmx");
exchangeService.TraceEnabled = true;
exchangeService.TraceFlags = TraceFlags.All;
exchangeService.Credentials = new OAuthCredentials(token.Result.AccessToken);
exchangeService.FindFolders(WellKnownFolderName.Root, new FolderView(10));
Appointment app = new Appointment(exchangeService);
app.Subject = "";
app.Body = "";
app.Location = "";
app.Start = DateTime.Now;
app.End = DateTime.Now.AddDays(1);
app.Save(SendInvitationsMode.SendToAllAndSaveCopy);
I have experienced this issue when I call the AcquireTokenByAuthorizationCodeAsync using result instead of using await key words and all these code was in a asynchronously controller in the MVC.
If you are in the same scenario, you can fix this issue by two ways:
1.Always using the async, await like code below:
public async System.Threading.Tasks.Task<ActionResult> About()
{
...
var result =await ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri("http://localhost:2694/GetAuthCode/Index/"), clcred, resource: "https://graph.microsoft.com/");
var accessToken = result.AccessToken;
...
}
2.Use the synchronization controller:
public void About()
{
...
var result =ac.AcquireTokenByAuthorizationCodeAsync(code, new Uri("http://localhost:2694/GetAuthCode/Index/"), clcred, resource: "https://graph.microsoft.com/").Result;
var accessToken = result.AccessToken;
...
}

passing access token to Jira using OAuth Authentication

I am using OAuth authenication in Jira to test some methods in jira using JIRA Rest Java Client. I have got the access token using OAuth authenication that I need to pass on Jira URL. Here is all what I have got to get access token.
Token is 38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Token secret is cnDSL8oJyuoaQdRcFDwgHzLppSshQn9b
Retrieved request token. go to http://bmh1060149:8080/plugins/servlet/oauth/authorize?oauth_token=38ESi9IJW5u3vKDslPFtuV1ZtzDpr6zi
Access token is : 015CeJiH8cpI5R3OKpNco158kApq8YwV
Now I am passing that access token to Jira URL but I am getting an empty array. Please let me know where I am doing wrong or what changes do I need to incorporate into my code to make this thing work. Here is my code.
public void getAllIssueTypesUsingOAuth(JiraCQCredential jcqcred) {
System.out.println("Inside getAllIssuetypeAssociatedToProject for JiraAdapterImpl");
//String username = jcqcred.getUserName();
//String password = jcqcred.getPassword();
String jiraURL = jcqcred.getJiraUrl();
if (!jiraURL.endsWith("/")) {
jiraURL = jiraURL + "/";
}
try {
String accessToken = JiraAdapterImpl.getAccessToken(); // This method is giving me access token
URL url = new URL(jiraURL + "rest/api/2" + "/" + "issuetype?access_token=" + accessToken);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
httpConnection.setRequestProperty("Content-Type", "application/json");
httpConnection.setRequestMethod("GET");
BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
String issueTypes = sb.toString();
System.out.println("Issuetype associated to project are\n" + issueTypes);
JSONArray jsonArray = new JSONArray(issueTypes);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String issueNames = (String) jsonObject.get("name");
System.out.println(issueNames);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
Its giving me an empty array like []
Hi After searching the little bit I finally managed to a find the solution to the above problem. After getting the access token just pass that access token to the makeAuthenticatedRequest(url, accessToken) method that will give you the resultant data which you want to retrive. Here url is the url which you want to hit to get the resultant data.
private AtlassianOAuthClient getJiraOAuthClient() {
final String baseURI = "http://bmh1060149:8080";
final String consumerKey = "hardcoded-consumer";
final String consumerPrivatekey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDFkPMZQaTqsSXI+bSI65rSVaDzic6WFA3WCZMVMi7lYXJAUdkXo4DgdfvEBO21Bno3bXIoxqS411G8S53I39yhSp7z2vcB76uQQifi0LEaklZfbTnFUXcKCyfwgKPp0tQVA+JZei6hnscbSw8qEItdc69ReZ6SK+3LHhvFUUP1nLhJDsgdPHRXSllgZzqvWAXQupGYZVANpBJuK+KAfiaVXCgA71N9xx/5XTSFi5K+e1T4HVnKAzDasAUt7Mmad+1PE+56Gpa73FLk1Ww+xaAEvss6LehjyWHM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etopX7NDbB0KNUklyiEvf72tUCtyDk5QBgSrqcCgYEAnlg3ByRd/qTFz/darZi9ehT68Cq0CS7/B9YvfnF7YKTAv6J2Hd/i9jGKcc27x6IMi0vf7zrqCyTMq56omiLdu941oWfsOnwffWRBInvrUWTj6yGHOYUtg2z4xESUoFYDeWwe/vX6TugL3oXSX3Sy3KWGlJhn/OmsN2fgajHRip0=";
AtlassianOAuthClient jiraoAuthClient = new AtlassianOAuthClient(consumerKey, consumerPrivatekey, baseURI, "");
return jiraoAuthClient;
}
Here is the code to get Access Token
private String getAccessToken() {
AtlassianOAuthClient jiraoAuthClient = getJiraOAuthClient();
TokenSecretVerifierHolder requestToken = jiraoAuthClient.getRequestToken();
String authorizeUrl = jiraoAuthClient.getAuthorizeUrlForToken(requestToken.token);
String token = requestToken.token;
String tokenSecret = requestToken.secret;
System.out.println("Token is " + requestToken.token);
System.out.println("Token secret is " + requestToken.secret);
System.out.println("Retrieved request token. go to " + authorizeUrl);
String accessToken = jiraoAuthClient.swapRequestTokenForAccessToken(token, tokenSecret, "");
System.out.println("Access token is : " + accessToken);
return accessToken;
}
This is the method you call to retrieve the data.
public void getAllCommentOfIssueUsingOAuth() {
logger.info("Inside getAllCommentOfIssue for JiraAdapterImpl");
AtlassianOAuthClient jiraoAuthClient = getJiraOAuthClient();
String accessToken = getAccessToken();
String url = "your Jira URL";
String responseAsString = jiraoAuthClient.makeAuthenticatedRequest(url, accessToken);
System.out.println(responseAsString);
}
This will give you the resultant JSON data or XML data in resultantString.

HttpClient.PostAsync returning Null on A Web API POST

I am trying to get response from an API on few GET and POST calls, whenever i try to get Response from a web API POST it gives an System.NullReferenceException: Object reference not set to an instance of an object.. I am using PostAsync to get response. It works absolutely fine on my local machine but is returning NULL response on deployment machine.
#region API_CALL
System.Net.Http.HttpClient Client = new System.Net.Http.HttpClient();
string CompleteURL = URL.Trim() + URL_FromJSON.Trim();
#region URL Construct For GET Requests
CompleteURL = GetURL(ParameterValue, CallType_FromJSON, CompleteURL);
#endregion URL Construct For GET Requests
string URLContent = string.Empty;
Client.BaseAddress = new System.Uri(CompleteURL);
byte[] cred = UTF8Encoding.UTF8.GetBytes(ClientID.Trim() + Constants.APIConstants.ColonConnector + ClientPass.Trim());
string Encoded = Convert.ToBase64String(cred);
Client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue(Constants.APIConstants.AuthTypeBearer, accessToken);
Client.DefaultRequestHeaders.Host = IPAddress.Trim();
CacheControlHeaderValue val = new CacheControlHeaderValue();
val.NoCache = true;
Client.DefaultRequestHeaders.CacheControl = val;
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(Constants.APIConstants.ContentType));
Client.DefaultRequestHeaders.Add(Constants.APIConstants.LicenseKey, LiscenseKEY);
Client.DefaultRequestHeaders.Add(Constants.APIConstants.PostmanToken, PostmanToken);
//client.DefaultRequestHeaders.Add(Constants.APIConstants.AccessToken, accessToken);
System.Net.Http.HttpContent Content = new StringContent(JSONData, UTF8Encoding.UTF8, Constants.APIConstants.ContentType);
// Only for debug purpos:
LogManager.Logger.Invoke(LogLevels.TraceDetail, Source, "Request to API: " + JSONData, Request.ActorID);
HttpResponseMessage Message = new HttpResponseMessage();
if (CallType_FromJSON == Constants.HttpMethod.Post)
{ Message = Client.PostAsync(CompleteURL, Content).Result; }
else if (CallType_FromJSON == Constants.HttpMethod.Get)
{ Message = Client.GetAsync(CompleteURL, HttpCompletionOption.ResponseContentRead).Result; }
string Description = string.Empty;
#region Response Logging
try
{
LogManager.Logger.Invoke(LogLevels.TraceDetail, Source, "Response from API: " + Message.Content.ReadAsStringAsync().Result, Request.ActorID);
}
catch(Exception EX)
{
LogManager.Logger.Invoke(LogLevels.TraceError, Source, "Exception while logging response from API" + EX.ToString()+"Stack: "+EX.StackTrace, Request.ActorID);
}
#endregion Response Logging
if (Message.IsSuccessStatusCode)
{
string Result = Message.Content.ReadAsStringAsync().Result;
ResponseJson = Result;
Description = Result;
}
else
{
try
{
string Result1 = Message.Content.ReadAsStringAsync().Result;
LogManager.Logger.Invoke(LogLevels.TraceInfo, Source, "Failed: ... Recieved JSON: " + Result1, Request.ActorID);
}
catch { }
return new TransactionResponse() { Response = Constants.ResponseCodes.Error };
}
#endregion API_CALL
break;
}
TransactionResponse Response = new TransactionResponse();
Response.Response = ResponseJson;
return Response;
}
catch (Exception Ex)
{
LogManager.ExpLogger.Invoke(Source, Ex, Request.ActorID);
return new TransactionResponse() { Response = Constants.ResponseCodes.Error };
}
the object : Message is null after execution of Message = Client.PostAsync(CompleteURL, Content).Result
Try reading as string asynch with the in the reach of postasynch, use it with the same block of code it works,
if (CallType_FromJSON == Constants.HttpMethod.Post)
{ Message = Client.PostAsync(CompleteURL, Content).Result; }
else if (CallType_FromJSON == Constants.HttpMethod.Get)
{ Message = Client.GetAsync(CompleteURL, HttpCompletionOption.ResponseContentRead).Result; }
string Description = string.Empty;
example:
var = httpresult.content.readasstringasyhnc();
You can also typecast to any model you want her.

Resources