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.
Related
How can I create a Cognito user with the account status confirmed using c#? After a user is created the account status displays FORCE_CHANGE_PASSWORD. Another thing is I need to create user without email address.
AmazonCognitoIdentityProviderClient cognitoProvider =
new AmazonCognitoIdentityProviderClient(region);
string userName = "user";
string tempPassword = "Temp#3434";
string newPassword = "RealPass#2019";
AdminCreateUserRequest adminUserCreateRequest = new AdminCreateUserRequest()
{
UserPoolId = poolId,
Username = userName,
TemporaryPassword = tempPassword
};
AdminCreateUserResponse signUpResponse = await cognitoProvider.AdminCreateUserAsync(adminUserCreateRequest);
Admin InitiateRequest
Dictionary<string, string> initialParams = new Dictionary<string, string>();
initialParams.Add("USERNAME", userName);
initialParams.Add("PASSWORD", tempPassword);
AdminInitiateAuthRequest initialRequest = new AdminInitiateAuthRequest()
{
AuthFlow = AuthFlowType.ADMIN_NO_SRP_AUTH,
AuthParameters = initialParams,
ClientId = appClientId_tenantApi,
UserPoolId = poolId
};
AdminInitiateAuthResponse resInitAuth = await cognitoProvider.AdminInitiateAuthAsync(initialRequest);
InitiateAuthRresponse has email as a required attribute.
{[requiredAttributes, ["userAttributes.email"]]}
But the documentation doesn't say so.
For ADMIN_NO_SRP_AUTH: USERNAME (required), SECRET_HASH (if app client is configured with client secret), PASSWORD (required), DEVICE_KEY
Admin Respond to challenge
var authParameters = new Dictionary<string, string>();
authParameters.Add("USERNAME", userName);
authParameters.Add("NEW_PASSWORD", newPassword);
AdminRespondToAuthChallengeRequest adminAuthRequest = new AdminRespondToAuthChallengeRequest()
{
UserPoolId = poolId,
ClientId = appClientId_tenantApi,
ChallengeName = ChallengeNameType.NEW_PASSWORD_REQUIRED,
ChallengeResponses = authParameters,
Session = session
};
cognitoProvider.AdminRespondToAuthChallengeAsync(adminAuthRequest);
I am thinking I may missed some user settings in Cognito to avoid email. Any one have similar experience ? or is this not possible to create user without email ?
During the creation of the user pool, under general settings;attributes as in the photocognito creation on aws one is required to choose the attributes that must be present, i believe in your case the email was selected by default hence the challenge request response you got.
The admin create user request requires the client to confirm the email for purposes of verification that the user owns the email.
A hack for the same would be to allow users to sign themselves up on your cognito configuration, then sign someone up then follow with a username and password, then proceed to confirm them as an admin
var signup = await cognitoClient.SignUpAsync(new SignUpRequest
{
Username = person.Username,
ClientId = cognitoOptions.ClientId,
Password = person.IdNumber,
});
var confirm = await cognitoClient.AdminConfirmSignUpAsync(new AdminConfirmSignUpRequest
{
Username = person.Username,
UserPoolId = cognitoOptions.UserPoolId
});
In case if anyone still looking for answer
Initalize Provider.
AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient("*************", "************", Amazon.RegionEndpoint.USWest);
Create user
AdminCreateUserResponse adminCreateUserResponse = await provider.AdminCreateUserAsync(new AdminCreateUserRequest
{
Username = "TestUser",
TemporaryPassword = "TempPassword#1",
UserPoolId = "us-west-**********"
});
Authenticate user
CognitoUserPool userPool = new CognitoUserPool("us-west-***", "***", provider);
CognitoUser user = new CognitoUser("TestUser", "******", userPool, provider, "**********");
InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
{
Password = "TempPassword#1"
};
AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
Vaidate user authentication result and get the user AccessToken
if (authResponse.AuthenticationResult == null)
{
if (authResponse.ChallengeName == ChallengeNameType.NEW_PASSWORD_REQUIRED)
{
//Console.WriteLine("Enter your desired new password:");
string newPassword = "NewPWD#1";// Console.ReadLine();
Dictionary<string, string> att = new Dictionary<string, string>();
att.Add("userAttributes.email", "testemail#xyz.com");
user.Attributes.Add("preferred_username", "TestUser1");
And update the new password using Accesstoken ( post update the User status will be confirmed)
authResponse = await user.RespondToNewPasswordRequiredAsync(new RespondToNewPasswordRequiredRequest()
{
SessionID = authResponse.SessionID,
NewPassword = newPassword,
},att);
accessToken = authResponse.AuthenticationResult.AccessToken;
}
I want to make a Cordova phone app and a web application. Both the application and the app share the same database.
On the mobile app, the user actions send requests to a web service ( over https ) that writes to the database. On the mobile app, I use https://oauth.io to let the user register and log in with multiple open auth providers. Trying to make it work for facebook, for now.
I just can't figure how to use the Identity user management in that context. Most of the examples I find are in the context of a web app where the user clicks and it calls the account controller. In my case, the oauth.io lib calls facebook, returns an access token, which I pass to my service.
The cordova app passes the accessToken to this method to my server side web service.
var client = new FacebookClient(accessToken);
if (client != null)
{
dynamic fbresult = client.Get("me");
if (fbresult["id"] != null)
{
var fbid = fbresult["id"].ToString();
and where do we go from now ?
how do I insert a new user
I tried this:
var user = new ApplicationUser() { UserName = fbresult["id"] };
Backend.Controllers.AccountController ac = new Controllers.AccountController();
ac.UserManager.CreateAsync(user);
Doesn't work because the usermanagement object inside the account controller is null.
There is an overload of the AccountController constructor but I have a feeling I'm doing this whole thing the wrong way.
Let's say the server side receives a facebook access token. How do use OWIN and Identity user management system from there?
Ok.
As suggested by a friend, I replaced the controllers etc from the original web api template for the ones in the Identity Sample Project
Here is the method called by the mobile app, with a angular jsonp
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public string StartSession(string accessToken)
{
if (!HttpContext.Current.Request.IsAuthenticated)
{
var client = new FacebookClient(accessToken);
if (client != null)
{
dynamic fbresult = client.Get("me");
if (fbresult["id"] != null)
{
string fbid = fbresult["id"].ToString();
ApplicationUser user = null;
using (var context = new ApplicationDbContext())
{
user = context.Users.FirstOrDefault(u => u.UserName.ToString() == fbid);
}
if (user == null)
{
CreateUserAsync(fbid);
return "user created. ";
}
else
{
HttpContext.Current.Session["user"] = "holy fuck";
return "user logged in. ";
}
}
}
return "ok";
}
else
{
return "already auth !";
}
}
here is the CreateUserAsync I made
public async System.Threading.Tasks.Task<bool> CreateUserAsync(string fbid)
{
using (var context = new ApplicationDbContext())
{
var newUser = new ApplicationUser() { UserName = fbid, Email = "xxx#gmail.com" };
var userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
try
{
var result = await userManager.CreateAsync(newUser, "Admin#123456");
var test = await context.SaveChangesAsync();
return result.Succeeded;
}
catch (Exception ex)
{
throw ex;
}
}
}
And then, when the mobile app calls back my web service, I can check if the session exists like so:
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public async Task<string> TestLogin(int id, string callback)
{
if (HttpContext.Current.Session["user"] != null)
{
return new JavaScriptSerializer().Serialize(new word() { Name = "woot" });
}
else
return new JavaScriptSerializer().Serialize(new word() { Name = "not logged" });
}
Yea, that's right. A if and a session. Just like I was doin' 13 years ago.
Also, while doing this abomination, I stumbled upon a hangin' problem in the IdentityConfig.cs file.
Apparantly, the problem is known by Microsoft and I guess it is probably fixed in the version 3 of Owin ? But I didn't know about that version 3 at that time, so I followed Program hangs during database initialization .
For some reason, some of the method posted in his solution didn't exist for me. I ended up fixing the code the best I could:
public static void InitializeIdentityForEF(ApplicationDbContext db)
{
//ApplicationUserManager userManager = HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
RoleManager<IdentityRole> roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(db));
const string name = "admin#example.com";
const string password = "Admin#123456";
const string roleName = "Admin";
IdentityRole adminRole = new IdentityRole(roleName);
//Create Role Admin if it does not exist
if (!roleManager.RoleExists(roleName))
{
roleManager.Create(adminRole);
PasswordHasher hasher = new PasswordHasher();
ApplicationUser adminUser = new ApplicationUser { UserName = name, Email = name, PasswordHash = hasher.HashPassword(password), LockoutEnabled = false };
db.Users.Add(adminUser);
IdentityUserRole userRole = new IdentityUserRole() { RoleId = adminRole.Id, UserId = adminUser.Id };
adminUser.Roles.Add(userRole);
var x = db.SaveChanges();
}
}
Also just in case someone is wondering how to call the svc service from the mobile, here is the code.
(it's a little bit messy, but the important parts are there.)
(keep in mind I am using https://oauth.io/ )
$scope.refresh = function () {
$http.jsonp("https://10.0.100.38:6443/Service1.svc/helloworld?id=1&callback=JSON_CALLBACK").success(function JSON_CALLBACK(result) {
OAuth.popup('facebook')
.done(function (oauthResult) {
oauthResult.me() // standardise lesfield firstname, first-name etc
.done(function (response) {
alert("3");
$http.jsonp("https://10.0.100.38:6443/Service1.svc/StartSession?accessToken=" +oauthResult.access_token + "&callback=JSON_CALLBACK").success(function JSON_CALLBACK(result) {
alert("done " +result); // StartSession serverside success ");
}).error(function (data, status, headers, config) {
alert("icierror2" +data + " " +status + " " +headers + " " + config);
$scope.status = status;
});
}).fail(function (error) {
alert("icierror3 " +error);
});
})
.fail(function (error) {
console.log(error);
});
alert(result.Name); // result de la svc request over https
}).error(function (data, status, headers, config) {
alert("icierror" +data + " " +status + " " + headers + " " +config);
$scope.status = status;
});
Problems
As of now, I am not creating a Login, only a user is created.
Also, the project's OWIN version is 2.0, and apparantly, a 3.0 exists.
To be honest, the more I read online the more I feel like everything I've done is a big hack around the right way to do it. I just couldn't figure it out. This is thing is incredibly huge, confusing, chaothic and broken. Yea, I've added an opinion to my answer.
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
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