Issue restoring local NuGet package through Azure Pipelines - asp.net-core

I have come across an issue in Azure Pipelines where I have a local NuGet package in my repo that I wish to include in the pipelines build alongside all other NuGet packages (which are all picked up from nuget.org normally). My project is built on ASP.NET Core, more specifically it is a Blazor server-side web application.
The local NuGet package "Breeze.Sharp.0.9.6.nupkg" is stored in my repo under: MySolution/packages
What is happening is that the nuget.org packages restore OK in pipelines but it fails when it tries to find my local NuGet package location and throws the below error:
1>/usr/share/dotnet/sdk/3.1.402/NuGet.targets(128,5): error : The local source '/home/vsts/work/1/Nuget/MySolution/packages' doesn't exist. [/home/vsts/work/1/s/MySolution/MySolution.sln]
NuGet.Protocol.Core.Types.FatalProtocolException: The local source '/home/vsts/work/1/Nuget/MySolution/packages' doesn't exist.
at NuGet.Protocol.LocalV3FindPackageByIdResource.GetVersionsCore(String id, ILogger logger)
at NuGet.Protocol.LocalV3FindPackageByIdResource.<>c__DisplayClass22_0.<GetVersions>b__0(String keyId)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at NuGet.Protocol.LocalV3FindPackageByIdResource.GetVersions(String id, SourceCacheContext cacheContext, ILogger logger)
at NuGet.Protocol.LocalV3FindPackageByIdResource.GetAllVersionsAsync(String id, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.Commands.SourceRepositoryDependencyProvider.GetAllVersionsAsync(String id, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.Commands.SourceRepositoryDependencyProvider.FindLibraryCoreAsync(LibraryRange libraryRange, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.Commands.SourceRepositoryDependencyProvider.<>c__DisplayClass19_0.<<FindLibraryAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at NuGet.Commands.SourceRepositoryDependencyProvider.FindLibraryAsync(LibraryRange libraryRange, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.DependencyResolver.ResolverUtility.<>c__DisplayClass9_1.<<FindLibraryFromSourcesAsync>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at NuGet.DependencyResolver.ResolverUtility.FindLibraryFromSourcesAsync(LibraryRange libraryRange, IEnumerable`1 providers, Func`2 action)
at NuGet.DependencyResolver.ResolverUtility.FindLibraryByVersionAsync(LibraryRange libraryRange, NuGetFramework framework, IEnumerable`1 providers, SourceCacheContext cacheContext, ILogger logger, CancellationToken token)
at NuGet.DependencyResolver.ResolverUtility.FindPackageLibraryMatchAsync(LibraryRange libraryRange, NuGetFramework framework, IEnumerable`1 remoteProviders, IEnumerable`1 localProviders, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.DependencyResolver.ResolverUtility.FindLibraryMatchAsync(LibraryRange libraryRange, NuGetFramework framework, String runtimeIdentifier, IEnumerable`1 remoteProviders, IEnumerable`1 localProviders, IEnumerable`1 projectProviders, IDictionary`2 lockFileLibraries, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
at NuGet.DependencyResolver.ResolverUtility.FindLibraryEntryAsync(LibraryRange libraryRange, NuGetFramework framework, String runtimeIdentifier, RemoteWalkContext context, CancellationToken cancellationToken)
at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge, TransitiveCentralPackageVersions transitiveCentralPackageVersions)
at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge, TransitiveCentralPackageVersions transitiveCentralPackageVersions)
at NuGet.DependencyResolver.RemoteDependencyWalker.WalkAsync(LibraryRange library, NuGetFramework framework, String runtimeIdentifier, RuntimeGraph runtimeGraph, Boolean recursive)
at NuGet.Commands.ProjectRestoreCommand.WalkDependenciesAsync(LibraryRange projectRange, NuGetFramework framework, String runtimeIdentifier, RuntimeGraph runtimeGraph, RemoteDependencyWalker walker, RemoteWalkContext context, CancellationToken token)
at NuGet.Commands.ProjectRestoreCommand.TryRestoreAsync(LibraryRange projectRange, IEnumerable`1 frameworkRuntimePairs, NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteDependencyWalker remoteWalker, RemoteWalkContext context, Boolean forceRuntimeGraphCreation, CancellationToken token, TelemetryActivity telemetryActivity)
at NuGet.Commands.RestoreCommand.ExecuteRestoreAsync(NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteWalkContext context, CancellationToken token, TelemetryActivity telemetryActivity)
at NuGet.Commands.RestoreCommand.ExecuteAsync(CancellationToken token)
at NuGet.Commands.RestoreRunner.ExecuteAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
at NuGet.Commands.RestoreRunner.ExecuteAndCommitAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
at NuGet.Commands.RestoreRunner.CompleteTaskAsync(List`1 restoreTasks)
at NuGet.Commands.RestoreRunner.RunAsync(IEnumerable`1 restoreRequests, RestoreArgs restoreContext, CancellationToken token)
at NuGet.Commands.RestoreRunner.RunAsync(RestoreArgs restoreContext, CancellationToken token)
at NuGet.Build.Tasks.BuildTasksUtility.RestoreAsync(DependencyGraphSpec dependencyGraphSpec, Boolean interactive, Boolean recursive, Boolean noCache, Boolean ignoreFailedSources, Boolean disableParallel, Boolean force, Boolean forceEvaluate, Boolean hideWarningsAndErrors, Boolean restorePC, Boolean cleanupAssetsForUnsupportedProjects, ILogger log, CancellationToken cancellationToken)
at NuGet.Build.Tasks.RestoreTask.ExecuteAsync(ILogger log)
Done executing task "RestoreTask" -- FAILED.
1>Done building target "Restore" in project "MySolution.sln" -- FAILED.
1>Done Building Project "/home/vsts/work/1/s/MySolution/MySolution.sln" (Restore target(s)) -- FAILED.
Build FAILED.
"/home/vsts/work/1/s/MySolution/MySolution.sln" (Restore target) (1) ->
(Restore target) ->
My first thoughts were the same as anyone elses... AH the path must be incorrect! However... I cannot seem to get it to work after trying various different paths to get to the packages folder to pick up my local NuGet package.
To assist, my config files are below.
azure-pipelines.yml:
trigger:
- master
pool:
vmImage: 'ubuntu-latest'
variables:
buildConfiguration: 'Release'
steps:
- task: NuGetToolInstaller#1
displayName: 'Use NuGet 4.9.1'
inputs:
versionSpec: 4.9.1
- task: DotNetCoreCLI#2
displayName: 'Restore NuGet Packages'
inputs:
command: 'restore'
projects: '**/*.sln'
feedsToUse: 'config'
nugetConfigPath: 'MySolution/NuGet.Config'
- task: DotNetCoreCLI#2
displayName: 'Build web project'
inputs:
command: 'build'
projects: $(SolutionPath)
NuGet.Config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
<add key="LocalPackages" value="MySolution/packages" />
</packageSources>
</configuration>
The part in question I have been messing about with is the "LocalPackages" element which is where I thought the issue could be, so have been trying all sorts of combinations of paths to try and narrow it down - but no luck - which has made me think this could be a red herring, but you never know I could be doing something stupid!
I understand there are best practices which can be followed here such as creating my own Artifacts feed of NuGet packages for maintainability, but this is going to be a refinement phase later for me, my focus at the moment is just to simply get the pipeline in a build state ready for deployment and testing.
Any help or guidance on this or things I can try to fix this would be greatly appreciated!
Let me know if more specific info is needed and I can provide!
Thank you.

It is the local packages path that causes the problem. You should set the value as <add key="LocalPackages" value="../s/MySolution/packages" />
If you check the dotnet restore task log, you will find a temp config was created, And the restore task was using this temp config file. See below.
So the LocalPackages path you specified in nuget.config file is relative to the temp config folder /home/vsts/work/1/Nuget.
Since your project is cloned in folder /home/vsts/work/1/s (ie. $(system.defaultworkingdirectory)). You should specify the LocalPackages path like below:
<add key="LocalPackages" value="../s/MySolution/packages" />

Related

ASP.NET Core 6 MVC - The view 'Index' was not found

I can run my asp.net 6 mvc app in VS2022 with no issues. When I publish to a folder and deploy to IIS or run the exe myself I get an error 'the view Index was not found'.
The search locations reported are correct. My views are in the correct folder.
I have also added Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation nuget package and updated Program.cs:
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
The *.cshtml files Build Action are set to Content in Visual Studio.
Nothing suggested in various stackoverlow posts resolves the issue. The majority are related to a VS2022 issue requiring Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation package to be added.
I've set stdoutLogEnabled="true" and verified the log generated when running through IIS matches the log output when calling the .exe. I don't believe this is an IIS issue.
Below is my Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews().AddRazorRuntimeCompilation();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddHttpContextAccessor();
var app = builder.Build();
app.UseExceptionHandler("/Home/Error");
app.UseStatusCodePagesWithReExecute("/Home/Error", "?code={0}");
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Nothing of interest in appsettings.json:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
The project file is as follows:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>MyFirstApp.MVC</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.0.123" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation" Version="6.0.10" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="7.0.2" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.4" />
<PackageReference Include="System.DirectoryServices.AccountManagement" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<Folder Include="wwwroot\images\" />
</ItemGroup>
</Project>
Below is the error log. Logging added to confirm Controller action method is completing with no error:
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
Content root path: D:\Projects\ReportViewer
**info: ReportViewer.MVC.Controllers.HomeController[0]
Into Index**
**info: ReportViewer.MVC.Controllers.HomeController[0]
About to return view Index**
fail: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[3]
The view 'Index' was not found. Searched locations: /Views/Home/Index.cshtml, /Views/Shared/Index.cshtml
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml
at Microsoft.AspNetCore.Mvc.ViewEngines.ViewEngineResult.EnsureSuccessful(IEnumerable`1 originalLocations)
at Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor.ExecuteAsync(ActionContext context, ViewResult result)
at Microsoft.AspNetCore.Mvc.ViewResult.ExecuteResultAsync(ActionContext context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|30_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
fail: Microsoft.AspNetCore.Mvc.ViewFeatures.ViewResultExecutor[3]
The view 'Error' was not found. Searched locations: /Views/Home/Error.cshtml, /Views/Shared/Error.cshtml
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[3]
An exception was thrown attempting to execute the error handler.
System.InvalidOperationException: The view 'Error' was not found. The following locations were searched:
/Views/Home/Error.cshtml
/Views/Shared/Error.cshtml
I'd really appreciate any suggestions you may have.
Thanks,
Lance
Turns out the publish step in VS was failing to resolve some MVC Analyser dlls. Despite this, it was still reporting the publish succeeded and generated the dlls and exe files.
Only spotted the publishing issue after scrolling through the publish output log for any clues.
Publishing problem was caused by having two versions of .NET6 installed on the dev machine. I removed the older version and updated dotnet environment variables to point to dotnet6 located in C:\Program Files....that broke the Dependency Frameworks in the MVP Project. The Path and Version entries were blank for Microsoft.AspnetCore.App and Microsoft.NETCore.App.
Under time pressure so created a new MVC project, copied all files across to this new project, published and deployed to IIS with no issues.

ElasticSearch with NEST in Kubernetes

I'm learning Kubernetes and trying to deploy ElasticSearch & Kibana. And in ElasticSearch v8. https is a default.
https://www.elastic.co/guide/en/elasticsearch/client/net-api/7.17/connecting-to-elasticsearch-v8.html
I tried to Index a document like this
var settings = new ConnectionSettings(new Uri("https://localhost:9200"))
.BasicAuthentication("elastic", "0fjaNokbmHSeS4kXeFV")
.DefaultIndex("people")
.RequestTimeout(TimeSpan.FromSeconds(300));
var client = new ElasticClient(settings);
var person = new Person
{
Id = 1,
FirstName = "Abc",
LastName = "Abc"
};
var indexResponse = client.IndexDocument(person);
if (!indexResponse.IsValid)
{
var debugInfo = indexResponse.DebugInformation;
var error = indexResponse.OriginalException;
}
But it does not work. Even I can browse https://localhost:9200 with this credentials elastic/0fjaNokbmHSeS4kXeFV
I tried to add https for my ingress and call the service to IndexDocument but it also did not work.
Has anyone faced this issue and could you please help me to make this run?
The exception throwed from NEST
Invalid NEST response built from a unsuccessful () low level call on PUT: /platforms/_doc/1
Audit trail of this API call:
1 ProductCheckOnStartup: Took: 00:00:00.0501715
[2] ProductCheckFailure: Node: https://localhost:9200/ Took: 00:00:00.0484845
OriginalException: Elasticsearch.Net.ElasticsearchClientException: The client is unable to verify that the server is Elasticsearch due to an unsuccessful product check call. Some functionality may not be compatible if the server is running an unsupported product. Call: Status code unknown from: GET /
---> Elasticsearch.Net.PipelineException: The client is unable to verify that the server is Elasticsearch due to an unsuccessful product check call. Some functionality may not be compatible if the server is running an unsupported product.
---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure: RemoteCertificateNameMismatch, RemoteCertificateChainErrors
at System.Net.Security.SslStream.SendAuthResetSignal(ProtocolToken message, ExceptionDispatchInfo exception)
at System.Net.Security.SslStream.ForceAuthenticationAsync[TIOAdapter](TIOAdapter adapter, Boolean receiveFirst, Byte[] reAuthenticationData, Boolean isApm)
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Boolean async, Stream stream, SslClientAuthenticationOptions sslOptions, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.ConnectAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.CreateHttp11ConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.GetHttpConnectionAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.RedirectHandler.SendAsync(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.DiagnosticsHandler.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.SendAsyncCore(HttpRequestMessage request, HttpCompletionOption completionOption, Boolean async, Boolean emitTelemetryStartStop, CancellationToken cancellationToken)
at Elasticsearch.Net.HttpConnection.RequestAsync[TResponse](RequestData requestData, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Elasticsearch.Net.RequestPipeline.ThrowIfTransientProductCheckFailure()
at Elasticsearch.Net.RequestPipeline.PingAsync(Node node, CancellationToken cancellationToken)
at Elasticsearch.Net.Transport1.PingAsync(IRequestPipeline pipeline, Node node, CancellationToken cancellationToken) at Elasticsearch.Net.Transport1.RequestAsync[TResponse](HttpMethod method, String path, CancellationToken cancellationToken, PostData data, IRequestParameters requestParameters)
--- End of inner exception stack trace ---
Request:
<Request stream not captured or already read to completion by serializer. Set DisableDirectStreaming() on ConnectionSettings to force it to be set on the response.>
Response:
<Response stream not captured or already read to completion by serializer. Set DisableDirectStreaming() on ConnectionSettings to force it to be set on the response.>
Thanks & best regards,

Active Directory Interactive authentication in ASP.NET Core Razor Pages Web App not working when deployed to Azure App Service

I have a web-app that is used to interact with an azure SQL database. It is working as intended, however when I change from using an SQL user/pass in the connection string to using Active Directory Interactive, I get an error when the web-app should be prompting to log in.
Please note this only occurs when the app is published as an Azure App Service, locally it works as intended.
I'm inexperienced so I'm having a hard time making sense of the error.
Below is my connection string.
"Connection1": "Server=xxx.database.windows.net; Initial Catalog=xxx; Authentication=Active Directory Interactive;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
And this is the error I receive when the user uses the connection string when loading a new page in development mode.
I'm honestly pretty overwhelmed with this. It seems like some sort of machine configuration issue and I don't know where to start.
Any advice appreciated! Stack below:
System.AggregateException: One or more errors occurred. (One or more errors occurred. (An HttpListenerException occurred while listening on http://localhost:56718/ for the system browser to complete the login. Possible cause and mitigation: the app is unable to listen on the specified URL; run 'netsh http add iplisten 127.0.0.1' from the Admin command prompt.))
---> System.AggregateException: One or more errors occurred. (An HttpListenerException occurred while listening on http://localhost:56718/ for the system browser to complete the login. Possible cause and mitigation: the app is unable to listen on the specified URL; run 'netsh http add iplisten 127.0.0.1' from the Admin command prompt.)
---> MSAL.NetCore.4.39.0.0.MsalClientException:
ErrorCode: http_listener_error
Microsoft.Identity.Client.MsalClientException: An HttpListenerException occurred while listening on http://localhost:56718/ for the system browser to complete the login. Possible cause and mitigation: the app is unable to listen on the specified URL; run 'netsh http add iplisten 127.0.0.1' from the Admin command prompt.
---> System.Net.HttpListenerException (5): Access is denied.
at System.Net.HttpListener.SetupV2Config()
at System.Net.HttpListener.Start()
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Platforms.Shared.Desktop.OsBrowser.DefaultOsBrowserWebUi.InterceptAuthorizationUriAsync(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Platforms.Shared.Desktop.OsBrowser.DefaultOsBrowserWebUi.AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, RequestContext requestContext, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceInternalAsync(IWebUI webUi, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceVerifierAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.GetTokenResponseAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenInteractiveParameters interactiveParameters, CancellationToken cancellationToken)
at Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.AcquireTokenInteractiveDeviceFlowAsync(IPublicClientApplication app, String[] scopes, Guid connectionId, String userId, SqlAuthenticationMethod authenticationMethod)
at Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.<>c__DisplayClass17_0.<<AcquireTokenAsync>b__0>d.MoveNext()
Inner Exception: System.Net.HttpListenerException (5): Access is denied.
at System.Net.HttpListener.SetupV2Config()
at System.Net.HttpListener.Start()
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at Microsoft.Data.SqlClient.SqlInternalConnectionTds.<>c__DisplayClass146_1.<GetFedAuthToken>b__1()
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.<>c.<.cctor>b__271_0(Object obj)
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.Tasks.Task.ExecuteWithThreadLocal(Task& currentTaskSlot, Thread threadPoolThread)
--- End of inner exception stack trace ---
at Microsoft.Data.ProviderBase.DbConnectionPool.CheckPoolBlockingPeriod(Exception e)
at Microsoft.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at Microsoft.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection)
at Microsoft.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
at Microsoft.Data.ProviderBase.DbConnectionPool.WaitForPendingOpen()
--- End of stack trace from previous location ---
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenInternalAsync(Boolean errorsExpected, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.InitializeReaderAsync(AsyncEnumerator enumerator, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
at xxx.Pages.xxx.IndexModel.OnGetAsync() in C:\Users\xxx\source\repos\xxx\xxx\Pages\xxx\Index.cshtml.cs:line 37
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.GenericTaskHandlerMethod.Convert[T](Object taskAsObject)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.ExecutorFactory.GenericTaskHandlerMethod.Execute(Object receiver, Object[] arguments)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeHandlerMethodAsync()
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeNextPageFilterAsync()
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Rethrow(PageHandlerExecutedContext context)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure.PageActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.Policy.AuthorizationMiddlewareResultHandler.HandleAsync(RequestDelegate next, HttpContext context, AuthorizationPolicy policy, PolicyAuthorizationResult authorizeResult)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
MSAL.NetCore.4.39.0.0.MsalClientException:
ErrorCode: http_listener_error
Microsoft.Identity.Client.MsalClientException: An HttpListenerException occurred while listening on http://localhost:56718/ for the system browser to complete the login. Possible cause and mitigation: the app is unable to listen on the specified URL; run 'netsh http add iplisten 127.0.0.1' from the Admin command prompt.
---> System.Net.HttpListenerException (5): Access is denied.
at System.Net.HttpListener.SetupV2Config()
at System.Net.HttpListener.Start()
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
--- End of inner exception stack trace ---
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Platforms.Shared.Desktop.OsBrowser.DefaultOsBrowserWebUi.InterceptAuthorizationUriAsync(Uri authorizationUri, Uri redirectUri, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Platforms.Shared.Desktop.OsBrowser.DefaultOsBrowserWebUi.AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, RequestContext requestContext, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceInternalAsync(IWebUI webUi, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.AuthCodeRequestComponent.FetchAuthCodeAndPkceVerifierAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.GetTokenResponseAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.InteractiveRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenInteractiveParameters interactiveParameters, CancellationToken cancellationToken)
at Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.AcquireTokenInteractiveDeviceFlowAsync(IPublicClientApplication app, String[] scopes, Guid connectionId, String userId, SqlAuthenticationMethod authenticationMethod)
at Microsoft.Data.SqlClient.ActiveDirectoryAuthenticationProvider.<>c__DisplayClass17_0.<<AcquireTokenAsync>b__0>d.MoveNext()
Inner Exception: System.Net.HttpListenerException (5): Access is denied.
at System.Net.HttpListener.SetupV2Config()
at System.Net.HttpListener.Start()
at Microsoft.Identity.Client.Platforms.Shared.DefaultOSBrowser.HttpListenerInterceptor.ListenToSingleRequestAndRespondAsync(Int32 port, String path, Func`2 responseProducer, CancellationToken cancellationToken)
I ended up getting things to work. In your appsettings for your deployed connection string set it to
Authentication=Active Directory Managed Identity;User Id='your azure object/principal id'
make sure the userid is the azure object/principal id and not the azure client id
I made a helper so I don't have to set the userId in the connection string directly but it gets picked up as an environment variable when deployed to azure. You can get your connection string from configuration, in my case I have a tenant service to get the connection string since my site is multi tenant
public static SqlConnection Create(ITenantService tenantService, IConfiguration configuration)
{
var tenantConnectionString = tenantService.GetConnectionString();
var connectionStringBuilder = new SqlConnectionStringBuilder(tenantConnectionString);
if (string.IsNullOrEmpty(connectionStringBuilder.UserID))
{
var clientId = configuration.GetValue<string>("AZURE_OBJECT_ID");
if (clientId != null) connectionStringBuilder.UserID = clientId;
}
return new SqlConnection(connectionStringBuilder.ConnectionString);
}
then just use in your startup
optionsBuilder.UseSqlServer(MyUtility.Create(TenantService, Configuration));

Getting error in Visual Studio 2013 xaml designer and Blend (Exception 0x80073CF9)

Suddenly it stopped working. Even with new and blank projects. Visual Studio 2012 still working (at the same machine). Tried to repair and reinstall Visual Studio 2013 - no success. While trying to view xaml code in the designer I getting this error:
System.Exception
Install failed. Please contact your software vendor. (Exception from HRESULT: 0x80073CF9)
at Microsoft.Expression.HostUtility.Platform.AppContainerProcessDomainFactory.CreateDesignerProcess(String applicationPath, String clientPort, Uri hostUri, IDictionary environmentVariables, Int32& processId, Object& processData)
at Microsoft.Expression.DesignHost.Isolation.Primitives.ProcessDomainFactory.ProcessIsolationDomain..ctor(ProcessDomainFactory factory, IIsolationBoundary boundary, AppDomainSetup appDomainInfo, FrameworkName targetFramework, String identifier, String baseDirectory)
at Microsoft.Expression.DesignHost.Isolation.Primitives.ProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)
at Microsoft.Expression.HostUtility.Platform.AppContainerProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)
at Microsoft.Expression.DesignHost.Isolation.Primitives.IsolationBoundary.Initialize()
at Microsoft.Expression.DesignHost.Isolation.Primitives.IsolationBoundary.CreateInstance[T](Type type)
at Microsoft.Expression.DesignHost.Isolation.IsolatedObjectFactory.Initialize()
at Microsoft.VisualStudio.ExpressionHost.Services.VSIsolationService.CreateObjectFactory(IIsolationTarget isolationTarget, IObjectCatalog catalog)
at Microsoft.Expression.DesignHost.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)
at Microsoft.Expression.DesignHost.IsolatedDesignerService.CreateLease(IIsolationTarget isolationTarget, CancellationToken cancelToken, DesignerServiceEntry& entry)
at Microsoft.Expression.DesignHost.IsolatedDesignerService.IsolatedDesignerView.CreateDesignerViewInfo(CancellationToken cancelToken)
at Microsoft.Expression.DesignHost.Isolation.IsolatedTaskScheduler.InvokeWithCulture[T](CultureInfo culture, Func`2 func, CancellationToken cancelToken)
at Microsoft.Expression.DesignHost.Isolation.IsolatedTaskScheduler.<>c__DisplayClassa`1.<StartTask>b__6()
at System.Threading.Tasks.Task`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
Update: Same error code while installing any WIndows Store app.
Modern UI App troubleshooter fixed my problem:

Exception from NinjectMvcHttpApplicationPlugin via Ninject.MVC3 Bootstrapper (in MVC4)

I know there are some questions already on this topic but I am still missing something that is causing this error. I installed ninject.mvc3 package which installs ninject and ninject.web.common packages. No modification was made in global.asax (as suggested in official documentation).
App_Start/NinjectWebCommon.cs's RegisterServices method has the Bind statement after loading the Kernel. I am getting this error with this stack trace when I try to run the site.
[InvalidOperationException: Sequence contains no elements]
System.Linq.Enumerable.Single(IEnumerable`1 source) +379
Ninject.Web.Mvc.NinjectMvcHttpApplicationPlugin.Start() in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectMvcHttpApplicationPlugin.cs:53
Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable`1 series, Action`1 action) in c:\Projects\Ninject\ninject\src\Ninject\Infrastructure\Language\ExtensionsForIEnumerableOfT.cs:32
Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs:53
Ninject.Web.Common.NinjectHttpApplication.Application_Start() in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\NinjectHttpApplication.cs:81
[HttpException (0x80004005): Sequence contains no elements]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +12864673
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +175
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +404
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +475
[HttpException (0x80004005): Sequence contains no elements]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12881540
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12722601
What step am I still missing?
The source says on line 53:
ModelValidatorProviders.Providers.Remove(
ModelValidatorProviders.Providers.OfType<DataAnnotationsModelValidatorProvider>)
.Single());
Have you in some way inhibited the addition of the DataAnnotationsModelValidatorProvider ? Probably not - therefore I suggest you've got two copies of the same logic in your system - do you have >1 NinjectWebCommon.cs ?
Another thing worth trying (in general - I have no specif reason why it should fix this case for you) is see if the same thing still happens when you use the Include Prerelease NuGet packages.