How can I inject IPrincipal using TinyIoC? - asp.net-mvc

This line:
container.Register<IPrincipal>().UsingConstructor(() => HttpContext.Current.User);
throws the following exception:
Cannot register type System.Security.Principal.IPrincipal - abstract
classes or interfaces are not valid implementation types for
SingletonFactory.
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:
Tss.Rhnncp.DietPlanner.Bootstap.TinyIoCRegistrationTypeException:
Cannot register type System.Security.Principal.IPrincipal - abstract
classes or interfaces are not valid implementation types for
SingletonFactory.
Source Error:
Line 2663: throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory");
Line 2664:
Line 2665: if (!IsValidAssignment(registerType, registerImplementation))
Line 2666: throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory");
Line 2667:

I'm not familiar with TinyIoc, but I expect you need something like this:
container.Register<IPrincipal>(() => HttpContext.Current.User);

Related

XNA Shadow mapping - invalid model?

I try to use shadow mapping sample from http://xbox.create.msdn.com/en-US/education/catalog/sample/shadow_mapping_1.
When I try to load my model there is an exception in:
effect.CurrentTechnique = effect.Techniques[techniqueName];
in DrawModel method.
An unhandled exception of type 'System.ArgumentNullException' occurred in Microsoft.Xna.Framework.Graphics.dll
Additional information: This method does not accept null for this parameter.
What can be wrong with my model?
Check that your techniqueName variable isn't null.
I'm betting effect.Techniques[null] throws a System.ArgumentNullException for the same reason Dictionary.Item does.

Why isn't my own Exception derived type recognised by Elmah?

I've just implemented Elmah for logging in my MVC3 app, and of course all is well, except that when I use signalling to log a custom exception, Elmah seems to 'see' the InnerException property of my custom exception, but not the custom exception itself.
When I use the code below to signal the exception, instead of seeing, "CtsDataException: Error" in my error log, as I would expect, I see, "DbEntityValidation: Validation failed for one or more entities.", the inner exception and its message. If I open the log item, I see that my custom exception has correctly been logged, so it looks like the 'exception descriptor' is wrong, not the actual log entry.
What am I doing wrong?
PS, my custom exception is as such:
public class CtsDataException: Exception
{
public CtsDataException(string message, Exception innerException): base(message, innerException)
{
ValidationResults = new List<CtsDbValidationResult>();
var vex = innerException as DbEntityValidationException;
if (vex != null)
{
ValidationResults = vex.EntityValidationErrors.Select(e => new CtsDbValidationResult(e)).ToList();
}
}
public IEnumerable<CtsDbValidationResult> ValidationResults { get; set; }
}
The signalling code looks like this:
protected void HandleDbEntityValidationException(DbEntityValidationException vex, string message)
{
var ctsEx = new CtsDataException(message, vex);
ErrorSignal.FromCurrentContext().Raise(ctsEx);
}
HandleDbEntityValidationException is on my base controller. It is invoked in derived controllers like this:
catch (DbEntityValidationException vx)
{
var msg = string.Format("Error updating employee '{0}'", entity.RefNum);
HandleDbEntityValidationException(vx, msg);
}
I've done some of my own testing and come to the conclusion that it's not ELMAH choosing to report only the InnerException. If you take a look at the details for the error and then click Original ASP.NET error page, you'll see that the original yellow screen that occurred will list the Exception Details as the InnerException and not the primary custom exception thrown. The stack trace further shows the original custom exception that was thrown instead. This is the information ELMAH is using in logging the error.
My testing consisted of creating a CustomException class that did nothing more than inherit from Exception. I then simply called:
throw new CustomException("error!", new NullReferenceException());
... and what got reported was the NullReferenceException with CustomException only appearing in the Stack Trace.
My theory of choice in this scenario is that ELMAH is choosing to display the exception that was thrown rather than the exceptions used to wrap it. If ELMAH had a way to include a message with the log, I think this "wrap in a more descriptive but ultimately irrelevant exception that is never thrown" malarkey could end.
I realize that I'm a few years late to actually answer the original question on time, but for others trying to achieve what I think was the OP's intention, I came across a bit of smartness in the LibLog package for Hangfire (slightly adapted):
var _errorType = Type.GetType("Elmah.Error, Elmah");
dynamic error = Activator.CreateInstance(_errorType, originalException);
error.Message = "Your custom message";
error.Type = "Error"; // Or type of original exception or ...
error.Time = DateTime.Now;
Elmah.ErrorLog.GetDefault(null).Log(error);

F# exception and inner exception property

in F# i can declare a custom exception like so:
exception Foo of string,
which will map the string to the Message property.
how do I declare one that I can later use to raise a caught exception as the inner exception of this one? In other words, how do i do something like (pseudo)
try
...
with e -> raise Foo (message, innerException) where innerException is e?
Thanks!
The simple declaration of exceptions using exception is limited in many ways. If you want to use other features of standard .NET exceptions (i.e. inner exception), then you can declare exception as a class:
open System
type FooException(message:string, innerException:Exception) =
inherit Exception(message, innerException)
You can also provide overloaded constructors, for example if you want to use null as a default value for InnerException.
The exception can be raised as an ordinary .NET exception using raise:
raise (new FooException(message, e))

Object reference not set to an instance of an object.(asp.net mvc)

Object reference not set to an instance of an object.
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.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 733: } Line 734: Line 735: private static bool
mAppDebug =
WebConfigurationManager.AppSettings["AppDebug"].ToLower().Contains("true");
Line 736: public static bool AppDebug Line 737: {
Source File: T:\MyProject\IMI03\Helper\IMISecurity.cs Line: 735
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an
object.] IMI03.Helper.IMIApplication..cctor() in
T:\MyProject\IMI03\Helper\IMISecurity.cs:735
[TypeInitializationException: The type initializer for
'IMI03.Helper.IMIApplication' threw an exception.]
IMI03.Helper.IMIApplication.set_PasswordDay(Int32 value) in
T:\MyProject\IMI03\Helper\IMISecurity.cs:683
IMI03.MvcApplication.Application_Start() in
T:\MyProject\IMI03\Global.asax.cs:52
Couldn't find the erro... what kind of error and how to recitfy it...please??
The "AppDebug" setting likely doesn't exist, so calling ToLower() on it is throwing a NullReferenceException. Make sure you've spelled everything correctly and that the setting is actually there.

EF 4.1 RC - 'System.Data.Entity.IDatabaseInitializer`1[TContext]' violates the constraint of type parameter 'TContext'

I've just updated my project (using NuGet) to Entity Framework 4.1 RC and receives this error msg:
GenericArguments[0],
'Notesnhac.Library.NotesnhacContext',
on
'System.Data.Entity.IDatabaseInitializer`1[TContext]'
violates the constraint of type
parameter 'TContext'.
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.TypeLoadException:
GenericArguments[0],
'Notesnhac.Library.NotesnhacContext',
on
'System.Data.Entity.IDatabaseInitializer`1[TContext]'
violates the constraint of type
parameter 'TContext'.
Source Error:
Line
114: DependencyResolver.SetResolver(new
StructureMapDependencyResolver(container));
Line 115: #endregion Line 116: }
Line 117: } Line 118:}
Source File: C:\projects\Kenny
Projects\Notesnhac\Notesnhac.Site\Global.asax.cs
Line: 116
Stack Trace:
[TypeLoadException:
GenericArguments[0],
'Notesnhac.Library.NotesnhacContext',
on
'System.Data.Entity.IDatabaseInitializer`1[TContext]'
violates the constraint of type
parameter 'TContext'.]
Notesnhac.Site.MvcApplication.Application_Start()
in C:\projects\Kenny
Projects\Notesnhac\Notesnhac.Site\Global.asax.cs:116
Version Information: Microsoft .NET
Framework Version:4.0.30319; ASP.NET
Version:4.0.30319.225
It says the error is on line 116 but I don't think it's where the error is. Here's a snip of the code where it says the error, line #116 is the curly brace right after #endregion:
protected void Application_Start()
{
// Initalizes the database
System.Data.Entity.Database.SetInitializer<NotesnhacContext>(new ContextInitializer());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
AutoMapperConfig.CreateMappings();
ControllerBuilder.Current.DefaultNamespaces.Add("Notesnhac.Site.Controllers");
#region StructureMap IoC
IContainer container = new Container(x =>
{
x.For<IControllerActivator>().Use<StructureMapControllerActivator>();
x.Scan(s =>
{
s.Assembly("Notesnhac.Library");
s.TheCallingAssembly();
s.AddAllTypesOf<IController>().NameBy(type => type.Name.Replace("Controller", "").ToLower());
s.WithDefaultConventions();
});
});
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
#endregion
}
Thanks.
The problem seems to be the line:
System.Data.Entity.Database.SetInitializer<NotesnhacContext>(new ContextInitializer());
The generic parameter TContext is required to be a DbContext subtype. And your strategy must implement IDatabaseInitializer.
You don't show the declaration of NotesnhacContext, but the compiler says that one of these is missing.
You shouldn't need to specify the type parameter at all; it will be inferred from the argument. You can just do:
System.Data.Entity.Database.SetInitializer(new ContextInitializer());
...presuming you first fix the issue with the declaration.

Resources