I am calling a web service in my php page. The web services are in C#. When I try to call a method using soap client object, it displays me error like:
System.NullReferenceException: Object reference not set to an instance of an object.
The code I use to call Web service method is :
$Username = "username";
$Password = "password";
$LifetimeRequest = 60*60*24;
$soap_data = array(
'Username' => $Username,
'Password' => $Password,
'LifetimeRequest' => $LifetimeRequest
);
$client = new SoapClient('http://50.56.173.161:8502/AdomniService.svc?wsdl');
$response = $client->ClientLogin($soap_data);
var_dump($response);
When I use var_dump it shows output like:
object(stdClass)#2 (1) {
["ClientLoginResult"]=>
object(stdClass)#3 (3) {
["Error"]=>
object(stdClass)#4 (5) {
["Private"]=>
float(2)
["Public"]=>
int(1)
["Details"]=>
string(284) "System.NullReferenceException: Object reference not set to an instance of an object.
at Adomni.AdomniService.ClientLogin(ClientLoginRequest request) in C:\Users\megiddo\Documents\Visual Studio 2010\Projects\Adomni\AdOmniAPIService\AdomniService\AdomniClientService.svc.cs:line 107"
["ErrorCode"]=>
int(0)
["ErrorMessage"]=>
NULL
}
["Status"]=>
int(-1)
["Token"]=>
object(stdClass)#5 (8) {
["Private"]=>
float(2)
["Public"]=>
int(1)
["EventNotificationUri"]=>
NULL
["IsManager"]=>
bool(false)
["LifetimeRequest"]=>
int(0)
["Password"]=>
NULL
["TokenId"]=>
int(0)
["UserName"]=>
NULL
}
}
}
Can anyone tell me what am I doing wrong here? Thanks in advance.
The code which was used in C# is like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Security;
using System.IO;
using System.Data;
using AdOmniWebPortal.AdOmniService;
namespace AdOmniWebPortal
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void AdOmniLogin_Authenticate(object sender, AuthenticateEventArgs e)
{
AdomniServiceClient Client = new AdomniServiceClient();
LoginRequest LoginRequest = new LoginRequest();
LoginResponse LoginResponse = new LoginResponse();
LoginRequest.Username = AdOmniLogin.UserName;
LoginRequest.Password = AdOmniLogin.Password;
LoginRequest.LifetimeRequest = 60*60*24;
//This guy will be changed
LoginRequest.EventNotificationURL = new Uri("http://herp-a-derp.com/awesome.html");
LoginResponse = Client.Login(LoginRequest);
if (LoginResponse.Status == 0)
{
System.Web.Security.FormsAuthentication.RedirectFromLoginPage(LoginResponse.Token.UserName, true);
LifetimeToken token = LoginResponse.Token;
Session["Token"] = token;
GetUserRequest request = new GetUserRequest() { Token = token };
GetUserResponse response = Client.GetUser(request);
if (response.GetUser.Type == AdOmniService.UserType.Seller)
{
Response.Redirect("~/Pages/Seller/SellerHomeDashboard.aspx");
}
if (response.GetUser.Type == AdOmniService.UserType.Client)
{
Response.Redirect("~/Pages/Buyer/BuyerHomeDashboard.aspx");
}
if (response.GetUser.Type == AdOmniService.UserType.None)
{
Response.Redirect("~/Pages/Buyer/BuyerHomeDashboard.aspx");
}
}
else
{
Response.Redirect("~/Login.aspx");
Response.Write(LoginResponse.Error.ErrorMessage);
}
}
}
}
I have put the whole .cs page content in Edit.
Use Fiddler (a http debug proxy)
that will allow you to peak inside of the request being made to the web service (in xml format)
so you can see if you are missing anything.
channel your c# client through fiddler, and take a look
http://www.fiddler2.com/fiddler2/
Maybe in your PHP script, you should also set the EventNotificationURL variable.
Take a look at this section in the error response:
["EventNotificationUri"]=>
NULL
Maybe the service expects you to pass in a EventNotificationUri value, just like you pass in the the Password, Username and LifetimeRequest.
[EDIT]
Try to change your variable name from Username to UserName. As far as I found out, PHP should be case sensitive in this matter, so "Username" != "UserName"
Related
I am working on a Windows app and am having some issues with cookies. Please note that I am working with Windows.Web.Http, not the System namespace HttpClient.
The API I'm working with uses an auth-header for authentication. Basically after a POST to login, I need a way to get the cookies returned and then use those cookies to perform the subsequent API calls. I posted an example of what I currently have, which succeeds. I can see the cookies in the result object. I'm just not entirely sure where to go from here / how to proceed. Thanks! Any ideas?
using MyApi.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Web.Http;
using Newtonsoft.Json;
using MyApi.Models.Auth;
using MyApi.Models;
namespace MyApi
{
public class MyService
{
private const string MyBaseUrl = "http://api.my.com:3000";
private readonly HttpClient _httpClient = new HttpClient();
public async Task<SignInResponse> AttemptLogin(string username, string password)
{
if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
throw new ArgumentException("Username or password is null or empty");
var uri = new Uri(string.Format("{0}/{1}", MyBaseUrl, "auth/signin"));
var authSignIn = new Models.Auth.SignInRequest();
authSignIn.Email = username;
authSignIn.Password = password;
var myObject = JsonConvert.SerializeObject(authSignIn);
// I see the headers in the result object, but I'm not
// sure the best way to a) get them out and b) shove them into
// all of the next calls
var result = await _httpClient.PostAsync(uri,
new HttpStringContent(myObject.ToString(),
Windows.Storage.Streams.UnicodeEncoding.Utf8,
"application/json"));
var content = await result.Content.ReadAsStringAsync();
var successResponse = new SignInResponse();
try
{
successResponse = JsonConvert.DeserializeObject<SignInResponse>(content);
}
catch (Exception)
{
var failResponse = JsonConvert.DeserializeObject<ErrorResponse>(content);
throw new Exception(failResponse.message);
}
return successResponse;
}
}
}
You can use HttpBaseProtocolFilter.CookieManager, e.g.:
var filter = new HttpBaseProtocolFilter();
var cookieManager = filter.CookieManager;
var uri = new Uri("http://api.my.com:3000");
foreach (var cookie in cookieManager.GetCookies(uri))
{
Debug.WriteLine(cookie.Name);
Debug.WriteLine(cookie.Value);
}
Notice, if the cookies are already in the HttpCookieContainer, the cookies will be automatically added in the next requests to http://api.my.com:3000, and no action is required from your side.
If you want to modify them or delete them, the HttpCookieContainer has methods to do that.
Take a look at Flurl. It presents a fluent interface over the Http bits, so you can say something like this to authenticate and reuse the connection with the cookies:
using (var fc = new FlurlClient().EnableCookies())
{
var url = new Url( "http://api.com/endpoint" ) ;
await url
.AppendPathSegment("login")
.WithClient(fc)
.PostUrlEncodedAsync(new { user = "user", pass = "pass" });
var page = await url
.AppendPathSegment("home")
.WithClient(fc)
.GetStringAsync();
// Need to inspect the cookies? FlurlClient exposes them as a dictionary.
var sessionId = fc.Cookies["session_id"].Value;
}
I am new to Google Compute Engine. Some one please help me with creating Google Compute Engine VMs programmatically using REST APIs in C#.
Here [1] you can found the API documentation to create an instance and at the bottom of the document the C# examples [2]:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Compute.v1;
using Google.Apis.Services;
using Newtonsoft.Json;
using System;
using System.Threading.Tasks;
using Data = Google.Apis.Compute.v1.Data;
namespace ComputeSample
{
public class ComputeExample
{
public static void Main(string[] args)
{
ComputeService computeService = new ComputeService(new BaseClientService.Initializer
{
HttpClientInitializer = GetCredential(),
ApplicationName = "Google-ComputeSample/0.1",
});
// Project ID for this request.
string project = "my-project"; // TODO: Update placeholder value.
// The name of the zone for this request.
string zone = "my-zone"; // TODO: Update placeholder value.
// TODO: Assign values to desired properties of `requestBody`:
Data.Instance requestBody = new Data.Instance();
InstancesResource.InsertRequest request = computeService.Instances.Insert(requestBody, project, zone);
// To execute asynchronously in an async method, replace `request.Execute()` as shown:
Data.Operation response = request.Execute();
// Data.Operation response = await request.ExecuteAsync();
// TODO: Change code below to process the `response` object:
Console.WriteLine(JsonConvert.SerializeObject(response));
}
public static GoogleCredential GetCredential()
{
GoogleCredential credential = Task.Run(() => GoogleCredential.GetApplicationDefaultAsync()).Result;
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped("https://www.googleapis.com/auth/cloud-platform");
}
return credential;
}
}
}
[1] https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert
[2] https://cloud.google.com/compute/docs/reference/rest/v1/instances/insert#examples
Hi guys I'm having trouble fetching products from amazon web api.
I have used this code from the internet, adding all the neccessary references. I tried adding a view and chose itemsearchresponce as the model class but it does not display the product, I get the following error:
Unable to generate a temporary class (result=1).
error CS0029: Cannot implicitly convert type 'AmazonProduct.com.amazon.webservices.ImageSet' to
'AmazonProduct.com.amazon.webservices.ImageSet[]'
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AmazonProduct.com.amazon.webservices;
namespace Forest.Controllers
{
public class AmazonController : Controller
{
private AmazonProduct.com.amazon.webservices.AWSECommerceService _Products;
public AmazonController()
{
_Products = new AmazonProduct.com.amazon.webservices.AWSECommerceService();
}
[HttpGet]
public ActionResult listProducts()
{
var searchIndex = "Shoes";
var keywords = "jordan";
// Create an ItemSearch wrapper
ItemSearch search = new ItemSearch();
search.AssociateTag = "[Your Associate ID]";
search.AWSAccessKeyId = "MyKey";
// search.Version= "2011-08-01";
// Create a request object
ItemSearchRequest request = new ItemSearchRequest();
// Fill the request object with request parameters
request.ResponseGroup = new string[] { "ItemAttributes" };
// Set SearchIndex and Keywords
request.SearchIndex = searchIndex;
request.Keywords = keywords;
// Set the request on the search wrapper
search.Request = new ItemSearchRequest[] { request };
ItemSearchResponse response = _Products.ItemSearch(search);
return View(response);
}
}
}
Go to the generated proxy and replace ImageSet[][] with ImageSet[].
Also take a look at Amazon Product Advertising API C# if you already haven't.
I'm testing the "OAuth/OAuth2/OAuthClient/Facebook.aspx" file from the DotNetOpenAuth.Samples solution.
here is the code (Simple authentication from Facebook directly in the PageLoad) :
namespace OAuthClient {
using System;
using System.Configuration;
using System.Net;
using System.Web;
using DotNetOpenAuth.ApplicationBlock;
using DotNetOpenAuth.ApplicationBlock.Facebook;
using DotNetOpenAuth.OAuth2;
public partial class Facebook : System.Web.UI.Page {
private static readonly FacebookClient client = new FacebookClient {
ClientIdentifier = ConfigurationManager.AppSettings["facebookAppID"],
ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(ConfigurationManager.AppSettings["facebookAppSecret"]),
};
protected void Page_Load(object sender, EventArgs e)
{
IAuthorizationState authorization = client.ProcessUserAuthorization();
if (authorization == null)
{
// Kick off authorization request
client.RequestUserAuthorization();
}
else
{
var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
this.nameLabel.Text = HttpUtility.HtmlEncode(graph.Name);
}
}
}
}
}
}
When the Page_Load is firing for the first time, authorization == null, so the client.RequestUserAuthorization(); call is executed, and then, Page_load is firing a second time.
Why ? I don't understand the mecanism.
I used fiddler to sniff the response sent back by facebook after "client.RequestUserAuthorization()", but it's always an empty body.
My final goal is to launch the authenfication process from a button. But when the "client.RequestUserAuthorization();" call is executed within a button, nothing is fired a second time... so authorization is always null.
I'm trying to write an online application to access my google analytics data using a google service account. Here's my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace GA_server2server_POC.Models
{
using System.Security.Cryptography.X509Certificates;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Util;
using Google.Apis.Services;
using Google.Apis.Requests;
public class Oauth_With_API
{
public static void ApiTest()
{
log4net.Config.XmlConfigurator.Configure();
const string ServiceAccountId = "xxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
const string ServiceAccountUser = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxdeveloper.gserviceaccount.com";
AssertionFlowClient client = new AssertionFlowClient(
GoogleAuthenticationServer.Description, new X509Certificate2("C:\\Users\\rcarter\\Downloads\\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable))
{
Scope = "https://www.googleapis.com/auth/analytics.readonly",
ServiceAccountId = ServiceAccountUser
};
OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
{
Authenticator = authenticator
});
string profileId = "ga:xxxxxxxx";
string startDate = "2013-07-01";
string endDate = "2013-07-15";
string metrics = "ga:visits";
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
request.Dimensions = "ga:date";
GaData data = request.Execute(); //error occurs here. After this, thread exits.
Console.WriteLine(data.TotalResults);
}
}
}
So far my code executes, but I get the following output:
WebDev.WebServer40.exe Information: 0 : DotNetOpenAuth, Version=4.0.0.11165, Culture=neutral, PublicKeyToken=2780ccd10d57b246 (official)
WebDev.WebServer40.exe Information: 0 : Preparing to send AssertionFlowMessage (2.0) message.
WebDev.WebServer40.exe Information: 0 : Sending AssertionFlowMessage request.
WebDev.WebServer40.exe Information: 0 : HTTP POST https://accounts.google.com/o/oauth2/token
WebDev.WebServer40.exe Information: 0 : The following required parameters were missing from the DotNetOpenAuth.OAuth2.Messages.AccessTokenFailedResponse message: {error,
}
WebDev.WebServer40.exe Information: 0 : Received UnauthorizedResponse response.
After this, the thread exits, and the program refuses to print any of the data. The trouble seems to occur at request.Execute();. The part that I find especially confusing, is that if I put a breakpoint on Console.WriteLine(data.TotalResults);, I can see the data I want in the local variable data. It contains everything I want to print, but I can't identify the cause of the error keeping it from doing anything after request.Execute();. After much searching, I haven't found much at all about the error listed above.
The code I'm using is based on the answer given to this question here. A few things have changed in the google analytics libraries since that question was answered, but much of my code is the same.
I've checked and re-checked all the account-specific variables. To test this, I'm running it on my local machine as a ASP.NET MVC 4 Web App.
Any help or advice on how to troubleshoot this issue is appreciated. Please let me know if I can provide more information which might help. Thanks for reading.
Try following one
using System.Security.Cryptography.X509Certificates;
using DotNetOpenAuth.OAuth2;
using Google.Apis.Analytics.v3;
using Google.Apis.Analytics.v3.Data;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Services;
private void TestMethod()
{
try
{
string scope_url = "https://www.googleapis.com/auth/analytics.readonly";
//client_id: This is the "Email Address" one, not the "Client ID" one... oddly...
string client_id = "************-***********************#developer.gserviceaccount.com";
//key_file: This is the physical path to the key file you downloaded when you created your Service Account
string key_file = #"***************************************-privatekey.p12";
//key_pass: This is probably the password for all key files, but if you're given a different one, use that.
string key_pass = "notasecret";
AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;
//key: Load up and decrypt the key
X509Certificate2 key = new X509Certificate2(key_file, key_pass, X509KeyStorageFlags.Exportable);
//client: we're using the AssertionFlowClient, because we're logging in with our certificate
AssertionFlowClient client = new AssertionFlowClient(desc, key) { ServiceAccountId = client_id, Scope = scope_url };
OAuth2Authenticator<AssertionFlowClient> auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
//gas: An instance of the AnalyticsService we can query
// AnalyticsService gas = null;// new AnalyticsService(auth);
var gas = new AnalyticsService(new BaseClientService.Initializer()
{
Authenticator = auth
});
//r: Creating our query
DataResource.GaResource.GetRequest r = gas.Data.Ga.Get("ga:*******", "2012-09-26", "2012-10-10", "ga:visitors");
//d: Execute and fetch the results of our query
GaData d = r.Fetch();
}
catch (Exception ex)
{
throw;
}
}