i'm seeing some weirdness in my Windows Phone app with MVVMCross.
I use ShowViewModel<MyViewModel>(); to load a new view on a command being executed.
I've changed that to:
ShowViewModel<MyViewModel>(new { First = "Hello", Second = "World", Answer = 42 });
But Init isn't being called in the MyViewModel, MyViewModel inherits from another class that in turn inherits from a MvxViewModel, I've even changed both view models to inherit directly from MvxViewModel.
If i used:
Mvx.Resolve<IMvxViewModelLoader>().LoadViewModel(MvxViewModelRequest<MyViewModel>.GetDefaultRequest(), null);
Init get's called, same for the InitFromBundle, I passed a bundle containing that test object but I didn't get the values passed through.
Init method just looks like this:
public void Init(string First, string Second, int Answer)
I'm totally confused, setup, app.cs all look like the navigation example, any ideas what I might have forgot?
Windows 8.1, VS 2013, Hot Tuna, Windows phone 8.
Init methods:
public void Init()
{
}
public void Init(string First, string Second, int Answer)
{
// use the values
var meh = "";
Mvx.Trace("Init called in {0}", GetType().Name);
}
protected override void InitFromBundle(IMvxBundle bundle)
{
}
You should use ShowViewModel<NameOfViewModelClass>(new { First = "Hello", Second = "World", Answer = 42 }); instead
Related
I am trying to write integration test case for one of my rest application which uses mongodb internally to persist the data
#DataMongoTest
#SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class MainControllerTest {
#LocalServerPort
private int port = 8080;
/* some test cases*/
}
but I am getting below error
java.lang.IllegalStateException: Configuration error: found multiple declarations of #BootstrapWith for test class [com.sample.core.controller.MainControllerTest]: [#org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTestContextBootstrapper), #org.springframework.test.context.BootstrapWith(value=class org.springframework.boot.test.context.SpringBootTestContextBootstrapper)]
looks like these two are mutually exclusive, so how to do the integration testing .
Use #AutoConfigureDataMongo with #SpringBootTest and this will resolve this ambiguity issue. #SpringBootTest and #DataMongoTest cannot be used together.
Answering to a very old post hoping it may help others.
#AutoConfigureDataMongo will connect to real database. In order to still use the embedded mongo, one can initiate the embedded mongoDb manually.
#SpringBootTest(classes = SubscriptionEventApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class SubscriptionEventApiIntegrationTest {
#BeforeAll
static void setup() throws Exception {
startEmbeddedMongoDbManually();
}
private static void startEmbeddedMongoDbManually() throws IOException {
final String connectionString = "mongodb://%s:%d";
final String ip = "localhost";
final int port = 27017;
ImmutableMongodConfig mongodConfig = MongodConfig
.builder()
.version(Version.V3_5_5)
.net(new Net(ip, port, Network.localhostIsIPv6()))
.build();
MongodStarter starter = MongodStarter.getDefaultInstance();
mongodExecutable = starter.prepare(mongodConfig);
mongodExecutable.start();
mongoTemplate = new MongoTemplate(MongoClients.create(String.format(connectionString, ip, port)), "test");
}
#AfterAll
static void clean() {
mongodExecutable.stop();
}
#Test
public void test() {
.....
}
}
Purushothaman suggested starting embedded MongoDB server manually. I am suggesting to start it automatically using #DataMongoTest, but creating WebTestClient manually instead.
Kotlin code below, translates to Java trivially:
#DataMongoTest
// #ContextConfiguration may not be needed for your case.
#ContextConfiguration(
classes = [
Application::class,
MainController::class,
// Add more needed classes for your tests here.
// ...
]
)
#TestPropertySource(properties = ["spring.mongodb.embedded.version=4.0.12"])
class MainControllerTest(
#Autowired
private val mainController: MainController,
// Add more beans needed for your tests here.
// ...
) {
// Creating a WebTestClient is easy and
// can be done in different ways.
// Here is one of the possible ways.
private val webTestClient: WebTestClient =
WebTestClient.bindToController(mainController).build()
#Test
fun someTest() {
// ...
}
}
I am making a framework for making fractals in processing, however, I need to use functions as parameters for a constructor of a class.
Something like:
class Fractal {
String name;
void initialize;
Fractal(String Name, void setup) {
...
}
}
I'm going to guess you're coming from a JavaScript background?
Traditionally, Java didn't really have a way to do this. Instead you'd pass an anonymous instance of an interface, like this:
interface Runner{
public void run();
}
class Fractal {
String name;
Runner initialize;
Fractal(String name, Runner setup) {
...
}
}
Runner r = new Runner(){
public void run(){
// whatever
}
}
Fractal fractal = new Fractal("name here", r);
Note that Java provides a Runnable interface that you can use instead of creating your own, but I wanted to spell it out here to make it more obvious.
As of Java 8, you can pass a reference to a function as a parameter. This is called a lambda function. Googling "Java lambda function" will return a ton of results.
From this answer:
public void pass() {
run(()-> System.out.println("Hello world"));
}
public void run(Runnable function) {
function.run();
}
Depending on how you're using Processing, you might be stuck with the first approach though, since I don't think the Processing editor supports Java 8 yet.
Although I'm relatively new to AutoMapper I'm using it in a small project I'm developing. I've never had problems using it before but now I'm facing some weird behavior passing parameters to a Custom Resolver.
Here's the scenario: I get a list of messages from my repository and then map those to a frontend friendly version of it. Nothing fancy, just some normal mapping between objects. I have a field in that frontend object that tells if a certain user already voted for that message and that's what I'm using the Custom Resolver for (it's that second "ForMember"):
public List<SupportMessageUi> GetAllVisible(string userId)
{
Mapper.CreateMap<SupportMessage, SupportMessageUi>()
.ForMember(dest => dest.Votes,
opt => opt.ResolveUsing<SupportMessageVotesResolver>())
.ForMember(dest => dest.UserVoted,
opt => opt.ResolveUsing<SupportMessagesUserVotedResolver>()
.ConstructedBy(() => new SupportMessagesUserVotedResolver(userId)));
var messages = _unitOfWork.MessagesRepository.Get(m => m.Visible);
var messagesUi = Mapper.Map<List<SupportMessageUi>>(messages);
return messagesUi;
}
I'm calling this method on a web service and the problem is: the first time I call the webservice (using the webservice console) it all runs perfectly. For example, if I pass '555' as the userId I get to this method with the correct value:
And in the Custom Resolver the value was correctly passed to the constructor:
The results returned are correct. The problem comes next. The second time I call the service, passing a different argument ('666' this time) the argument that gets to the constructor of the Custom Resolver is the old one ('555'). Here's what I mean:
Right before mapping the objects we can see that the value passed to the constructor was correct ('666'):
But when it gets to the constructor of the Resolver the value is wrong, and is the old one ('555'):
All subsequent calls to the service use the original value in the Custom Resolver constructor ('555'), independently of the value I pass to the service (also happens if I make the call from another browser). If I shut down the server and relaunch it I can pass a new parameter (that will be used in all other calls until I shut it down again).
Any idea on why this is happening?
It's happening because AutoMapper.CreateMap is a static method, and only needs to be called once. With the CreateMap code in your web method, you're trying to call it every time you call that method on your web service. Since the web server process stays alive between calls (unless you restart it, like you said) then the static mappings stay in place. Hence, the necessity of calling AutoMapper.Reset, as you said in your answer.
But it's recommended that you put your mapping creation in AppStart or Global or a static constructor or whatever, so you only call it once. There are ways to call Map that allow you to pass in values, so you don't need to try to finesse things with the constructor of your ValueResolver.
Here's an example using a ValueResolver (note the change to implementing IValueResolver instead of inheriting ValueResolver<TSource, TDestination>):
[Test]
public void ValueTranslator_ExtraMapParameters()
{
const int multiplier = 2;
ValueTranslator translator = new ValueTranslator();
Mapper.AssertConfigurationIsValid();
ValueSource source = new ValueSource { Value = 4 };
ValueDest dest = translator.Translate(source, multiplier);
Assert.That(dest.Value, Is.EqualTo(8));
source = new ValueSource { Value = 5 };
dest = translator.Translate(source, multiplier);
Assert.That(dest.Value, Is.EqualTo(10));
}
private class ValueTranslator
{
static ValueTranslator()
{
Mapper.CreateMap<ValueSource, ValueDest>()
.ForMember(dest => dest.Value, opt => opt.ResolveUsing<ValueResolver>().FromMember(src => src.Value));
}
public ValueDest Translate(ValueSource source, int multiplier)
{
return Mapper.Map<ValueDest>(source, opt => opt.Items.Add("multiplier", multiplier));
}
private class ValueResolver : IValueResolver
{
public ResolutionResult Resolve(ResolutionResult source)
{
return source.New((int)source.Value * (int)source.Context.Options.Items["multiplier"]);
}
}
}
private class ValueSource { public int Value { get; set; } }
private class ValueDest { public int Value { get; set; } }
And here's an example using a TypeConverter:
[Test]
public void TypeTranslator_ExtraMapParameters()
{
const int multiplier = 3;
TypeTranslator translator = new TypeTranslator();
Mapper.AssertConfigurationIsValid();
TypeSource source = new TypeSource { Value = 10 };
TypeDest dest = translator.Translate(source, multiplier);
Assert.That(dest.Value, Is.EqualTo(30));
source = new TypeSource { Value = 15 };
dest = translator.Translate(source, multiplier);
Assert.That(dest.Value, Is.EqualTo(45));
}
private class TypeTranslator
{
static TypeTranslator()
{
Mapper.CreateMap<TypeSource, TypeDest>()
.ConvertUsing<TypeConverter>();
}
public TypeDest Translate(TypeSource source, int multiplier)
{
return Mapper.Map<TypeDest>(source, opt => opt.Items.Add("multiplier", multiplier));
}
private class TypeConverter : ITypeConverter<TypeSource, TypeDest>
{
public TypeDest Convert(ResolutionContext context)
{
TypeSource source = (TypeSource)context.SourceValue;
int multiplier = (int)context.Options.Items["multiplier"];
return new TypeDest { Value = source.Value * multiplier };
}
}
}
private class TypeSource { public int Value { get; set; } }
private class TypeDest { public int Value { get; set; } }
Answering myself: I was not using AutoMapper.Reset(). Once I did that everything started working properly.
Helpful reading: http://www.markhneedham.com/blog/2010/01/27/automapper-dont-forget-mapper-reset-at-the-start/
I have Class that is CCNode extended from one of its methods i want to excute actions
but none of then are running :
from this class :
class GameController : public CCNode
where i have also this:
void GameController::onEnter()
{
CCNode::onEnter();
}
this is the code i have :
bool GameController::removeFinalGems(CCArray* gemsToRemove)
{
onGemScaleInAnim = CCCallFuncND::create(this,
callfuncND_selector(GameController::OnGemScaleInAnim),gemsToRemove);
onRemoveGemScaleInAnim = CCCallFuncND::create(this,
callfuncND_selector(GameController::OnRemoveGemScaleInAnim),gemsToRemove);
CCSequence* selectedGemScaleInAndRemove = CCSequence::create(onGemScaleInAnim,
onRemoveGemScaleInAnim,
NULL);
bool b = this->isRunning();
CCAction *action = this->runAction(selectedGemScaleInAndRemove);
return true;
}
void GameController::OnGemScaleInAnim(CCNode* sender,void* data)
{
CCArray *gemsToRemove = (CCArray*) data;
}
void GameController::OnRemoveGemScaleInAnim(CCNode* sender,void* data)
{
CCArray *gemsToRemove = (CCArray*) data;
}
also i added check to see if there is actions running before and after
and its look like before its equal 0 and after it is equal 1
int na = this->numberOfRunningActions(); //equal 0
CCAction *action = this->runAction(selectedGemScaleInAndRemove);
int na0 = this->numberOfRunningActions();//equal 1 so there is action
it never gets to the OnRemoveGemScaleInAnim and OnGemScaleInAnim methods
I ran into this problem on cocos2d-x when porting an iOS cocos2d app.
After your "runAction" call, add the following line of code to check to see if paused target(s) is the culprit:
CCDirector::sharedDirector()->getActionManager()->resumeTarget( this );
In my case, this was the reason why actions were not being run. It seems that CCTransitionFade's (from screen transitions) resulted in pauses. It might be due to construction of nodes done during init, although I have not tested that theory.
I have a group of classes that implement an interface for my application start-up activities. Here is the registration code:
private static void ConfigureContainer()
{
var container = new WindsorContainer();
container.Register(AllTypes.Of<IStartupTask>()
.FromAssembly(Assembly.GetExecutingAssembly()))
...
var serviceLocator = container.Resolve<IServiceLocator>();
ServiceLocator.SetLocatorProvider(() => serviceLocator);
}
In order to get the tasks, I use this and it works as expected:
public static void Run()
{
var tasks = ServiceLocator.Current.GetAllInstances<IStartupTask>();
foreach (var task in tasks)
{
task.Execute();
}
}
Here is my problem: I have one task that depends on another being run first. There is an InitializeDatabase task that needs to run before the PopulateDatabse task. There are also a bunch of other tasks that are run and I would rather not split the InitializeDatabase task out, if there is some Castle config that will allow me to order the resolution of the types. I don't want to specify the complete order of the types being resolved since that defeats the purpose of the automatic registration, just that InitializeDatabase is the first or PopulateDatabase is last.
Is there a way to register which types should be resolved first without specifying the order of all the types?
Here's one way to do it, it might not be very pretty but it works:
[AttributeUsage(AttributeTargets.Class)]
public class FirstAttribute: Attribute {}
public interface IService {}
public class ThirdService : IService { }
[First]
public class FirstService : IService { }
public class SecondService: IService {}
[Test]
public void WindsorOrder() {
var container = new WindsorContainer();
container.Register(AllTypes.Of<IService>()
.FromAssembly(Assembly.GetExecutingAssembly()));
var intf = container.ResolveAll<IService>()
.OrderByDescending(i => i.GetType().GetCustomAttributes(typeof(FirstAttribute), true).Length)
.ToArray();
Assert.IsInstanceOfType(typeof(FirstService), intf[0]);
}
If you remove [First] from FirstService, the first will be ThirdService and the test will fail.
Use HandlerSelector for that