Google Drive Api - Custom IDataStore with Entity Framework - c#

I implemented my custom IDataStore so that I can store End User Tokens on my database instead of the default implementation, which is saved on FileSystem within %AppData%.
public class GoogleIDataStore : IDataStore
{
...
public Task<T> GetAsync<T>(string key)
{
TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
var user = repository.GetUser(key.Replace("oauth_", ""));
var credentials = repository.GetCredentials(user.UserId);
if (key.StartsWith("oauth") || credentials == null)
{
tcs.SetResult(default(T));
}
else
{
var JsonData = Newtonsoft.Json.JsonConvert.SerializeObject(Map(credentials));
tcs.SetResult(NewtonsoftJsonSerializer.Instance.Deserialize<T>(JsonData));
}
return tcs.Task;
}
}
Controller
public async Task<ActionResult> AuthorizeDrive(CancellationToken cancellationToken)
{
var result = await new AuthorizationCodeMvcApp(this, new GoogleAppFlowMetadata()).
AuthorizeAsync(cancellationToken);
if (result.Credential == null)
return new RedirectResult(result.RedirectUri);
var driveService = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "My app"
});
//Example how to access drive files
var listReq = driveService.Files.List();
listReq.Fields = "items/title,items/id,items/createdDate,items/downloadUrl,items/exportLinks";
var list = listReq.Execute();
return RedirectToAction("Index", "Home");
}
The issue happens on the redirect event. After that first redirect it works fine.
I found out that something is different on the redirect event. On the redirect event the T is not a Token Response, but a string. Also, the key is prefixed with "oauth_".
So I assume that I should return a different result on the redirect, but I have no clue what to return.
The error I get is : Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"State is invalid", Description:"", Uri:""
Google Source Code Reference
https://code.google.com/p/google-api-dotnet-client/source/browse/Src/GoogleApis.DotNet4/Apis/Util/Store/FileDataStore.cs?r=eb702f917c0e18fc960d077af132d0d83bcd6a88
https://code.google.com/p/google-api-dotnet-client/source/browse/Src/GoogleApis.Auth/OAuth2/Web/AuthWebUtility.cs?r=eb702f917c0e18fc960d077af132d0d83bcd6a88
Thanks for your help

I am not exactly sure why yours isnt working but this is a copy of the code i use. The full class can be found here DatabaseDatastore.cs
/// <summary>
/// Returns the stored value for the given key or <c>null</c> if the matching file (<see cref="GenerateStoredKey"/>
/// in <see cref="FolderPath"/> doesn't exist.
/// </summary>
/// <typeparam name="T">The type to retrieve</typeparam>
/// <param name="key">The key to retrieve from the data store</param>
/// <returns>The stored object</returns>
public Task<T> GetAsync<T>(string key)
{
//Key is the user string sent with AuthorizeAsync
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key MUST have a value");
}
TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
// Note: create a method for opening the connection.
SqlConnection myConnection = new SqlConnection("user id=" + LoginName + ";" +
#"password=" + PassWord + ";server=" + ServerName + ";" +
"Trusted_Connection=yes;" +
"database=" + DatabaseName + "; " +
"connection timeout=30");
myConnection.Open();
// Try and find the Row in the DB.
using (SqlCommand command = new SqlCommand("select RefreshToken from GoogleUser where UserName = #username;", myConnection))
{
command.Parameters.AddWithValue("#username", key);
string RefreshToken = null;
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
RefreshToken = myReader["RefreshToken"].ToString();
}
if (RefreshToken == null)
{
// we don't have a record so we request it of the user.
tcs.SetResult(default(T));
}
else
{
try
{
// we have it we use that.
tcs.SetResult(NewtonsoftJsonSerializer.Instance.Deserialize<T>(RefreshToken));
}
catch (Exception ex)
{
tcs.SetException(ex);
}
}
}
return tcs.Task;
}

The API stores (at least) two values in your IDataStore. Here is what the authorization process looks like from an empty IDataStore's point of view (note which lines set a value and which lines get a value):
Getting IDataStore value: MyKey <= null
Setting IDataStore value: oauth_MyKey => "http://localhost..."
Setting IDataStore value: MyKey => {"access_token":"...
Getting IDataStore value: oauth_MyKey <= "http://localhost..."
Getting IDataStore value: MyKey <= {"access_token":"...
At first, the API tries to find a stored access_token, but there is none in the data store (which just returns null), and the API starts the authorization process. The "oauth_..." key is some state info the API needs during this process, and is normally set before it is retrieved (in my experience).
However, if your IDataStore never received a value with an "oauth_.." key, and thus has nothing to return, simply return null, and the API should create a new one when needed.

Related

Get messages which contain an attachment via gmail API

I'm building an app based on the Gmail API. I can see all messages from the current inbox, but I need to limit this to only messages which have an attachment. How can I do this?
This is my GoogleController.cs:
[HttpGet]
[Authorize]
public async Task<IActionResult> GetListEmail(string LabelId, string nameLabel)
{
string UserEmail = User.FindFirst(c => c.Type == ClaimTypes.Email).Value;
var service = GetService();
List<My_Message> listMessages = new List<My_Message>();
List<Message> result = new List<Message>();
var emailListRequest = service.Users.Messages.List(UserEmail);
emailListRequest.LabelIds = LabelId;
emailListRequest.IncludeSpamTrash = false;
emailListRequest.MaxResults = 1000;
var emailListResponse = await emailListRequest.ExecuteAsync();
if (emailListResponse != null && emailListResponse.Messages != null)
{
foreach (var email in emailListResponse.Messages)
{
var emailInfoRequest = service.Users.Messages.Get(UserEmail, email.Id);
var emailInfoResponse = await emailInfoRequest.ExecuteAsync();
if (emailInfoResponse != null)
{
My_Message message = new My_Message();
message.Id = listMessages.Count + 1;
message.EmailId = email.Id;
foreach (var mParts in emailInfoResponse.Payload.Headers)
{
if (mParts.Name == "Date")
message.Date_Received = mParts.Value;
else if (mParts.Name == "From")
message.From = mParts.Value;
else if (mParts.Name == "Subject")
message.Title = mParts.Value;
}
listMessages.Add(message);
}
}
}
ViewBag.Message = nameLabel;
return View("~/Views/Home/Index.cshtml", listMessages);
}
I think a simpler solution would be to query in the Users.messages.list endpoint without the need to create filters.
You can actually use the parameter q to make a query like you would in the GMail searchbox, if not familiar you can look at the whole list of operators.
In fact there is an example to make use of this query parameter in the documentation:
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using System.Collections.Generic;
// ...
public class MyClass {
// ...
/// <summary>
/// List all Messages of the user's mailbox matching the query.
/// </summary>
/// <param name="service">Gmail API service instance.</param>
/// <param name="userId">User's email address. The special value "me"
/// can be used to indicate the authenticated user.</param>
/// <param name="query">String used to filter Messages returned.</param>
public static List<Message> ListMessages(GmailService service, String userId, String query)
{
List<Message> result = new List<Message>();
UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
request.Q = query; // inform this with the right query
do
{
try
{
ListMessagesResponse response = request.Execute();
result.AddRange(response.Messages);
request.PageToken = response.NextPageToken;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}
} while (!String.IsNullOrEmpty(request.PageToken));
return result;
}
// ...
}
So for your case you just need to add the line
emailListRequest.Q = "has:attachment";
before executing the request, doing like this will not create a whole filter for your account, so maybe it's more convenient for your case.
use a filter with criteria like this => criteria.query="has:attachment"
see also here => https://developers.google.com/gmail/api/v1/reference/users/settings/filters#resource
For testing any filter you can use GMail:
image

Delete Secret on Azure Keyvault not working

I have a web API method which creates secrets on azure key vault and it works fine, I also have a delete method that deletes an entity and its associated secrets, however, this method is not deleting the key on azure key vault, but it's not throwing an exception either!
Here the helper methods:
public async Task OnCreateSecretAsync(string name, string value)
{
Message = "Your application description page.";
int retries = 0;
bool retry = false;
try
{
/* The below 4 lines of code shows you how to use AppAuthentication library to set secrets from your Key Vault*/
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var result = await keyVaultClient.SetSecretAsync(ConfigurationManager.AppSettings["VaultUrl"].ToString(), name, value)
.ConfigureAwait(false);
SecretIdentifier = result.Id;
/* The below do while logic is to handle throttling errors thrown by Azure Key Vault. It shows how to do exponential backoff which is the recommended client side throttling*/
do
{
long waitTime = Math.Min(GetWaitTime(retries), 2000000);
result = await keyVaultClient.SetSecretAsync(ConfigurationManager.AppSettings["VaultUrl"].ToString(), name, value)
.ConfigureAwait(false);
Message = result.Id;
retry = false;
}
while (retry && (retries++ < 10));
}
/// <exception cref="KeyVaultErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
catch (KeyVaultErrorException keyVaultException)
{
Message = keyVaultException.Message;
if ((int)keyVaultException.Response.StatusCode == 429)
retry = true;
}
}
/// <summary>
/// Deletes secrets
/// </summary>
/// <param name="name">Secret</param>
/// <param name="value">Value</param>
/// <returns></returns>
public async Task OnDeleteSecretAsync(string name)
{
Message = "Your application description page.";
int retries = 0;
bool retry = false;
try
{
/* The below 4 lines of code shows you how to use AppAuthentication library to set secrets from your Key Vault*/
AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
KeyVaultClient keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
var result = await keyVaultClient.DeleteSecretAsync(ConfigurationManager.AppSettings["VaultUrl"].ToString(), name)
.ConfigureAwait(false);
SecretIdentifier = result.Id;
/* The below do while logic is to handle throttling errors thrown by Azure Key Vault. It shows how to do exponential backoff which is the recommended client side throttling*/
do
{
long waitTime = Math.Min(GetWaitTime(retries), 2000000);
result = await keyVaultClient.DeleteSecretAsync(ConfigurationManager.AppSettings["VaultUrl"].ToString(), name)
.ConfigureAwait(false);
Message = result.Id;
retry = false;
}
while (retry && (retries++ < 10));
}
/// <exception cref="KeyVaultErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
catch (KeyVaultErrorException keyVaultException)
{
Message = keyVaultException.Message;
if ((int)keyVaultException.Response.StatusCode == 429)
retry = true;
}
}
And here the methods where I call them from:
public async Task<IHttpActionResult> AddGlobalDesignTenant([FromBody]GlobalDesignTenant globaldesigntenant)
{
var telemetry = new TelemetryClient();
try
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
string domainUrl = globaldesigntenant.TestSiteCollectionUrl;
string tenantName = domainUrl.Split('.')[0].Remove(0, 8);
globaldesigntenant.TenantName = tenantName;
var globalDesignTenantStore = CosmosStoreHolder.Instance.CosmosStoreGlobalDesignTenant;
byte[] data = Convert.FromBase64String(globaldesigntenant.base64CertFile);
var cert = new X509Certificate2(
data,
globaldesigntenant.CertificatePassword,
X509KeyStorageFlags.Exportable |
X509KeyStorageFlags.MachineKeySet |
X509KeyStorageFlags.PersistKeySet);
try
{
using (var cc = new AuthenticationManager().GetAzureADAppOnlyAuthenticatedContext(globaldesigntenant.TestSiteCollectionUrl,
globaldesigntenant.Applicationid,
globaldesigntenant.TenantName + ".onmicrosoft.com",
cert, AzureEnvironment.Production))
{
cc.Load(cc.Web, p => p.Title);
cc.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
}
}
catch (Exception ex)
{
return BadRequest("Cant authenticate with those credentials");
}
KeyVaultHelper keyVaultHelperPFX = new KeyVaultHelper();
await keyVaultHelperPFX.OnCreateSecretAsync("GlobalDesignTenantPFXFileBAse64"+ tenantName, globaldesigntenant.base64CertFile);
globaldesigntenant.SecretIdentifierBase64PFXFile = keyVaultHelperPFX.SecretIdentifier;
KeyVaultHelper keyVaultHelperPassword = new KeyVaultHelper();
await keyVaultHelperPassword.OnCreateSecretAsync("GlobalDesignTenantCertPassword" + tenantName, globaldesigntenant.CertificatePassword);
globaldesigntenant.SecretIdentifieCertificatePassword = keyVaultHelperPassword.SecretIdentifier;
globaldesigntenant.CertificatePassword = string.Empty;
globaldesigntenant.base64CertFile = string.Empty;
var added = await globalDesignTenantStore.AddAsync(globaldesigntenant);
return Ok(added);
}
catch (Exception ex)
{
string guid = Guid.NewGuid().ToString();
var dt = new Dictionary<string, string>
{
{ "Error Lulo: ", guid }
};
telemetry.TrackException(ex, dt);
return BadRequest("Error Lulo: " + guid);
}
}
public async Task<IHttpActionResult> DeleteGlobalDesignTenant(string id)
{
var telemetry = new TelemetryClient();
try
{
var globalDesignTenantStore = CosmosStoreHolder.Instance.CosmosStoreGlobalDesignTenant;
var globalDesignTenant = await globalDesignTenantStore.FindAsync(id, "globaldesigntenants");
KeyVaultHelper keyVaultHelperPFX = new KeyVaultHelper();
await keyVaultHelperPFX.OnDeleteSecretAsync("GlobalDesignTenantPFXFileBAse64" + globalDesignTenant.TenantName);
KeyVaultHelper keyVaultHelperPassword = new KeyVaultHelper();
await keyVaultHelperPassword.OnDeleteSecretAsync("GlobalDesignTenantCertPassword" + globalDesignTenant.TenantName);
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = await globalDesignTenantStore.RemoveAsync(globalDesignTenant);
return Ok(result);
}
catch (Exception ex)
{
string guid = Guid.NewGuid().ToString();
var dt = new Dictionary<string, string>
{
{ "Error Lulo: ", guid }
};
telemetry.TrackException(ex, dt);
return BadRequest("Error Lulo: " + guid);
}
}
Based on my test, await keyVaultClient.DeleteSecretAsync(ConfigurationManager.AppSettings["VaultUrl"].ToString(), name) will delete the secret with specified name.
So, please set a break-point at the delete calling. Then run your application to see if it hits, and check if the parameters were expected values.

How to get the hub notification that is not full?

I have a notification hub, and it, have a hub-namespace and it is almost full.
I'll create another hub, how do I programmatically know (Android), which one should I enter the user?
Android source code:
public class NotificationSettings {
public static String SenderId = "MyFirebaseSenderId";
public static String HubName = "myhub-hub";
public static String HubListenConnectionString = "Endpoint=sb://myapp.serv.../;SharedAccessKeyName=D..ure;SharedAccessKey=K..t/n8I/X..=";
}
RegistrationIntent:
public class RegistrationIntentService extends IntentService {
private static final String TAG = "RegIntentService";
private NotificationHub hub;
public RegistrationIntentService() {
super(TAG);
}
public ApplicationUtils getApplicationUtils() {
return (ApplicationUtils) getApplication();
}
#Override
protected void onHandleIntent(Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String resultString = null;
String regID = null;
String storedToken = null;
String tag = null;
try {
tag ="_UserId:" + getApplicationUtils().getUsuario().Id;
} catch (Exception e){
return;
}
try {
if(FirebaseInstanceId.getInstance() == null){
FirebaseApp.initializeApp(this);
}
String FCM_token = FirebaseInstanceId.getInstance().getToken();
SaveSharedPreferences.setFCM(getApplicationContext(),FCM_token);
Log.d(TAG, "FCM Registration Token: " + FCM_token);
// Storing the registration id that indicates whether the generated token has been
// sent to your server. If it is not stored, send the token to your server,
// otherwise your server should have already received the token.
if (((regID=sharedPreferences.getString("registrationID", null)) == null)){
NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
NotificationSettings.HubListenConnectionString, this);
Log.d(TAG, "Attempting a new registration with NH using FCM token : " + FCM_token);
regID = hub.register(FCM_token, tag).getRegistrationId();
// If you want to use tags...
// Refer to : https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-routing-tag-expressions/
// regID = hub.register(token, "tag1,tag2").getRegistrationId();
resultString = "New NH Registration Successfully - RegId : " + regID;
Log.d(TAG, resultString);
sharedPreferences.edit().putString("registrationID", regID ).apply();
sharedPreferences.edit().putString("FCMtoken", FCM_token ).apply();
}
// Check if the token may have been compromised and needs refreshing.
else if (!((storedToken=sharedPreferences.getString("FCMtoken", "")).equals(FCM_token))) {
NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
NotificationSettings.HubListenConnectionString, this);
Log.d(TAG, "NH Registration refreshing with token : " + FCM_token);
regID = hub.register(FCM_token, tag).getRegistrationId();
// If you want to use tags...
// Refer to : https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-routing-tag-expressions/
// regID = hub.register(token, "tag1,tag2").getRegistrationId();
resultString = "New NH Registration Successfully - RegId : " + regID;
Log.d(TAG, resultString);
sharedPreferences.edit().putString("registrationID", regID ).apply();
sharedPreferences.edit().putString("FCMtoken", FCM_token ).apply();
}
else {
resultString = "Previously Registered Successfully - RegId : " + regID;
}
} .............................................
Now, it follows my downend code below, I do not know if it would be important in this case. But, it is developed in C # .Net:
public static async void sendPushNotification(ApiController controller, DataObjects.Notification notification)
{
// Get the settings for the server project.
HttpConfiguration config = controller.Configuration;
MobileAppSettingsDictionary settings =
controller.Configuration.GetMobileAppSettingsProvider().GetMobileAppSettings();
// Get the Notification Hubs credentials for the Mobile App.
string notificationHubName = settings.NotificationHubName;
string notificationHubConnection = settings
.Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
// Create a new Notification Hub client.
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
// Android payload
JObject data = new JObject();
data.Add("Id", notification.Id);
data.Add("Descricao", notification.Descricao);
...
//alteração com a colocação da tag priority em caso de erro teste sem
var androidNotificationPayload = "{ \"data\" : {\"message\":" + JsonConvert.SerializeObject(data) + "}}";
try
{
// Send the push notification and log the results.
String tag = "_UserId:"+notification.Id_usuario;
//var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload);
var result = await hub.SendGcmNativeNotificationAsync(androidNotificationPayload, tag);
// Write the success result to the logs.
config.Services.GetTraceWriter().Info(result.State.ToString());
}
catch (System.Exception ex)
{
// Write the failure result to the logs.
config.Services.GetTraceWriter().Error(ex.Message, null, "Push.SendAsync Error");
}
}
I need a lot of help on this issue.
Thank you so much for this.
According to your description, I suggest you could write a api method which will insert new user to the notification hub(not on the client side) after checking the registrations is full or not.
We could use NotificationHubClient.GetAllRegistrationsAsync Method to get all AllRegistrations to local. Then we could count its number.
After checking successfully, then we will check enter user to which hub.
The workflow is:
New user registered:
Client: Send the user information to server web api method
Server: Check the notification hub is full(By calling NotificationHubClient.GetAllRegistrationsAsync or directly registered user if it failed registered into new hub)
Besides, notification hub provides different pricing tier.
I suggest you could consider scaling up your pricing tier to support multiple active devices.

Google Calendar API v3 - Request time out when deploy on server

I tried to logged in localhost and everything works properly.
The code:
public static bool LoginGoogleCalendar(string clientId, string clientSecret, string idGCalendarUser, string calendarServiceScope, string folder)
{
try
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret,
},
new[] { calendarServiceScope },
idGCalendarUser,
CancellationToken.None, new FileDataStore(folder)).Result;
return true;
}
catch (Exception ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
return false;
}
}
(I set properly the authorization for fileDataStore)
In Google Developers Console:
Redirect URIs: http://localhost/authorize/
Javascript Origins: http://localhost:8081
I use Visual Studio 2013, IIS 8
When i try the login to the server, will block the entire server for minutes and the answer after is: System.Web.HttpException Request timed out.
In Google Developers Console:
Redirect URIs: http://pippo.pluto.it/authorize/
Javascript Origins: http://pippo.pluto.it
On the server: IIS 7
The reference to my example:
https://developers.google.com/google-apps/calendar/instantiate
I walked into to same problem. Alot of examples on the internet tell you to use this class. For web applications this is not the class to use though. This class wil work perfect for "offline" applications, but when you use this class on the IIS server it wil try to open the popup on the server but it wont let it.
The class I use: GoogleAuthorizationCodeFlow
using Google.Apis.Analytics.v3;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Requests;
using Google.Apis.Auth.OAuth2.Web;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
namespace GoogleOauth2DemoWebApp
{
public class GoogleOauth
{
public AnalyticsService Handle(string _userId, string _connectionString, string _googleRedirectUri, string _applicationName, string[] _scopes)
{
try
{
string UserId = _userId;//The user ID wil be for examlpe the users gmail address.
AnalyticsService service;
GoogleAuthorizationCodeFlow flow;
//use extended class to create google authorization code flow
flow = new ForceOfflineGoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
DataStore = new DbDataStore(_connectionString),//DataStore class to save the token in a SQL database.
ClientSecrets = new ClientSecrets { ClientId = "XXX-YOUR CLIENTID-XXX", ClientSecret = "XXX-YOURCLIENTSECRET-XXX" },
Scopes = _scopes,
});
var uri = HttpContext.Current.Request.Url.ToString();
string redirecturi = _googleRedirectUri;//This is the redirect URL set in google developer console.
var code = HttpContext.Current.Request["code"];
if (code != null)
{
var token = flow.ExchangeCodeForTokenAsync(UserId, code,
uri.Substring(0, uri.IndexOf("?")), CancellationToken.None).Result;
var test = HttpContext.Current.Request["state"];
// Extract the right state.
var oauthState = AuthWebUtility.ExtracRedirectFromState(
flow.DataStore, UserId, HttpContext.Current.Request["state"]).Result;
HttpContext.Current.Response.Redirect(oauthState);
}
else
{
var result = new AuthorizationCodeWebApp(flow, redirecturi, uri).AuthorizeAsync(UserId,
CancellationToken.None).Result;
if (result.RedirectUri != null)
{
// Redirect the user to the authorization server.
HttpContext.Current.Response.Redirect(result.RedirectUri);
}
else
{
// The data store contains the user credential, so the user has been already authenticated.
service = new AnalyticsService(new BaseClientService.Initializer()
{
HttpClientInitializer = result.Credential,
ApplicationName = _applicationName
});
return service;
}
}
return null;
}
catch (Exception ex)
{
throw ex;
}
}
internal class ForceOfflineGoogleAuthorizationCodeFlow : GoogleAuthorizationCodeFlow
{
public ForceOfflineGoogleAuthorizationCodeFlow(GoogleAuthorizationCodeFlow.Initializer initializer) : base(initializer) { }
public override AuthorizationCodeRequestUrl CreateAuthorizationCodeRequest(string redirectUri)
{
var ss = new Google.Apis.Auth.OAuth2.Requests.GoogleAuthorizationCodeRequestUrl(new Uri(AuthorizationServerUrl));
ss.AccessType = "offline";
ss.ApprovalPrompt = "force";
ss.ClientId = ClientSecrets.ClientId;
ss.Scope = string.Join(" ", Scopes);
ss.RedirectUri = redirectUri;
return ss;
}
};
}
}
Also I user a DataStore class. Saving the tokens to a file on you server isnt the best practice. I used a SQL database.
Example of the datastore class. It will make a table for you, not the best way but for testing perpose good enough.
using Google.Apis.Json;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GoogleOauth2DemoWebApp
{
public class DbDataStore : IDataStore
{
readonly string connectionString;
public string ConnectionString { get { return connectionString; } }
private Boolean _ConnectionExists { get; set; }
public Boolean connectionExists { get { return _ConnectionExists; } }
/// <summary>
/// Constructs a new file data store with the specified folder. This folder is created (if it doesn't exist
/// yet) under the current directory
/// </summary>
/// <param name="folder">Folder name</param>
public DbDataStore(String _connectionString)
{
connectionString = _connectionString;
SqlConnection myConnection = this.connectdb(); // Opens a connection to the database.
if (_ConnectionExists)
{
// check if the Table Exists;
try
{
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select 1 from GoogleUser where 1 = 0",
myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
var hold = myReader["Column1"];
}
}
catch
{
// table doesn't exist we create it
SqlCommand myCommand = new SqlCommand("CREATE TABLE [dbo].[GoogleUser]( " +
" [username] [nvarchar](4000) NOT NULL," +
" [RefreshToken] [nvarchar](4000) NOT NULL," +
" [Userid] [nvarchar](4000) NOT NULL" +
" ) ON [PRIMARY]", myConnection);
myCommand.ExecuteNonQuery();
}
}
myConnection.Close();
}
/// <summary>
/// Stores the given value for the given key. It creates a new file (named <see cref="GenerateStoredKey"/>) in
/// <see cref="FolderPath"/>.
/// </summary>
/// <typeparam name="T">The type to store in the data store</typeparam>
/// <param name="key">The key</param>
/// <param name="value">The value to store in the data store</param>
public Task StoreAsync<T>(string key, T value)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key MUST have a value");
}
var serialized = NewtonsoftJsonSerializer.Instance.Serialize(value);
SqlConnection myConnection = this.connectdb();
if (!_ConnectionExists)
{
throw new Exception("Not connected to the database");
}
// Try and find the Row in the DB.
using (SqlCommand command = new SqlCommand("select Userid from GoogleUser where UserName = #username", myConnection))
{
command.Parameters.AddWithValue("#username", key);
string hold = null;
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
hold = myReader["Userid"].ToString();
}
myReader.Close();
if (hold == null)
{
try
{
// New User we insert it into the database
string insertString = "INSERT INTO [dbo].[GoogleUser] ([username],[RefreshToken],[Userid]) " +
" VALUES (#key,#value,'1' )";
SqlCommand commandins = new SqlCommand(insertString, myConnection);
commandins.Parameters.AddWithValue("#key", key);
commandins.Parameters.AddWithValue("#value", serialized);
commandins.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Error inserting new row: " + ex.Message);
}
}
else
{
try
{
// Existing User We update it
string insertString = "update [dbo].[GoogleUser] " +
" set [RefreshToken] = #value " +
" where username = #key";
SqlCommand commandins = new SqlCommand(insertString, myConnection);
commandins.Parameters.AddWithValue("#key", key);
commandins.Parameters.AddWithValue("#value", serialized);
commandins.ExecuteNonQuery();
}
catch (Exception ex)
{
throw new Exception("Error updating user: " + ex.Message);
}
}
}
myConnection.Close();
return TaskEx.Delay(0);
}
/// <summary>
/// Deletes the given key. It deletes the <see cref="GenerateStoredKey"/> named file in <see cref="FolderPath"/>.
/// </summary>
/// <param name="key">The key to delete from the data store</param>
public Task DeleteAsync<T>(string key)
{
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key MUST have a value");
}
SqlConnection myConnection = this.connectdb();
if (!_ConnectionExists)
{
throw new Exception("Not connected to the database");
}
// Deletes the users data.
string deleteString = "delete from [dbo].[GoogleUser] " +
"where username = #key";
SqlCommand commandins = new SqlCommand(deleteString, myConnection);
commandins.Parameters.AddWithValue("#key", key);
commandins.ExecuteNonQuery();
myConnection.Close();
return TaskEx.Delay(0);
}
/// <summary>
/// Returns the stored value for the given key or <c>null</c> if the matching file (<see cref="GenerateStoredKey"/>
/// in <see cref="FolderPath"/> doesn't exist.
/// </summary>
/// <typeparam name="T">The type to retrieve</typeparam>
/// <param name="key">The key to retrieve from the data store</param>
/// <returns>The stored object</returns>
public Task<T> GetAsync<T>(string key)
{
//Key is the user string sent with AuthorizeAsync
if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("Key MUST have a value");
}
TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
// Note: create a method for opening the connection.
SqlConnection myConnection = new SqlConnection(this.ConnectionString);
myConnection.Open();
// Try and find the Row in the DB.
using (SqlCommand command = new SqlCommand("select RefreshToken from GoogleUser where UserName = #username;", myConnection))
{
command.Parameters.AddWithValue("#username", key);
string RefreshToken = null;
SqlDataReader myReader = command.ExecuteReader();
while (myReader.Read())
{
RefreshToken = myReader["RefreshToken"].ToString();
}
if (RefreshToken == null)
{
// we don't have a record so we request it of the user.
tcs.SetResult(default(T));
}
else
{
try
{
// we have it we use that.
tcs.SetResult(NewtonsoftJsonSerializer.Instance.Deserialize<T>(RefreshToken));
}
catch (Exception ex)
{
tcs.SetException(ex);
}
}
}
return tcs.Task;
}
/// <summary>
/// Clears all values in the data store. This method deletes all files in <see cref="FolderPath"/>.
/// </summary>
public Task ClearAsync()
{
SqlConnection myConnection = this.connectdb();
if (!_ConnectionExists)
{
throw new Exception("Not connected to the database");
}
// Removes all data from the Table.
string truncateString = "truncate table [dbo].[GoogleUser] ";
SqlCommand commandins = new SqlCommand(truncateString, myConnection);
commandins.ExecuteNonQuery();
myConnection.Close();
return TaskEx.Delay(0);
}
/// <summary>Creates a unique stored key based on the key and the class type.</summary>
/// <param name="key">The object key</param>
/// <param name="t">The type to store or retrieve</param>
public static string GenerateStoredKey(string key, Type t)
{
return string.Format("{0}-{1}", t.FullName, key);
}
//Handel's creating the connection to the database
private SqlConnection connectdb()
{
SqlConnection myConnection = null;
try
{
myConnection = new SqlConnection(this.ConnectionString);
try
{
myConnection.Open();
// ensuring that we are able to make a connection to the database.
if (myConnection.State == System.Data.ConnectionState.Open)
{
_ConnectionExists = true;
}
else
{
throw new ArgumentException("Error unable to open connection to the database.");
}
}
catch (Exception ex)
{
throw new ArgumentException("Error opening Connection to the database: " + ex.Message);
}
}
catch (Exception ex)
{
throw new ArgumentException("Error creating Database Connection: " + ex.Message);
}
return myConnection;
}
}
}
using the class:
GoogleOauth g = new GoogleOauth();
AnalyticsService service = g.Handle(userEmailAddress,
connectionString, redirectUrl,
"YOURAPLICATIONNAME",
new[] {AnalyticsService.Scope.AnalyticsReadonly});
DataResource.RealtimeResource.GetRequest request = service.Data.Realtime.Get(String.Format("ga:{0}", profileId), "rt:activeUsers");
RealtimeData feed = request.Execute();
If people are intrested I can upload a sample project to github.

"The ConnectionString property is invalid." when I know it is valid

I have an ASP.NET MVC application where the database is on an IBM i-Series server. I have the application development close to completion when I started to get a The ConnectionString property is invalid. error popping up:
only at log on
after the first successful log on after rebuilding
anyone logged on can still work normally
Also, note that this problem only shows up for one project in my solution. The other project uses the exact same connection string and doesn't have this problem (copied and pasted to be 100% sure). I am in active development on these projects, but have not touched the connections strings nor worked with the AccountController and related model classes after getting the login working.
I am using Visual Studio 2008 and .NET version 3.5.
Connection String:
<connectionStrings>
<add name="IbmIConnectionString" connectionString="DataSource=192.168.50.200;DefaultCollection=QMFILES;Naming=sql;UserID=XXX;Password=XXXX;"/>
</connectionStrings>
Account Controller Logon method:
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
string fullName = String.Empty;
string employeeId = String.Empty;
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
EmployeeLoginModel elm = new EmployeeLoginModel();
elm.GetUserInfo(model.UserName, model.Password, out fullName, out employeeId);
// Update the AuthCookie to include the last 4 digits of the SSN.
string userDataString = String.Format("{0}|{1}|{2}", model.Password, fullName.Trim(), employeeId.Trim());
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(model.UserName, model.RememberMe);
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, userDataString);
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Add(authCookie);
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Employee Login Model:
public class EmployeeLoginModel
{
public string UserName { set; get; }
public string Password { set; get; }
private iDB2Connection conn;
/// <summary>
/// Initializes a new instance of the <see cref="EmployeeLoginModel"/> class.
/// </summary>
public EmployeeLoginModel()
{
conn = new iDB2Connection(ConfigurationManager.ConnectionStrings["IbmIConnectionString"].ConnectionString);
}
/// <summary>
/// Determines whether [is valid user] [the specified username].
/// </summary>
/// <param name="username">The username.</param>
/// <param name="password">The password.</param>
/// <returns>
/// <c>true</c> if [is valid user] [the specified username]; otherwise, <c>false</c>.
/// </returns>
public bool IsValidUser(string username, string password)
{
int count = 0;
// Get the data from the iSeries
using (conn)
{
string sqlStatement = "SELECT COUNT(XXXXX) FROM XXXXX WHERE UPPER(XXXXXX) = #1 AND XXXXXX = #2";
iDB2Command cmd = new iDB2Command(sqlStatement, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#1", username.ToUpper());
cmd.Parameters.Add("#2", password);
conn.Open();
count = (Int32)cmd.ExecuteScalar();
conn.Close();
}
return ((count == 0) ? false : true);
}
Another very trivial reason for getting this error is, that the required DB2 drivers are not installed.
The inner exception stated
Unable to load DLL 'cwbdc.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)
Type: System.DllNotFoundException
After posting this, I had a theory. I was switching between browsers getting things setup for a demo. I changed my method to:
public bool IsValidUser(string username, string password)
{
int count = 0;
// Get the data from the iSeries
using (iDB2Connection conn = new iDB2Connection(ConfigurationManager.ConnectionStrings["IbmIConnectionString"].ConnectionString))
{
string sqlStatement = "SELECT COUNT(XXXXXX) FROM XXXXXX WHERE UPPER(XXXXXX) = #1 AND XXXXXX = #2";
iDB2Command cmd = new iDB2Command(sqlStatement, conn);
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#1", username.ToUpper());
cmd.Parameters.Add("#2", password);
conn.Open();
count = (Int32)cmd.ExecuteScalar();
conn.Close();
}
return ((count == 0) ? false : true);
}
It seems to be working now. I wonder if that was the problem.
I think because you use the connection outside the using statement, so it will be closed after go to other function, so when you call in IsValidUser, it will throw exception. in the second code, you use it in using statement, after call it will be Garbage Collection released. And it is work.

Categories