ASP.NET MVC 5 : no IUserTokenProvider is registered when sending forgot password email - asp.net-mvc-5

I'm trying to send a reset password email, but I keep receiving the error
No IUserTokenProvider is registered
on the line
string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
I think the issue is with Simple Injector and how I'm doing the registration? In ApplicationUserManager I have the line
manager.UserTokenProvider = new DataProtectorTokenProvider<User, long>(dataProtectionProvider.Create("ASP.NET Identity"));
and it's being called, but when I set a breakpoint in the ForgotPassword method, the UserTokenProvider is null.
My account controller looks like this:
private ApplicationUserManager _userManager;
public AccountController(ApplicationUserManager userManager, IUserAuditCommand userAuditCommand, IUserViewModelBuilder builder, IMapper mapper)
{
UserManager = userManager;
_userAuditCommand = userAuditCommand;
_mapper = mapper;
_builder = builder;
_emailClient = new EmailClient();
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
ModelState.AddModelError("", "The user either does not exist or is not confirmed.");
return View();
}
// Send an email with this link
string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here");
return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return View(model);
}
ApplicationUserManager:
public class ApplicationUserManager : UserManager<User, long>
{
public ApplicationUserManager(ApplicationUserStore store) : base(store) { }
private const int PASSWORD_HISTORY_LIMIT = 5;
public override async Task<IdentityResult> ChangePasswordAsync(long userId, string currentPassword, string newPassword)
{
if (await IsPreviousPassword(userId, newPassword))
{
return await Task.FromResult(IdentityResult.Failed("Cannot reuse old password"));
}
var result = await base.ChangePasswordAsync(userId, currentPassword, newPassword);
if (result.Succeeded)
{
var store = Store as ApplicationUserStore;
await store.AddToPreviousPasswordsAsync(await FindByIdAsync(userId), PasswordHasher.HashPassword(newPassword));
}
return result;
}
public override async Task<IdentityResult> ResetPasswordAsync(long userId, string token, string newPassword)
{
if (await IsPreviousPassword(userId, newPassword))
{
return await Task.FromResult(IdentityResult.Failed("Cannot reuse old password"));
}
var result = await base.ResetPasswordAsync(userId, token, newPassword);
if (result.Succeeded)
{
var store = Store as ApplicationUserStore;
await store.AddToPreviousPasswordsAsync(await FindByIdAsync(userId), PasswordHasher.HashPassword(newPassword));
}
return result;
}
private async Task<bool> IsPreviousPassword(long userId, string newPassword)
{
var store = Store as ApplicationUserStore;
// List<PreviousPassword> passwords = await store.PreviousPasswords(userId);
var user = await FindByIdAsync(userId);
var query = user.PreviousPasswords.OrderByDescending(x => x.CreateDate).Take(PASSWORD_HISTORY_LIMIT);
query = query.Where(x => PasswordHasher.VerifyHashedPassword(x.Password, newPassword) != PasswordVerificationResult.Failed);
if (query.Any())
{
return true;
}
return false;
}
public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
{
var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<IdentityContext>()));
manager.MaxFailedAccessAttemptsBeforeLockout = 3;
manager.DefaultAccountLockoutTimeSpan = System.TimeSpan.FromMinutes(15);
manager.UserLockoutEnabledByDefault = true;
// Configure validation logic for usernames
manager.UserValidator = new UserValidator<User, long>(manager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = false,
};
// Configure validation logic for passwords
manager.PasswordValidator = new PasswordValidator
{
RequiredLength = 8,
RequireNonLetterOrDigit = false,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug in here.
manager.RegisterTwoFactorProvider(
"PhoneCode",
new PhoneNumberTokenProvider<User, long>
{
MessageFormat = "Your security code is: {0}"
});
manager.RegisterTwoFactorProvider(
"EmailCode",
new EmailTokenProvider<User, long>
{
Subject = "Security Code",
BodyFormat = "Your security code is: {0}"
});
manager.EmailService = new EmailService();
//manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider = new DataProtectorTokenProvider<User, long>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
}
}
SimpleInjectorInitializer:
container.Register<HttpContextBase>(() => new HttpContextWrapper(HttpContext.Current), Lifestyle.Scoped);
container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
container.Register(() => new ApplicationUserManager(new ApplicationUserStore(container.GetInstance<IdentityContext>())), Lifestyle.Scoped);
Error Message:
No IUserTokenProvider is registered.
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.NotSupportedException: No IUserTokenProvider is registered.
Source Error (Line 274 highlighted):
Line 272: // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
Line 273: // Send an email with this link
Line 274: string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
Line 275: var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
Line 276: await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking here");
Stack Trace:
[NotSupportedException: No IUserTokenProvider is registered.]
Microsoft.AspNet.Identity.<GenerateUserTokenAsync>d__127.MoveNext() +639
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +29
ILETSB.OfficerPortal.UI.Controllers.<ForgotPassword>d__21.MoveNext() in C:\Users\aoldfield\source\repos\ILETSB.OfficerPortal\ILETSB.OfficerPortal.UI\Controllers\AccountController.cs:274
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +102
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +64
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +97
System.Web.Mvc.Async.<>c__DisplayClass8_0.<BeginInvokeAsynchronousActionMethod>b__1(IAsyncResult asyncResult) +17
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.<>c__DisplayClass11_0.<InvokeActionMethodFilterAsynchronouslyRecursive>b__0() +58
System.Web.Mvc.Async.<>c__DisplayClass11_2.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(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__DisplayClass3_6.<BeginInvokeAction>b__4() +35
System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__1(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.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
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) +45
System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
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.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
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.InvokeEndHandler(IAsyncResult ar) +161
System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +128

Related

Secured Asp.net Core2.2 WebAPI with Azure AD Authentication is not working on IIS but working fine on IIS Express using Visual Studio

I created web API using .NET Core 2.2 and authenticate with Azure AD using username and password with:
await app.AcquireTokenByUsernamePassword(scopes, userName, Password).ExecuteAsync();
Using Visual Studio web API authentication code is working fine But When the same API is deployed on IIS we get the below exception for:
await app.AcquireTokenByUsernamePassword(scopes, userName, Password).ExecuteAsync();
authentication method.
InnerException:
The operation was canceled.
Stack Exception: at System.Net.Http.HttpClient.HandleFinishSendAsyncError(Exception e, CancellationTokenSource cts)
at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
at Microsoft.Identity.Client.Http.HttpManager.ExecuteAsync(Uri endpoint, IDictionary`2 headers, HttpContent body, HttpMethod method, ILoggerAdapter logger, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Http.HttpManager.ExecuteWithRetryAsync(Uri endpoint, IDictionary`2 headers, HttpContent body, HttpMethod method, ILoggerAdapter logger, Boolean doNotThrow, Boolean retry, CancellationToken cancellationToken)
at Microsoft.Identity.Client.Http.HttpManager.SendGetAsync(Uri endpoint, IDictionary`2 headers, ILoggerAdapter logger, Boolean retry, CancellationToken cancellationToken)
at Microsoft.Identity.Client.OAuth2.OAuth2Client.ExecuteRequestAsync[T](Uri endPoint, HttpMethod method, RequestContext requestContext, Boolean expectErrorsOn200OK, Boolean addCommonHeaders, Func`2 onBeforePostRequestData)
at Microsoft.Identity.Client.OAuth2.OAuth2Client.DiscoverAadInstanceAsync(Uri endPoint, RequestContext requestContext)
at Microsoft.Identity.Client.Instance.Discovery.NetworkMetadataProvider.SendInstanceDiscoveryRequestAsync(Uri authority, RequestContext requestContext)
at Microsoft.Identity.Client.Instance.Discovery.NetworkMetadataProvider.FetchAllDiscoveryMetadataAsync(Uri authority, RequestContext requestContext)
at Microsoft.Identity.Client.Instance.Discovery.NetworkMetadataProvider.GetMetadataAsync(Uri authority, RequestContext requestContext)
at Microsoft.Identity.Client.Instance.Discovery.InstanceDiscoveryManager.FetchNetworkMetadataOrFallbackAsync(RequestContext requestContext, Uri authorityUri)
at Microsoft.Identity.Client.Instance.Discovery.InstanceDiscoveryManager.GetMetadataEntryAsync(AuthorityInfo authorityInfo, RequestContext requestContext, Boolean forceValidation)
at Microsoft.Identity.Client.Instance.AuthorityManager.RunInstanceDiscoveryAndValidationAsync()
at Microsoft.Identity.Client.Internal.Requests.UsernamePasswordRequest.ExecuteAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenByUsernamePasswordParameters usernamePasswordParameters, CancellationToken cancellationToken)
Authrntication Code:
string clientId = "XXXXXXXXXXXXX";
string tenanat = "XXXXXXXXXXXXXXXXXXXX";
string authority = "https://login.microsoftonline.com/" + tenanat;
string[] scopes = new string[] { "user.read" };
IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.Build();
var securePassword = new SecureString();
foreach (char c in Password.ToCharArray())
securePassword.AppendChar(c);
var result = await app.AcquireTokenByUsernamePassword(scopes, userName, Password)ExecuteAsync();
return result.IdToken;
string clientId = "XXXXXXXXXXXXX";
string tenanat = "XXXXXXXXXXXXXXXXXXXX";
string authority = "https://login.microsoftonline.com/" + tenanat;
string[] scopes = new string[] { "user.read" };
IPublicClientApplication app;
app = PublicClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.Build();
var securePassword = new SecureString();
foreach (char c in Password.ToCharArray())
securePassword.AppendChar(c);
var result = await app.AcquireTokenByUsernamePassword(scopes, userName, Password).ExecuteAsync();
return result.IdToken;

C# Map Reduce failing with "{"Response status code does not indicate success: 403 (Forbidden)."} sometimes 401: credentials required

An unhandled exception of type System.AggregateException occurred in mscorlib.dll
Inner Exception: {"Response status code does not indicate success: 403 (Forbidden)."}
sometime get: {"Response status code does not indicate success: 401 (Credentials required)."}
All the logins are correct.
Hadoop.Connect() connect properly.
Stack trace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean
includeTaskCanceledExceptions) at
System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout,
CancellationToken cancellationToken) at
System.Threading.Tasks.Task.Wait() at
Microsoft.Hadoop.WebClient.WebHCatClient.WebHcatMapReduceStreamingExecutor.Execute(Boolean
throwOnError) at
Microsoft.Hadoop.MapReduce.Execution.Hadoop.StreamingJobExecutorBase.ExecuteCore(Type
mapper, Type reducer, Type combiner, HadoopJobConfiguration config)
at
Microsoft.Hadoop.MapReduce.Execution.Hadoop.StreamingJobExecutorBase.Execute(Type
mapperType, Type reducerType, Type combinerType,
HadoopJobConfiguration config) at
Microsoft.Hadoop.MapReduce.Execution.Hadoop.StreamingJobExecutorBase.Execute[TMapper,TReducer](HadoopJobConfiguration
config) at Pwc.Demo.HDPClient.Program.Main(String[] args) in C:\ASC
Project Info\TalentExchange\Demo
project\Pwc.Demo.HDPClient\Pwc.Demo.HDPClient\Program.cs:line 49 at
System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[]
args) at System.AppDomain.ExecuteAssembly(String assemblyFile,
Evidence assemblySecurity, String[] args) at
Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
preserveSyncCtx) at
System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state) at
System.Threading.ThreadHelper.ThreadStart()
class Program
{
static void Main(string[] args)
{
HadoopJobConfiguration myConfig = new HadoopJobConfiguration();
myConfig.InputPath = "asv://hdsto-something-.net/data/in/reviews.txt";
myConfig.OutputFolder = "asv://hd-something-.blob.core.windows.net/data/out/";
Environment.SetEnvironmentVariable("HADOOP_HOME", #"C:\apps\dist\hadoop-2.7.1.2.3.3.1-25\bin");
Environment.SetEnvironmentVariable("JAVA_HOME", #"C:\Program Files\Java\jre1.8.0_101\bin\javaw.exe");
Uri azureCluster = new Uri("https://somename--Demo.azurehdinsight.net");
string clusterUserName = "***";
string clusterPassword = "****";
// This is the name of the account under which Hadoop will execute jobs.
// Normally this is just "Hadoop".
string hadoopUserName = "Hadoop";
// Azure Storage Information.
string azureStorageAccount = "somestore.blob.core.windows.net";
string azureStorageKey = "***==";
string azureStorageContainer = "**";
bool createContinerIfNotExist = false;
IHadoop myCluster = Hadoop.Connect(azureCluster,
clusterUserName,
hadoopUserName,
clusterPassword,
azureStorageAccount,
azureStorageKey,
azureStorageContainer,
createContinerIfNotExist);
//execute mapreduce job
MapReduceResult jobResult =
myCluster.MapReduceJob.Execute<MySimpleMapper, MySimpleReducer>(myConfig);
int exitCode = jobResult.Info.ExitCode;
string exitStatus = "Failure";
if (exitCode == 0) exitStatus = "Success";
exitStatus = exitCode + " (" + exitStatus + ")";
Console.WriteLine();
Console.Write("Exit Code = " + exitStatus);
Console.Read();
}
}
public class MySimpleMapper : MapperBase
{
public override void Map(string inputLine, MapperContext context)
{
int value = int.Parse(inputLine);
string key = (value % 2 == 0) ? "even" : "odd";
context.EmitKeyValue(key, value.ToString());
}
}
public class MySimpleReducer : ReducerCombinerBase
{
public override void Reduce(string key, IEnumerable<string> values, ReducerCombinerContext context)
{
//initialize counters
int myCount = 0;
int mySum = 0;
//count and sum incoming values
foreach (string value in values)
{
mySum += int.Parse(value);
myCount++;
}
context.EmitKeyValue(key, myCount + "t" + mySum);
}
}
Error snapshot:
Your input path should not be to a specific file, but a directory. That directory should only contain files and not folders.
myConfig.InputPath = "asv://hdsto-something-.net/data/in/";

Handling WCF services in orchard and integration with orchard notification

Here is my case, I wrote a wcf and it is working with orchard perfectly.
I'm going to handle events messages such as warnings and exceptions so I add a ServiceAdapter
and ClientServiceLocator to my project :
ServiceAdapter:
public class ServiceAdapter<TService>
where TService : class, IContract
{
public TResult Execute<TResult>(Func<TService, TResult> command)
where TResult : IDtoResponseEnvelop
{
try
{
var dispatcher = ClientServiceLocator.Instance().CommandDispatcher;
var result = DispatchCommand(() => dispatcher.ExecuteCommand(command));
if (result.Response.HasWarning)
{
ClientServiceLocator.Instance()
.WarningManager
.HandleBusinessWarning(result.Response.BusinessWarnings);
}
if (result.Response.HasException)
{
ClientServiceLocator.Instance()
.ExceptionManager
.HandleBusinessException(result.Response.BusinessException);
}
return result;
}
finally
{
}
}
private static TResult DispatchCommand<TResult>(Func<TResult> dispatcherCommand)
where TResult : IDtoResponseEnvelop
{
var asynchResult = dispatcherCommand.BeginInvoke(null, null);
while (!asynchResult.IsCompleted)
{
}
return dispatcherCommand.EndInvoke(asynchResult);
}
}
ClientServiceLocator:
public class ClientServiceLocator
{
static readonly Object LocatorLock = new object();
private static ClientServiceLocator InternalInstance;
private ClientServiceLocator() { }
public static ClientServiceLocator Instance()
{
if (InternalInstance == null)
{
lock (LocatorLock)
{
// in case of a race scenario ... check again
if (InternalInstance == null)
{
InternalInstance = new ClientServiceLocator();
}
}
}
return InternalInstance;
}
#region IClientServices Members
public IBusinessExceptionManager ExceptionManager { get; set; }
public IBusinessWarningManager WarningManager { get; set; }
public ICommandDispatcher CommandDispatcher { get; set; }
#endregion
}
BusinessExceptionManager:
class BusinessExceptionManager
: IBusinessExceptionManager, IDependency
{
private Localizer T { get; set; }
private readonly INotifier _notifier;
public BusinessExceptionManager(INotifier notifier)
{
_notifier = notifier;
T = NullLocalizer.Instance;
}
public void HandleBusinessException(BusinessExceptionDto exceptionDto)
{
_notifier.Add(NotifyType.Error, T(exceptionDto.Message));
}
}
BusinessWarningManager:
class BusinessWarningManager
: IBusinessWarningManager, IDependency
{
private Localizer T { get; set; }
private readonly INotifier _notifier;
public BusinessWarningManager(INotifier notifier)
{
_notifier = notifier;
T = NullLocalizer.Instance;
}
public void HandleBusinessWarning(IEnumerable<BusinessWarning> warnings)
{
var message = string.Join(Environment.NewLine, warnings.Select(w => w.Message));
_notifier.Add(NotifyType.Warning, T(message));
}
}
Here is the controller:
public class SectorsAdminController : Controller
{
private dynamic Shape { get; set; }
private Localizer T { get; set; }
private readonly INotifier _notifier;
private readonly ISiteService _siteService;
private ServiceAdapter<ISectorService> _sectorServiceAdapter;
public SectorsAdminController(ISiteService siteService, INotifier notifier, IShapeFactory shapeFactory)
{
Shape = shapeFactory;
T = NullLocalizer.Instance;
_notifier = notifier;
_siteService = siteService;
_sectorServiceAdapter = new ServiceAdapter<ISectorService>();
}
public ActionResult Index()
{
var model = Shape.Sectors(Sectors: _sectorServiceAdapter.Execute(s => s.FindAll()).Sectors);
return View((object)model);
}
}
Here is the error:
Oops. Something went wrong ... sorry
An unhandled exception has occurred and the request was terminated. Please refresh the page. If the error persists, go back
Object reference not set to an instance of an object.
System.NullReferenceException: Object reference not set to an instance of an object. Server stack trace: at SAS.Admin.Services.ServiceAdapter1.<>c__DisplayClass31.b__0() at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Object[]& outArgs) at System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage msg, IMessageSink replySink) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message reqMsg, Boolean bProxyCase) at System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed, MessageData& msgData) at System.Func1.EndInvoke(IAsyncResult result) at SAS.Admin.Services.ServiceAdapter1.Execute[TResult](Func2 command) at SAS.Admin.Controllers.SectorsAdminController.Index() at lambda_method(Closure , ControllerBase , Object[] ) 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.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.b__3f() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass48.b__41() at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.<>c__DisplayClass48.b__41()
Why would you use a Poor's Man Singleton? I would start by using ISingletonDependency on your IClientServices members, if that is what you need
Get rid of the horrible ServiceLocator, then add IDependency to your ServiceAdapter.
As matter of fact change everything to let Orchard handle instantiation. I do not see why your ServiceAdapter could not be a simple Service instantiated by your Controller, then each one of your IClientServices created as Providers in your Service.

Using SimpleHoneypot with mvc5

I recently upgraded my project from MVC4 to MVC5 and SimpleHoneyPot.MVC4 found here SimpleHoneypot.MVC4 stopped working.
How can resolve it? What is this error, and why does it happen?
Thanks you in advance, for any help
Exception Details: "Entry point was not found".
Stack Trace:
[EntryPointNotFoundException: Entry point was not found.]
System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType) +20
System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId, Boolean isExplicitValue, String format, IDictionary`2 htmlAttributes) +549
System.Web.Mvc.Html.InputExtensions.TextBox(HtmlHelper htmlHelper, String name, Object value, String format, IDictionary`2 htmlAttributes) +44
SimpleHoneypot.Core.HoneypotWorker.GetHtml(HtmlHelper helper, HttpContextBase httpContext) +83
SimpleHoneypot.Core.Honeypot.GetHtml(HtmlHelper helper) +73
SimpleHoneypot.HtmlHelpers.HoneypotHelper.HoneypotInput(HtmlHelper helper) +5
ASP._Page_Views_Shared__SetQuestionAnswer_cshtml.Execute() in d:\net\Mvc4App\Project1\Views\Shared\_SetQuestionAnswer.cshtml:45
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +198
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +104
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +90
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, TextWriter writer, ViewEngineCollection viewEngineCollection) +277
System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper htmlHelper, String partialViewName, Object model) +58
ASP._Page_Views_Question_SelectMessagesLinq_cshtml.Execute() in d:\net\Mvc4App\Project1\Views\Question\SelectMessagesLinq.cshtml:85
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +198
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +104
System.Web.WebPages.StartPage.RunPage() +17
System.Web.WebPages.StartPage.ExecutePageHierarchy() +64
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +78
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +235
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +107
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +291
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +13
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +56
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +420
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +52
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +173
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) +36
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +28
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
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) +36
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +54
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +31
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514812
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

ServiceStack response after a successful authentication throws error. what is missing?

I used a restconsole to post:
http://MyApp/auth/credentials
My Custom AuthProvider below:
public class MyAppCredentialsAuthProvider : CredentialsAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService,
string userName, string password)
{
//Add here your custom auth logic (database calls etc)
//Return true if credentials are valid, otherwise false
SetUp();
var userDao = _appHost.Container.Resolve<IUserDao>();
bool isValid = false;
if (string.IsNullOrEmpty(userName))
return false;
if (string.IsNullOrEmpty(password))
return false;
var user = userDao.GetUserByUsername(userName);
if (user == null)
return false;
if (string.IsNullOrEmpty(user.Password))
return false;
if (CheckPassword(password, user.Password))
{
bool isApproved = user.IsApproved;
if (isApproved && user.Status == (short)Status.Active)
{
isValid = true;
user.IsOnLine = true;
user.LastLoginDate = DateTime.Now;
userDao.Update(user);
}
}
return isValid;
}
public override void OnAuthenticated(IServiceBase authService,
IAuthSession session, IOAuthTokens tokens,
Dictionary<string, string> authInfo)
{
try
{
// Authenticate the user.
var userRepo = authService.TryResolve<IUserDao>();
var user = userRepo.GetUserByUsername(session.UserAuthName);
session.LastName = user.Lastname;
session.UserName = user.Username;
session.Email = user.UserEmail;
session.DisplayName = user.Lastname + " " + user.Othernames;
session.IsAuthenticated = true;
//Important: You need to save the session!
SessionExpiry = new TimeSpan(0, 5, 0);
authService.SaveSession(session, SessionExpiry);
}
catch (Exception exc)
{
// log error
}
}
public void SetUp()
{
_appHost = new BasicAppHost().Init();
var container = _appHost.Container;
var dbFactory = new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["MyAppDB"].ConnectionString, SqlServerDialect.Provider);
container.Register<IDbConnectionFactory>(dbFactory);
container.RegisterAutoWiredAs<UserDao, IUserDao>();
}
}
After execution exists public override void OnAuthenticated(...)
I get the error below:
Server Error in '/' Application.
Object reference not set to an instance of an object.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
ServiceStack.WebHost.Endpoints.Support.EndpointHandlerBase.HandleException(IHttpRequest httpReq, IHttpResponse httpRes, String operationName, Exception ex) +206
ServiceStack.WebHost.Endpoints.RestHandler.ProcessRequest(IHttpRequest httpReq, IHttpResponse httpRes, String operationName) +1058
ServiceStack.WebHost.Endpoints.Support.EndpointHandlerBase.ProcessRequest(HttpContext context) +264
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +341
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +69
What params or configuration or step am i missing?
Thanks.

Resources