CachedAnonymousMethodDelegate1 in code disassembled from reflector - porting

I'm exploring the possibility of porting silverlight's System.ComponentModel.DataAnnotations to the desktop in order to reuse validation done in my silverlight business objects (don't ask...).
The problem is I'm getting code like...
// Methods
protected ValidationAttribute() : this(CS$<>9__CachedAnonymousMethodDelegate1)
{
if (CS$<>9__CachedAnonymousMethodDelegate1 == null)
{
CS$<>9__CachedAnonymousMethodDelegate1 = new Func<string>(null, (IntPtr) <.ctor>b__0);
}
}
protected ValidationAttribute(Func<string> errorMessageAccessor)
{
this._syncLock = new object();
this._errorMessageResourceAccessor = errorMessageAccessor;
}
protected ValidationAttribute(string errorMessage) : this(new Func<string>(class2, (IntPtr) this.<.ctor>b__2))
{
}
Is there anyway that I can work around this?

This is the way an anonymous delegate looks like, after compilation.
You could change the anonymous delegate in the source to be a declared delegate.
Then it should be no problem to reverse engineer it with a reflector like tool.

Related

Actionscript in a single class or in multiple scenes?

I am completely new to Actionscript and Adobe Flash CS6 and for a little bit of fun I have decided to try and make a little game. I had a few newbie (or noob-y) questions to ask about a general implementation approach.
The documentation I've been reading so far suggests creating a new flash project, and then create a document class so:
package {
import flash.display.MovieClip;
public class MyMainClass extends MovieClip {
public function MyMainClass() {
}
}
}
and I am wondering if I use this MainClass to code the whole game or include actionscript within a scene and have multiple scenes, or some combination of both.
Lets say I had a wanted 5 Levels in my game, would I do something like:
package {
import flash.display.MovieClip;
public class MyMainClass extends MovieClip {
public function MyMainClass() {
StartLevel1();
StartLevel2();
StartLevel3();
StartLevel4();
StartLevel5();
}
public function StartLevel1() {
// Do something
}
public function StartLevel2() {
// Do something
}
public function StartLevel3() {
// Do something
}
public function StartLevel4() {
// Do something
}
public function StartLevel5() {
// Do something
}
}
}
or create 5 scenes with actionscript in each scene?
Can anyone provide me with a bit of a starting point?
Thanks
I don't know of anyone who has anything good to say about scenes.
However, as you intuit, the timeline itself is a wonderful tool for managing the state of your Flash assets over time. If you use it, you also get the hidden advantage that you don't have to download 100% of your file to be able to use it (so you can reduce or even eliminate the need for a preloader by unchecking "Export in frame N" on your library symbols.
Lars has quite rightly pointed out that there are very few developers who understand this technique, and I know of exactly one who can and will help people who are interested in exploring this technique. That person is helping you right now. So if you choose to go that way, keep in mind you are mostly on your own except if I happen to notice your post and respond to it.
I am not in favor of timeline scripts, with a very few exceptions. What I suggest is a "both and" approach, where you use a Document Class to control timeline instances.
Your document Class might look something like this:
public class Game extends MovieClip {
protected var _level:ILevel;//Interface your Level MovieClips will implement
protected var levelController:LevelController = new LevelControler();
protected var currentLevel:int;
protected var maxLevels:int = 5;
public function Game() {
levelController.addEventListener(LevelEventKind.LEVEL_COMPLETE, nextLevel);
levelController.addEventListener(LevelEventKind.LEVEL_FAILED, gameOver);
startLevel(currentLevel);
}
public function startLevel(levelNumber:int):void {
goToLabel('Level' + String(levelNumber));
}
public function get level():ILevel {
return _level;
}
public function set level(value:ILevel):void {
_level = value;
//internally, this should release all listeners to the last
//level object (if any) so you don't get a memory leak
levelController.level = _level;
}
protected function nextLevel(e:Event):void {
if (currentLevel < maxLevels) {
startLevel(++currentLevel);
} else {
//do you won logic here
}
}
protected function gameOver(e:Event):void {
//do bombed out logic here
}
protected function goToLabel(label:String):void {
for each (var frameLabel:FrameLabel in currentLabels) {
if (frameLabel.name==label) {
//if your swf is media-heavy, may want to check that frame
//is loaded if you chose to reduce/eliminate preloader
goToAndStop(label);
return;
}
}
trace('no such label as', label);
}
}
What this gets you is a game where you can change how the different levels look without changing a single line of ActionScript, and you can change how they work by assigning different Base Classes that implement ILevel slightly differently. You can also change your functionality by swapping out different flavors of LevelController, but your Main Document Class (Game in this instance) would be aware of this change (wheras the other changes could be made without altering Game at all).

How to resolve generic type at runtime

I'm trying to build a command processor that can take any command that implements a marker interface (or maybe descends from a base class). The processor will handle the command that it is asked to process. However I'm struggling with resolving the true generic type as Resolve(Type) returns an object.
I'm not sure is how to cast this if at all possible?
public void Process(ICommand command)
{
var c = command.GetType();
var t = typeof(ICommandHandler<>).MakeGenericType(new[] { c });
var o = container.Resolve(t);
//((ICommandHandler)o).Handle(command); *** This doesn't work
}
The calling code would be something like this -
Dispatcher.Process(new SomeCommand(Guid.NewGuid(),"Param1",12345));
If you absolutely have to call the ICommandHandler<T>.Handle method and you have no other control over the design of the system, then reflection may be your only choice. There's no great way to deal with the switch from generic to non-generic.
Otherwise, you may have a couple of options.
First, if your Dispatcher.Process can be made generic, you can save all the casting.
public static class Dispatcher
{
public static void Process<T>(T command) where T : ICommand
{
var handler = container.Resolve<ICommandHandler<T>>();
handler.Handle(command);
}
}
This is a pretty common solution to a problem like this that I've seen out in the wild.
If you can't do that, then you may be able to make your ICommandHandler<T> interface implement a non-generic ICommandHandler base interface.
public interface ICommandHandler
{
void Handle(ICommand command);
}
public interface ICommandHandler<T> : ICommandHandler
{
void Handle(T command);
}
In this latter case you'd have to switch your strongly-typed command handler implementations to call the same internal logic for generic or basic handling or you'll get different handling based on the call, which would be bad:
public class SomeCommandHandler : ICommandHandler<SomeCommand>
{
public void Handle(ICommand command)
{
var castCommand = command as SomeCommand;
if(castCommand == null)
{
throw new NotSupportedException("Wrong command type.");
}
// Hand off to the strongly-typed version.
this.Handle(castCommand);
}
public void Handle(SomeCommand command)
{
// Here's the actual handling logic.
}
}
Then when you resolve the strongly-typed ICommandHandler<T> your cast down to ICommandHandler (as shown in your question's sample code) will work.
This is also a pretty common solution, but I've seen it more in systems that existed before generics were available where an updated API was being added.
However, in all cases here, the problem really isn't that Autofac is returning an object; it's a class/type design problem that affects any generic-to-non-generic conversion scenario.
Using Reflection - but is this the best way to approach this?
public void Process(Command command)
{
var c = command.GetType();
var ot = typeof(ICommandHandler<>);
var type = ot.MakeGenericType(new[] { c });
var mi = type.GetMethod("Handle");
var o = container.Resolve(type);
mi.Invoke(o, new object[] { command });
}

asp.net MVC 2 - most elegant way of isolating guard code - guarding against null controller parameters

I have a very simple problem, but I'm looking for the 'best' solution to the following:
I have multiple controller actions something like this:
public ActionResult DoSomething(PackageViewModel packageByName, DoSomethingInputModel inputModel)
{
if (packageByName == null)
{
Response.StatusCode = 404;
Response.StatusDescription = "Package not found : " + RouteData.GetRequiredString("packageName");
return View("Error");
}
...
What is the best way to isolate this cross cutting concern?
I can make a function
I can use an AOP tool like PostSharp
ActionFilter
Other?
In fact ActionFilter is an AOP. Write your own ActionFilter implementation to chceck if parameter is not null. If you always need to check the same thing on the beggining of your controller execution then it's the best way. It's easy to write, resusable in whole application and very MVC 2.
Here's what I implemented (based on #ƁukaszW.pl answer)
Hopefully this will save someone some time.
public class GuardAgainstNullPackage : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
BookingController controller = ((BookingController)filterContext.Controller);
if (filterContext.ActionParameters["packageByName"] == null || !(filterContext.ActionParameters["packageByName"] is PackageViewModel))
{
controller.Response.StatusCode = 404;
controller.Response.StatusDescription = "Package not found : " + filterContext.RouteData.GetRequiredString("packageName");
filterContext.Result = new ViewResult() { ViewName = "Error" };
}
base.OnActionExecuting(filterContext);
}
}

This 404 seems unavoidable - what am I doing wrong? [Ninject 2.0 with ASP.NET MVC 2 on .NET 4]

I downloaded the fairly new Ninject 2.0 and Ninject.Web.Mvc (targeting mvc2) sources today, and successfully built them against .NET 4 (release configuration). When trying to run an application using Ninject 2.0, i keep getting 404 errors and I can't figure out why.
This is my global.asax.cs (slightly shortified, for brevity):
using ...
using Ninject;
using Ninject.Web.Mvc;
using Ninject.Modules;
namespace Booking.Web
{
public class MvcApplication : NinjectHttpApplication
{
protected override void OnApplicationStarted()
{
Booking.Models.AutoMapperBootstrapper.Initialize();
RegisterAllControllersIn(Assembly.GetExecutingAssembly());
base.OnApplicationStarted();
}
protected void RegisterRoutes(RouteCollection routes)
{
...
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Entry", action = "Index", id = "" }
);
}
protected override IKernel CreateKernel()
{
INinjectModule[] mods = new INinjectModule[] {...};
return new StandardKernel(mods);
}
}
}
The EntryController exists, and has an Index method that simply does a return View(). I have debugged, and verified that the call to RegisterAllControllersIn() is executed. I have also tried to use Phil Haacks Routing debugger but I still get a 404.
What do I do to find the cause of this?
Are your routes being registered? Is that being called from the base class?
Also make sure that you are registering your controllers properly. I'm not sure how Ninject's controller factory expects it, but it might require a specific name or something.

EFPocoAdapter -- PopulatePocoEntity has null PocoEntity

I'm trying EF with the EFPocoAdapter for the first time. I have a relatively simple TPH scenario with one table and two types, each inheriting from an abstract base class.
My model validates through EdmGen, and my PocoAdapter.cs and xxxEntities.cs files generate fine as well. (well, actually, there are some namespace problems that I'm currently tweaking by hand until we figure out where to go next.)
When I run a simple test to retrieve data:
using (CINFulfillmentEntities context = new CINFulfillmentEntities())
{
// use context
var alerts = from p in context.Notifications.OfType<Alert>()
select p;
foreach (var alert in alerts)
{
Assert.IsNotNull(alert);
}
}
I get an error in the PocoAdapter class, claiming that PocoEntity is null is the following method inside my base class's adapter:
public override void PopulatePocoEntity(bool enableProxies)
{
base.PopulatePocoEntity(enableProxies);
PocoEntity.Owner = _Owner.CreatePocoStructure();
if (!(PocoEntity is IEntityProxy))
{
}
}
Any ideas from anyone?
So, after a little more debugging, I think this is related to proxies. Inside PocoAdapterBase we have the following method:
protected PocoAdapterBase(TPocoClass pocoObject)
{
_context = ThreadLocalContext.Current;
bool allowProxies = false;
if (_context != null)
{
allowProxies = _context.EnableChangeTrackingUsingProxies;
}
_pocoEntity = pocoObject ?? (TPocoClass)(allowProxies ? CreatePocoEntityProxy() : CreatePocoEntity());
Init();
InitCollections(allowProxies);
RegisterAdapterInContext();
}
The line that sets _pocoEntity calls CreatePocoEntityProxy, which returns null.
More info as I find it.