I am currently building an app and am trying to write a webjob to
take an mp4file i have uploaded to blob storage and create an asset which i then can encode and prepare to stream using azure media services.
public class Functions
{
// This function will get triggered/executed when a new message is written
// on an Azure Queue called queue.
static string accName = "copied from portal ";
static string accKey = "as above";
static CloudMediaContext context = new CloudMediaContext(accName,accName);
// Use the cached credentials to create CloudMediaContext.
//static CloudMediaContext context = new CloudMediaContext(accName,accKey);
public static void ProcessVideo(
[QueueTrigger("videorequest")] VideoBlobInformation blobInfo,
[Blob("{ProfileId}/{BlobName}", FileAccess.Read)] Stream input,
[Blob("{ProfileId}/{BlobNameWithoutExtension}_stream.mp4")] CloudBlockBlob outputBlob)
{
VideoBlobInformation b = blobInfo;
using (Stream output = outputBlob.OpenWrite())
{
ConvertAndPrepareVideo(b,input, output);
}
// Entity Framework context class is not thread-safe, so it must
// be instantiated and disposed within the function.
using (impulsevidContext db = new impulsevidContext())
{
//var id = blobInfo.ProfileId;
//Video ad = db.Videos.Find(id);
//if (ad == null)
//{
// throw new Exception(String.Format("AdId {0} not found, can't create thumbnail", id.ToString()));
//}
//ad.StreamUrl = outputBlob.Uri.ToString();
//db.SaveChanges();
}
}
public static void ConvertAndPrepareVideo(VideoBlobInformation info,Stream input, Stream output)
{
var storageAccount = new CloudStorageAccount(new StorageCredentials("accnameofstorage", "storage account associated with azure media services"), true);
//output all webjob input blobs into a container -mediacontroller-
var cloudBlobClient = storageAccount.CreateCloudBlobClient();
var mediaBlobContainer = cloudBlobClient.GetContainerReference("impfile");
mediaBlobContainer.CreateIfNotExists();
IAsset sourceAsset = context.Assets.Where(a => a.Id == info.VideoId).First();
}
I am using a single storage account that i upload to.
i keep getting this error 400 no matter what i try caused by this line
IAsset sourceAsset = context.Assets.Where(a => a.Id == info.VideoId).First();
which causes this log error
Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception while executing function: Functions.ProcessVideo ---> System.Net.WebException: The remote server returned an error: (400) Bad Request.
at System.Net.WebClient.UploadValues(Uri address, String method, NameValueCollection data)
at System.Net.WebClient.UploadValues(String address, String method, NameValueCollection data)
at Microsoft.WindowsAzure.MediaServices.Client.AcsTokenProvider.<>c__DisplayClass47_2.b__0()
at Microsoft.Practices.TransientFaultHandling.RetryPolicy.<>c__DisplayClass1.b__0()
at Microsoft.Practices.TransientFaultHandling.RetryPolicy.ExecuteAction[TResult](Func1 func)
at Microsoft.Practices.TransientFaultHandling.RetryPolicy.ExecuteAction(Action action)
at Microsoft.WindowsAzure.MediaServices.Client.AcsTokenProvider.RefreshToken()
at Microsoft.WindowsAzure.MediaServices.Client.AcsTokenProvider.GetAccessToken()
at Microsoft.WindowsAzure.MediaServices.Client.AcsTokenProvider.GetAuthorizationHeader()
at Microsoft.WindowsAzure.MediaServices.Client.OAuth.OAuthDataServiceAdapter.AddAccessTokenToRequest(WebRequest request)
at Microsoft.WindowsAzure.MediaServices.Client.AzureMediaServicesClassFactory.<>c__DisplayClass21_0.<GetAccountApiEndpoint>b__0()
at Microsoft.Practices.TransientFaultHandling.RetryPolicy.<>c__DisplayClass1.<ExecuteAction>b__0()
at Microsoft.WindowsAzure.MediaServices.Client.TransientFaultHandling.MediaRetryPolicy.ExecuteAction[TResult](Func1 func)
at Microsoft.Practices.TransientFaultHandling.RetryPolicy.ExecuteAction(Action action)
at Microsoft.WindowsAzure.MediaServices.Client.AzureMediaServicesClassFactory.GetAccountApiEndpoint(OAuthDataServiceAdapter dataServiceAdapter, ServiceVersionAdapter versionAdapter, Uri apiServer, UserAgentAdapter userAgentAdapter, IWebRequestAdapter clientRequestIdAdapter)
at Microsoft.WindowsAzure.MediaServices.Client.AzureMediaServicesClassFactory.<>c__DisplayClass24_0.b__0()
at Microsoft.WindowsAzure.MediaServices.Client.Cache1.GetOrAdd(String key, Func1 valueFactory, Func1 expirationFactory)
at Microsoft.WindowsAzure.MediaServices.Client.AzureMediaServicesClassFactory.CreateAzureMediaServicesEndPoint(Uri azureMediaServicesEndpoint, MediaContextBase mediaContext)
at Microsoft.WindowsAzure.MediaServices.Client.AzureMediaServicesClassFactory..ctor(Uri azureMediaServicesEndpoint, CloudMediaContext mediaContext)
at Microsoft.WindowsAzure.MediaServices.Client.CloudMediaContext.get_MediaServicesClassFactory()
at Microsoft.WindowsAzure.MediaServices.Client.AssetCollection.<.ctor>b__2_0()
at System.Lazy1.CreateValue()
at System.Lazy1.LazyInitValue()
at System.Lazy1.get_Value()
at Microsoft.WindowsAzure.MediaServices.Client.AssetCollection.get_Queryable()
at Microsoft.WindowsAzure.MediaServices.Client.BaseCollection1.get_Provider()
at System.Linq.Queryable.Where[TSource](IQueryable1 source, Expression1 predicate)
at VideoProcess.Functions.ConvertAndPrepareVideo(VideoBlobInformation info, Stream input, Stream output)
at VideoProcess.Functions.ProcessVideo(VideoBlobInformation blobInfo, Stream input, CloudBlockBlob outputBlob)
at lambda_method(Closure , Functions , Object[] )
at Microsoft.Azure.WebJobs.Host.Executors.VoidMethodInvoker1.InvokeAsync(TReflected instance, Object[] arguments)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`1.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__21.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__19.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__13.MoveNext()
--- End of inner exception stack trace ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__13.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__10.MoveNext()
context = new CloudMediaContext(new MediaServicesCredentials(
accName,
accKey));
should be set within the ConvertAndPrepareVideo method not outside
Related
So I wrote a little c# utility which connects to my devops azure repo and downloads a bunch of files in a zip, then unpacks the zip file(s) and then does a text search and replace to customise the files.
This utility was working fine up to Friday 8th. On Monday 11th the utility started telling me i was unauthorised.
This utility is used by 3 other colleagues and it is still working a-ok for them, just not me :(
The utility has been working fine for over 4 months until his week.
Here's the pertinent code:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Client;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.TeamFoundation.Core.WebApi;
using Microsoft.VisualStudio.Services.WebApi;
using System.IO;
using System.IO.Compression;
namespace ########.######.####.#######
{
class Program
{
const String c_collectionUri = "https://dev.azure.com/#################";
const String c_projectName = "########.######.#######.######.#########";
const String c_variableGroupId = "########-####-####-####-############"; // id for the LIVE project / repos
const String download_dir = #"C:\###########\";
const String dev_short_name_txt = "$$dev_shortname$$";
const String dev_long_name_txt = "$$dev_long_name$$";
const String todays_date_txt = "$$todays_date$$";
static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();
private static string dev_short_name;
private static string dev_long_name;
private static string todays_date;
static void Main(string[] args)
{
// gets just the username, e.g. ############
dev_short_name = Environment.UserName;
Console.WriteLine("Who are you : " + dev_short_name);
DateTime today = DateTime.Today; // As DateTime
todays_date = today.ToString("dd/MM/yyyy"); // As String
Console.WriteLine("Today is : " + todays_date);
// Interactively ask the user for credentials, caching them so the user isn't constantly prompted
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
// Connect to Azure DevOps Services
VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
Console.WriteLine("");
Console.WriteLine("Projects....");
Console.WriteLine("");
ProjectHttpClient projectClient = connection.GetClient<ProjectHttpClient>();
TeamHttpClient teamClient = connection.GetClient<TeamHttpClient>();
// Call to get the list of projects
IEnumerable<TeamProjectReference> projects = projectClient.GetProjects().Result;
Dictionary<TeamProjectReference, IEnumerable<WebApiTeam>> results = new Dictionary<TeamProjectReference, IEnumerable<WebApiTeam>>();
// Iterate over the returned projects
foreach (var project in projects)
{
// Get the teams for the project
IEnumerable<WebApiTeam> teams = teamClient.GetTeamsAsync(project.Name).Result;
// Add the project/teams item to the results dictionary
results.Add(project, teams);
Console.WriteLine(" " + project.Id + " " + project.Name);
Here's the error output:
Who are you : ###############
Today is : 14/07/2022
Projects....
Unhandled Exception: Microsoft.VisualStudio.Services.WebApi.VssServiceResponseException: Unauthorized
at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<HandleResponseAsync>d__53.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<SendAsync>d__51.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.VssHttpClientBase.<SendAsync>d__47`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.Location.Client.LocationHttpClient.<GetConnectionDataAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<GetConnectionDataAsync>d__56.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<ConnectAsync>d__41.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<EnsureConnectedAsync>d__39.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<CheckForServerUpdatesAsync>d__38.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<FindServiceDefinitionAsync>d__35.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.VssServerDataProvider.<LocationForCurrentConnectionAsync>d__29.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.LocationService.<ResolveLocationDataAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.Location.LocationService.<GetLocationDataAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.VssConnection.<GetClientInstanceAsync>d__20.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.VssConnection.<GetClientServiceImplAsync>d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.VssConnection.<GetClientAsync>d__14`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.VisualStudio.Services.WebApi.TaskExtensions.SyncResult[T](Task`1 task)
at Microsoft.VisualStudio.Services.WebApi.VssConnection.GetClient[T]()
at ########.######.####.#######.Program.Main(String[] args) in C:\########\########.######.####.#######\########.######.####.#######\Program.cs:line 60
I've googled around and tried various things like:
deleting C:\Users\###########\AppData\Local.IdentityService
clearing temp internet files / folders from both Edge and Chrome
removing all generic credetials from the Credential Manager
using alternatives to VssCredentials / VssClientCredentialStorage / VssConnection like:
// Interactively ask the user for credentials, caching them so the user isn't constantly prompted
VssCredentials creds = new VssClientCredentials();
creds.Storage = new VssClientCredentialStorage();
Console.WriteLine("creds : " + creds.Windows.ToString());
Console.WriteLine("creds2 : " + creds.Storage.ToString());
// Connect to Azure DevOps Services
VssConnection connection;
ProjectHttpClient projectClient;
try
{
connection = new VssConnection(new Uri(c_collectionUri), creds);
projectClient = connection.GetClient<ProjectHttpClient>();
}
catch (VssServiceResponseException e)
{
Console.WriteLine(e);
connection = new VssConnection(new Uri(c_collectionUri), new VssAadCredential());
//connection = new VssConnection(new Uri(c_collectionUri), new VssBasicCredential(string.Empty, personalAccessToken));
//connection = new VssConnection(new Uri(c_collectionUri), new VssBasicCredential("##############","###################################"));
projectClient = connection.GetClient<ProjectHttpClient>();
}
//VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
//VssConnection connection = new VssConnection(new Uri(c_collectionUri), new VssAadCredential());
But I still can't get in!!!
I'm not aware of any changes being made to my device.
Our IT guys fixed this one. I was missing a trusted site setting, which they've added via a browser GPO for edge / chrome.
:)
I am working on Google Sheet Api, the below attached code is working fine in development environment. After deploying website in IIS, I am phasing the belwo error. I am working with ASP.NET MVC Environment.
System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=131872634482-gh84b1avui5t9f5ugfv667eiotkivu1p.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A56626%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__16.MoveNext()
--- End of inner exception stack trace ---
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__1.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task1.get_Result()
at EmailDashboard.Extensions.SpreadsheetV4Extensions.GetService() in D:\Project\EmailDashboard\SourceCodeWeb\EmailDashboard\Extensions\SpreadsheetV4Extensions.cs:line 43
---> (Inner Exception #0) System.NotSupportedException: Failed to launch browser with "https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id=131872634482-gh84b1avui5t9f5ugfv667eiotkivu1p.apps.googleusercontent.com&redirect_uri=http%3A%2F%2F127.0.0.1%3A56626%2Fauthorize%2F&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fspreadsheets" for authorization. See inner exception for details. ---> System.ComponentModel.Win32Exception: Access is denied
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__16.MoveNext()
--- End of inner exception stack trace ---
at Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.d__16.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.AuthorizationCodeInstalledApp.d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__1.MoveNext()<---
public SheetsService GetService()
{
try
{
string path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/client_Secret_Sheet.json");
UserCredential credential = null;
using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
string folderPath = System.Web.Hosting.HostingEnvironment.MapPath("~/Credentials/");
if (folderPath != null)
{
string filePath = Path.Combine(folderPath, "SpreadsheetCredentials");
if (Directory.Exists(filePath))
{
var directoryInfo = new DirectoryInfo(filePath);
//foreach (FileInfo file in directoryInfo.GetFiles()) {
// file.Delete();
//}
//foreach (DirectoryInfo dir in directoryInfo.GetDirectories()) {
// dir.Delete(true);
//}
}
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { SheetsService.Scope.Spreadsheets },
Environment.UserName,
CancellationToken.None,
new FileDataStore(filePath, true)).Result;
}
}
// Create Drive API service.
SheetsService service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = _applicationName,
});
return service;
}
catch (Exception ex)
{
throw new Exception(ex);
}
}
So looking at your code you are trying to make an authorized client by doing:
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { SheetsService.Scope.Spreadsheets },
Environment.UserName,
CancellationToken.None,
new FileDataStore(filePath, true)).Result;
This is advised for doing installed apps in your PC. For deploying this in a server you would need to change your code.
All the process and option you have is very detailed in this page. Basically Google has a package to implement the authentication in MVC.
Reference
NuGet Package for Google.Apis.Auth.Mvc
Github Library for Google C# API
Google.Apis.Http.Configurable MessageHandler.d__59.MoveNext() --- End of stack trace from previous location where exception was thrown --- at
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at
System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult() at Google.Apis.Auth.OAuth2.Requests.TokenRequestExtenstions.d__0.MoveNext() --- End of stack trace from previous location where exception was thrown ---
It is working fine with one server but not working with another server
private static async Task<string> GetAccessToken()
{
//var buildDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string token = string.Empty;
try
{
List<string> scope = new List<string>();
scope.Add(firebaseMessagingURL); //Will Not Change --Until or unless changes by google
GoogleCredential googlCredentail = GoogleCredential.FromJson(firebasecredential).CreateScoped(scope);
token = await googlCredentail.UnderlyingCredential.GetAccessTokenForRequestAsync();
return token;
}
catch (Exception ex)
{
Logging.WriteLog(ex, Logging.LogMsgType.General, Logging.CacheStoresName.Empty.ToString());
}
return token;
}
So I have been working on this UWP App for work. I ran a test program on my developer site and got it to work perfectly. I recreated the UWP App to access it on my company's platform and I am hitting a snag. When I try to submit the data I get an MsalUIRequiredException error.
{Microsoft.Identity.Client.MsalUiRequiredException: Null user was passed in AcquiretokenSilent API. Pass in a user object or call acquireToken authenticate.
at Microsoft.Identity.Client.Internal.Requests.SilentRequest..ctor(AuthenticationRequestParameters authenticationRequestParameters, Boolean forceRefresh)
at Microsoft.Identity.Client.ClientApplicationBase.<AcquireTokenSilentCommonAsync>d__34.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Identity.Client.ClientApplicationBase.<AcquireTokenSilentAsync>d__31.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at AshburnGeneratorApp.Authentication.<AquireTokenAsync>d__0.MoveNext()
ErrorCode: user_null
StatusCode: 0
Claims: }
I can see that it is telling me to use a tenant-specific endpoint or /organizations, which I thought I was. So that is where I get confused.
{Microsoft.Identity.Client.MsalServiceException: AADSTS90130: Application '87f68831-d1ea-493c-8b94-e61fcd1c4a08' (AshburnGeneratorApp) is not supported over the /common or /consumers endpoints. Please use the /organizations or tenant-specific endpoint.
Trace ID: 888ba8ca-400f-43f9-8267-290c8e748100
Correlation ID: 121ef843-ef32-4126-aea8-0e17322df657
Timestamp: 2018-08-21 11:06:35Z
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.VerifyAuthorizationResult()
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.<PreTokenRequestAsync>d__9.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.<RunAsync>d__33.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Identity.Client.PublicClientApplication.<AcquireTokenForLoginHintCommonAsync>d__21.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Identity.Client.PublicClientApplication.<AcquireTokenAsync>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at AshburnGeneratorApp.Authentication.<AquireTokenAsync>d__0.MoveNext()
ErrorCode: invalid_request
StatusCode: 0
Claims: }
The PUT is going to
https://graph.microsoft.com/v1.0/sites/companyname.sharepoint.com,495435b4-60c3-49b7-8f6e-1d262a120ae5,0fad9f67-35a8-4c0b-892e-113084058c0a/lists/18a725ac-83ef-48fb-a5cb-950ca2378fd0/items
where "companyname" is my actual company name.
If I run a GET on the Graph Explorer, the link works great. So I know I am missing something simple somewhere.
The following code kicks off the authentication:
private async void SubmitButton_Click(object sender, RoutedEventArgs e)
{
var (authResult, message) = await Authentication.AquireTokenAsync();
ResultText.Text = message;
if (authResult != null)
{
await SubmitDataWithTokenAsync(submiturl, authResult.AccessToken);
}
}
Which will call this code:
public static async Task<(AuthenticationResult authResult, string message)> AquireTokenAsync()
{
AuthenticationResult authResult = null;
string message = String.Empty;
string[] scopes = App.scopes;
try
{
authResult = await App.PublicClientApp.AcquireTokenSilentAsync(scopes, App.PublicClientApp.Users.FirstOrDefault());
}
catch (MsalUiRequiredException ex)
{
// A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
try
{
authResult = await App.PublicClientApp.AcquireTokenAsync(scopes);
}
catch (MsalException msalex)
{
message = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
}
}
catch (Exception ex)
{
message = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
}
return (authResult, message);
}
Scopes set
public static string[] scopes = new string[] { "user.ReadWrite", "Sites.ReadWrite.All" };
and last bit of code
private static string ClientId = "87f68831-d1ea-493c-8b94-e61fcd1c4a08";
public static PublicClientApplication PublicClientApp { get; } = new PublicClientApplication(ClientId);
I knew it was something simple. I had not registered the app for v2.0. Once I did that, everything worked great.
I get this exception intermittently in my asp.net mvc 5 c# web application:
Server cannot append header after HTTP headers have been sent.
It just happens uploading images to S3 method (Web Api Controller).
The presendrequestheaders in Global.asax
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app != null &&
app.Context != null)
{
app.Context.Response.Headers.Remove("Server");
}
}
The method that trigger the error:
[HttpPost]
[Route("UploadImageJSON")]
public IHttpActionResult UploadImageJSON(HttpRequestMessage request)
{
var httpRequest = HttpContext.Current.Request;
// Check if files are available
if (httpRequest.Files.Count != 1) return BadRequest();
var postedFile = httpRequest.Files[0];
var contentType = postedFile.ContentType;
if (!contentType.Contains("image"))
{
return StatusCode(HttpStatusCode.NotAcceptable);
}
var keyUploadFiles = Constants.UrlS3Amazon +
S3.UploadToS3WithStream(postedFile.InputStream, contentType);
return Json(JsonConvert.SerializeObject(keyUploadFiles));
}
EDIT: More information... I have my Web App hosted in Elastic BeanStalk with a load balancer, the load balancer has installed a SSL Certificate, and the connection between the load balancer and the EC2 instances are in ports 80. Maybe it could be helpful.
The Elmah log:
System.Web.HttpException (0x80004005): Server cannot append header after HTTP headers have been sent.
at System.Web.HttpHeaderCollection.SetHeader(String name, String value, Boolean replace)
at Microsoft.Owin.Host.SystemWeb.CallHeaders.AspNetResponseHeaders.Set(String key, String[] values)
at Microsoft.Owin.Infrastructure.OwinHelpers.AppendHeaderUnmodified(IDictionary2 headers, String key, String[] values)
at Microsoft.Owin.ResponseCookieCollection.Append(String key, String value, CookieOptions options)
at Microsoft.Owin.Security.Cookies.CookieAuthenticationHandler.<ApplyResponseGrantAsync>d__b.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationHandler.<TeardownAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware1.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware2.<Invoke>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware2.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNet.Identity.Owin.IdentityFactoryMiddleware`2.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Owin.Mapping.MapMiddleware.d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Thanks!!
have you tried with removing app.Context.Response.Headers.Remove("Server"); i think there is this is the issue?