FileStream - Path found in console-application but not in mvc - json

Iv'e used this guide drive quickstart and successfully got it worked in a console-app.
Now I'm trying to do the same thing in an mvc-application, but I got error when creating a new FileStream.
The code a use is exactly the same in mvc instead this time i'ts triggered by a button-click. This is my code:
using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.PageSize = 10;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute()
.Files;
I got error at 'using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))'
My 'client_secret.json'-file is stored at the root of my mvc project.
And I've done the step: Select client_secret.json, and then go to the Properties window and set the Copy to Output Directory field to Copy always.
Why is this not working in my mvc-app?
The error I get is 'System.IO.FileNotFoundException' - '{"Cannot find file c:\windows\system32\inetsrv\client_secret.json.":"c:\windows\system32\inetsrv\client_secret.json"}'

Related

Adobe AIR file upload response data in complete handler is null while fiddler(web debugger) shows that json is returned as response

When uploading a file from adobe AIR to a backbone server, the response returned is not anyway accessible when using file.upload(request) function, while i can see json response in fiddler(web debugger and in task manager), also it was working fine when using URLLoader.load() instead of file.upload()
var url = "api url of backbone server ";
request = null;
file = null;
request = new air.URLRequest(url);
request.useCache = false;
var authorization = new air.URLRequestHeader("Authorization", "Bearer "+accessToken);
var contentType = new air.URLRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
var Accept = new air.URLRequestHeader("Accept", "application/json;charset=UTF-8");
request.requestHeaders.push(authorization);
request.requestHeaders.push(contentType);
request.requestHeaders.push(Accept);
file = new air.File(path);
pathNative = file.nativePath;
var directory = getDirectoryFromPath(pathNative);
params = new air.URLVariables();
params.parent_id = directory.directory_id;
params.name = file.name;
request.data = params;
request.method = air.URLRequestMethod.POST;
request.contentType = 'multipart/form-data, boundary='+boundary;
var file = new air.File(path);
file.upload(request);
file.addEventListener(air.Event.COMPLETE, function(e){
air.Introspector.Console.log(file);
air.Introspector.Console.log(e);
air.Introspector.Console.log(e.target.data);
});
This is the console for complete event as you can see returned data is null.
see console
while in fiddler shows that json is returned.
see fiddler
Seems like it's a known issue on iOS? Are you trying to do this from iOS?
https://forums.adobe.com/thread/1720117?start=0&tstart=0
I ran into the same problem. Instead of using air.Event.COMPLETE, try to use air.DataEvent.UPLOAD_COMPLETE_DATA:
file.addEventListener(air.DataEvent.UPLOAD_COMPLETE_DATA, function(e){
air.Introspector.Console.log(e.data);
});

Download Azure Blob image to memorystream in Windows Phone 8.1

The code below will copy an image file from Azure blob storage, and create a new image file locally. This local image will then be added to a List for further databinding to the XAML UI.
string accountName = "testacc";
string accountKey = "123abc";
string container = "textcontainer";
List<Mydata> items = new List<Mydata>();
BitmapImage bitmapToShow = new BitmapImage();
StorageCredentials creds = new StorageCredentials(accountName, accountKey);
CloudStorageAccount acc = new CloudStorageAccount(creds, useHttps: true);
CloudBlobClient cli = acc.CreateCloudBlobClient();
CloudBlobContainer sampleContainer = cli.GetContainerReference(container);
CloudBlockBlob blob = sampleContainer.GetBlockBlobReference("xbox.jpg");
// Here I need to copy the data stream directely to the BitmapImage instead of creating a file first
StorageFile photoFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("temp_image.jpg", CreationCollisionOption.ReplaceExisting);
await blob.DownloadToFileAsync(photoFile);
bitmapToShow = new BitmapImage(new Uri(photoFile.Path));
items.Add(new Mydata() { image = bitmapToShow });
DataBinding.ItemsSource = items;
The code below will copy an image file from Azure blob storage, and create a new image file locally. This local image will then be added to a List for further databinding to the XAML UI.
Hovewer - in order to get more efficient, I am looking for a way to avoid creating the image file locally first. I am looking for a way where the image file in the Azure blob storage are copied to a MemoryStream and then passed directely into a BitmapImage.
I have not fiugred out to code that myself, and the code snippets I have not found, do not work for Windows Phone 8.1. I am programming in C# for Windows Phone 8.1 Universal App (not Silverlight).
Can someone help me with the code needed to get that functionality?
Would this work?
Stream photoStream = await blob.DownloadToStreamAsync(photoFile)
bitmapToShow = new BitmapImage(photoStream);
Hope it helps,
Drew
I found that this Works. It might not be perfect, but it Works. Comments or corrections are welcome.
string accountName = "testacc";
string accountKey = "123abc";
string container = "textcontainer";
List<Mydata> items = new List<Mydata>();
BitmapImage bitmapToShow = new BitmapImage();
InMemoryRandomAccessStream memstream = new InMemoryRandomAccessStream();
StorageCredentials creds = new StorageCredentials(accountName, accountKey);
CloudStorageAccount acc = new CloudStorageAccount(creds, useHttps: true);
CloudBlobClient cli = acc.CreateCloudBlobClient();
CloudBlobContainer sampleContainer = cli.GetContainerReference(container);
CloudBlockBlob blob = sampleContainer.GetBlockBlobReference("xbox.jpg");
await blob.DownloadToStreamAsync(memstream.CloneStream());
bitmapToShow.SetSource(memstream);
items.Add(new Mydata() { image = bitmapToShow });
DataBinding.ItemsSource = items;

Gdrive unable to download and not upload

I am using GDRive insertFile and RevtrieveAllFiles to upload and download files to googledrive.
I created a client secret and Id and modified the credentials.
the code is based on the post in code project http://www.codeproject.com/KB/WPF/488185/GDrive_Uploader_Sample.zip
but it fails debuggin the Utilities.InsertFile
in the file.upload it fails with exceptionvalue cannot be null - uriString .
in the download it fails in FileList files = request.Fetch(); with
// First, create a reference to the service you wish to use.
// For this app, it will be the Drive service. But it could be Tasks, Calendar, etc.
// The CreateAuthenticator method is passed to the service which will use that when it is time to authenticate
// the calls going to the service.
_service = new DriveService(CreateAuthenticator());
// Open a dialog box for the user to pick a file.
OpenFileDialog dialog = new OpenFileDialog();
dialog.AddExtension = true;
dialog.DefaultExt = ".txt";
dialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Multiselect = false;
dialog.ShowDialog();
File body = new File();
body.Title = System.IO.Path.GetFileName(dialog.FileName);
body.Description = "A test document";
body.MimeType = "text/plain";
System.IO.Stream fileStream = dialog.OpenFile();
byte[] byteArray = new byte[fileStream.Length];
fileStream.Read(byteArray, 0, (int)fileStream.Length);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
// Get a listing of the existing files...
List<File> fileList = Utilities.RetrieveAllFiles(_service);
// Set a flag to keep track of whether the file already exists in the drive
bool fileExists = false;
foreach (File item in fileList)
{
if (item.Title == body.Title)
{
// File exists in the drive already!
fileExists = true;
MessageBoxResult result = System.Windows.MessageBox.Show("The file you picked already exists in your Google Drive. Do you wish to overwrite it?", "Confirmation", MessageBoxButton.YesNoCancel);
if (result == MessageBoxResult.Yes)
{
// Yes... overwrite the file
Utilities.UpdateFile(_service, item.Id, item.Title, item.Description, item.MimeType, dialog.FileName, true);
List<File> allFiles = Utilities.RetrieveAllFiles(_service);
}
else if (result == MessageBoxResult.No)
{
// MessageBoxResult.No code here
File f= Utilities.insertFile(_service, System.IO.Path.GetFileName(dialog.FileName), "An uploaded document", "", "text/plain", dialog.FileName);
}
else
{
// MessageBoxResult.Cancel code here
return;
}
break;
}
}
// Check to see if the file existed. If not, it is a new file and must be uploaded.
if (!fileExists)
{
File file= Utilities.insertFile(_service, System.IO.Path.GetFileName(dialog.FileName), "An uploaded document", "", "text/plain", dialog.FileName);
var list = Utilities.RetrieveAllFiles(_service);
}
System.Windows.MessageBox.Show("Upload Complete");
open gdrive and set sdk to On. that will enable the application to access the gdrive account

gsutil on a Google Compute Engine VM can't use service account authentication with a key file

I'm launching an instance from the google .net API and despite my best efforts I can't get it to copy anything to or from storage. Currently I'm authenticating with a developer console service account like this:-
string ServiceAccountEmail = "blahblah#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(ServiceAccountEmail)
{
Scopes = new[] { ComputeService.Scope.Compute, ComputeService.Scope.DevstorageFullControl }
}.FromCertificate(certificate));
var cs = new ComputeService(new BaseClientService.Initializer
{
ApplicationName = "appname",
HttpClientInitializer = (Google.Apis.Http.IConfigurableHttpClientInitializer)credential,
});
Google.Apis.Compute.v1.Data.Instance newinst = new Google.Apis.Compute.v1.Data.Instance();
newinst.Name = "generatedinstance";
newinst.MachineType = "https://www.googleapis.com/compute/v1/projects/projectid/zones/zone/machineTypes/n1-standard-1";
Google.Apis.Compute.v1.Data.AttachedDisk ad = new Google.Apis.Compute.v1.Data.AttachedDisk();
ad.AutoDelete = true;
ad.Boot = true;
ad.Type = "PERSISTENT";
ad.InitializeParams = new Google.Apis.Compute.v1.Data.AttachedDiskInitializeParams();
ad.InitializeParams.DiskName = "newdisk";
ad.InitializeParams.SourceImage = "https://www.googleapis.com/compute/v1/projects/projectid/global/images/customimage";
ad.InitializeParams.DiskType = "https://www.googleapis.com/compute/v1/projects/projectid/zones/zone/diskTypes/pd-standard";
ad.Mode = "READ_WRITE";
newinst.Disks = new List<Google.Apis.Compute.v1.Data.AttachedDisk>();
newinst.Disks.Add(ad);
Google.Apis.Compute.v1.Data.NetworkInterface ni = new Google.Apis.Compute.v1.Data.NetworkInterface();
ni.Network = "https://www.googleapis.com/compute/v1/projects/projectid/global/networks/default";
ni.AccessConfigs = new List<Google.Apis.Compute.v1.Data.AccessConfig>();
ni.AccessConfigs.Add(new Google.Apis.Compute.v1.Data.AccessConfig
{
Type = "ONE_TO_ONE_NAT",
Name = "External NAT",
});
newinst.NetworkInterfaces = new List<Google.Apis.Compute.v1.Data.NetworkInterface>();
newinst.NetworkInterfaces.Add(ni);
var start = new Google.Apis.Compute.v1.Data.Metadata.ItemsData();
start.Key = "startup-script";
start.Value = "*startup script* includes gsutil cp which won't work without service account attached";
newinst.Metadata = new Google.Apis.Compute.v1.Data.Metadata();
newinst.Metadata.Kind = "compute#metadata";
newinst.Metadata.Items = new List<Google.Apis.Compute.v1.Data.Metadata.ItemsData>();
newinst.Metadata.Items.Add(start);
newinst.ServiceAccounts = new List<Google.Apis.Compute.v1.Data.ServiceAccount>();
//var sa = new Google.Apis.Compute.v1.Data.ServiceAccount();|with this section
//sa.Email = "blahblah#developer.gserviceaccount.com"; |the instance won't
//sa.Scopes = new[] { ComputeService.Scope.Compute, |start. (An equivalent
ComputeService.Scope.DevstorageFullControl }; |is found in instance
//newinst.ServiceAccounts.Add(sa); |start REST request)
var instinsert = new InstancesResource.InsertRequest(cs, newinst, "projectid", "zone");
var insertresponse = instinsert.Execute();
The message I get when I try to use gsutil cp is "You do not currently have an active account selected.". Can anyone tell me where I'm going wrong?
You need to run gcloud auth activate-service-account blahblah#developer.gserviceaccount.com --key-file path_to_key.p12 to tell the Cloud SDK (including gsutil) about your service account.
As per the code provided, I can see that the original example has
var certificate = new X509Certificate2(#"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
I notice you are missing the '#'in your code. I'm not very familiar with .Net. I have tested these examples in python and this one. When creating my instance I added the service account for GCS and the file is uploaded correctly.
OKAY! Problem solved. The part I was getting wrong was the bit commented out in the question-
var sa = new Google.Apis.Compute.v1.Data.ServiceAccount();
sa.Email = "blahblah#developer.gserviceaccount.com";
sa.Scopes = new[] { ComputeService.Scope.Compute,
ComputeService.Scope.DevstorageFullControl };
newinst.ServiceAccounts.Add(sa);
I needed the email for the main service account for the developer console in this section rather than the same service account I used to create the credentials but don't ask me why. Point is the instance launches and gsutil is now happily copying away.
Thanks for your time and help everyone!
Ross

AssertionFlowClient depreceated, trying to use ServiceAccountCredential, but it won't work

I've tried creating a DriveService using service account acting on behalf of another user.
I've copied this code from google documentation found here https://developers.google.com/drive/delegation
static DriveService BuildService() {
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
var provider = new AssertionFlowClient(GoogleAuthenticationServer.Description, certificate)
{
ServiceAccountId = SERVICE_ACCOUNT_EMAIL,
Scope = DriveService.Scopes.Drive.GetStringValue(),
};
var auth = new OAuth2Authenticator<AssertionFlowClient>(provider, AssertionFlowClient.GetState);
return new DriveService(auth);
}
but I get this warning when trying to build the project:
Warning 4 'Google.Apis.Authentication.OAuth2.DotNetOpenAuth.AssertionFlowClient' is obsolete: 'AssertionFlowClient is not supported any more and it's going to be removed in 1.7.0-beta. Consider using ServiceAccountCredential from the new Google.Apis.Auth NuGet package.'
and I also get this error:
Error 11 Argument 1: cannot convert from 'Google.Apis.Authentication.OAuth2.OAuth2Authenticator' to 'Google.Apis.Services.BaseClientService.Initializer'
Then I googled ServiceAccountCredential and ended up with this code (derived from this page: https://code.google.com/p/google-api-dotnet-client/wiki/OAuth2#Service_Accounts)
static DriveService BuildService() {
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(SERVICE_ACCOUNT_EMAIL)
{
User = "someone#mydomain.mygbiz.com",
Scopes = new[] { DriveService.Scope.DriveFile }
}.FromCertificate(certificate));
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
return service;
}
When I try to build this code it seems all fine, but when I run it I get the following error.
A first chance exception of type 'System.Security.Cryptography.CryptographicException' occurred in mscorlib.dll
Additional information: Det går inte att hitta det begärda objektet.
(Translated : The requested object cannot be found)
If there is a handler for this exception, the program may be safely continued.
The error occurs on this line:
X509Certificate2 certificate = new X509Certificate2(SERVICE_ACCOUNT_PKCS12_FILE_PATH, "notasecret", X509KeyStorageFlags.Exportable);
Anyone have any ideas?
Update 2013 Oct 31
I have tried this code:
{
Console.WriteLine("Drive API - Service Account");
Console.WriteLine("==========================");
String serviceAccountEmail = "<some email>#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = "<someuser>#<mydomain>.mygbiz.com",
Scopes = new[] { DriveService.Scope.Drive }
}.FromCertificate(certificate));
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "DrvMgr",
});
Console.WriteLine("Executing listing");
FileList UserFiles = service.Files.List().Execute();
I get this error message:
An unhandled exception of type 'Google.Apis.Auth.OAuth2.Responses.TokenResponseException' occurred in Google.Apis.dll
Additional information: Error:"access_denied", Description:"", Uri:""
It looks like the path to your p12 file is incorrect. See the Plus.ServiceAccount sample for a working solution.
I think that in this sample, the key.p12 was added to the project as a content file which is always copied to the output directory. Then mentioning "key.p12" file path from the code will result in grabbing this file from the output folder.