UserPrincipal.FindByIdentity sometimes failing with DirectoryServicesCOMException: An operations error occurred - asp.net

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

Related

Java.Net.SocketException Error: Socket closed in System.net.Http httpClient, occurs only when sending files larger than 50kbs

I am making a program in xamarin, which uses http requests to get data from an API made in net.core 2.0, but some requests (most of them actually) culminate in the following error:
System.AggregateException: One or more errors occurred. ---> Java.Net.SocketException: Socket closed
at Java.Interop.JniEnvironment+InstanceMethods.CallIntMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x00069] in <286213b9e14c442ba8d8d94cc9dbec8e>:0
at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualInt32Method (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0002a] in <286213b9e14c442ba8d8d94cc9dbec8e>:0
at Java.Net.HttpURLConnection.get_ResponseCode () [0x0000a] in <b781ed64f1d743e7881ac038e0fbdf85>:0
at Xamarin.Android.Net.AndroidClientHandler+<>c__DisplayClass45_0.<DoProcessRequest>b__1 () [0x00000] in <b781ed64f1d743e7881ac038e0fbdf85>:0
at System.Threading.Tasks.Task`1[TResult].InnerInvoke () [0x0000f] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
at System.Threading.Tasks.Task.Execute () [0x00000] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
--- End of stack trace from previous location where exception was thrown ---
at Xamarin.Android.Net.AndroidClientHandler+<DoProcessRequest>d__45.MoveNext () [0x0036c] in <b781ed64f1d743e7881ac038e0fbdf85>:0
--- End of stack trace from previous location where exception was thrown ---
at Xamarin.Android.Net.AndroidClientHandler+<SendAsync>d__40.MoveNext () [0x00230] in <b781ed64f1d743e7881ac038e0fbdf85>:0
--- End of stack trace from previous location where exception was thrown ---
at System.Net.Http.HttpClient+<SendAsyncWorker>d__49.MoveNext () [0x000ca] in <25ebe1083eaf4329b5adfdd5bbb7aa57>:0
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional (System.Boolean includeTaskCanceledExceptions) [0x00011] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
at System.Threading.Tasks.Task`1[TResult].GetResultCore (System.Boolean waitCompletionNotification) [0x0002b] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
at System.Threading.Tasks.Task`1[TResult].get_Result () [0x0000f] in <d4a23bbd2f544c30a48c44dd622ce09f>:0
at FonoApp.Services.DataService.SendImageAsync (System.String token, FonoApp.Model.Imagem imagem) [0x00059] in C:\Projetos Sorri\FonoApp\AppTeste\AppTeste\Services\DataService.cs:154
--- End of inner exception stack trace ---}
This error occurs in this code snippet:
public async Task<String> SendImage(string token, Imagem imagem)
{
string baseAddress = #"http://192.168.0.4:5000/" + VersaoApi + #"/Imagem/";
var json = JsonConvert.SerializeObject(imagem);
var contentString = new StringContent(json, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", token);
try
{
HttpResponseMessage tokenResponse = client.PostAsync(baseAddress, contentString).Result;//Erro ocorre nesta linha
var jsonContent = tokenResponse.Content.ReadAsStringAsync().Result;
return jsonContent;
}
catch (Exception e)
{
return e.InnerException.Message.ToString();
}
}
From what I researched, and discovered from this error, means that the connection is being closed either by the server or by the client, but I can't even know who closes the connection suddenly let alone prevent this / exception error, I don't know if it matters but I am testing the app on an android 4.2-API 17 tablet. Thanks in advance for any guidance on this as I am still learning how to program in C #.
one thing I forgot to say before was that Postman API requests work without problems
I noticed something interesting the error I get only occurs when trying to send images larger than 100 kb by http request, how can I increase the send and receive weight limit on my server?
Firstly, you need to use await instead of Result() to make this method async:
var jsonContent = await tokenResponse.Content.ReadAsStringAsync();
And yes, this exception occurs when internet connection is lost. You can do these things to make your app more usable:
Display a warning message in try-catch block
Check internet connection by using Xamarin.Essentials.Connectivity plugin
Set a timeout for your HttpClient object and catch the TimeoutException to display proper message

Sequence contains no elements error when reading metadata

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

ReadAsMultipartAsync Throws System.ArgumentException

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.

Encountering error 'The Provider encountered an unknown error' while trying WebSecurity.CreateAccount in asp.net webpage

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)

CRM 2011 Dicovery Service FaultException

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.

Resources