System.NotImplementedException : "The method or operation is not implemented." FoolProofValidation - asp.net-mvc-4

In my MVC4 application I'm using MVC FoolProof library
In my Metadata class I have
public class R_DealsMetaData
{
public int ID { get; set; }
public int UserId { get; set; }
public bool CodeGenerated { get; set; }
[Required(ErrorMessage="Please Enter Description")]
[Display(Name="Promotion Name:")]
public string Description { get; set; }
[Required(ErrorMessage = "Please select one Option")]
[Display(Name = "Deal Buy:")]
public int Buy { get; set; }
[Required(ErrorMessage = "Please select one Option")]
[Display(Name = "Deal Free:")]
public int Free { get; set; }
public Nullable<bool> Status { get; set; }
public string Type { get; set; }
[DataType(DataType.Date)]
public System.DateTime CreateDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")]
[Required(ErrorMessage = "Please select Expiry Date")]
[Display(Name = "Promotion Expiry Date:")]
public System.DateTime ExpiryDate { get; set; }
[RequiredIf("Type", "P", ErrorMessage = "Please select")]
public Nullable<int> PointEarnType { get; set; }
[RequiredIf("PointEarnType", 2, ErrorMessage = "Please enter value")]
public string PointEarnMealText { get; set; }
[RequiredIf("Type","V",ErrorMessage="Please enter")]
public string VolumeBuyText { get; set; }
[RequiredIf("Type","V",ErrorMessage="Please enter")]
public string VolumeEarnText { get; set; }
}
But at my controller post method an exception has been thrown on db.SaveChanges
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(R_Deals r_deals)
{
if (ModelState.IsValid)
{
db.R_Deals.Add(r_deals);
db.SaveChanges();
}
}
Following are the details of exception
An unexpected exception was thrown during validation of 'PointEarnType' when invoking Foolproof.RequiredIfAttribute.IsValid. See the inner exception for details.
Stack Trace Details
[NotImplementedException: The method or operation is not implemented.]
Foolproof.ModelAwareValidationAttribute.IsValid(Object value) +59
System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(Object value, ValidationContext validationContext) +115
System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(Object value, ValidationContext validationContext) +29
System.Data.Entity.Internal.Validation.ValidationAttributeValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) +198
[DbUnexpectedValidationException: An unexpected exception was thrown during validation of 'PointEarnType' when invoking Foolproof.RequiredIfAttribute.IsValid. See the inner exception for details.]
System.Data.Entity.Internal.Validation.ValidationAttributeValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) +299
System.Data.Entity.Internal.Validation.PropertyValidator.Validate(EntityValidationContext entityValidationContext, InternalMemberEntry property) +148
System.Data.Entity.Internal.Validation.EntityValidator.ValidateProperties(EntityValidationContext entityValidationContext, InternalPropertyEntry parentProperty, List`1 validationErrors) +203
System.Data.Entity.Internal.Validation.TypeValidator.Validate(EntityValidationContext entityValidationContext, InternalPropertyEntry property) +105
System.Data.Entity.Internal.Validation.EntityValidator.Validate(EntityValidationContext entityValidationContext) +55
System.Data.Entity.Internal.InternalEntityEntry.GetValidationResult(IDictionary`2 items) +299
System.Data.Entity.DbContext.ValidateEntity(DbEntityEntry entityEntry, IDictionary`2 items) +89
System.Data.Entity.DbContext.GetValidationErrors() +289
System.Data.Entity.Internal.InternalContext.SaveChanges() +107
System.Data.Entity.Internal.LazyInternalContext.SaveChanges() +53
System.Data.Entity.DbContext.SaveChanges() +52
MOU.Controllers.RDealsController.Create(R_Deals r_deals) in e:\MVC Projects\MouMvc\Controllers\RDealsController.cs:197
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +434
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +60
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeSynchronousActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +50
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +75
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +125
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +321
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +321
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +321
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +139
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__DisplayClass2a.<BeginInvokeAction>b__20() +68
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) +40
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) +44
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) +39
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) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9690164
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
What should I do in this case? Not getting actually where I am going wrong .
Please Help me! Thanks

Foolproof Validation has problems with EntityFramework.
For more details see this bug report

Related

System.Data.SqlClient.SqlException: Invalid column name 'Faculty_Id'

Controller:
public async Task<ActionResult> Create([Bind(Include = "Id,Terms,Semester,Sections,Course,CreditHourTheory,CreditHourLab,Labinstructor,Faculty,Rooms,Day,Date,TimeStart,TimeEnd")] TimeTable.Models.TimeTable timetable)
{
if (ModelState.IsValid)
{
db.TimeTable.Add(timetable);
await db.SaveChangesAsync();
return RedirectToAction("Create");
}
return View(timetable);
}
In the view i have use the dropdown to get the value from the database and to insert this selected value in the another table in database
#Html.DropDownList("FId", null, String.Empty, new { #class = "form-control input-md cc2", #disabled = "disabled", #required = "" })
Model:
[Table("TimeTable")]
public class TimeTable
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Terms { get; set; }
public string Semester { get; set; }
public int SectionsId { get; set; }
[ForeignKey("SectionsId")]
public Sections Sections { get; set; }
public int CourseId { get; set; }
[ForeignKey("CourseId")]
public Course Course { get; set; }
public string CreditHourTheory { get; set; }
public string CreditHourLab { get; set; }
public int? LabInstructorId { get; set; }
[ForeignKey("LabInstructorId")]
public Faculty Labinstructor { get; set; }
public int FacultyId { get; set; }
[ForeignKey("FacultyId")]
public Faculty Faculty { get; set; }
public int RoomId { get; set; }
[ForeignKey("RoomId")]
public Rooms Rooms { get; set; }
public string Day { get; set; }
public DateTime Date { get; set; }
public TimeSpan TimeStart { get; set; }
public TimeSpan TimeEnd { get; set; }
}
Server Error in '/' Application.
Invalid column name 'Faculty_Id'.
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.Data.SqlClient.SqlException: Invalid column name 'Faculty_Id'.
Source Error:
Line 54: {
Line 55: db.TimeTable.Add(timetable);
Line 56: await db.SaveChangesAsync();
Line 57: return RedirectToAction("Create");
Line 58: }
Source File: c:\Users\NoorMuhammad\Documents\Visual Studio 2013\Projects\TimeTable\TimeTable\Controllers\HomeController.cs Line: 56
Stack Trace:
[SqlException (0x80131904): Invalid column name 'Faculty_Id'.]
System.Data.SqlClient.SqlCommand.b__24(Task1 result) +1792654
System.Threading.Tasks.ContinuationResultTaskFromResultTask2.InnerInvoke() +81
System.Threading.Tasks.Task.Execute() +45
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
System.Data.Entity.Utilities.CultureAwaiter1.GetResult() +123
System.Data.Entity.Core.Mapping.Update.Internal.d__0.MoveNext() +1068
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
System.Data.Entity.Utilities.CultureAwaiter1.GetResult() +71
System.Data.Entity.Core.Mapping.Update.Internal.d__0.MoveNext() +676
[UpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Data.Entity.Core.Mapping.Update.Internal.d__0.MoveNext() +1044
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
System.Data.Entity.Utilities.CultureAwaiter1.GetResult() +66
System.Data.Entity.Core.Objects.d__3d1.MoveNext() +1138
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
System.Data.Entity.Utilities.CultureAwaiter1.GetResult() +66
System.Data.Entity.Core.Objects.<SaveChangesToStoreAsync>d__39.MoveNext() +619
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.ConfiguredTaskAwaiter.GetResult() +24
System.Data.Entity.SqlServer.<ExecuteAsyncImplementation>d__91.MoveNext() +457
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
System.Data.Entity.Utilities.CultureAwaiter1.GetResult() +66
System.Data.Entity.Core.Objects.d__31.MoveNext() +1165
[DbUpdateException: An error occurred while updating the entries. See the inner exception for details.]
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter1.GetResult() +24
TimeTable.Controllers.<Create>d__8.MoveNext() in c:\Users\NoorMuhammad\Documents\Visual Studio 2013\Projects\TimeTable\TimeTable\Controllers\HomeController.cs:56
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.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase1.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__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase1.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.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase1.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.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase1.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.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase1.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.WrappedAsyncVoid1.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
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34274

why it throws an exception when i tried to save a user?

This related to my previous post, even though it was original posted as this post it ran in to another problem to which it was answered. So to avoid complexity i have decided to re-post it with a confirmed single error!
i have the following Create() post method to save a user to mst_users table.
[HttpPost]
public ActionResult Create(CustomerVM custObject)
{
if ( ModelState.IsValid )
{
mst_users user = new mst_users
{
uName=custObject.User,
password=custObject.Password,
dtCreated=DateTime.UtcNow,
isLocked=false
};
db.mst_users.Add(user);
db.SaveChanges();
}
}
}
when the methods executes at db.SaveChanges() it throws the error Object is not set an instance of an object but i have initialzed all required fields for the table but it shows me a field in a view that belongs to another collection but its not part of users table here is the video
here is the user object:
here is the error:
Object reference not set to an instance of an object.
Source of the error
Line 44: </div>
Line 45: <div class="editor-field">
Line 46: #Html.DropDownListFor(model => model.NameTitle, Model.NameTitleColl)
Line 47: #Html.ValidationMessageFor(model => model.NameTitle)
Line 48: </div>
Here is the stack:
[NullReferenceException: Object reference not set to an instance of an object.]
ASP._Page_Views_Customer_Create_cshtml.Execute() in c:\aspmvc4-test\test1\test1\Views\Customer\Create.cshtml:46
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +197
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +96
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +62
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +76
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +259
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +294
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17() +23
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation) +242
System.Web.Mvc.<>c__DisplayClass1c.<InvokeActionResultWithFilters>b__19() +21
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +175
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +89
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() +9651796
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
try to do something like this
mst_users user = new mst_users();
user.uName=custObject.User;
user.password=custObject.Password;
user.dtCreated=DateTime.UtcNow;
user.isLocked=false;
db.mst_users.Add(user);
db.SaveChanges();
the problem was solved, even when i tagged the db table dtUpdated as not null and assigned with getDate() i must send a date from client else throws the above error!

RavenDb JsonIgnore Attribute throws error when generating document key

Im moving out from Guid to string (HiLo) keys which is suggested by RavenDb docs.
Some of my DomainEvents gets fired inside the constructor so the Id should be known before firing the event. When I was using Guid, I'll just create Guid.NewGuid() to generate Id. But for the HiLo provided by RavenDb, what I did was an extension method to generate keys for me and then pass to my Entity constructor as argument.
RavenDb Version: RavenDb.Client 3.0.30000
Note that this is a copy-paste code I found on the internet :)
public static class RavenDbExtensions
{
public static string GenerateIdFor<T>(this IDocumentSession session)
{
// We need the advanced session in order to ensure that the keys are generated in the correct database.
// session.Advanced.DocumentStore.DatabaseCommands is not sufficient.
var advancedSession = session.Advanced as DocumentSession;
if (advancedSession == null)
throw new InvalidOperationException();
// An entity instance is required to generate a key, but we only have a type.
// In our case, the entities don't have public constructors so we must use reflection.
var entity = Activator.CreateInstance(typeof(T), true);
// Generate an ID using the commands and conventions from the current session
return advancedSession.Conventions.GenerateDocumentKey(
advancedSession.DocumentStore.Identifier,
advancedSession.DatabaseCommands,
entity);
}
}
My controller method.
[HttpPost]
[ValidateAntiForgeryToken]
[Route("add", Name = "courses.add")]
public ActionResult Add(AddViewModel model)
{
if (!ModelState.IsValid)
{
model.Categories = DocumentSession.Query<Category>().ToList();
return View(model);
}
string courseId = DocumentSession.GenerateIdFor<Course>();
var course = Course.Create(
courseId,
model.Title,
CourseCode.FromString(model.Code),
StandardDuration.Create(model.Days, model.HoursPerDay),
model.StandardPrice,
model.CategoryId);
DocumentSession.Store(course);
return RedirectToAction("Add");
}
I have this class with JsonIgnore (Raven.Imports.Newtonsoft.Json) attribute
public class StandardDuration : ValueObject
{
private StandardDuration(int days, int hoursPerDay)
{
Days = days;
HoursPerDay = hoursPerDay;
}
public int Days { get; private set; }
public int HoursPerDay { get; private set; }
public static StandardDuration Create(int days, int hoursPerDay)
{
if (days <= 0)
throw new DomainModelException("Days should be atleast one");
if (hoursPerDay <= 0)
throw new DomainModelException("CreditHours should be greater than zero");
return new StandardDuration(days, hoursPerDay);
}
[JsonIgnore]
public int CreditHours
{
get { return HoursPerDay * Days; }
}
protected override IEnumerable<object> GetEqualityComponents()
{
yield return Days;
yield return HoursPerDay;
}
}
which throws an error
Attempt by method 'Raven.Client.Document.DocumentConvention.DefaultTypeTagName(System.Type)' to access method 'Raven.Imports.Newtonsoft.Json.Utilities.TypeExtensions.IsGenericType(System.Type)' failed.
UPDATE
I cant reproduce the error on the code above due to same issue but before showing the page.
But Im facing the same issue even on non JsonIgnore decorated classes.
public class Category : Entity
{
private Category() { }
private Category(Guid id, string name)
{
Id = id;
Name = name;
}
public string Name { get; private set; }
public static Category Create(Guid id, string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new DomainModelException("Category name should not be blank or null.");
return new Category(id, name);
}
}
controller action
[HttpPost]
[Route("add", Name = "course_categories.add")]
public ActionResult Add(string name)
{
if (ModelState.IsValid)
{
var courseCategory = Category.Create(Guid.NewGuid(), name);
DocumentSession.Store(courseCategory);
AddSuccessMessage("Course Category created");
return RedirectToRoute("course_categories.add_page");
}
ModelState.AddModelError("", "An error occurred please try again.");
return View();
}
stack trace:
[MethodAccessException: Attempt by method 'Raven.Client.Document.DocumentConvention.DefaultTypeTagName(System.Type)' to access method 'Raven.Imports.Newtonsoft.Json.Utilities.TypeExtensions.IsGenericType(System.Type)' failed.]
Raven.Client.Document.DocumentConvention.DefaultTypeTagName(Type t) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:264
Raven.Client.Document.DocumentConvention.GetTypeTagName(Type type) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:296
Raven.Client.Document.DocumentConvention.DefaultFindFullDocumentKeyFromNonStringIdentifier(Object id, Type type, Boolean allowNull) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:152
Raven.Client.Document.GenerateEntityIdOnTheClient.GetIdAsString(Object entity, Object value, String& id) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\GenerateEntityIdOnTheClient.cs:49
Raven.Client.Document.GenerateEntityIdOnTheClient.TryGetIdFromInstance(Object entity, String& id) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\GenerateEntityIdOnTheClient.cs:33
Raven.Client.Document.InMemoryDocumentSessionOperations.Store(Object entity) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\InMemoryDocumentSessionOperations.cs:646
Web.Features.CourseCategories.CourseCategoriesController.Add(String name) in E:\Projects\Akademia\Presentation\Web\Features\CourseCategories\CourseCategoriesController.cs:39
lambda_method(Closure , ControllerBase , Object[] ) +104
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9721605
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Invalid object name 'dbo.UserRoles'

I am getting this error: [SqlException (0x80131904): Invalid object name 'dbo.UserRoles'.], but I can't catch where error is. I can retrieve other data from other tables, but not this.
conditions are:
connection string in web.config:
<add name="myStoreConnection" connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|\myStore.mdf';Integrated Security=True" providerName="System.Data.SqlClient" />
context:
public class AdminMyStoreConnection : DbContext
{
public DbSet<UserRole> UserRoles { get; set; }
}
sql script to create database:
CREATE TABLE [dbo].[UserRoles] (
[RoleId] INT IDENTITY (1, 1) NOT NULL,
[RoleName] NVARCHAR (256) NOT NULL,
PRIMARY KEY CLUSTERED ([RoleId] ASC),
UNIQUE NONCLUSTERED ([RoleName] ASC)
);
model:
[Table("UserRoles")]
public class UserRole
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int RoleId { get; set; }
public string RoleName { get; set; }
}
controller with index view:
private UsersContext db = new UsersContext();
public ActionResult Index()
{
return View(db.Customers.ToList());
}
view:
#using myStore.Helpers
#model IEnumerable<myStore.Areas.Administrator.Models.UserRole>
#{
ViewBag.Title = "Roles management";
}
<h2>Roles management</h2>
<div class="admin-container">
<div class="bcontrol">
<i class="icon-plus-sign"></i> Create New Entry
</div>
#{
var grid = new WebGrid(Model, defaultSort: "RoleId", canSort:true, canPage: true, rowsPerPage:20);
}
#grid.GetHtml(
tableStyle: "tadmin",
alternatingRowStyle: "alt",
selectedRowStyle: "selected-row",
columns:
grid.Columns(
grid.Column("RoleId",
header: "ID " + Html.SortDirection(ref grid, "RoleId"),
style: "tadmin-id"),
grid.Column("RoleName",
header: "Role Name " + Html.SortDirection(ref grid, "RoleName"),
format: #<text><a href="#Url.Action("Details", "Roles", new { id = item.RoleId })" >#item.RoleName</a></text>),
grid.Column("Control", style: "tadmin-control", canSort: false,
format:
#<text><i class="icon-edit"></i> Edit
<i class="icon-list"></i> Details
<i class="icon-minus-sign"></i> Delete</text>)
)
)</div>
and error message:
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.Data.SqlClient.SqlException: Invalid object name 'dbo.UserRoles'.
Source Error:
Line 19: public ActionResult Index()
Line 20: {
Line 21: return View(db.UserRoles.ToList());
Line 22: }
Line 23:
and stack trace:
[SqlException (0x80131904): Invalid object name 'dbo.UserRoles'.]
System.Data.SqlClient.SqlConnection.OnError(SqlException exception,
Boolean breakConnection, Action`1 wrapCloseInAction) +1753986
System.Data.SqlClient.SqlInternalConnection.OnError(SqlException
exception, Boolean breakConnection, Action`1 wrapCloseInAction)
+5296058 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject
stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558
System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior,
SqlCommand cmdHandler, SqlDataReader dataStream,
BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject
stateObj, Boolean& dataReady) +1682
System.Data.SqlClient.SqlDataReader.TryConsumeMetaData() +59
System.Data.SqlClient.SqlDataReader.get_MetaData() +90
System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds,
RunBehavior runBehavior, String resetOptionsString) +365
System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean
async, Int32 timeout, Task& task, Boolean asyncWrite) +1379
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method, TaskCompletionSource`1 completion, Int32 timeout, Task& task,
Boolean asyncWrite) +175
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String
method) +53
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method) +134
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior) +41
System.Data.Common.DbCommand.ExecuteReader(CommandBehavior behavior)
+10 System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) +437
[EntityCommandExecutionException: An error occurred while executing
the command definition. See the inner exception for details.]
System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands(EntityCommand
entityCommand, CommandBehavior behavior) +507
System.Data.Objects.Internal.ObjectQueryExecutionPlan.Execute(ObjectContext
context, ObjectParameterCollection parameterValues) +730
System.Data.Objects.ObjectQuery`1.GetResults(Nullable`1
forMergeOption) +131
System.Data.Objects.ObjectQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
+36 System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() +72
System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator() +23
System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator()
+40 System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +369 System.Linq.Enumerable.ToList(IEnumerable`1
source) +58
myStore.Areas.Administrator.Controllers.RolesController.Index() in
d:.projects\trains\myStore\myStore\Areas\Administrator\Controllers\RolesController.cs:21
lambda_method(Closure , ControllerBase , Object[] ) +62
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase
controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext
controllerContext, IDictionary`2 parameters) +211
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary`2
parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.b__41()
+28 System.Web.Mvc.Async.<>c__DisplayClass8`1.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.b__33()
+57 System.Web.Mvc.Async.<>c__DisplayClass4f.b__49()
+223 System.Web.Mvc.Async.<>c__DisplayClass37.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.b__20()
+24 System.Web.Mvc.Async.<>c__DisplayClass25.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.b__18(IAsyncResult
asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.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.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.b__3(IAsyncResult
asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.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()
+9628700 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
The problem was unfortunately very simple - as i have 2 areas - main and administrator and respectively i have 2 types of data connection, i have only 1 connection string in webconfig. after i added second line for admin context and all works
thanks for attention )
so the problem was incomplete (misconfiguration) in webconfig
This usually simply means a configuration issue
perhaps there genuinely is no such table
perhaps the table is there, but isn't the the dbo scheme
perhaps the db is case-sensitive (make sure that both table names are spelled correctly
Source
Your table name in database must be the exactly same with dbSet<> name in dbContext if not rerun the migration. (running update-databse before declaring the dbSets can lead to that problem)
Like below

webapi IPrincipal and authorize

this is about security MVC4 RC and "Install-Package Microsoft.AspNet.WebApi".
I create a custom Identity : System.Security.Principal.IIdentity where i store some valuable string's and int's in the authentication cookie:
[Serializable]
public class SiteIdentity : IIdentity
{
public SiteIdentity(string name, string displayName, int userId, int siteId)
{
this.Name = name;
this.DisplayName = displayName;
this.UserId = userId;
this.SiteId = siteId;
}
public SiteIdentity(string name, UserInfo userInfo)
: this(name, userInfo.DisplayName, userInfo.UserId, userInfo.SiteId)
{
if (userInfo == null) throw new ArgumentNullException("userInfo");
this.AuthenticationType = userInfo.AutheticationType;
this.ClaimsIdentifier = userInfo.ClaimsIdentifier;
}
public SiteIdentity(FormsAuthenticationTicket ticket)
: this(ticket.Name, UserInfo.FromString(ticket.UserData))
{
if (ticket == null) throw new ArgumentNullException("ticket");
}
... not complete but i think you guess.
But first of all the structure of my webapi controller. I have created and extension controller, from where i extend all my webapi controllers:
public class _AuthorizedApiController : ApiController
{
protected readonly Site.Web.Domain.Services.IUserServices _userServices;
public _AuthorizedApiController(Site.Web.Domain.Services.IUserServices userServices)
{
if (userServices == null) throw new ArgumentNullException("userServices");
this._userServices = userServices;
}
protected int CurrentUserId
{
get { return this.User.SiteIdentity().UserId; }
}
private Site.Web.Domain.Models.User currentUser;
public Site.Web.Domain.Models.User CurrentUser
{
get
{
return this.currentUser ??
(this.currentUser = this._userServices.GetUserFromIdentity(this.User.SiteIdentity()));
}
}
protected int CurrentSiteId
{
get { return this.User.SiteIdentity().SiteId; }
}
}
so my webapi controller is:
public class ServicioController : _AuthorizedApiController
{
//http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
//http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling
static readonly IServicioStatusRepository repositoryServicioStatus =
new ServicioStatusRepository(new Site.Web.Data.DatabaseFactory());
public ServicioController(Site.Web.Domain.Services.IUserServices userServices)
: base(userServices)
{
}
public IEnumerable<ServicioStatusA> GetServiciosStatus()
{
IEnumerable<ServicioStatusA> coleccion;
var estevalor = CurrentUser.SiteId;
}
As you can see i use IoC but the issue is that when i try to read CurrentUser.SiteId. I get this error:
Unable to cast object of type 'System.Web.Security.FormsIdentity' to type 'Site.Web.Models.SiteIdentity'.
in this return function:
public static Site.Web.Models.SiteIdentity SiteIdentity(this System.Security.Principal.IPrincipal principal)
{
return (Site.Web.Models.SiteIdentity)principal.Identity;
}
I use this "artifact" in global.asax.cs to keep session and information:
public override void Init()
{
this.PostAuthenticateRequest += this.PostAuthenticateRequestHandler;
// this.EndRequest += this.EndRequestHandler;
base.Init();
}
private void PostAuthenticateRequestHandler(object sender, EventArgs e)
{
if (IsWebApiRequest())
{
string esto = "popopopopo";
}
HttpCookie authCookie = this.Context.Request.Cookies[FormsAuthentication.FormsCookieName];
if (IsValidAuthCookie(authCookie))
{
// var formsAuthentication = ServiceLocator.Current.GetInstance<IFormsAuthentication>();
var formsAuthentication = new FormsAuthenticationService();
var ticket = formsAuthentication.Decrypt(authCookie.Value);
var siteIdentity = new SiteIdentity(ticket);
this.Context.User = new GenericPrincipal(siteIdentity, null);
// Reset cookie for a sliding expiration.
formsAuthentication.SetAuthCookie(this.Context, ticket);
}
}
and what i guess is that when there is a "normal" MVC call every works fine but when there is a webapi call i can recover everything from the cookie but i´ve got:
System.Security.Principal.GenericPrincipal
+ Identity: Site.Web.Model.SiteIdentity
instead of :
System.Security.Principal.GenericPrincipal
+ Identity: System.web.security.FormsIdentity
Thank you in advance for your support
ADEN-UM:
googling i try to keep the Identity in the thread also, so inside PostAuthenticateRequestHandler i type:
System.Threading.Thread.CurrentPrincipal = this.Context.User;
but now i have for all request the following error in any request not only webapi:
[SerializationException: Type is not resolved for member 'Site.Web.Models.SiteIdentity,Site.Web, Version=1.0.0.0, Culture=neutral,PublicKeyToken=null'.]
Microsoft.VisualStudio.WebHost.Connection.get_RemoteIP() +0
Microsoft.VisualStudio.WebHost.Request.GetRemoteAddress() +65
System.Web.HttpRequest.get_IsLocal() +23
System.Web.Configuration.CustomErrorsSection.CustomErrorsEnabled(HttpRequest request) +86
System.Web.HttpContextWrapper.get_IsCustomErrorEnabled() +45
System.Web.Mvc.HandleErrorAttribute.OnException(ExceptionContext filterContext) +72
System.Web.Mvc.ControllerActionInvoker.InvokeExceptionFilters(ControllerContext controllerContext, IList`1 filters, Exception exception) +115
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +105
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +45
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +61
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +49
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__4(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +25
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8970061
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184