Here is what im trying to do , i got a webpage with signin page with cresedentials from our database , then once is logged in it should redirect you to main page where you should see the data in charts.
The problem is I used gdata v2.4 but every time i want make a request i have to set the cresedentials again, then v3.0 with oauth 2.0 it said we don't need to this anymore by access token.
I managed to make it work but the problem is if the user been asked to login with gmail account and the email and password doesnt match the profile id of the request it gives the 403 error (forbidden access) this is the code . i tried to use service account no chance , any one knows whats the problem?
log4net.Config.XmlConfigurator.Configure();
//string Scope = AnalyticsService.Scopes.Analytics.ToString().ToLower();
//string scopeUrl = "https://www.google.com/analytics/feeds/" + Scope;
string Scope = "https://www.google.com/analytics/feeds/";
const string ServiceAccountId = "xxxxxxxxxxx.apps.googleusercontent.com";
const string ServiceAccountUser = "xxxxxxxxxxx#developer.gserviceaccount.com";
string key = string.Empty;
foreach (string keyname in Directory.GetFiles(Server.MapPath("/"), "*.p12", SearchOption.AllDirectories))
{
key = keyname;
}
AssertionFlowClient client = new AssertionFlowClient(
GoogleAuthenticationServer.Description, new X509Certificate2(key, "notasecret", X509KeyStorageFlags.Exportable))
{
Scope = Scope,
ServiceAccountId = ServiceAccountUser//,ServiceAccountUser = ServiceAccountUser
};
WebServerClient myWebServerClient = new WebServerClient(GoogleAuthenticationServer.Description);
myWebServerClient.ClientIdentifier = this.ClientID;
myWebServerClient.ClientSecret = this.ClientSecret;
OAuth2Authenticator<WebServerClient> authenticator = new OAuth2Authenticator<WebServerClient>(myWebServerClient, GetAuthorization);
AnalyticsService service = new AnalyticsService(authenticator);
string profileId = Session["_ProfileID"].ToString() ;
string startDate = StartDate;
string endDate = EndDate;
string metrics = "ga:visits";
DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);
request.Dimensions = "ga:date";
request.StartIndex = 1;
request.MaxResults = 500;
GaData data = request.Fetch();
return data;
dont bother anymore , i got it right with offline access . Thanks for showing the SUPPORT
Related
I recently deployed Parse Server to Amazon which is working fine when I connect and create users from iOS but doesn't work when I try to connect from Unity3D and there are no logs aswell. Is there any specific setting or something for Unity?? What am I missing? Below is the code for both platforms;
Unity Code (Not working)
// Initialization
string serverUrl = "http://myserverip.amazonaws.com:80/parse/";
ParseClient.Initialize(new ParseClient.Configuration {ApplicationId = "MYAPPID", WindowsKey = "MYCLIENTKEY", Server = serverUrl});
// User Creation
ParseUser user = new ParseUser ();
user.Username = "myname";
user.Password = "mypass";
user.SignUpAsync ().ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled){
Debug.Log("Faliled" + t.IsFaulted);
}
else{
Debug.Log("Success");
var userId = ParseUser.CurrentUser.ObjectId;
print (userId);
}
});
iOS Code (working)
// Initialization
[Parse initializeWithConfiguration:[ParseClientConfiguration configurationWithBlock:^(id<ParseMutableClientConfiguration> _Nonnull configuration) {
configuration.applicationId = #"MYAPPID";
configuration.clientKey = #"MYCLIENTKEY";
configuration.server = #"http://myinstanceIP.amazonaws.com:80/parse";
configuration.localDatastoreEnabled = YES;
}]];
// User Creation
PFUser *user = [PFUser user];
user.username = #"my name2";
user.password = #"my pass";
user.email = #"email2#example.com";
[user signUp];
You have to set appID and client key in ParseInitializeBehaviour before calling ParseClient.Initialize. Which is pretty weird because ParseClient.Initialize also takes appID and client key but I got it working this way.
Also add "/" at the end of your server url.
ParseInitializeBehaviour _script = new GameObject("ParseInitializeBehaviour").AddComponent<ParseInitializeBehaviour> ();
_script.applicationID = "APPID";
_script.dotnetKey = "CLIENTKEY";
ParseClient.Initialize (new ParseClient.Configuration ()
{
WindowsKey = "APPID",
ApplicationId = "CLIENTKEY",
Server = serverUrl
});
Everything else i.e signup, signin etc. works normally after this.
I'm developing an application to insert row to one of my spreadsheet (like database). The problem is, it always asking new access code. Please help me to avoid expiring the access code or I just want to update my google drive account excel. Sometimes there will be a easy code, may I using wrong code? Below is my code:
string CLIENT_ID = "HIDE";
string CLIENT_SECRET = "HIDE";
string SCOPE = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds";
string REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob";
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.ClientId = CLIENT_ID;
parameters.ClientSecret = CLIENT_SECRET;
parameters.RedirectUri = REDIRECT_URI;
parameters.Scope = SCOPE;
string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
auth.Text = authorizationUrl;
info.Text = ("Please visit the URL above to authorize your OAuth " +"request token. Once that is complete, type in your access code to "+ "continue...");
parameters.AccessCode = accc.Text;
OAuthUtil.GetAccessToken(parameters);
string accessToken = parameters.AccessToken;
acc2.Text = accessToken;
GOAuth2RequestFactory requestFactory =
new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
service.RequestFactory = requestFactory;
string USERNAME = "HIDE";
string PASSWORD = "HIDE";
service.setUserCredentials(USERNAME, PASSWORD);
SpreadsheetQuery query = new SpreadsheetQuery();
SpreadsheetFeed feed = service.Query(query);
if (feed.Entries.Count == 0)
{
Console.WriteLine("None");
}
SpreadsheetEntry spreadsheet = (SpreadsheetEntry)feed.Entries[0];
Console.WriteLine(spreadsheet.Title.Text);
WorksheetFeed wsFeed = spreadsheet.Worksheets;
WorksheetEntry worksheet = (WorksheetEntry)wsFeed.Entries[0];
AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);
ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString());
ListFeed listFeed = service.Query(listQuery);
ListEntry row = new ListEntry();
row.Elements.Add(new ListEntry.Custom() { LocalName = "no.", Value = "#" });
service.Insert(listFeed, row);
You can make a request for "offline" access when requesting the access token. The server will return a "refresh token" and with this toke you can request a new "access token" when it expires without having the user to grant permissions again.
Here you can find documentation on that.
Check this tutorial, it will help you to obtain the access token and refresh token programmatically instead of having to open the browser and copy the token.
I trying using Google Analytics with C# to get stats information to display in my webiste
Here is my code
public ActionResult Index()
{
string userName = "admin#email.com";
string passWord = "mypass";
string profileId = "ga:xxxxxxxx";
string key = "2d751338cb092ef8da65f716e37a48604386c9sw";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data"+key;
var service = new AnalyticsService("API Project");
service.setUserCredentials(userName, passWord);
var dataQuery = new DataQuery(dataFeedUrl)
{
Ids = profileId,
Metrics = "ga:pageviews",
Sort = "ga:pageviews",
GAStartDate = new DateTime(2010, 3, 1).ToString("yyyy-MM-dd"),
GAEndDate = DateTime.Now.ToString("yyyy-MM-dd")
};
var dataFeed = service.Query(dataQuery);
var totalEntry = dataFeed.Entries[0];
ViewData["Total"] = ((DataEntry)(totalEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var yesterdayEntry = dataFeed.Entries[0];
ViewData["Yesterday"] = ((DataEntry)(yesterdayEntry)).Metrics[0].Value;
dataQuery.GAStartDate = DateTime.Now.ToString("yyyy-MM-dd");
dataQuery.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
dataFeed = service.Query(dataQuery);
var todayEntry = dataFeed.Entries[0];
ViewData["Today"] = ((DataEntry)(todayEntry)).Metrics[0].Value;
return View(dataFeed.Entries);
}
But when i run the code it always said "{"Invalid credentials"}"
Not sure why i facing this error while i checked many time about the key,username,password and profileId
Anyone facing this problem,can help me?
Many thanks
I think that your url is wrong. try in this way (you are missing ?key=).
string dataFeedUrl = "https://www.google.com/analytics/feeds/data?key="+key;
refer this google example where there is this example that should help you
public DataFeedExample()
{
// Configure GA API.
AnalyticsService asv = new AnalyticsService("gaExportAPI_acctSample_v2.0");
// Client Login Authorization.
asv.setUserCredentials(CLIENT_USERNAME, CLIENT_PASS);
// GA Data Feed query uri.
String baseUrl = "https://www.google.com/analytics/feeds/data";
DataQuery query = new DataQuery(baseUrl);
query.Ids = TABLE_ID;
query.Dimensions = "ga:source,ga:medium";
query.Metrics = "ga:visits,ga:bounces";
query.Segment = "gaid::-11";
query.Filters = "ga:medium==referral";
query.Sort = "-ga:visits";
query.NumberToRetrieve = 5;
query.GAStartDate = "2010-03-01";
query.GAEndDate = "2010-03-15";
Uri url = query.Uri;
Console.WriteLine("URL: " + url.ToString());
// Send our request to the Analytics API and wait for the results to
// come back.
feed = asv.Query(query);
}
refer also this guide to configure your project
Also follow this guide to use OAuth 2.0
I have this below code to get calendar entries using the google Calendar API (https://developers.google.com/google-apps/calendar/) which uses OAuth2.
It works well.
private IList<string> scopes = new List<string>();
private CalendarService calendarService;
private void InitializeCalendarService()
{
// Add the calendar specific scope to the scopes list
scopes.Add(CalendarService.Scopes.Calendar.GetStringValue());
// Display the header and initialize the sample
CommandLine.EnableExceptionHandling();
CommandLine.DisplayGoogleSampleHeader("Google.Api.Calendar.v3 Sample");
// Create the authenticator
//FullClientCredentials credentials = PromptingClientCredentials.EnsureFullClientCredentials();
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
FullClientCredentials credentials = new FullClientCredentials();
credentials.ClientId = "XYZ.apps.googleusercontent.com";
credentials.ClientSecret = "XYZ";
credentials.ApiKey = "XYZ";
provider.ClientIdentifier = credentials.ClientId;
provider.ClientSecret = credentials.ClientSecret;
OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the calendar service using an initializer instance
BaseClientService.Initializer initializer = new BaseClientService.Initializer();
initializer.Authenticator = auth;
calendarService = new CalendarService(initializer);
CalendarList list = calendarService.CalendarList.List().Execute();
// do something with the list .. the list is all good
}
public IAuthorizationState GetAuthorization(NativeApplicationClient client)
{
// You should use a more secure way of storing the key here as
// .NET applications can be disassembled using a reflection tool.
const string STORAGE = "google.samples.dotnet.calendar";
const string KEY = "s0mekey";
// Check if there is a cached refresh token available.
IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(STORAGE, KEY);
if ((state != null))
{
try
{
client.RefreshToken(state);
return state;
// we are done
}
catch (DotNetOpenAuth.Messaging.ProtocolException ex)
{
CommandLine.WriteError("Using an existing refresh token failed: " + ex.Message);
CommandLine.WriteLine();
}
}
// Retrieve the authorization from the user
string[] array = new string[scopes.Count];
scopes.CopyTo(array,0);
state = AuthorizationMgr.RequestNativeAuthorization(client, array);
AuthorizationMgr.SetCachedRefreshToken(STORAGE, KEY, state);
return state;
}
How can I use the similar OAuth2Authenticator to fetch Contacts?
I am able to fetch contacts using the below code, but its not password-less, I need to get it working using Oath2. The example below uses Gdata contacts api v2. I can see that i can pass through OAuth2Authenticator but im not exactly sure how to do it correctly (i cant see any valid examples in C# on the google site) and fetch the access code based on what the user is selecting.
I cant see how to use OAuth2Authenticator with the contacts api v3 (https://developers.google.com/google-apps/contacts/v3/)
RequestSettings rsLoginInfo = new RequestSettings("", email,pwd);
rsLoginInfo.AutoPaging = true;
ContactsRequest cRequest = new ContactsRequest(rsLoginInfo);
// fetch contacts list
Feed<Contact> feedContacts = cRequest.GetContacts();
foreach (Contact gmailAddresses in feedContacts.Entries)
{
// Looping to read email addresses
foreach (EMail emailId in gmailAddresses.Emails)
{
lstContacts.Add(emailId.Address);
}
}
I ended up doing this by fetching the access code by having a browser control read the Document title value when the user selects the google account and grants access.
eg:
To Generate URL
RedirectURI = "urn:ietf:wg:oauth:2.0:oob"
OAuth2Parameters parameters = new OAuth2Parameters()
{
ClientId = clientId,
ClientSecret = clientSecret,
RedirectUri = redirectUri,
Scope = requiredScope
};
// Request authorization from the user (by opening a browser window):
string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
var loginUri = new Uri(url);
// This form has browser control
GoogleLoginForm form = new GoogleLoginForm(loginUri, redirectUri);
var dr = form.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
parameters.AccessCode = form.OAuthVerifierToken;
}
Then In GoogleLoginForm :
We have a browser control and registered browserControl_Navigated event and the do the below. The DocumentTitle contains the AccessCode which is used to generate the token.
private void GoogleLoginForm_Load(object sender, EventArgs e)
{
wbGoogleLogin.Url = _loginUri;
}
private void wbGoogleLogin_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string fullPath = e.Url.ToString();
WebBrowser control = sender as WebBrowser;
if (control != null && !string.IsNullOrEmpty(control.DocumentTitle) && control.DocumentTitle.Contains("Success code"))
{
_OAuthVerifierToken = control.DocumentTitle.Replace("Success code=","");
DialogResult = DialogResult.OK;
}
}
This way it can be done in the same piece of code, without having to write a complicated callback service of some sort to read the access token back into our system.
Not exactly sure why the calendar api has this built in, and the contacts API doesn't.
Firstly, the quick answer to your question. I believe that the IAuthorizationState has similar properties to OAuth2Parameters. Thus, you should be able to do this (combining it with the code you have for the calender):
OAuth2Authenticator<NativeApplicationClient> auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
//This will call your GetAuthorization method
auth.LoadAccessToken()
RequestSettings settings = new RequestSettings("appName", auth.State.AccessToken);
ContactsRequest cRequest = new ContactsRequest(settings);
// fetch contacts list
Feed<Contact> feedContacts = cRequest.GetContacts();
foreach (Contact gmailAddresses in feedContacts.Entries)
{
// Looping to read email addresses
foreach (EMail emailId in gmailAddresses.Emails)
{
lstContacts.Add(emailId.Address);
}
}
This should work as the RequestSettings allows you to specify an access token. That being said, I myself prefer to use :
var parameters = new OAuth2Parameters()
{
//Client
ClientId = CLIENT_ID,
ClientSecret = CLIENT_SECRET,
RedirectUri = redirectUri,
Scope = "https://www.google.com/m8/feeds",
ResponseType = "code"
};
//User clicks this auth url and will then be sent to your redirect url with a code parameter
var authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
.
.
.
//using the code parameter
parameters.AccessCode = code;
OAuthUtil.GetAccessToken(parameters);
var settings = new RequestSettings(applicationName, parameters);
var cr = new ContactsRequest(settings);
//Now you can use contacts as you would have before
Although, Ive only tested this with Web Server Apps, so maybe the authenticator is needed for your situation? I found these source codes handy:
OAuth2Demo
IAuthorizationState
OAuth2Authenticator
I am trying to connect to the Google Analytics reporting API to get basic pageview stats. Im trying to follow this tutorial (http://www.arboundy.com/2012/04/getting-started-with-google-analytics-in-c/). I'm having trouble setting the correct bits to get a successful auth as it seems google has changed the APIs a lot lately so the original config doesn't seem to work.
Heres what I currently have:
Service = new AnalyticsService("MyDemoApp");
Service.setUserCredentials("user#gmail.com", "password");
AccountQuery AccountsQuery = new AccountQuery("https://www.googleapis.com/analytics/v3/data/ga"/*Not sure what goes here this gives a 400*/);
AccountFeed AccountsFeed = Service.Query(AccountsQuery); // 400 error here
Any ideas how to connect to this via the V3 api (which appears to be the one I got from NuGet)
this must work for u in c#. (i have tried and worked)
string username = "youremailuser#domain.com";
string pass = "yourpassword";
string gkey = "?key=YourAPIkEY";
string dataFeedUrl = "https://www.google.com/analytics/feeds/data" + gkey;
string accountFeedUrl = "https://www.googleapis.com/analytics/v2.4/management/accounts" + gkey;
AnalyticsService service = new AnalyticsService("WebApp");
service.setUserCredentials(username, pass);
DataQuery query1 = new DataQuery(dataFeedUrl);
query1.Ids = "ga:12345678";
query1.Metrics = "ga:visits";
query1.Sort = "ga:visits";
query1.GAStartDate = new DateTime(2012, 1, 2).ToString("yyyy-MM-dd");
query1.GAEndDate = DateTime.Now.ToString("yyyy-MM-dd");
query1.StartIndex = 1;
DataFeed dataFeedVisits = service.Query(query1);
foreach (DataEntry entry in dataFeedVisits.Entries)
{
string st = entry.Title.Text;
string ss = entry.Metrics[0].Value;
visits = ss;
}
for more details Read data from Google data API