I'm trying to upload a CSV file using google analytics api and it gives me a status failed.
The error that I'm getting is variable is null: parameter name base uri
I have given the permissions for google analytics api in developer console and I'm using service account to generate the key and the id's.
This is my code snippet
const string serviceAccountEmail = "716698526626-6s61a3tbe1m5mofo9#developer.gserviceaccount.com";
const string serviceAccountPKCSP12FilePath = #"C:\SVN\GAPforInboundandWeb-1f6bfb.p12";
X509Certificate2 certificate = new X509Certificate2(serviceAccountPKCSP12FilePath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
var service = new AnalyticsService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "GAPforInboundandWeb"
});
FileStream realCsv = new FileStream("c:\\real.csv", FileMode.Open);
// Create the service.
try
{
var upload = service.Management.DailyUploads.Upload("50288725", "UA-50288725-1", "Oy_0JTPvRGCB3Vg5OKVIMQ",
"2014-09-22", 1, ManagementResource.DailyUploadsResource.UploadMediaUpload.TypeEnum.Cost, realCsv,
"application/octet-stream");
upload.Reset = true;
var res = upload.Upload();
res.BytesSent.ToString();
res.Status.ToString();
}
I resolved the same problem. In my case, its a wrong DataSourceId.
Try this:
const string serviceAccountEmail = "716698526626-6s61a3tbe1m5mofo9#developer.gserviceaccount.com";
const string serviceAccountPKCSP12FilePath = #"C:\SVN\GAPforInboundandWeb-1f6bfb.p12";
X509Certificate2 certificate = new X509Certificate2(serviceAccountPKCSP12FilePath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { AnalyticsService.Scope.Analytics }
}.FromCertificate(certificate));
var service = new AnalyticsService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "GAPforInboundandWeb"
});
FileStream realCsv = new FileStream("c:\\real.csv", FileMode.Open);
// Create the service.
try
{
var dataSource = srv.Management.CustomDataSources.List(AccountId, WebId).Execute();
var strDataSourceId = "Oy_0JTPvRGCB3Vg5OKVIMQ";
if(dataSource!=null && dataSource.Items.Length>0)
strDataSourceId =dataSource.Items[0].Id;
var upload = service.Management.DailyUploads.Upload("50288725", "UA-50288725-1", strDataSourceId,
"2014-09-22", 1, ManagementResource.DailyUploadsResource.UploadMediaUpload.TypeEnum.Cost, realCsv,
"application/octet-stream");
upload.Reset = true;
var res = upload.Upload();
res.BytesSent.ToString();
res.Status.ToString();
}
Use List methods on service.Management.CustomDataSources and service.Management.Uploads in this order for check your config.
Related
How to stop my livestream in YouTube while completed my live telecast using c#
How to stop the livestream Using c# Code, can you please give some suggestion
string[] scopes = { "https://www.googleapis.com/auth/youtube", "https://www.googleapis.com/auth/youtube.upload" };
var creadentails = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = YTPublishSettings.PublisherClientId,
ClientSecret = YTPublishSettings.PublisherClientSecret,
},
scopes, "user", default).Result;
if (creadentails.Token.IsExpired(SystemClock.Default))
creadentails.RefreshTokenAsync(CancellationToken.None).Wait();
var secrets = new ClientSecrets
{
ClientId = YTPublishSettings.PublisherClientId,
ClientSecret = YTPublishSettings.PublisherClientSecret,
};
var token = new TokenResponse { RefreshToken = creadentails.Token.RefreshToken };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer { ClientSecrets = secrets }),
"user", token);
var service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = credentials,
ApplicationName = "**************",
});
var broadcast = new LiveStream
{
Cdn = new CdnSettings
{
FrameRate = "35fps",
IngestionType = "rtmp",
Resolution = "720p"
},
Snippet = new LiveStreamSnippet
{
Description = Description,
Title = Title,
},
};
var request = service.LiveStreams.Delete(YTPublishSettings.PublisherId);
var response = request.Execute();
return new YouTubeStreamDeleteStatus()
{
success = "Deleted",
};
How can end My YouTube live stream API in c#?
This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 2 months ago.
My overall project is to create a spreadsheet, populate it, move it to a new location and lock it.
So far creating the sheet and populating it is fine. However, when I attempt to move the file I get the following error:
Happens at this part of the code: var getRequest = DriveService.Files.Get(fileId);
System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
My code is:
static void Init()
{
UserCredential credential;
//Reading Credentials File...
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/sheets.googleapis.com-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
// Creating Google Sheets API service...
SheetsService = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Create a Drive API service client
DriveService DriveService = new DriveService(new Google.Apis.Services.BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
static void CreateSheet()
{
// Create a new sheet with a single tab
string sheetName = "Test Create Sheet";
var NewSheet = new Google.Apis.Sheets.v4.Data.Spreadsheet();
NewSheet.Properties = new SpreadsheetProperties();
NewSheet.Properties.Title = sheetName;
var newSheet = SheetsService.Spreadsheets.Create(NewSheet).Execute();
SpreadsheetId = newSheet.SpreadsheetId;
Sheet = "Sheet1";
}
static void MoveSheet()
{
// Get the ID of the sheet you want to move
string sheetId = SpreadsheetId;
// Get the ID of the folder you want to move the sheet to
string folderId = "XXXXXBeNF2rG0PA6bsi89YugahH-XXXX";
// Retrieve the existing parents to remove
string fileId = sheetId;
var getRequest = DriveService.Files.Get(fileId);
getRequest.Fields = "parents";
var file = getRequest.Execute();
var previousParents = String.Join(",", file.Parents);
// Move the file to the new folder
var updateRequest =
DriveService.Files.Update(new Google.Apis.Drive.v3.Data.File(),
fileId);
updateRequest.Fields = "id, parents";
updateRequest.AddParents = folderId;
updateRequest.RemoveParents = previousParents;
//file = updateRequest.Execute();
}
It turns out I had a duplicate word (DriveService):
// Create a Drive API service client
DriveService DriveService = new DriveService(new Google.Apis.Services.BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
Should have been this:
// Create a Drive API service client
DriveService = new DriveService(new Google.Apis.Services.BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
}
I am now beyond that issue and have a new one in the form of:
The service drive has thrown an exception. HttpStatusCode is Forbidden. Insufficient Permission: Request had insufficient authentication scopes.
I am building a YouTube app for windows 8.1.
I am having a trouble with, add(Insert) subscription is fail
my code:
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secrets.json"),
new[] { Uri.EscapeUriString(YouTubeService.Scope.Youtube) },
"user",
CancellationToken.None);
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
HttpClientInitializer = credential,
ApplicationName = "AppName"
});
Subscription body = new Subscription();
body.Snippet = new SubscriptionSnippet();
body.Snippet.ChannelId = "UC-kezFAw46x-9ctBUqVe86Q";
try
{
var addSubscriptionRequest = youtubeService.Subscriptions.Insert(body, "snippet");
var addSubscriptionResponse = await addSubscriptionRequest.ExecuteAsync();
}
catch (Exception e)
{
throw e;
}
When I set a breakpoint at the first line.
when execute to last line, breaks this function
Update(2015-11-14):
Error Message:
The subscription resource specified in the request must use the snippet.resorceId property to identify the channel that is being subscribed to [400]
Successful Code:
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secrets.json"),
new[] { Uri.EscapeUriString(YouTubeService.Scope.Youtube) },
"user",
CancellationToken.None);
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
//ApiKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
HttpClientInitializer = credential,
ApplicationName = "4GameTV"
});
try
{
Subscription body = new Subscription();
body.Snippet = new SubscriptionSnippet();
body.Snippet.ResourceId = new ResourceId();
body.Snippet.ResourceId.ChannelId = "UC-kezFAw46x-9ctBUqVe86Q"; //replace with specified channel id
var addSubscriptionRequest = youtubeService.Subscriptions.Insert(body, "snippet");
var addSubscriptionResponse = await addSubscriptionRequest.ExecuteAsync();
}
catch (Exception e)
{
throw e;
}
Your authentication seems a bit off from what I normally use. Also ApiKey is only needed if you want to access public data.
string[] scopes = new string[] { YouTubeService.Scope.Youtube };
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret }
, scopes
, "test"
, CancellationToken.None
, new FileDataStore("Daimto.YouTube.Auth.Store")).Result;
YouTubeService service = new YouTubeService(new YouTubeService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "YouTube Data API Sample",
});
I'm writing a small desktop app that will upload file to google drive. So everything is fine when I'm sign in my google account, but when I'm not, program raises browser on this page "https://accounts.google.com/ServiceLogin". I'm using this code:
ClientSecrets secret = new ClientSecrets();
secret.ClientId = "my_client_id";
secret.ClientSecret = "my_client_secret";
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secret, new[] { DriveService.Scope.Drive }, "user", CancellationToken.None).Result;
var service = new DriveService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "TestUpload" });
File body = new File();
body.Title = "Title123";
body.Description = "Decription123";
body.MimeType = "image/png";
byte[] arr = System.IO.File.ReadAllBytes(fileName);
System.IO.MemoryStream stream = new System.IO.MemoryStream(arr);
FilesResource.InsertMediaUpload request = service.Files.Insert(body, stream, "image/png");
request.Upload();
So how can I authorize programmatically with out raising the browser?
Most of your problem is the fact that you are not saving the Authentication. You are requesting access but not saving it. In the following example fileDataStore stores the authentication information in a file on your pc in %AppData% this way next time you run the program no authentication will be needed, and it also wont require that you are logged into Google at the time.
//Scopes for use with the Google Drive API
string[] scopes = new string[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile};
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
UserCredential credential =
GoogleWebAuthorizationBroker
.AuthorizeAsync(new ClientSecrets { ClientId = CLIENT_ID
, ClientSecret = CLIENT_SECRET }
,scopes
,Environment.UserName
,CancellationToken.None
,new FileDataStore("Daimto.GoogleDrive.Auth.Store")
).Result;
DriveService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
public static File uploadFile(DriveService _service, string _uploadFile, string _parent) {
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description = "File uploaded by Diamto Drive Sample";
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
request.Upload();
return request.ResponseBody;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else {
Console.WriteLine("File does not exist: " + _uploadFile);
return null;
}
}
This code is ripped from the Google Drive C# upload tutorial, if you want more information on what its doing and how it works you may want to check that. There is also a working Sample project in the Google-Dotnet-Samples project on GitHub. The tutorial is based upon that sample project.
Is there any sample how to access a google service API using service account in .net?
private const string SERVICE_ACCOUNT_EMAIL = "xxxxxxxxxxx#developer.gserviceaccount.com";
private const string SERVICE_ACCOUNT_PKCS12_FILE_PATH = #"\path\test-privatekey.p12";
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((new BaseClientService.Initializer()
{
Authenticator = auth
});
}
This isn't successful in returning a OAuth connection. How can this be done?
Create a Service Account Keys credencial
Create private key for service. (Key json).
Example:
{
"type": "service_account",
"project_id": "...",
"private_key_id": "....",
"private_key": "....",
"client_email": ".....#developer.gserviceaccount.com",
"client_id": "....",
"auth_uri": "...accounts.google.com/o/oauth2/auth",
"token_uri": "...accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "...www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "...www.googleapis.com/robot/v1/metadata/x509/....-compute%40developer.gserviceaccount.com"
}
With this json you must generate a c# class. You can using (http://json2csharp.com/). This is faster
Use this code to generate credencial:
var _pathJson = #"C:\servicekey.json";
var json = File.ReadAllText(_pathJson);
var cr = JsonConvert.DeserializeObject<PersonalServiceAccountCred>(json);
// "personal" service account credential
// Create an explicit ServiceAccountCredential credential
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.ClientEmail)
{
Scopes = new[] { YouTubeService.Scope.YoutubeUpload /*Here put scope that you want use*/}
}.FromPrivateKey(cr.PrivateKey));
This case work in my site
var certificate = new X509Certificate2("pathTo***.p12", "notasecret", X509KeyStorageFlags.Exportable);
var serviceAccountEmail = "********-*********#developer.gserviceaccount.com";
var userAccountEmail = "******#gmail.com";
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { DriveService.Scope.Drive },
User = userAccountEmail
}.FromCertificate(certificate));
// Create the service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "*****",
});