Haxe Reflection Method to Access a Static Field? - reflection

I'm looking for a way to use reflection to get and set static fields of a Class. Is that possible, or is that too dynamic for Haxe?

You mean, if it's too static for Reflection :)? No, it is not
var cl = Type.resolveClass("MyClass");
trace(Reflect.fields(cl));
trace(Reflect.field(cl, "field"));
trace(Reflect.setField(cl, "field", 0));

In addition, you can get all static fields of a class using Type.getClassFields() (or Type.getInstance() for instance ones). Take a look here : https://api.haxe.org/Type.html

Related

how to hide metadata in web api 2, odata

I have defined odata route using MapODataServiceRoute in my WebApiConfig.
config.Routes.MapODataServiceRoute("CompanyoOdata", "odata", GetImplicitEdm(config));
private static IEdmModel GetImplicitEdm(HttpConfiguration config)
{
ODataModelBuilder builder = new ODataConventionModelBuilder(config, true);
builder.EntitySet<Company>("Company");
builder.EntitySet<Photo>("Photos");
builder.EntitySet<Country>("Country");
return builder.GetEdmModel();
}
The data service works just fine. But I want to achieve few things.
I don't want to expose my metadata or associations because i'm using it internally and will not need metadata. How can I restrict access to these information (i.e restrict access to http://www.sample.com/odata/#metadata or http://www.sample.com/odata/$metadata)
secondly, I want to ignore some properties from getting serialized. I found two ways of doing this.
Using data contracts and marking properties with [DataMember] attribute or [IgnoreDataMember] attribute
Using Ignore method on EntitySet when building the model
I can't use the first method as I'm using Database first approach for entity framework hence can't decorate the entity with attributes. I thought I can achieve this by using MetaDataType, but it seems it only works for DataAnnotations.
I used second method with success, but you can't pass more than one property in the ignore method. Has to do it to individual property that I need to ignore, which is a bit tedious. Is there another way to do this?
any help really appreciated.
If want to hide metadata (/$metadata) or service document (/), can remove the the MetadataRoutingConvention from existing routing conventions, e.g.:
var defaultConventions = ODataRoutingConventions.CreateDefault();
var conventions = defaultConventions.Except(
defaultConventions.OfType<MetadataRoutingConvention>());
var route = config.MapODataServiceRoute(
"odata",
"odata",
model,
pathHandler: new DefaultODataPathHandler(),
routingConventions: conventions);
If only expose a few properties per type, can use ODataModelBuilder instead of ODataConventionModelBuilder. E.g., some example:
ODataModelBuilder builder = new ODataModelBuilder();
EntityTypeConfiguration<Customer> customer = builder.EntitySet<Customer>("Customers").EntityType;
customer.HasKey(c => c.Id);
customer.Property(c => c.Name);

Force CamelCase on ASP.NET WebAPI Per Controller

In ASP.NET WebAPI, I know you can set the default json formatter to use camel case using CamelCasePropertyNamesContractResolver() in the global.aspx which will force ALL json serialization to camel case.
However, I need to be able to set it on a "Per Controller" instance, instead of a Global solution.
Is this possible?
Thanks to #KiranChalla I was able to achieve this easier than I thought.
Here is the pretty simple class I created:
using System;
using System.Linq;
using System.Web.Http.Controllers;
using System.Net.Http.Formatting;
using Newtonsoft.Json.Serialization;
public class CamelCaseControllerConfigAttribute : Attribute, IControllerConfiguration
{
public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor)
{
var formatter = controllerSettings.Formatters.OfType<JsonMediaTypeFormatter>().Single();
controllerSettings.Formatters.Remove(formatter);
formatter = new JsonMediaTypeFormatter
{
SerializerSettings = {ContractResolver = new CamelCasePropertyNamesContractResolver()}
};
controllerSettings.Formatters.Add(formatter);
}
}
Then just add the attribute to any Controller class you want CamelCase.
[CamelCaseControllerConfig]
Yes, it's possible...you can use IControllerConfiguration to define per-controller specific configuration..
This is a sample which describes this scenario. You can quickly take a look at how this interface should be used over here(from the sample).
This Stack Overflow answer should be helpful. It shows you how to create an ActionFilter which can be applied to any action where you wish to use CamelCasing.
I know this is pretty old, but I had a problem with the accepted answer because there were other necessary changes to the formatter that were no longer present after removing and re-adding. I did this by just modifying the existing formatter as shown in this Gist: https://gist.github.com/mauricedb/5356933.

Symfony2 + inject static class

i'm new here and i hope my question is not too trivial.
I have a package with a static class in it (a Grid Builder) and want to use it in symfony2
So i know about the Class loading and the Service Container but i don't get the Container to work.
The Grid Class is depending on 2 other static classes (one for configuration and one for the SQL Query´s)
The Code to use the class is as following:
$Grid = Grid::get_instance();
$Grid->table('products');
echo $Grid->renderGrid();
And internally the class uses calls like GridConfig::database() - so i Thought maybe i cann simply add all three classes to the Service.yml but that doesn't do anything.
So my question is: How can I inject the Static class in a way that I can use it in the Controller?
Is it Possible and if yes what would be the best Practice case to do it?
Thank you for any help.
Since it is static then there really is no need to inject it. Something like:
$grid = \Grid::get_instance;
Should work. If Grid uses namespaces then you need to add that as well. And you will need to ensure the autoloader can find it.
Of course using globals is kind of frowned up. What you can do is to write your own service to act as a wrapper.
class MyGridService
{
protected $grid;
public function getInstance()
{
if (!$this->grid) $this->grid = \Grid::get_instance();
return $this->grid;
}
}
Add MyGridService to your services.yml file then from the controller you can do:
$grid = $this->get('my_grid_service')->getInstance();
You should define a service that uses a factory method to instantiate the object:
service_name:
class: The\Class\Name\Of\The\Created\Object
factory: [ "Grid", "get_instance" ]
Now you can inject the object into your depending class by injecting the service.
See http://symfony.com/doc/current/components/dependency_injection/factories.html

Using asMock, how can I satisfy a concrete and interface requirement in SetupResult.forCall

The ValidationManager has a public Dictionary for storing UI components that implement the IValidatable interface.
I am testing a command class that needs an instance of ValidationManager and I want it to fail the validations. So I override the ValidationManager's "validateItem()" method like so:
var validationManagerRepos:ValidationManager = ValidationManager(mockRepository.createStub(ValidationManager));
var validationItem:IValidatable = IValidatable(mockRepository.createStub(IValidatable));
var validatableItems:Dictionary = new Dictionary();
validatableItems[validationItem] = false;
SetupResult.forCall(validationManagerRepos.validateItem(validationItem)).returnValue(false);
My problem is in the execute method of the command. It checks to see if the validationItem is both a DisplayObject (isVisble) and IValidatable. Any slick way to stub a typed object AND an interface? Or do I just need to create an instance of some existing object that already satisfies both?
for (var iVal:Object in validationManager.validatableItems)
{
if (isVisible(DisplayObject(iVal)))
{
passed = validationManager.validateItem(IValidatable(iVal));
eventDispatcher.dispatchEvent(new ValidationEvent(ValidationEvent.VALIDATE_COMPLETED, IValidatable(iVal), passed));
if (!passed)
{
allPassed = false;
}
}
}
I'm fairly sure you can't do both within asMock. It's a limitation of the Flash Player because of lack of polymorphism.
I believe what you'll have to do is create a testing object that does both (extend DisplayObject and implement IValidatable) and create a mock object of that.
The concept of a "multimock" is certainly possible, but floxy (the framework that asmock uses to generate dynamic proxies) doesn't support it. I previously considered adding support for it, but it would be difficult to expose via the various Mock metadata and there's be other issues to worry about (like method name clashes).
I agree with J_A_X's recommendation of creating a custom class and then mocking that.

What is the best way to reuse functions in Flex MVC environment?

I am using a Cairngorm MVC architecture for my current project.
I have several commands which use the same type of function that returns a value. I would like to have this function in one place, and reuse it, rather than duplicate the code in each command. What is the best way to do this?
Create a static class or static method in one of your Cairngorm classes.
class MyStatic
{
public static function myFunction(value:String):String
{
return "Returning " + value;
}
}
Then where you want to use your function:
import MyStatic;
var str:String = MyStatic.myFunction("test");
Another option is to create a top level function (a la "trace"). Check out this post I wrote here.
You have lots of options here -- publicly defined functions in your model or controller, such as:
var mySharedFunction:Function = function():void
{
trace("foo");
}
... static methods on new or existing classes, etc. Best practice probably depends on what the function needs to do, though. Can you elaborate?
Create an abstract base class for your commands and add your function in the protected scope. If you need to reuse it anywhere else, refactor it into a public static method on a utility class.

Resources