I'm getting this error in my Azure WebJob. Any idea what may be causing it?
I'm using Ninject to handle DI in my Azure WebJobs console app.
I've already set the Bind statements for all my services. Services call repositories. Do I need to bind repositories as well?
When I run the WebJob, it picks up the message in the queue but fails with the following message. I think this is related to Ninject.
Microsoft.Azure.WebJobs.Host.FunctionInvocationException:
Microsoft.Azure.WebJobs.Host.FunctionInvocationException: Exception
while executing function: Functions.ProcessQueueMessage --->
System.MissingMethodException: No parameterless constructor defined
for this object. at
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean
publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstanceT at
Microsoft.Azure.WebJobs.Host.Executors.DefaultJobActivator.CreateInstanceT
at
Microsoft.Azure.WebJobs.Host.Executors.ActivatorInstanceFactory1.Create()
at
Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker1.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.Azure.WebJobs.Host.Executors.FunctionExecutor.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
Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.d__2c.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__1.MoveNext()
Here's the Program class:
class Program
{
static readonly IKernel Kernel = new StandardKernel();
static JobHostConfiguration config;
static void Main()
{
BootStrapIoc();
var host = new JobHost();
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
private static void BootStrapIoc()
{
Kernel.Load(Assembly.GetExecutingAssembly());
config = new JobHostConfiguration
{
JobActivator = new MyJobActivator(Kernel)
};
}
}
Here's MyJobActivator
public class BrmJobActivator : IJobActivator
{
private readonly IKernel _container;
public MyJobActivator(IKernel container)
{
_container = container;
}
public T CreateInstance<T>()
{
return _container.Get<T>();
}
}
Here's Ninject Bindings:
public class NinjectBindings : Ninject.Modules.NinjectModule
{
public override void Load()
{
Bind<IConfiguration>().ToMethod(ctx => {
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json");
IConfigurationRoot Configuration = builder.Build();
return Configuration;
});
Bind<IAccountsServices>().To<AccountsServices>();
Bind<IBlogServices>().To<BlogServices>();
// Bind<IAccountsRepository>().To<AccountsRepository>();
// Bind<IBlogsRepository>().To<BlogsRepository>();
}
}
According to the error message, "System.MissingMethodException: No parameterless constructor defined for this object", it seems that you miss parameter config for ininitializing JobHost in the main function.
If it is that case, please use the following code in the main function. It works correctly.
JobHost host = new JobHost(config)
While without config parameter to initializing JobHost then I got the same error message.
The following is my detail steps:
In the main function, changed code as following:
IKernel Kernel = new StandardKernel();
Kernel.Load(Assembly.GetExecutingAssembly());
var config = new JobHostConfiguration
{
JobActivator = new MyJobActivator(Kernel)
};
var host = new JobHost(config);
host.RunAndBlock();
I create the demo with your code supplied and change class name BrmJobActivator to MyJobActivator. And in the NinJect Bindings.cs load function just keep following codes:
Bind<IAccountsServices>().To<AccountsServices>();
Bind<IBlogServices>().To<BlogServices>();
Then it works correctly for me.
Related
I try to get an auth token with Azure AD and certificate and a consolo app.
when I try to get the auth token i get the "ObjectC Object reference not set to an instance of an object".
this is the code
string _path = #"path_to_cert_file";
// Load the certificate into an X509Certificate object.
var cert_file = System.IO.File.ReadAllBytes(_path);
X509Certificate2 cert = new X509Certificate2(cert_file);
//byte[] certificateContents = Convert.FromBase64String(_options.Certificate);
//X509Certificate2 certificate = new X509Certificate2(certificateContents);
ClientCertificate = new ClientAssertionCertificate("clint_id", cert);
TokenCache cache = new TokenCache();
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token", false, cache);
AuthenticationResult result = null;
string o365Token = "";
try
{
result = await authContext.AcquireTokenAsync("https://graph.microsoft.com", ClientCertificate);
o365Token = result.AccessToken;
}
catch (Exception ex)
{
throw;
}
when i try to get the token i have the error with this stacktrace
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform.SigningHelper.SignWithCertificate(String message, X509Certificate2 certificate)
at Microsoft.IdentityModel.Clients.ActiveDirectory.ClientAssertionCertificate.Sign(String message)
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.ClientCreds.JsonWebToken.Sign(IClientAssertionCertificate credential, Boolean sendX5c)
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.ClientCreds.ClientKey.AddToParameters(IDictionary`2 parameters)
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.DictionaryRequestParameters..ctor(String resource, ClientKey clientKey)
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.<SendTokenRequestAsync>d__72.MoveNext()
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.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.<CheckAndAcquireTokenUsingBrokerAsync>d__62.MoveNext()
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.ConfiguredTaskAwaitable.ConfiguredTaskAwaiter.GetResult()
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.<RunAsync>d__60.MoveNext()
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.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenForClientCommonAsync>d__37.MoveNext()
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.ConfiguredTaskAwaitable`1.ConfiguredTaskAwaiter.GetResult()
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenAsync>d__61.MoveNext()
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`1.GetResult()
at TestTeams.Program.<GetTokenAsync>d__10.MoveNext() in
I ran into this issue recently as well when trying to read a X509Certificate2 from a file, and use it to create a ClientAssertionCertificate. It turned out to be an issue with the certificate itself. There was no private key in the file, and that was the cause of the "object not set" exception in:
Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Platform.SigningHelper.SignWithCertificate(String message, X509Certificate2 certificate).
When you export the certificate to a file, make sure to include the private key and make it password protected. As Tony Ju mentioned, you need to update the authority as well. Then the following code should work for you:
string _path = #"path_to_cert_file";
string _password = "cert file password";
// Load the certificate into an X509Certificate object.
X509Certificate2 cert = new X509Certificate2(_path, _password);
ClientCertificate = new ClientAssertionCertificate("clint_id", cert);
TokenCache cache = new TokenCache();
AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/{tenant_id}", false, cache);
AuthenticationResult result = null;
string o365Token = "";
try
{
result = await authContext.AcquireTokenAsync("https://graph.microsoft.com", ClientCertificate);
o365Token = result.AccessToken;
}
catch (Exception ex)
{
throw;
}
The authority url is not correct, it should be https://login.microsoftonline.com/{tenant_id}.
AuthenticationContext authContext = new AuthenticationContext({authority url});
You can take a look at this article.
I'd like to use the contract API to change the Inventory ID on items. It seems like I should be able to do this, but I think I'm missing how I send the new InventoryID to the invoked method.
I'm using a web service endpoint with the ChangeID method added. Under the parameters I added a parameter named key and mapped to CD (which is what the field is called in the dialog, and how it's used in a change project order example), but I'm not really clear on how I associate via the mapped object.
I've got this code:
Dim strItemCode As String = "18r1"
Dim TheItem As StockItem = soapClient.Get(New StockItem With {
.InventoryID = New StringSearch With {.Value = strItemCode},
.WarehouseDetails = New StockItemWarehouseDetail() {New StockItemWarehouseDetail With {.ReturnBehavior = ReturnBehavior.All}}})
Dim TheInvokedResult As InvokeResult = soapClient.Invoke(TheItem, New ChangeID With {.key = New StringValue With {.Value = "18r1TJK"}})
It works up to the point that it does in fact load the item, but when I try the invoked result I get an error. The error seems like I might be passing the wrong parameters, which of course would make sense, but the docs have something tantalizingly close to this so I thought I would give it a whirl. Thanks in advance.
System.ServiceModel.FaultException
HResult=0x80131501
Message=System.ArgumentNullException: Value cannot be null.
Parameter name: key
at PX.Api.ContractBased.Soap.WebApiSoapController.Post(ISoapSystemContract systemContract, XmlReader requestReader, String serviceNamespace, String internalNamespace, MethodInfo method, Func`1 serviceFactory, IEdmModel edmModel)
at PX.Api.ContractBased.Soap.WebApiSoapController.<Post>d__8.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at PX.Api.ContractBased.Soap.WebApiSoapController.<Login>d__6.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext()
Source=mscorlib
StackTrace:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at InventoryEditor.ServiceReference1.DefaultSoap.Invoke(Entity entity, Action action)
at InventoryEditor.ServiceReference1.DefaultSoapClient.Invoke(Entity entity, Action action) in C:\Data Files\InventoryEditor\InventoryEditor\InventoryEditor\Connected Services\ServiceReference1\Reference.vb:line 65002
at InventoryEditor.Form1.Button1_Click(Object sender, EventArgs e) in C:\Data Files\InventoryEditor\InventoryEditor\InventoryEditor\Form1.vb:line 24
at System.Windows.Forms.Control.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnClick(EventArgs e)
at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.ButtonBase.WndProc(Message& m)
at System.Windows.Forms.Button.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
at InventoryEditor.My.MyApplication.Main(String[] Args) in :line 81
Well, turns out posting here was the inspiration I needed to find the answer. The trick is to use the "populate" when creating the WSE extension. You can then search for the dialog and it will populate the proper results into the parameters and boom, item code renaming.
Using sustainsys I am trying to setup SAML authentication as well as a backdoor for standard username/password authentication via in app form.
I can log in and out via SAML without any issue.
I can log in via the in app form but when it comes to logging out, while it does log out successfully I get an exception:
[SqlException]: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)
at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData, DbConnectionPool pool, String accessToken, Boolean applyTransientFaultHandling, SqlAuthenticationProviderManager sqlAuthProviderManager)
at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
at System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
at System.Data.SqlClient.SqlConnection.Open()
at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
[HttpException]: Unable to connect to SQL Server database.
at System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString)
at System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install)
at System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString)
at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString)
[HttpException]: Unable to connect to SQL Server database.
at System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString)
at System.Web.DataAccess.SqlConnectionHelper.EnsureDBFile(String connectionString)
at System.Web.DataAccess.SqlConnectionHelper.GetConnection(String connectionString, Boolean revertImpersonation)
at System.Web.Security.SqlRoleProvider.GetRolesForUser(String username)
at WebMatrix.WebData.SimpleRoleProvider.GetRolesForUser(String username)
at System.Web.Security.RolePrincipal.GetRoles()
at System.Web.Security.RoleClaimProvider.<get_Claims>d__4.MoveNext()
at System.Security.Claims.ClaimsIdentity.<get_Claims>d__51.MoveNext()
at System.Security.Claims.ClaimsIdentity.FindFirst(String type)
at System.Security.Claims.ClaimsPrincipal.FindFirst(String type)
at Sustainsys.Saml2.WebSso.LogoutCommand.InitiateLogout(HttpRequestData request, Uri returnUrl, IOptions options, Boolean terminateLocalSession)
at Sustainsys.Saml2.WebSso.LogoutCommand.Run(HttpRequestData request, String returnPath, IOptions options)
at Sustainsys.Saml2.Owin.Saml2AuthenticationHandler.<ApplyResponseGrantAsync>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.Owin.Security.Infrastructure.AuthenticationHandler.<ApplyResponseCoreAsync>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.<ApplyResponseAsync>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.AuthenticationMiddleware`1.<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.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<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.Owin.Security.Infrastructure.AuthenticationMiddleware`1.<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.Owin.Cors.CorsMiddleware.<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.IdentityFactoryMiddleware`2.<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.IdentityFactoryMiddleware`2.<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.IdentityFactoryMiddleware`2.<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.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContextStage.<RunApp>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.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.<DoFinalWork>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar)
at Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar)
at System.Web.HttpApplication.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
The logoff controller looks like:
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Login", "Account");
}
And the middleware is setup like this:
app.CreatePerOwinContext(SystemContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/account/samllogin"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
validateInterval: TimeSpan.FromDays(30),
regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
}
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
app.UseSaml2Authentication(new Saml2AuthenticationOptions(true));
I am using this same controller for logging out both SAML authenticated users, as well as the standard in-app username/password authenticated users.
For the SAML user, the logoff works with no issues.
When logging out non-SAML users it makes its way through all of the middleware, it successfully executes the controller, thus logging out successfully but following this, it spits out this exception.
I'm having some difficulty debugging this but I believe the issue might be occurring in Sustainsys.Saml2.WebSSO.LogOutCommand.InitiateLogout where claims such as SessionIndex are looked up, but of course does not exist as the user didn't authenticate with SAML.
I'm guessing the authentication handler should not even hit this code block if the user isn't SAML authenticated.
Am I missing some configuration to enable non-SAML users alongside SAML users?
The exception is really strange here so I could be way off base with this.
The problem is that a legacy role provider is active and tries to read roles from a database that doesn't exist.
Add these lines to web.config to get rid of it:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="RoleManager" />
</modules>
Thanks MikeSW for the syntax.
Getting the below error when I run the api in IIS Express or console or docker. I'm suspecting it has something to do with the bad visual studio 2017 update to 15.5.4 as I had received this warning: Couldn't uninstall Microsoft.VisualStudio.Debugger.CoreClr.x64
BadImageFormatException: Invalid number of sections in declared in PE header.
Stack Trace
System.Reflection.PortableExecutable.PEHeaders.ReadSectionHeaders(ref PEBinaryReader reader)
System.Reflection.PortableExecutable.PEHeaders..ctor(Stream peStream, int size, bool isLoadedImage)
System.Reflection.PortableExecutable.PEReader..ctor(Stream peStream, PEStreamOptions options, int size)
System.Reflection.PortableExecutable.PEReader..ctor(Stream peStream, PEStreamOptions options)
Microsoft.CodeAnalysis.ModuleMetadata.CreateFromStream(Stream peStream, PEStreamOptions options)
Microsoft.AspNetCore.Mvc.Razor.Compilation.MetadataReferenceFeatureProvider.CreateMetadataReference(string path)
Microsoft.AspNetCore.Mvc.Razor.Compilation.MetadataReferenceFeatureProvider.PopulateFeature(IEnumerable parts, MetadataReferenceFeature feature)
Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager.PopulateFeature(TFeature feature)
Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorReferenceManager.GetCompilationReferences()
System.Threading.LazyInitializer.EnsureInitializedCore(ref T target, ref bool initialized, ref object syncLock, Func valueFactory)
Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorReferenceManager.get_CompilationReferences()
Microsoft.AspNetCore.Mvc.Razor.Internal.LazyMetadataReferenceFeature.get_References()
Microsoft.CodeAnalysis.Razor.CompilationTagHelperFeature.GetDescriptors()
Microsoft.AspNetCore.Razor.Language.DefaultRazorTagHelperBinderPhase.ExecuteCore(RazorCodeDocument codeDocument)
Microsoft.AspNetCore.Razor.Language.RazorEnginePhaseBase.Execute(RazorCodeDocument codeDocument)
Microsoft.AspNetCore.Razor.Language.DefaultRazorEngine.Process(RazorCodeDocument document)
Microsoft.AspNetCore.Razor.Language.RazorTemplateEngine.GenerateCode(RazorCodeDocument codeDocument)
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CompileAndEmit(string relativePath)
Microsoft.AspNetCore.Mvc.Razor.Internal.RazorViewCompiler.CreateCacheEntry(string normalizedPath)
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNetCore.Mvc.Razor.Internal.DefaultRazorPageFactoryProvider.CreateFactory(string relativePath)
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.CreateCacheResult(HashSet expirationTokens, string relativePath, bool isMainPage)
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.OnCacheMiss(ViewLocationExpanderContext expanderContext, ViewLocationCacheKey cacheKey)
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.LocatePageFromViewLocations(ActionContext actionContext, string pageName, bool isMainPage)
Microsoft.AspNetCore.Mvc.Razor.RazorViewEngine.FindView(ActionContext context, string viewName, bool isMainPage)
Microsoft.AspNetCore.Mvc.ViewEngines.CompositeViewEngine.FindView(ActionContext context, string viewName, bool isMainPage)
Microsoft.AspNetCore.Mvc.ViewFeatures.Internal.ViewResultExecutor.FindView(ActionContext actionContext, ViewResult viewResult)
Microsoft.AspNetCore.Mvc.ViewResult+d__26.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__19.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__24.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResultExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__22.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__17.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+d__15.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware+d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware+d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware+d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+d__7.MoveNext()
UPDATE
Inspite of reinstalling VS2017 I'm still seeing the same error. Any help will be truly appreciated. thanks!
I have an issue with EPPLUS linked pictures.
My ExtJs website has a button that calls my Microsoft Azure webapi, and creates and downloads an excel file using EPPLUS. Everything works fine UNTIL I add a excel linked picture to the template I am using. (the template is saved on the Azure app service)
The weird thing is it works fine when the app service is run locally, but when I publish to Azure I get the error.
Here is the error...
System.Runtime.InteropServices.ExternalException (0x80004005): A generic error occurred in GDI+.
at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(MemoryStream stream)
at System.Drawing.ImageConverter.ConvertTo(ITypeDescriptorContext context, CultureInfo culture, Object value, Type destinationType)
at OfficeOpenXml.Drawing.ExcelPicture..ctor(ExcelDrawings drawings, XmlNode node)
at OfficeOpenXml.Drawing.ExcelDrawing.GetDrawing(ExcelDrawings drawings, XmlNode node)
at OfficeOpenXml.Drawing.ExcelDrawings.AddDrawings()
at OfficeOpenXml.Drawing.ExcelDrawings..ctor(ExcelPackage xlPackage, ExcelWorksheet sheet)
at OfficeOpenXml.ExcelWorksheet.Save()
at OfficeOpenXml.ExcelWorkbook.Save()
at OfficeOpenXml.ExcelPackage.GetAsByteArray(Boolean save)
at xxxV003.Models.RepositoryExcel.ExcelSheet(FileInfo xlTemplate, String cName, String calcMethod, String username, Int32 cid)
at xxxV003.Models.RepositoryExcel.CreatePosSheet(String cName, String _calcMethod, String username, Int32 cid, HttpRequestMessage Request)
at lambda_method(Closure , Object , Object[] )
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.<GetExecutor>b__9(Object instance, Object[] methodParameters)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken)
--- 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.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>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 System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>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 System.Web.Http.Filters.AuthorizationFilterAttribute.<ExecuteAuthorizationFilterAsyncCore>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 System.Web.Http.Controllers.AuthenticationFilterResult.<ExecuteAsync>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 System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()