I am using Kentor Auth Services and trying to get it to work with Thinktecture Identity Server. I am getting this error when reading the metadata:
Sequence contains no elements
Here is the code that I am using in the Startup.cs file:
var authServicesOptions = new Kentor.AuthServices.Owin.KentorAuthServicesAuthenticationOptions(false)
{
SPOptions = new SPOptions
{
EntityId = new EntityId("https://dev.identity.research.ufl.edu:4432/AuthServices")
},
SignInAsAuthenticationType = signInAsType,
AuthenticationType = "saml2p",
Caption = "SAML2p",
};
authServicesOptions.IdentityProviders.Add(new IdentityProvider(
new EntityId("urn:edu:ufl:dev:00856"),
authServicesOptions.SPOptions)
{
MetadataLocation = "https://dev.identity.research.ufl.edu:4432/EMvc/Metadata.txt",
});
app.UseKentorAuthServicesAuthentication(authServicesOptions);
Also I'm including the error message and part of the stack trace below.
Thanks very much for any help you can provide in how I should troubleshoot this error.
Sincerely,
Cheryl Bearden
[InvalidOperationException: Sequence contains no elements]
System.Linq.Enumerable.Single(IEnumerable1 source) +310
Kentor.AuthServices.IdentityProvider.ReadMetadataIdpDescriptor(ExtendedEntityDescriptor metadata) +108
Kentor.AuthServices.IdentityProvider.ReadMetadata(ExtendedEntityDescriptor metadata) +132
Kentor.AuthServices.IdentityProvider.DoLoadMetadata() +127
Kentor.AuthServices.IdentityProvider.ReloadMetadataIfRequired() +169
Kentor.AuthServices.IdentityProvider.CreateAuthenticateRequest(AuthServicesUrls authServicesUrls) +73
Kentor.AuthServices.WebSso.SignInCommand.InitiateLoginToIdp(IOptions options, IDictionary2 relayData, AuthServicesUrls urls, IdentityProvider idp, Uri returnUrl) +36
Kentor.AuthServices.WebSso.SignInCommand.Run(EntityId idpEntityId, String returnPath, HttpRequestData request, IOptions options, IDictionary`2 relayData) +447
Kentor.AuthServices.Owin.d__1.MoveNext() +781
Related
I encountered a strange issue with Hangfire. I'm getting sometimes (totally randomly) error about Unable to resolve service for type 'AW.Services.Interfaces.ISmsService' while attempting to activate 'AW.Services.Jobs.SendSmsJob'. When I click requeue on dashboard on this failed job it either fails again or finish with success. It happens really randomly and I don't have any idea what is happening.
I have registered my interface in IoC of course like this: services.AddTransient<ISmsService, SmsService>();.
I'm using the following packages versions:
.NET Core 3.1
Hangfire v1.7.9
Hangfire.AspNetCore v1.7.9
Hangfire.Console v1.4.2
Hangfire.PostgreSql v1.6.4.1
My hangfire's configuration in startup.cs is the following:
services.AddHangfire(config =>
{
config.UsePostgreSqlStorage(Configuration["AW_API_DB_CONNECTIONSTRING"]);
config.UseConsole();
});
GlobalConfiguration.Configuration.UseSerializerSettings
(
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
}
);
(...)
app.UseHangfireServer(new BackgroundJobServerOptions
{
WorkerCount = backgroundProcessingWorkersCount
});
app.UseHangfireServer(new BackgroundJobServerOptions
{
WorkerCount = backgroundProcessingWorkersCount,
Queues = new[] { JobQueueTypes.Transactions }
});
app.UseHangfireDashboard("/dashboard", new DashboardOptions
{
Authorization = new[] { new AgriWalletDashboardAuthFilter() },
I
Below I've copied the entire log from hangfire's dashboard:
Unable to resolve service for type 'AW.Services.Interfaces.ISmsService' while attempting to activate 'AW.Services.Jobs.SendSmsJob'. System.InvalidOperationException: Unable to resolve service for type 'AW.Services.Interfaces.ISmsService' while attempting to activate 'AW.Services.Jobs.SendSmsJob'. at
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider
provider) at
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.CreateInstance(IServiceProvider
provider, Type instanceType, Object[] parameters) at
Hangfire.Server.CoreBackgroundJobPerformer.Perform(PerformContext
context)
at Hangfire.Server.BackgroundJobPerformer.<>c__DisplayClass9_0.b__0()
at Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter
filter, PerformingContext preContext, Func1 continuation at
Hangfire.Server.BackgroundJobPerformer.InvokePerformFilter(IServerFilter
filter, PerformingContext preContext, Func1 continuation) at
Hangfire.Server.BackgroundJobPerformer.PerformJobWithFilters(PerformContext
context, IEnumerable`1 filters) at
Hangfire.Server.BackgroundJobPerformer.Perform(PerformContext context)
at Hangfire.Server.Worker.PerformJob(BackgroundProcessContext context,
IStorageConnection connection, String jobId)
Migration from netcore2 to netcore3 may cause issues with Dependency Injection. Please verify the project Program.cs and Startup.cs classes
https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-3.1&tabs=visual-studio
I have tried searching on here and Google for an answer to this but have yet to find one. I am using what I have found to be fairly standard for .NET 4.0 upload to Web API service. Here is the code:
public HttpResponseMessage Post()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
StringBuilder sb = new StringBuilder();
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MyMultipartFormDataStreamProvider(root);
var task = Request.Content.ReadAsMultipartAsync(provider).ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
// This will give me the form field data
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
sb.Append(string.Format("{0}: {1}", key, val));
}
}
// This will give me any file upload data
foreach (MultipartFileData file in provider.FileData)
{
sb.Append(file.Headers.ContentDisposition.FileName);
sb.Append("Server file path: " + file.LocalFileName);
}
return new HttpResponseMessage()
{
Content = new StringContent(sb.ToString())
};
});
return Request.CreateResponse(HttpStatusCode.OK);
}
When I create a very basic form with a input type=file and submit it I am getting an exception thrown for files over about 800Kb. Here is the exception:
System.ArgumentException was unhandled by user code
HResult=-2147024809
Message=Value does not fall within the expected range.
Source=mscorlib
StackTrace:
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHR(Int32 errorCode)
at System.Web.Hosting.IIS7WorkerRequest.GetServerVariableInternal(String name)
at System.Web.Hosting.IIS7WorkerRequest.GetServerVariable(String name)
at System.Web.Hosting.IIS7WorkerRequest.GetRemoteAddress()
at System.Web.HttpWorkerRequest.IsLocal()
at System.Web.Configuration.CustomErrorsSection.CustomErrorsEnabled(HttpRequest request)
at System.Web.HttpContextWrapper.get_IsCustomErrorEnabled()
at System.Web.Http.WebHost.HttpControllerHandler.<>c__DisplayClassa.<ConvertRequest>b__9()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Web.Http.HttpConfiguration.ShouldIncludeErrorDetail(HttpRequestMessage request)
at System.Net.Http.HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage request, HttpStatusCode statusCode, Func`2 errorCreator)
at System.Net.Http.HttpRequestMessageExtensions.CreateErrorResponse(HttpRequestMessage request, HttpStatusCode statusCode, Exception exception)
at aocform.Controllers.ValuesController.<>c__DisplayClass2.<Post>b__1(Task`1 t) in c:\Users\fred_malone\Documents\Visual Studio 2012\Projects\aocform\aocform\Controllers\ValuesController.cs:line 30
at System.Threading.Tasks.ContinuationResultTaskFromResultTask`2.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
InnerException:
I check the App_Data folder and I see part of the file there. This small part is not always the same size either, like maybe it cuts off at a certain size.
I have adjusted both the maxRequestLength and the maxAllowedContentLength to large numbers with no success.
What does this message mean and what should I be looking at to fix it?
Thanks.
We are a team where everyone of us experience this somewhat random error. The error is listed below and appears on the line: UserPrincipal.FindByIdentity(principalContext, windowsPrincipal.Identity.Name);
It works just fine several days/weeks/months, and then one of us get this error.
On our test server, where we do not deploy changes to as frequently as our local machines, it works for many months before we get this error.
If we change the application pool from ApplicationPoolIdentity to NetworkService, that works. However, after switching back to ApplicationPoolIdentity the same error appears.
IISreset does not help.
Rebooting the computer always solves the problem, so the ApplicationPoolIdentity has no problems to authenticate us on a daily basis.
This is the code (somewhat modified) that we use:
var windowsPrincipal = principal as WindowsPrincipal;
if (windowsPrincipal == null)
return null;
try
{
var principalContext = new PrincipalContext(ContextType.Domain);
var userPrincipal = UserPrincipal.FindByIdentity(principalContext, windowsPrincipal.Identity.Name);
if (userPrincipal == null) return null;
return userPrincipal.Surname;
}
Here is the error message:
An operations error occurred.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.DirectoryServices.DirectoryServicesCOMException: An operations error occurred.
Source Error:
var principalContext = new PrincipalContext(ContextType.Domain);
var userPrincipal = UserPrincipal.FindByIdentity(principalContext, windowsPrincipal.Identity.Name);
Stack Trace:
[DirectoryServicesCOMException (0x80072020): An operations error occurred.
]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +628309
System.DirectoryServices.DirectoryEntry.Bind() +44
System.DirectoryServices.DirectoryEntry.get_AdsObject() +42
System.DirectoryServices.PropertyValueCollection.PopulateList() +29
System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName) +63
System.DirectoryServices.PropertyCollection.get_Item(String propertyName) +163
System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInitNoContainer() +521413
System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit() +51
System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() +161
System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx() +42
System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate) +29
System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, String identityValue) +81
If you are not disposing it in a finaly block, you'll eventually run out of resources...
Using (var principalContext = new PrincipalContext(ContextType.Domain))
{
var userPrincipal = UserPrincipal.FindByIdentity(principalContext,
windowsPrincipal.Identity.Name);
if (userPrincipal == null) return null;
return userPrincipal.Surname;
}
should help
I am new to asp.net. I am trying to create a simple login and register webpage with WebMatrix. But I get the following error when I try to create an account:
The Provider encountered an unknown error.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.Security.MembershipCreateUserException: The Provider encountered an unknown error.
Source Error:
Line 32: db.Execute("INSERT INTO UserData (Email,Name) VALUES (#0,#1)", email, username);
Line 33:
Line 34: WebSecurity.CreateAccount(email,password);
Line 35: Response.Redirect("Homepage.cshtml");
Line 36: }
Source File: c:\Users\admin\Documents\My Web Sites\Login\Register.cshtml Line: 34
Stack Trace:
[MembershipCreateUserException: The Provider encountered an unknown error.]
WebMatrix.WebData.SimpleMembershipProvider.CreateAccount(String userName, String password, Boolean requireConfirmationToken) +1312
WebMatrix.WebData.WebSecurity.CreateAccount(String userName, String password, Boolean requireConfirmationToken) +31
ASP._Page_Register_cshtml.Execute() in c:\Users\admin\Documents\My Web Sites\Login\Register.cshtml:34
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +207
System.Web.WebPages.WebPage.ExecutePageHierarchy(IEnumerable`1 executors) +68
System.Web.WebPages.WebPage.ExecutePageHierarchy() +156
System.Web.WebPages.StartPage.RunPage() +19
System.Web.WebPages.StartPage.ExecutePageHierarchy() +65
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.WebPages.WebPageHttpHandler.ProcessRequestInternal(HttpContextBase httpContext) +119
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
Any help is appreciated. Thanks.
I just had the same issue ... I was using
WebSecurity.CreateAccount(model.UserName, model.Password);
and above generated issue ..
then I tried:
WebSecurity.CreateAccountAndUser(model.UserName, model.Password);
and find out that I was missing other required fields of my Users table (UserProfile). Following worked for me:
WebSecurity.CreateAccountAndUser(model.UserName, model.Password, new {RequiredColumn1 = Value1, RequiredColumn2 = Value 2, ...... });
The post is old, but hope this can help others..
Be sure to:
Create the User record first
Invoke WebMatrix to create the User account.
Below is my code which resolved the same issue you're having:
public ActionResult SignUp(SignUpModel model)
{
if (ModelState.IsValid)
{
using (MorphometryContext context = new MorphometryContext())
{
User user = new User
{
Email = model.Email,
FirstName = model.FirstName,
LastName = model.LastName,
Username = model.UserName
};
context.Users.Add(user);
context.SaveChanges();
}
// Attempt to register the user
try
{
WebSecurity.CreateAccount(model.UserName, model.Password);
}
catch (MembershipCreateUserException e)
{
ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
return View();
}
WebSecurity.Login(model.UserName, model.Password);
return RedirectToAction("Index", "Projects");
}
Also, you don't want to Respoonse.Redirect to a .cshtml file. Instead you should return a RedirectToAction and pass in the Action and Controller names.
I've just had this problem - but by your code it might not be the same thing. I was trying to create the membership record before creating the record in my own user table. It has to be the other way round.
So I'd check that your INSERT INTO UserData query was actually working.
In my case; It was because of Culture;
the Membership provider for creating account with CreateUserAndAccount function, first create a user. it is ok for now, and the user successfully added to the Database.
But for creating account, It runs the below query to get userID to create new account for it:
SELECT [userID] from [User] Where (UPPER([userName]) = #0);
Here is where exception thrown because in some culture upper casing the letters is different, for example in turkish, the upper case for 'i' is 'İ'.
I Don't know how to solve this problem for this moment, and I'll try to learn it.
In my case I was creating a user named "admin" and exception throw. I change the user name to "mesut" And it runs successfully.
please make sure if you have a culture specific letters in userName field.(or email in your case), (as soon as I found how to solve it I will post it here)
I have asked the same question at http://social.microsoft.com/Forums/en-US/crmdevelopment/thread/d5d00302-8f7b-4efc-873b-c54b3e29749d but didn't get an answer. So, I will give another try at stackoverflow.
I was running the example code from the crm 2011 training kit.
var creds = new ClientCredentials();
var dsp = new DiscoveryServiceProxy( dinfo, creds);
dsp.Authenticate();
var orgRequest = new RetrieveOrganizationRequest();
var response = dsp.Execute(orgRequest);
var orgResponse = response as RetrieveOrganizationsResponse;
if (orgResponse != null)
comboOrgs.ItemsSource = orgResponse.Details;
At the line of var response = dsp.Execute(orgRequest), I got the FaltException`1, the detailed message is as follows
System.ServiceModel.FaultException`1 was unhandled
Message=organizationName
Source=mscorlib
Action=http://schemas.microsoft.com/xrm/2011/Contracts/Discovery/IDiscoveryService/ExecuteDiscoveryServiceFaultFault
StackTrace:
Server stack trace:
at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.Xrm.Sdk.Discovery.IDiscoveryService.Execute(DiscoveryRequest request)
at Microsoft.Xrm.Sdk.Client.DiscoveryServiceProxy.Execute(DiscoveryRequest request)
I was able to access the Discovery.svc file using browser. So the server url should be correct. Is this an authentication problem?
Is this for Microsoft CRM Online or on-premise? For Online, I know you would want to use something along the lines of what is found in the SDK -
// Connect to the Discovery service.
// The using statement assures that the service proxy will be properly disposed.
using (DiscoveryServiceProxy _serviceProxy = new DiscoveryServiceProxy(serverConfig.DiscoveryUri,
serverConfig.HomeRealmUri,
serverConfig.Credentials,
serverConfig.DeviceCredentials))
{
// You can choose to use the interface instead of the proxy.
IDiscoveryService service = _serviceProxy;
#region RetrieveOrganizations Message
// Retrieve details about all organizations discoverable via the
// Discovery service.
RetrieveOrganizationsRequest orgsRequest =
new RetrieveOrganizationsRequest()
{
AccessType = EndpointAccessType.Default,
Release = OrganizationRelease.Current
};
RetrieveOrganizationsResponse organizations =
(RetrieveOrganizationsResponse)service.Execute(orgsRequest);
}
There are overloads for the DiscoveryServiceProxy class but if you provide some more details on what you are trying to connect to, I think it will narrow it down.