Operation is not valid due to the current state of the object.( SPWebApplication.Update) - wcf

I get this error when trying to add user policy whithin sharepoint 2010 web application programmatically:
Operation is not valid due to the current state of the object.
Here's a code sample:
public Boolean AddUser(SoftwareUser user)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (site = new SPSite(siteUrl))
{
using (web = site.RootWeb)
{
web.AllowUnsafeUpdates = true;
SPUser spUser = web.EnsureUser(user.UserShortname);
web.Groups["MySolution Members"].AddUser(spUser);
if (spUser != null)
{
if (user.Email != null)
{
spUser.Email = user.Email;
}
spUser.Update();
SPWebApplication webApp = site.WebApplication;
SPPolicy policy = webApp.Policies.Add(spUser.Name, "deny");
policy.PolicyRoleBindings.Add(webApp.PolicyRoles["deny"]);
webApp.Update();
}
web.AllowUnsafeUpdates = false;
}
}
});
return true;
}
Thank you in advance.
Find below the stacktrace:
System.InvalidOperationException: Operation is not valid due to the current state of the object.
System.InvalidOperationException: Operation is not valid due to the current state of the object.
at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)
at Microsoft.SharePoint.Utilities.SPUtility.ValidateFormDigest()
at Microsoft.SharePoint.Administration.SPPersistedObject.BaseUpdate()
at Microsoft.SharePoint.Administration.SPWebApplication.Update()
at WcfServices.WFService.<>c__DisplayClass2c.<AddUser>b__2b() in C:\SourceCode\DEV-_V5.2.5\WCFServices\SP2010\WcfServices\WcfServices\WFService.svc.cs:line 980
at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.<RunWithElevatedPrivileges>b__2()
at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param)
at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode)
at WcfServices.WFService.AddUser(SoftwareUser user) in C:\SourceCode\DEV-_V5.2.5\WCFServices\SP2010\WcfServices\WcfServices\WFService.svc.cs:line 959
at SyncInvokeAddUser(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage4(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)

Do NOT call .Update() inside Evelvated Permission’s delegate
Just do it below SPSecurity.RunWithElevatedPrivileges

Related

Handling 'Sequence has no elements' exception dup

I just finished my ASP.NET hospital management app, everything works fine, but if I try to add a doctor I get this error:
System.InvalidOperationException HResult=0x80131509
Message=Sequence contains no elements
Source=Hospital Management System
StackTrace:
at Hospital_Management_System.Controllers.DoctorController.Index(String message) in C:\Users\mouha\OneDrive\Bureau\Hospital Management System\Hospital Management System\Controllers\DoctorController.cs:line 37
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3d()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass46.b__3f()
The code:
public ActionResult Index(string message)
{
var date = DateTime.Now.Date;
ViewBag.Messege = message;
var user = User.Identity.GetUserId();
// The exception is being thrown here
var doctor = db.Doctors.Single(c => c.ApplicationUserId == user);
var model = new CollectionOfAll
{
Ambulances = db.Ambulances.ToList(),
Departments = db.Department.ToList(),
Doctors = db.Doctors.ToList(),
Patients = db.Patients.ToList(),
Medicines = db.Medicines.ToList(),
ActiveAppointments = db.Appointments.Where(c => c.DoctorId == doctor.Id).Where(c => c.Status).Where(c => c.AppointmentDate >= date).ToList(),
PendingAppointments = db.Appointments.Where(c => c.DoctorId == doctor.Id).Where(c => c.Status == false).Where(c => c.AppointmentDate >= date).ToList(),
AmbulanceDrivers = db.AmbulanceDrivers.ToList(),
Announcements = db.Announcements.Where(c => c.AnnouncementFor == "Doctor").ToList()
};
return View(model);
}

IFeatureCollection is disposed Object name: Collection in a Task?

I want to run a Task to save the logs into a database table.
But it seems like that the HttpContext is disposedin the other thread.
Here is my code:
_ = Task.Run(() =>
{
using (var db = LogContext())
{
var request = new LoginLog
{
Url = context.HttpContext.Request.Path,
UserAgent = context.HttpContext?.Request?.Headers?[HeaderNames.UserAgent].ToString()
};
await db.AddAsync(request);
db.SaveChanges();
}
});
Here is the exception trackInfo:
at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.ThrowContextDisposed()
at Microsoft.AspNetCore.Http.Features.FeatureReferences`1.Fetch[TFeature, TState](TFeature & cached, TState state, Func`2 factory)
at Microsoft.AspNetCore.Http.DefaultHttpRequest.get_Path()
at PowerMan.Applet.Api.Infrastructure.Filters.RequestFilter.<> c__DisplayClass4_0.< OnActionExecutionAsync > b__1() in / Users / zhaojing / Projects / PowerMan.Api / PowerMan / PowerMan.Applet / PowerMan.Applet.Api / Infrastructure / Filters / RequestFilter.cs:line 112
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.<> c.<.cctor > b__274_0(Object obj)
at System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(Thread threadPoolThread, ExecutionContext executionContext, ContextCallback callback, Object state)
Is it the Task which make the exceptions?
Most definitely the context is disposed after the request completes.
So you will need to capture the values you will need before starting the background operation:
var url = context.HttpContext.Request.Path;
var userAgent = context.HttpContext?.Request?.Headers?[HeaderNames.UserAgent].ToString();
_ = Task.Run(() =>
{
using (var db =LogContext())
{
var request = new LoginLog
{
Url = url,
UserAgent = userAgent
};
await db.AddAsync(request);
db.SaveChanges();
}
});

How to get a user from an IGraphServiceClient object?

I have a POST method and want to get a user from an IGraphServiceClient object (in the Graph.Microsoft package and namespace).
The GET method works fine. Then I take a user from this list and set them as a parameter for my POST method.
public async Task<Dictionary<string, List<string>>> GetUserGroupsAsync(ICollection<string> userIds)
{
var aggregatedUserGroupMap = new Dictionary<string, List<string>>();
foreach (string userId in userIds)
{
try
{
var userMemberOfCollectionRequest = graphServiceClient.Users[userId].MemberOf.Request();
var userMemberOfCollection = await userMemberOfCollectionRequest.GetAsync().ConfigureAwait(false);
if (!aggregatedUserGroupMap.ContainsKey(userId)) { aggregatedUserGroupMap.Add(userId, new List<string>()); }
foreach (var memberOf in userMemberOfCollection) { aggregatedUserGroupMap[userId].Add(memberOf.Id); }
}
catch (Exception ex)
{
throw ex;
}
}
return aggregatedUserGroupMap;
}
The values in the incoming string collection, userIds, are user email addresses, copied from the GET result.
The value of userMemberOfCollectionRequest looks fine. The RequestUrl property contains "https://graph.microsoft.com:443/v1.0/users/my-email#compagny.com/memberOf". Headers and QueryOptions are empty collections.
In the above method, the following line throws an exception:
var userMemberOfCollection = await userMemberOfCollectionRequest.GetAsync().ConfigureAwait(false);
The exception message reads:
Request_ResourceNotFound
Resource 'my-email#compagny.com' does not exist or one of its queried reference-property objects are not present.
at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
at Microsoft.Graph.UserMemberOfCollectionWithReferencesRequest.GetAsync(CancellationToken cancellationToken)
at xxx.xxx.BusinessComponent.GraphBC.GetUserGroupsAsync(ICollection`1 userIds) in C:\workspace\xxx\xxx.xxx\xxx.xxx.Core\BusinessComponent\GraphBC.cs:line 50
Does anyone have an idea for where I should look to solve this problem?
The solution was not to use the email, instead using the ObjectId property (a GUID instead of an email).

The translation of String.IndexOf to SQL does not support versions with a StringComparison argument occurs

i have build one predicate for filter grid view record filter :
public static IQueryable<T> FilterForColumn<T>(this IQueryable<T> queryable, string colName, string searchText)
{
if (colName != null && searchText != null)
{
var parameter = Expression.Parameter(typeof(T), "m");
var propertyExpression = Expression.Property(parameter, colName);
System.Linq.Expressions.ConstantExpression searchExpression = null;
System.Reflection.MethodInfo containsMethod = null;
// this must be of type Expression to accept different type of expressions
// i.e. BinaryExpression, MethodCallExpression, ...
System.Linq.Expressions.Expression body = null;
Expression ex1 = null;
Expression ex2 = null;
Expression converted = null;
propertyExpression = Expression.Property(parameter, colName);
searchExpression = Expression.Constant(searchText);
containsMethod = typeof(string).GetMethod("IndexOf", new[] { typeof(string), typeof(StringComparison) });
ConstantExpression compareExpression = Expression.Constant(StringComparison.OrdinalIgnoreCase);
ex1 = Expression.Call(propertyExpression, containsMethod, searchExpression, compareExpression);
body = Expression.NotEqual(ex1, Expression.Constant(-1));
var predicate = Expression.Lambda<Func<T, bool>>(body, new[] { parameter });
return queryable.Where(predicate);
}
}
this not working with this queries :
post = db.Posts.Where(p => (p.ToUser_id.Equals(user_id) || p.ToUser_id.Equals(null)) && p.User_id != user_id).OrderByDescending(p => p.Sent_Datetime).Select(p => new
{
Id = p.Id,
Title = p.Title,
Publisher = db.Users.Where(u => u.Id.Equals(p.User_id)).Select(u => u.First_name + ' ' + u.Last_name).FirstOrDefault(),
ToUser = db.Users.Where(u => u.Id.Equals(p.ToUser_id)).Select(u => u.First_name + ' ' + u.Last_name).FirstOrDefault(),
PublishDate = p.Sent_Datetime,
IsFile = p.IsFileAttached,
CategoryName = db.Categories.Where(c => c.Id.Equals(p.Category_id)).Select(c => c.Category_name).FirstOrDefault(),
status_name = db.Status.Where(s => s.Id.Equals(p.status_id)).Select(s => s.status_name).FirstOrDefault(),
Group_name = db.Groups.Where(g => g.Id.Equals(p.group_id)).Select(g => g.Group_name).FirstOrDefault(),
FileSize = p.TotalFileSize
}).FilterForColumn(ColumnName, SearchText).ToList();
i have found this error like :
The translation of String.IndexOf to SQL does not support versions with a StringComparison argument.
what this error saying i don't understand....
Update
as per comment suggested i modify my code :
default:
searchExpression = Expression.Constant(searchText);
containsMethod = typeof(string).GetMethod("SqlMethods.Like", new[] { typeof(string) });
body = Expression.Call(propertyExpression, containsMethod, searchExpression);
break;
but now it's give me error like :
Value cannot be null.
Parameter name: method
Update
i have found new error like :
Server Error in '/CRM' Application.
Static method requires null instance, non-static method requires non-null instance.
Parameter name: instance
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.ArgumentException: Static method requires null instance, non-static method requires non-null instance.
Parameter name: instance
Source Error:
Line 75: searchExpression = Expression.Constant(searchText);
Line 76: containsMethod = typeof(System.Data.Linq.SqlClient.SqlMethods).GetMethod("Like", new[] { typeof(string), typeof(string) });
Line 77: body = Expression.Call(propertyExpression, containsMethod, searchExpression);
Line 78: break;
Line 79: }
Source File: f:\CRM\App_Code\Helper.cs Line: 77
Stack Trace:
[ArgumentException: Static method requires null instance, non-static method requires non-null instance.
Parameter name: instance]
System.Linq.Expressions.Expression.ValidateStaticOrInstanceMethod(Expression instance, MethodInfo method) +4189320
System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, IEnumerable`1 arguments) +55
System.Linq.Expressions.Expression.Call(Expression instance, MethodInfo method, Expression[] arguments) +29
Helper.FilterForColumn(IQueryable`1 queryable, String colName, String searchText) in f:\CRM\App_Code\Helper.cs:77
Staff_Raise_Ticket.FillGrid(String StartAlpha, Int32 GroupByENTYPE, String ColumnName, String SearchText) in f:\CRM\Staff\Raise_Ticket.aspx.cs:625
Staff_Raise_Ticket.btnsearch_Click(Object sender, EventArgs e) in f:\CRM\Staff\Raise_Ticket.aspx.cs:1918
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +176
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1

MonoTouch Parameter Array Length does not match the number of message body parts exception

I am writing a MonoTouch app for iPhone and i am getting the following exception when calling a WCF web service.
Parameter array length does not match the number of message body parts at System.ServiceModel.Dispatcher.WebMessageFormatter+WebClientMessageFormatter.SerializeRequest (System.ServiceModel.Channels.MessageVersion messageVersion, System.Object[] parameters) [0x0003e] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel.Web/System.ServiceModel.Dispatcher/WebMessageFormatter.cs:310
at System.ServiceModel.Description.WebHttpBehavior+ClientPairFormatter.SerializeRequest (System.ServiceModel.Channels.MessageVersion messageVersion, System.Object[] parameters) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel.Web/System.ServiceModel.Description/WebHttpBehavior.cs:142
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.CreateRequest (System.ServiceModel.Dispatcher.ClientOperation op, System.Object[] parameters) [0x0001e] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:611
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.Request (System.ServiceModel.Description.OperationDescription od, System.Object[] parameters) [0x0002d] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:512
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.DoProcess (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters) [0x00038] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:482
at System.ServiceModel.MonoInternal.ClientRuntimeChannel.Process (System.Reflection.MethodBase method, System.String operationName, System.Object[] parameters) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System.ServiceModel/System.ServiceModel/ClientRuntimeChannel.cs:462
I am calling the service with the following methods (Some namespaces have been removed for readability):
public void Begin ()
{
try
{
WebHttpBinding bnd = new WebHttpBinding (WebHttpSecurityMode.Transport);
bnd.MaxBufferSize=2147483647;
bnd.MaxReceivedMessageSize=2147483647;
EndpointAddress addr = new EndpointAddress (new Uri(this.Url));
ServiceClient service = new ServiceClient (bnd, addr);
service.Endpoint.Behaviors.Add(new WebHttpBehavior());
Login login = new Login()
{
InstitutionId=this.InstitutionNumber.ToString ("D4"),
CompanyNumber = (int)this.CompanyId,
Password = this.Password,
UserName = this.Username
};
LoginRequest loginRequest = new LoginRequest{} (GetClientLoginData(), login);
service.LoginCompleted += HandleServiceLoginCompleted;
service.LoginAsync(loginRequest);
}
catch (Exception e)
{
if(failed != null)
{
failed(new ErrorInformation(e));
}
}
}
void HandleServiceLoginCompleted (object sender, LoginCompletedEventArgs e)
{
if(e.Cancelled)
{
if (failed != null)
{
failed (new ErrorInformation ("Request was cancelled"));
}
}
else if(e.Error != null)
{
if (failed != null)
{
failed (new ErrorInformation (e.Error));
}
}
else
{
ServiceClient service = sender as ServiceClient;
LoginResponse response = e.Result;
if (response.LoginResult)
{
if (success != null)
success ();
}
else
{
if (failed != null)
failed (new ErrorInformation (response.errmsg));
}
}
}
When I run this e.Error in HandleServiceLoginCompleted is not null (it is the above exception). I ran wireshark and no packets are sent to the server at all. The service works correctly when called by other means (such as ASP.NET web pages.) I generated the service reference using silverlight's slsvcutil.exe.
Set bnd.ReaderQuotas.MaxArrayLength = int.MaxValue
There are also some other limits that you can increase in ReaderQuotas.