Getting Null Result from web Service in Asp.net - c#

I am trying to use a web service in my asp.net project. I add the web reference and trying to use the some of the functions of that service.I am trying to fetch some values from the web service.For this process First I am sending some data to web service for process.This is the code which I am trying to use
wsezp.ApiService ws = new wsezp.ApiService();
ws.Recharge("589746656", "608669", "1234567890", "5", "10", "12345");
wsezp.Result rs = new wsezp.Result();
string Requestid = rs.reqid;
string Status = rs.status;
Response.Write("Status of Requestid " + Requestid + "is " + Status);
As per my Document I will get my result like this
<recharge>
<reqid>0000<reqid/>
<status>SUCCESS</status>
<remark>recharge_transaction_id</remark>
<balance>your api balance</balance>
<mn>mobile number</mn>
<field1>operator transaction id</field1>
</recharge>
But I am getting null in the strings which I declare. Please tell me how can I use the web service for post the request and get back the result from the web service

Looks to me as if you are creating a new result. Are sure the call to recharge doesn't return the result you are looking for ? That would make sense.
wsezp.Result rs = ws.Recharge(...

Related

Invaild Json Result through Web Api in angular js

I have build a http post web api in asp which return the following string in Json
RootObject rootObject = new RootObject()
{
status = "User Registered"
};
msg = JsonConvert.SerializeObject(rootObject);
Below is my angular js controller in which I am consuming that web api
.controller('signupCtrl', function($scope,$http,$ionicPopup,$state,$ionicHistory) {
$scope.signup=function(data){
var link = 'http://xxxxxxxxxxxxxxxxxxxxxx/api/Home/RegisterUser';
//using http post
//passing values to parameter
$http.post(link, {RegisterName : data.name, RegisterUserName : data.username, RegisterPassword : data.password , RegisterEmail: data.mail , RegisterMobile : data.mobile})
.then(function (res){ //if a response is recieved from the server.
$scope.response = res; //contains Register Result
console.log($scope.response);
});
}
})
With the above code I am getting following result in google chrome console
I am try to get that status only to match it value but I am unable to do so.
The doubt I am having is that json format
console.log(JSON.stringify($scope.response)) will do what you need.
If you're wanting those particular value, you can just access those and pass them to log.
console.log($scope.response.data['status']);
you get the json as :
$scope.response = res.data;
might be you require JSON.parse(res.data) or $.parseJSON(res.data) for getting json object

Cognitive Services Operation Status API not returning any results

As per this link, Cognitive Services Topic Detection API not returning any results!
I have tried calling the OperationStatus API after the request from DetectTopics API has successfully been submitted. I created an AzureMachineLearningTextAnalytics object that I call the OperationStatus (OperationId , Key).
The response that I got back was : Status : RanToCompletion.
The result is however coming as null and the error message that I got when I debug into the generated REST API call was
"Internal error while executing BES operation".*
Has anyone been able to get results from the OperationStatus API? Can anyone please provide any suggestions regarding this issue ?
When using the Azure Cognative Services Text Analytics REST APIS with the generated Swagger definitions, use the WithOperationalResponseAsync method to get the operational response related to the request. From that you can query the status of the original request. A simplified C# example is as follows:
AzureMachineLearningTextAnalytics textAnalyzer = new AzureMachineLearningTextAnalytics();
var topicResult = textAnalyzer.DetectTopicsWithOperationResponseAsync(textAnalyticsAccountKey, null, null, null, topicDetection);
string operationId = topicResult.Result.Response.Headers.Location.Segments[topicResult.Result.Response.Headers.Location.Segments.Length - 1];
var status = textAnalyzer.OperationStatus(operationId, textAnalyticsAccountKey);
while ((((MySample.TextAnalytics.Models.OperationResult)status).Status == "NotStarted") ||
(((MySample.TextAnalytics.Models.OperationResult)status).Status == "Running"))
{
System.Threading.Thread.Sleep(20000);
status = textAnalyzer.OperationStatus(operationId, textAnalyticsAccountKey);
}
if (((Terawe.Retail.TextAnalytics.Models.OperationResult)status).Status == "Failed")
{
// Log an error to the console
Console.WriteLine($"Topic detection failed with status: {((MySample.TextAnalytics.Models.OperationResult)status).Message}");
}
else
{
// Process the phrases
}

why response.d returns null while response has a valid set of results - in asp.net web api

I am trying to use Web Api in my application. Everything seems to be working accept reading the json data. Below is my jQuery code that calls the web api method, and the values of the variables. As you may see, response.d returns an undefined value whereas response actually has a set of values.
Here is the web api method:
public IEnumerable<DiscussionWall> GetDiscussionWallsByCourse(int courseid)
{
gEchoLuDBContext db = new gEchoLuDBContext();
var discussionwalls = db.DiscussionWalls.Where(dw => dw.CourseId == courseid);
if (discussionwalls == null)
throw new HttpResponseException(HttpStatusCode.NotFound);
else
return discussionwalls;
}
Why I cannot simply use response.d in this case? Response is in this format { $id="1", $values=[3] }? How can I read $values array?
The following line solved the problem.
var discussionwalls = response['$values'];
However, I wonder if this creates a security issue, and I wonder why response.d did not work in this scenario. Does anyone have an idea?

File_get_contents returning null/invalid format. when webservice which is been called returns an object

I have a C#(Rest Service) web service which returns an object.
public object[] GetObject()
{
object[] arr = new object[3];
arr[0] = "String literal";
arr[1] = 3;
arr[2] = null;
return arr;
}
My Interface consists of following code
[OperationContract]
[WebGet(UriTemplate = "/TestWcf", BodyStyle = WebMessageBodyStyle.Bare)]
object[] GetObject(); //i tried including ResponseFormat = WebMessageFormat.Xml also
My Php file which calls the web service consists of
$result=file_get_contents('http://example/TestWcf');
When i perform echo $result; its displaying the value but im not able to use it in the file or to perform any operation as it was taking null value.I tried using
$result = new SimpleXMLElement($result) ;//even $result[1]
but the $result value was null.Please help
Just wanted to add one more thing if the return value from the web service is string,int etc.. im getting the value n also can be used but when its object this problem exists
May be you are trying to access the web service which required "Authentication"
For this kind of Web Services, you need to send the authentication details which are provided by Service providers in request headers
Normally, you have to use cURL of SOAP protocols to do this.

how to solve 403 error in google analytics api call

I'm using the code in the following post:
Google Analytics API - Programmatically fetch page views in server side
but getting a 403 forbidden error on the highlighted line below. I don't think it's a credential issue, becuase my credentials are correct, as I have checked and double checked, and also I log in to the analytics account with these credentials. So maybe it is somekind of folder permissions issue ?
//-------------- Get Auth Token -------------------
WebClient webClient = new WebClient();
NameValueCollection data = new NameValueCollection();
data.Add("accountType", "GOOGLE");
data.Add("Email", "xxxx#gmail.com");
data.Add("Passwd", "xxxx");//Passwd, not a misspell.
data.Add("service", "analytics");
data.Add("source", "xxxx-xxxx-xx");//Could be anything.
byte[] bytes = webClient.UploadValues("https://www.google.com/accounts/ClientLogin", "POST", data);
string tokens = Encoding.UTF8.GetString(bytes);
string authToken = extractAuthToken(tokens);
//-------------- Get page views -------------------
string feed = "https://www.google.com/analytics/feeds/data";
//Required:
string ids = "ga:xxxx";
string metrics = "ga:pageviews";
string startDate = "2011-06-25";
string endDate = "2011-07-25";
//Optional:
string dimensions = "ga:pagePath";
string sort = "-ga:pageviews";
string feedUrl = string.Format("{0}?ids={1}&dimensions={2}&metrics={3}&sort={4}&start-date={5}&end-date={6}",
feed, ids, dimensions, metrics, sort, startDate, endDate);
webClient.Headers.Add("Authorization", "GoogleLogin " + authToken);
// This is the line I get the 403 error on:
**string result = webClient.DownloadString(feedUrl);**
//-------------- Extract data from xml -------------------
XDocument xml = XDocument.Parse(result);
var ns1 = "{http://www.w3.org/2005/Atom}";
var ns2 = "{http://schemas.google.com/analytics/2009}";
var q = from entry in xml.Descendants()
where entry.Name == ns1 + "entry"
select new
{
PagePath = entry.Element(ns2 + "dimension").Attribute("value").Value,
Views = entry.Element(ns2 + "metric").Attribute("value").Value
};
//-------------- Do something with data -------------------
foreach (var page in q)
{
Debug.WriteLine(page.PagePath + " " + page.Views);
}
//-------------- Help Method -------------------
private string extractAuthToken(string data)
{
var tokens = data.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
return tokens.Where(token => token.StartsWith("Auth=")).Single();
}
If you call the Google Analytics API too frequently, you could get 403 Forbidden errors. From that link:
General Analytics API quotas. These apply to both the Analytics APIs, i.e., Management API and Core Reporting API:
- 50,000 requests per project per day
- 10 queries per second (QPS) per IP
I've seen 403 errors returned from the AdWords API when my applications have made too many consecutive calls, so that potentially could be the cause of your problem.
EDIT
If you're not able to make any calls at all, then review the steps listed here under "Before You Begin". According to the documentation, you'll need to register your application through the Google API console before you can use the API.

Categories