Getting traceback information from IronPython exceptions - exception

I have IronPython hosted within my application, whenever I catch an exception thrown from a script, I get unhelpful gibberish like this:
IronPython.NewTypes.System.Exception_1$1: Error occurred during conversion ---> Microsoft.Scripting.ArgumentTypeException: expected int, got DispMethod
at _stub_$245##245(Closure , CallSite , Object )
at Microsoft.Scripting.Actions.MatchCaller.Call1[T0,TRet](Func`3 target, CallSite site, Object[] args)
at Microsoft.Scripting.Actions.CallSite`1.UpdateAndExecute(Object[] args)
at Microsoft.Scripting.Actions.UpdateDelegates.Update1[T,T0,TRet](CallSite site, T0 arg0)
at _stub_$227##227(Closure , CallSite , Object )
at IronPython.Runtime.Converter.Convert(Object value, Type to)
at IronPython.Runtime.Operations.ArrayOps.SetItem(Array data, Int32 index, Object value)
at _stub_$244##244(Closure , CallSite , Object , Object , Object )
at Microsoft.Scripting.Actions.MatchCaller.Call3[T0,T1,T2,TRet](Func`5 target, CallSite site, Object[] args)
at Microsoft.Scripting.Actions.CallSite`1.UpdateAndExecute(Object[] args)
at Microsoft.Scripting.Actions.UpdateDelegates.Update3[T,T0,T1,T2,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2)
at ConvertToFgf$223##223(Closure , Object , Object , Object )
at _stub_$192##192(Closure , CallSite , CodeContext , Object , Object , Object , Object )
at Microsoft.Scripting.Actions.MatchCaller.Call5[T0,T1,T2,T3,T4,TRet](Func`7 target, CallSite site, Object[] args)
at Microsoft.Scripting.Actions.CallSite`1.UpdateAndExecute(Object[] args)
at Microsoft.Scripting.Actions.UpdateDelegates.Update5[T,T0,T1,T2,T3,T4,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
at Convert$224##224(Closure , Object , Object )
--- End of inner exception stack trace ---
at Convert$224##224(Closure , Object , Object )
at _stub_$42##42(Closure , CallSite , CodeContext , Object , Object , Object )
at Microsoft.Scripting.Actions.MatchCaller.Call4[T0,T1,T2,T3,TRet](Func`6 target, CallSite site, Object[] args)
at Microsoft.Scripting.Actions.CallSite`1.UpdateAndExecute(Object[] args)
at Microsoft.Scripting.Actions.UpdateDelegates.Update4[T,T0,T1,T2,T3,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3)
at Run$225##225(Closure )
What I would like to get instead is the python traceback. Is there anyway to get this information?

If you just need a text version you can do:
engine.GetService<ExceptionOperations>().FormatException(exception);
If you really need the Python track back object I would suggest:
Func<PythonTuple> exc_info = engine.Operations.GetMember<Func<PythonTuple>>(engine.GetSysModule(), "exc_info");
Save that somewhere useful and then when you need to invoke it:
TraceBack tb = (TraceBack)exc_info()[2];
That'll work as long as you're catching the exception.
A slightly less supported but easier way to do this would be:
TraceBack tb = PythonOps.GetExceptionInfoLocal(context, exception)[2];
But you need a CodeContext to do this. In 2.0 you can get a CodeContext by:
new CodeContext(new PythonDictionary(), HostingHelpers.GetLanguageContext(engine));

Related

Why is caching objects using System.Web.HttpContext.Current.Cache.Insert suddenly causing Ninject to throw OutOfMemory exceptions?

I have a few actions in my .NET MVC application that go through a decent amount of data and return a JSON object to my views. In order to speed things up a little bit, I've started caching the JSON objects and returning those instead of going through all of the data if only a short time has passed:
System.Web.HttpContext.Current.Cache.Insert(System.Web.HttpContext.Current.User.Identity.Name + "WB", result, null, DateTime.UtcNow.AddMinutes(1), TimeSpan.Zero);
// result is the object that gets converted to JSON
result = new
{
TopDepartures = TopDepartures.ToArray(),
YesterdayFlights = YesterdayFlights.Count(),
TodayFlights = TodayFlights.Count(),
TomorrowFlights = TomorrowFlights.Count(),
LastMonthPax = LastMonthPax.ToString("#,##0"),
YesterdayPax = YesterdayPax.ToString("#,##0"),
PaxMonthToDate = PaxMonthToDate.ToString("#,##0"),
FirstCheckInLocalTime = FirstCheckIn.EstimatedCheckIn.ToString("HH:mm"),
FirstCheckInOrigin = FirstCheckIn.OriginIATA,
FirstCheckInDestination = FirstCheckIn.DestinationIATA,
FirstCheckInSDT = FirstCheckIn.ScheduledDepartureTime.ToString("HH:mm"),
FirstCheckInSAT = FirstCheckIn.ScheduledArrivalTime.ToString("HH:mm"),
FirstCheckInFlightNo = FirstCheckIn.CarrierCode + " " + FirstCheckIn.FlightNo,
LastCheckInLocalTime = LastCheckIn.EstimatedCheckIn.ToString("HH:mm"),
LastCheckInOrigin = LastCheckIn.OriginIATA,
LastCheckInDestination = LastCheckIn.DestinationIATA,
LastCheckInSDT = LastCheckIn.ScheduledDepartureTime.ToString("HH:mm"),
LastCheckInSAT = LastCheckIn.ScheduledArrivalTime.ToString("HH:mm"),
LastCheckInFlightNo = LastCheckIn.CarrierCode + " " + LastCheckIn.FlightNo,
TomorrowFirstCheckInLocalTime = TomorrowFirstCheckIn.EstimatedCheckIn.ToString("HH:mm"),
TomorrowFirstCheckInOrigin = TomorrowFirstCheckIn.OriginIATA,
TomorrowFirstCheckInDestination = TomorrowFirstCheckIn.DestinationIATA,
TomorrowFirstCheckInSDT = TomorrowFirstCheckIn.ScheduledDepartureTime.ToString("HH:mm"),
TomorrowFirstCheckInSAT = TomorrowFirstCheckIn.ScheduledArrivalTime.ToString("HH:mm"),
TomorrowFirstCheckInFlightNo = TomorrowFirstCheckIn.CarrierCode + " " + TomorrowFirstCheckIn.FlightNo,
};
I do a check at the beginning of the Action:
var cachedResult = System.Web.HttpContext.Current.Cache.Get(System.Web.HttpContext.Current.User.Identity.Name + "WB");
if (cachedResult != null)
{
return Json(cachedResult, JsonRequestBehavior.AllowGet);
}
The problem is, ever since I implemented this, Ninject has been periodically firing OutOfMemory exceptions. I've been researching this but I haven't been able to find anything explicitly referencing a link between caching and Ninject OutOfMemory exceptions. There also doesn't appear to be a specific pattern that causes the exception to be fired. It will run fine for hours of changes and testing and then suddenly the site will stop working and I'll see the OutOfMemory exception in the logs. Then other times it'll happen immediately.
This Action is called and the object retrieved by an AJAX call on my view, if that information is relevant.
Here is the stack trace:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.Collections.Generic.HashSet`1.SetCapacity(Int32 newSize, Boolean forceNewHashCodes)
at System.Collections.Generic.HashSet`1.IncreaseCapacity()
at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value)
at System.Collections.Generic.HashSet`1.Add(T item)
at Ninject.Activation.Caching.ActivationCache.AddActivatedInstance(Object instance)
at Ninject.Activation.Strategies.ActivationCacheStrategy.Activate(IContext context, InstanceReference reference)
at Ninject.Activation.Pipeline.<>c__DisplayClass2.<Activate>b__0(IActivationStrategy s)
at Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[T](IEnumerable`1 series, Action`1 action)
at Ninject.Activation.Pipeline.Activate(IContext context, InstanceReference reference)
at Ninject.Activation.Context.ResolveInternal(Object scope)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<>c__DisplayClass15.<Resolve>b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectListIterator`2.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__94`1.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
at Ninject.Infrastructure.Language.ExtensionsForIEnumerable.ToArraySlow(IEnumerable series, Type elementType)
at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent)
at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target)
at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
at Ninject.Activation.Context.ResolveInternal(Object scope)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<>c__DisplayClass15.<Resolve>b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
at Ninject.Planning.Targets.Target`1.GetValue(Type service, IContext parent)
at Ninject.Planning.Targets.Target`1.ResolveWithin(IContext parent)
at Ninject.Activation.Providers.StandardProvider.GetValue(IContext context, ITarget target)
at Ninject.Activation.Providers.StandardProvider.<>c__DisplayClass4.<Create>b__2(ITarget target)
at System.Linq.Enumerable.WhereSelectArrayIterator`2.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Ninject.Activation.Providers.StandardProvider.Create(IContext context)
at Ninject.Activation.Context.ResolveInternal(Object scope)
at Ninject.Activation.Context.Resolve()
at Ninject.KernelBase.<>c__DisplayClass15.<Resolve>b__f(IBinding binding)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at Ninject.ResolutionExtensions.Get(IResolutionRoot root, Type service, IParameter[] parameters)
at AirlineChoiceDashboard.WebUI.Infrastructure.NinjectControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in D:\Development\Airline Choice Dashboard\Source Code\Development\WebUI\Infrastructure\NinjectControllerFactory.cs:line 38

Using NancyFX with Razor view engine, how?

I am using the latest NancyFX via nuget and have installed the Razor view engine also via nuget because the SSVE doesn't suit my needs (I need more conditional logic options).
The trouble is that all I can get is a 500 error anytime I call a Razor view:
Nancy.RequestExecutionException: Oh noes! ---> System.NullReferenceException: Object reference not set to an instance of an object.
at Nancy.ViewEngines.DefaultViewCache.GetOrAdd[TCompiledView](ViewLocationResult viewLocationResult, Func`2 valueFactory)
at Nancy.ViewEngines.Razor.RazorViewEngine.GetOrCompileView(ViewLocationResult viewLocationResult, IRenderContext renderContext, Assembly referencingAssembly, Type passedModelType)
at System.Dynamic.UpdateDelegates.UpdateAndExecute5[T0,T1,T2,T3,T4,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
at CallSite.Target(Closure , CallSite , RazorViewEngine , ViewLocationResult , IRenderContext , Assembly , Object )
at Nancy.ViewEngines.Razor.RazorViewEngine.GetViewInstance(ViewLocationResult viewLocationResult, IRenderContext renderContext, Assembly referencingAssembly, Object model)
at System.Dynamic.UpdateDelegates.UpdateAndExecute5[T0,T1,T2,T3,T4,TRet](CallSite site, T0 arg0, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
at Nancy.ViewEngines.Razor.RazorViewEngine.<>c__DisplayClass27.b__26(Stream stream)
at Nancy.Responses.MaterialisingResponse.PreExecute(NancyContext context)
--- End of inner exception stack trace ---
at Nancy.NancyEngine.InvokeOnErrorHook(NancyContext context, ErrorPipeline pipeline, Exception ex)
I call the view here:
return View["Content/views/IO/fileBrowser/ViewPage2.cshtml", dirListing];
There is no error till that point.
The view is totally blank, no code at all. I have also tried view a new view specifying layout, still a 500 error. I've tried referencing the model I am passing, also tried not passing the model. Its all the same. How are you meant to use Razor with Nancy? What is the null reference?..
Nancy's super fun path has been nothing but frustration for me, nothing works out of the box :(
In the root of your web application you should have a views folder, all paths are relative to the views folder.
Without knowing what your module looks like I will give you an example:
public class ProductsModule : NancyModule
{
public ProductsModule()
{
Get["/"] = _ =>
{
....
return ["index", mymodel];
}
}
}
By default, not including other conventions including localization, Nancy will look for a folder called products inside views for a view named index.
So your folder structure should be:
-root
--views
---products
----index.cshtml
If the view is not found, it will then look back 1 directory inside views. so if your directory structure was:
-root
--views
---index.cshtml
Then it would find your view and render it.
There's much more to the discovery of views but this is the general design that you would use most often.

Unable to cast object of type nullable(of object) using entity framework

I'm currently using a scenario of MVC 4 WebAPI w Entity Framework database first modelling. Within my apicontroller it is giving me an error of:
An error has occurred.
Unable to cast object of type
'WhereSelectEnumerableIterator2[VB$AnonymousType_42[System.Nullable1[System.Guid],System.Collections.Generic.IEnumerable1[CK5.Airline]],VB$AnonymousType_51[System.Nullable1[System.Guid]]]'
to type 'System.Collections.Generic.IEnumerable1[CK5.Airline]'.
</ExceptionMessage>
<ExceptionType>System.InvalidCastException</ExceptionType>
<StackTrace> at lambda_method(Closure , Object , Object[] ) at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass13.<GetExecutor>b__c(Object
instance, Object[] methodParameters) at
System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object
instance, Object[] arguments) at
System.Threading.Tasks.TaskHelpers.RunSynchronously[TResult](Func1
func, CancellationToken cancellationToken)
Public Class AirlineController
Inherits ApiController
' GET api/Airline
Function GetAirlines() As IEnumerable(Of Airline)
Using db As New DefaultEntities
Return From p In db.Airlines.AsEnumerable Order By {p.Name} Group By ParentID = p.ParentID Into parentIDGroup = Group Select New With {.ParentID = ParentID}
End Using
End Function
End Class
Within my entity model object the ParentID is a nullable(of guid) type and I believe causing the problem. I've had this working before using a Linq2Sql scenerio, but with the update, this is giving me a problem. I don't believe it's a problem with the web api structure, just w entity framework. Where am I going wrong?
i fixed it. 1) For some reason EF doesn't like to use the statement Using db as New DBContext, it closes the connection before use I think. 2) I'm not sure why either, but it also doesn't like using lambda statements. So it didn't like the Order By or Group By statement. I'll have to look in to that. 3) problem was a bit unrelated, but as this was being a database first EF, I had also put in the globabl.asax this statement: Database.SetInitializer(New DropCreateDatabaseIfModelChanges(Of DefaultEntities)()). Thinking it would update the model or database based on changes. It lied to me. =/

ClassCastException when converting from String to Object.. why?

I am just playing with MessageFormat but when I try to pass a String to MessageFormat format method it compiles fine but then I get a runtime classcast exception. Here is the code.
MessageFormat format = new MessageFormat("");
Object obj = Integer.toHexString(10);
format.format(obj);
Now the runtime exception I get is as follows.
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to [Ljava.lang.Object;
at java.text.MessageFormat.format(Unknown Source)
at java.text.Format.format(Unknown Source)
at JavaCore2.Codepoint.main(Codepoint.java:21)
MessageFormat.format() takes an argument of type Object[] (an Object array), whereas you are passing in a single Object.
You will have to create an array out of your Integer:
MessageFormat format = new MessageFormat("{0}");
Object[] args = { Integer.toHexString(10) };
String result = format.format(args);

IronPython Microsoft.Scripting Exception

I am trying to run IronPython code with c#.
I created a simple console application (.net 4) and added IronPython.dll , IronPython.Modules.dll and Microsoft.Scripting and wrote the next code -
using Microsoft.Scripting.Hosting;
namespace app
{
class Program
{
static void Main(string[] args)
{
ScriptRuntime runtime = IronPython.Hosting.Python.CreateRuntime();
ScriptEngine engine = runtime.GetEngine("py");
engine.Execute("print 'hello!'");
}
}
}
While trying to run this , I get an exception -
Unhandled Exception:
System.Reflection.TargetInvocationException:
Exception has been thrown by the
target of an invocation. --->
System.IO.FileNotFoundException :
Could not load file or assembly
'Microsoft.Scripting, Version=1.0.0.0,
Culture
=neutral, PublicKeyToken=31bf3856ad364e35' or
one of its dependencies. The syste m
cannot find the file specified. at
Core.LanguageProvider.Python..ctor(Stream
stream) --- End of inner exception
stack trace --- at
System.RuntimeMethodHandle._InvokeConstructor(IRuntimeMethodInfo
method, O bject[] args,
SignatureStruct& signature,
RuntimeType declaringType) at
System.RuntimeMethodHandle.InvokeConstructor(IRuntimeMethodInfo
method, Ob ject[] args,
SignatureStruct signature, RuntimeType
declaringType) at
System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags
invokeAttr, B inder binder, Object[]
parameters, CultureInfo culture) at
System.RuntimeType.CreateInstanceImpl(BindingFlags
bindingAttr, Binder bin der, Object[]
args, CultureInfo culture, Object[]
activationAttributes) at
System.Activator.CreateInstance(Type
type, BindingFlags bindingAttr, Binde
r binder, Object[] args, CultureInfo
culture, Object[]
activationAttributes) at
System.Activator.CreateInstance(Type
type, Object[] args) at
Core.LanguageRuntime.RegisterLanguageProvider(Type
providerType) in D:\cod
e\CodeRunner\Core\LanguageRuntime.cs:line
30 at Test.Program.Main(String[]
args) in
D:\code\CodeRunner\Test\Program.cs:lin
e 19 Press any key to continue . . .
I really , dont know what to do , searched at google and dont find a solution.
I will be glad to get help.
Whic version of iron python are you using ? The syntax you show seems belong to an older version, now you should have something like:
var ipy = Python.CreateRuntime();
anyway this blog post seems to be really accurate on pointing the correct reference to use. Anyway, ensure you have the latest IronPython version.