Better Exception Message in Extension Method - c#

We have the the following extension method:
public static class HttpResponseMessageExtensions
{
[DebuggerStepThrough]
public static async Task<T> ToAsync<T>(this HttpResponseMessage response)
{
if (!response.IsSuccessStatusCode)
{
var message = string.Format("There was a problem extracting the content from the response. Status: {0}. Reason: {1}", response.StatusCode, response.ReasonPhrase);
var exception = new Exception(message);
throw exception;
}
var stringContent = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(stringContent);
}
}
This method has serveral issues. The one I'm curious about is the Source Error when debugging an MVC project, we get the extension code itself as the error:
Line 16: var message = string.Format("There was a problem extracting the content from the response. Status: {0}. Reason: {1}", response.StatusCode, response.ReasonPhrase);
Line 17: var exception = new Exception(message);
Line 18: throw exception;
Ideally we'd have this point at the calling method, since this is much more helpful.
The Stack Trace is even less helpful:
[Exception: There was a problem extracting the content from the response. Status: InternalServerError. Reason: Internal Server Error]
Brightree.HomeHealth.Extensions.<ToAsync>d__0`1.MoveNext() in c:\code\CareAnyware\Trunk\HomeHealth\HomeHealth.SDK\Extensions\HttpResponseMessageExtensions.cs:18
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Brightree.HomeHealth.<Login>d__7.MoveNext() in c:\code\CareAnyware\Trunk\HomeHealth\HomeHealth.SDK\Users.cs:44
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Brightree.HomeHealth.Infrastructure.<Authenticate>d__4.MoveNext() in c:\code\CareAnyware\Trunk\HomeHealth\HomeHealth.SDK\Infrastructure\HomeHealthContext.cs:235
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
Brightree.HomeHealth.Web.Controllers.<Login>d__26.MoveNext() in c:\code\CareAnyware\Trunk\HomeHealth\HomeHealth.Web\Controllers\AccountController.cs:66
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129
Is there something we could implement to make to provide more helpful information?

Regarding more helpful information, this could be a good candidate for Caller Information attributes.
public static class HttpResponseMessageExtensions
{
[DebuggerStepThrough]
public static async Task<T> ToAsync<T>(this HttpResponseMessage response, [CallerMemberName] string callerName = null, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLine = -1)
{
if (!response.IsSuccessStatusCode)
{
var message = string.Format("There was a problem extracting the content from the response. Status: {0}. Reason: {1}. Calling method is {2} in {3}:line {4}", response.StatusCode, response.ReasonPhrase, callerName, callerFilePath, callerLine);
var exception = new Exception(message);
throw exception;
}
var stringContent = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<T>(stringContent);
}
}

Related

Server error in logout: contentPath null or empty

I made a web with authentication. When I press the logout button the following error shows, but the logout is correct. I mean, if you reload the page the login form appears and works fine.
Server Error in '/' Application.
Value cannot be null or empty.
Parameter name: contentPath
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: Value cannot be null or empty.
Parameter name: contentPath
Source Error:
[No relevant source lines]
Source File: c:\Users\User\AppData\Local\Temp\Temporary ASP.NET Files\vs\f60d396e\617997\App_Web_hs3arjh1.3.cs Line: 0
Stack Trace:
[ArgumentException: Value cannot be null or empty.
Parameter name: contentPath]
System.Web.Mvc.UrlHelper.GenerateContentUrl(String contentPath, HttpContextBase httpContext) +130
System.Web.Mvc.UrlHelper.Content(String contentPath) +42
ASP._Page_Views_Shared__Layout_cshtml.Execute() in c:\Users\Manuel\AppData\Local\Temp\Temporary ASP.NET Files\vs\f60d396e\617997\App_Web_hs3arjh1.3.cs:0
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +177
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +80
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +113
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer) +26
System.Web.WebPages.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter writer) +210
System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +27
System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, HelperResult content) +31
System.Web.WebPages.WebPageBase.Write(HelperResult result) +32
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +101
System.Web.WebPages.WebPageBase.PopContext() +146
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +120
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +297
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +248
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +27
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +58
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +349
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +69
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +188
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +124
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +27
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +32
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +26
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +24
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +29
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +23
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9742689
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
This is the code to make the logout.
[HttpPost]
public ActionResult Logout()
{
System.Web.Security.FormsAuthentication.SignOut();
Session.Clear();
Session.RemoveAll();
return RedirectToAction("Login", "Login");
}
I tried to make the logout without the session lines but it keeps the session.

Value cannot be null. Parameter name: value, CreateIdentityAsync?

I created a ViewModel(UserModel) that implement IUser<int> (for customizing ASP.NET Identity 2.0)
public class UserModel : IUser<int>
{
public int Id { get; set; }
public string SecurityStamp { get; set; }
[Display(Name = "Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public string FullName { get; set; }
[Display(Name = "Username")]
public string UserName { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "E-Mail")]
public string Email { get; set; }
[Display(Name = "Photo")]
public string PhotoPath { get; set; }
public List<Claim> Claims { get; set; }
[IgnoreMapping]
public List<CommentModel> Comments { get; set; }
}
Everything is well, but GenerateUserIdentityAsync method.
The following code is my GenerateUserIdentityAsync in UserModel:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<UserModel, int> manager)
{
this.SecurityStamp = Guid.NewGuid().ToString();
this.Claims = new List<Claim>();
ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);//Exception : Value cannot be null. Parameter name: value
return userIdentity;
}
An exception has occurred in CreateIdentityAsync method with the following stack trace
ArgumentNullException: Value cannot be null.
Parameter name: value]
System.Security.Claims.Claim..ctor(String type, String value, String valueType, String issuer, String originalIssuer, ClaimsIdentity subject, String propertyKey, String propertyValue) +10798181
System.Security.Claims.Claim..ctor(String type, String value) +34
Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext() +1458
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Smartiz.UI.Models.<GenerateUserIdentityAsync>d__2.MoveNext() in e:\Works\Smartiz\Smartiz.UI\Models\UserModels.cs:215
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Smartiz.UI.Controllers.<SignInAsync>d__58.MoveNext() in e:\Works\Smartiz\Smartiz.UI\Controllers\AccountController.cs:448
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
Smartiz.UI.Controllers.<ExternalLoginCallback>d__3c.MoveNext() in e:\Works\Smartiz\Smartiz.UI\Controllers\AccountController.cs:315
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651188
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Could you please guide me where my wrong is ?
I faced the same issue while upgrading from ASP.NET Identity 1 to ASP.NET Identity 2 and I solved it by putting a random string in the field SecurityStamp.
I found this solution here.
I hope it works for you too.
As Sam mentioned in his comment for the previous answer, my solution to this problem was to make sure that the user I was creating in in the Seed method of the EF Migration had something in the SecurityStamp. Once I did that and did a update-database -force, I was able to log in just fine.
context.Users.AddOrUpdate(u => u.UserName,
new ApplicationUser
{
UserName = "demo",
Email = "demo#demo.com",
EmailConfirmed = true,
PhoneNumberConfirmed = true,
PasswordHash = password,
PhoneNumber = "111-222-3344",
SecurityStamp = Guid.NewGuid().ToString() //THIS IS WHAT I NEEDED
});
If you created your user through some other means, you should be able to fix it by putting a string in the users db column via sql and have the same success.
In a similar way to Kevin, we were also experiencing this issue. It turns out that when seeding the database someone had forgotten to set the UserName property which produced this same error.
I had a more generic issue - some of my claims had Null values in the AspNetUserClaims table after a sql upgrade routine had run.
I solved the issue by setting the ClaimValues to an empty string.
For me it was overriding UserName field, in order to use my own Display attribute. I was using the following in my ApplicationUser class:
[Display(Name = "Whatever")]
public new string UserName { get; set; }
When I remove this, signin works as expected. I have also overriden Email and PhoneNumber but UserName causes the issue.
This problem kicked me around the office for a few hours.
This was the line causing the problem:
result = signinManager.PasswordSignIn(txtthecrmusername.Text, txtthecrmpassword.Text, RememberMe.Checked, shouldLockout:=False)
In the end, I'd added a custom field to AspNetUsers and left it null. In my haste I'd also forgotten to set it to nothing when creating users.
Custom user claims cannot be null but standard claims can.
I have stucked with the SignInManager failing to sign in the newly created user with the same error.
Solution:
I have found out that just assiging a role to the user upon creation solved the issue. Hope it helps somebody else.
await userManager.AddToRoleAsync(user, UserRoles.Basic.ToString());
For others who came here after searching for the cause of "Value cannot be null. Parameter name: value" without "CreateIdentityAsync" error, The problem may be a null value in DataAnnotations like: [Display(Name = "")]
the reason for this error is due to the empty value in on of the validation attributes
[Display(Name = " ")]

Unable to fix 'The object cannot be deleted because it was not found in the ObjectStateManager.' [duplicate]

This question already has answers here:
The object cannot be deleted because it was not found in the ObjectStateManager
(10 answers)
Closed 8 years ago.
I am getting the following error when I try to delete an object from the datase using LINQ.
The object cannot be deleted because it was not found in the ObjectStateManager.
Note: When I try to run the query directly from the database, the object is deleted.
Code where I am getting the error:
public void deleteStorage(CommonLayer.TblNewsStorage storageToDelete)
{
using(DBTicketSystemEntities e = new DBTicketSystemEntities())
{
e.TblNewsStorage.DeleteObject(storageToDelete);
e.SaveChanges();
}
}
Stack Trace:
[InvalidOperationException: The object cannot be deleted because it was not found in the ObjectStateManager.]
System.Data.Objects.ObjectContext.DeleteObject(Object entity, EntitySet expectedEntitySet) +3061568
System.Data.Objects.ObjectSet`1.DeleteObject(TEntity entity) +18
DataLayer.DAStorage.deleteStorage(TblNewsStorage storageToDelete) in C:\Users\Eric\Desktop\Development\Library News\LibraryNews\DataLayer\DAStorage.cs:38
BusinessLayer.Storage.deleteStorage(String id) in C:\Users\Eric\Desktop\Development\Library News\LibraryNews\BusinessLayer\Storage.cs:43
NewsLibrary.Controllers.StorageController.Delete(TblNewsStorage storage) in C:\Users\Eric\Desktop\Development\Library News\LibraryNews\NewsLibrary\Controllers\StorageController.cs:61
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9688704
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Try sending the ID of the object you want to delete then query it inside your context instead of sending the whole object :
public void deleteStorage(int ID)
{
using(DBTicketSystemEntities e = new DBTicketSystemEntities())
{
//Like That
var selectedItem = e.TblNewsStorage.Where( t => t.ID == ID).FirstOrDefault();
e.TblNewsStorage.DeleteObject(selectedItem);
e.SaveChanges();
}
}
try below code:-
e.TblNewsStorage(storageToDelete).State = System.Data.EntityState.Deleted;
e.SaveChanges();
OR
e.TblNewsStorage.Attach(storageToDelete);
e.TblNewsStorage.Remove(storageToDelete);
e.SaveChanges();

ASP.Net Identity Custom Field Losing Value on Create User

So, I have an interesting issue with MVC5, EF6 and ASP.Net Identity. I've added a custom field to the ApplicationUser but when I attempt to create a new user with UserManager.CreateAsync() I get the following error:
The 'IsConfirmed' property on 'ApplicationUser' could not be set to a 'null' value. You must set this property to a non-null value of type 'System.Boolean'.
Note: When debugging user.IsConfirmed is not null has the value false as it should.
The code in question is as follows:
ApplicationUser user = new ApplicationUser()
{
UserName = model.UserName,
Email = model.Email,
ConfirmationToken = confirmationToken,
IsConfirmed = false
};
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
And the definition of AplicationUser:
public class ApplicationUser : IdentityUser
{
public string Email { get; set; }
public string ConfirmationToken { get; set; }
public bool IsConfirmed { get; set; }
}
Finally, the stack trace:
[ConstraintException: The 'IsConfirmed' property on 'ApplicationUser' could not be set to a 'null' value. You must set this property to a non-null value of type 'System.Boolean'. ]
System.Data.Entity.Core.Common.Internal.Materialization.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal) +152
System.Data.Entity.Core.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling(Int32 ordinal, String propertyName, String typeName) +95
lambda_method(Closure , Shaper ) +1007
System.Data.Entity.Core.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly(Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet) +737
lambda_method(Closure , Shaper ) +501
System.Data.Entity.Core.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper) +281
System.Data.Entity.Core.Common.Internal.Materialization.SimpleEnumerator.MoveNext() +105
System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() +52
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +164
System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.<GetElementFunction>b__1(IEnumerable`1 sequence) +83
System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.ExecuteSingle(IEnumerable`1 query, Expression queryRoot) +107
System.Data.Entity.Core.Objects.ELinq.ObjectQueryProvider.System.Linq.IQueryProvider.Execute(Expression expression) +197
System.Data.Entity.Internal.Linq.DbQueryProvider.Execute(Expression expression) +149
System.Linq.Queryable.FirstOrDefault(IQueryable`1 source) +251
Microsoft.AspNet.Identity.EntityFramework.UserStore`1.FindByNameAsync(String userName) +1174
Microsoft.AspNet.Identity.<FindByNameAsync>d__d.MoveNext() +231
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Microsoft.AspNet.Identity.<ValidateUserName>d__0.MoveNext() +832
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
Microsoft.AspNet.Identity.<ValidateAsync>d__4.MoveNext() +433
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext() +629
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Microsoft.AspNet.Identity.<CreateAsync>d__10.MoveNext() +883
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
L33THub.Web.Controllers.<Register>d__d.MoveNext() in c:\Users\rwn\Documents\Visual Studio 2013\Projects\L33THub\L33THub.Web\Controllers\AccountController.cs:121
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +117
System.Web.Mvc.Async.<>c__DisplayClass48.<InvokeActionMethodFilterAsynchronouslyRecursive>b__41() +323
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514812
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Okay, so...a bit embarrassing but the reason this was failing is that I had stored procedures trying to grab the values of null fields because I never cleared out the user store before testing and was using the same usernames. I had taken about a two week break between efforts on this project, but still...oops. :P Thank you to all the patient souls who helped me through this.

Method not found: 'System.Object Newtonsoft.Json.Linq.JToken.ToObject(System.Type)'

Our mvc project with json.net running without any problem on every developer except the one with the new windows 8.1 system. How can we find source of the method not found problem ?
details of the exception ;
[MissingMethodException: Method not found: 'System.Object Newtonsoft.Json.Linq.JToken.ToObject(System.Type)'.]
ExtensionMethods.Eval(Object o, String propertyName) in c:\Users\maxSEPHIROTH\Documents\Visual Studio 2012\Projects\LogiSysMvc\LogiSysMvc\ClassLibrary\ExtensionMethods.cs:136
ASP.<>c__DisplayClass20.<Execute>b__1(CallbackPanelSettings settings) in c:\Users\maxSEPHIROTH\Documents\Visual Studio 2012\Projects\LogiSysMvc\LogiSysMvc\LogiSysMvc\Views\Genel_Personel\GridViewEditFormPartial.cshtml:430
DevExpress.Web.Mvc.UI.ExtensionsFactory.CreateExtension(Action`1 method) +137
DevExpress.Web.Mvc.UI.ExtensionsFactory.CallbackPanel(Action`1 method) +43
ASP._Page_Views_Genel_Personel_GridViewEditFormPartial_cshtml.Execute() in c:\Users\maxSEPHIROTH\Documents\Visual Studio 2012\Projects\LogiSysMvc\LogiSysMvc\LogiSysMvc\Views\Genel_Personel\GridViewEditFormPartial.cshtml:11
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +271
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +121
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +191
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +762
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +74
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +388
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +72
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +303
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +155
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +184
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +66
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +68
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +65
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +45
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +47
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +151
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +66
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.Mvc.<>c__DisplayClassa.<EndProcessRequest>b__9() +44
System.Web.Mvc.<>c__DisplayClass4.<Wrap>b__3() +34
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Func`1 func) +69
System.Web.Mvc.ServerExecuteHttpHandlerWrapper.Wrap(Action action) +123
System.Web.Mvc.ServerExecuteHttpHandlerAsyncWrapper.EndProcessRequest(IAsyncResult result) +133
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride) +1097
You should check Newtonsoft.Json library version on that computer (also in GAC). Non-generic ToObject methods where introduced in November last year, so there is slight chance this causes problem.

Categories

Resources