contract call from a contract fails (succeeds in VM) - return-value

The following test contracts work as expected Via Remix when deployed and run in the JavaScript VM but when run with the "Injected Web3" the generation of the secondary contract TestA02 T2 is generated and populated as expected, all get functions called via the primary contract TestA01 return "0" values. If you copy the address of the TestA02 contract and address it directly from Remix, the expected values are returned. Code follows below.
Is this a bug or a misunderstanding on my part?
Instructions:
Using Remix from Mist Version 0.10.0 Compile and Deploy the Primary Contract CODE TestA01.
Call the genEntry function passing any address.
Then call any of the get functions.
CODE:
Primary Contract CODE TestA01:
pragma solidity ^0.4.17;
import "browser/TestA02.sol";
contract TestA01 {
TestA02 T2;
constructor() public {
T2 = new TestA02();
}
function genEntry(address a) public {
T2.add(a);
}
function get() public view returns(address) {return(T2.get(0));}
function get(uint i) view public returns(address) {return(T2.get(i));}
function getSize() public view returns(uint) {return(T2.getSize());}
function getT2() public view returns(address) {return(address(T2));}
}
Secondary Contract CODE TestA02:
pragma solidity ^0.4.17;
contract TestA02 {
uint _size;
mapping(uint => address) private arrayMap;
constructor() public {
_size = 0;
}
function add(address a) public {
arrayMap[_size++] = a;
}
function get() public view returns(address) {return(arrayMap[0]);}
function get(uint i) public view returns(address) {return(arrayMap[i]);}
function getSize() public view returns(uint) {return(_size);}
}

Related

How do I combine a Controlled Lifetime relationship type (i.e. Owned<T>) with a delegate factory?

In my application, I have a service that requires a constructor parameter not resolved by Autofac, that I instantiate using a delegate factory:
public class Service
{
public Service(string parameter /*, ... other dependencies */)
{
}
public delegate Service Factory(string parameter);
}
This works great! I really love this feature.
I also like the Controlled Lifetime relationship, so I can let my component depend on a Func<Owned<ISomething>> like this:
public class Component
{
private Func<Owned<ISomething>> _somethingFactory;
/* constructor omitted for brevity */
public void DoSomethingUseful()
{
using (var ownedSomething = _somethingFactory())
{
/* Lots of useful code here */
}
}
}
My problem is that now I want to combine the two. I can't have an instance of Func<Owned<Service>> injected, because it needs that parameter, so my current solution is to abstract the factory away into another service, say IServiceFactory:
public interface IServiceFactory
{
Service Create(string parameter);
}
...implemented as such:
public class ServiceFactory : IServiceFactory
{
private Service.Factory _internalFactory;
public ServiceFactory(Service.Factory internalFactory)
{
_internalFactory = internalFactory;
}
public Service Create(string parameter)
{
return _internalFactory(parameter);
}
}
My component then becomes this:
public class Component
{
Func<Owned<IServiceFactory>> _serviceFactoryFactory;
/* ... */
}
The need for such a field name leaves a bad taste in my mouth to the point that I suspect there must be a cleaner way to handle this case.
Is there another way?
You could change your injected factory to include the string parameter:
private Func<string, Owned<ISomething>> _somethingFactory;
Then you can pass the string to the factory when you want to create a new instance:
public void DoSomethingUseful()
{
using (var ownedSomething = _somethingFactory("my parameter"))
{
/* Lots of useful code here */
}
}
I've created a .NET Fiddle with a small working sample.

Getting TinyIoc current container in a Nancy project

I'm building a small Nancy web project.
In a method of one of my classes (not a nancy module), I would like to basically do:
var myThing = TinyIoC.TinyIoCContainer.Current.Resolve<IMyThing>();
However, there is only one registration in .Current (non public members, _RegisteredTypes) which is:
TinyIoC.TinyIoCContainer.TypeRegistration
Naturally, in my above code, I'm getting:
Unable to resolve type: My.Namespace.IMyThing
So, I guess I'm not getting the same container registered in my bootstrapper?
Is there a way to get at it?
EDIT
To flesh out a bit more of what I'm trying to do:
Basically, my url structure looks something like:
/{myType}/{myMethod}
So, the idea being, going to: /customer/ShowAllWithTheNameAlex would load the Customer service, and execute the showAllWithTheNameAlex method
How I do this is:
public interface IService
{
void DoSomething();
IEnumerable<string> GetSomeThings();
}
I then have an abstract base class, with a method GetService that returns the service.
It's here that i'm trying to use the TinyIoC.TinyIoCContainer.Current.Resolve();
In this case, it would be TinyIoC.TinyIoCContainer.Current.Resolve("typeName");
public abstract class Service : IService
{
abstract void DoSomething();
abstract IEnumerable<string> GetSomeThings();
public static IService GetService(string type)
{
//currently, i'm doing this with reflection....
}
}
Here's my implementation of the service.
public class CustomerService : Service
{
public void DoSomething()
{
//do stuff
}
public IEnumerable<string> GetSomeThings()
{
//return stuff
}
public IEnumerable<Customer> ShowAllWithTheNameAlex()
{
//return
}
}
Finally, I have my Nancy Module, that looks like:
public class MyModule : NancyModule
{
public MyModule()
{
Get["/{typeName}/{methodName}"] = p => ExecuteMethod(p.typeName, p.methodName);
}
private dynamic ExecuteMethod(string typeName, string methodName)
{
var service = Service.GetService(typeName);
var result = service.GetType().GetMethod(methodName).Invoke(service, null);
//do stuff
return result; //or whatever
}
}
#alexjamesbrown - The short answer is, you don't. Nancy was specifically designed so that you did not deal with the container directly. You mention that the class, that you want to take a dependency on IMyThing, is not a NancyModule. Well this is not an issue, as long as one of your modules has a reference to it, then those dependencies can also have their own dependencies that will be satisfied at runtime.
public interface IGreetingMessageService
{
string GetMessage();
}
public class GreetingMessageService: IGreetingMessageService
{
public string GetMessage()
{
return "Hi!";
}
}
public interface IGreeter
{
string Greet();
}
public class Greeter
{
private readonly IGreetingMessageService service;
public Greeter(IGreetingMessageService service)
{
this.service = service;
}
public string Greet()
{
return this.service.GetMessage();
}
}
public class GreetingsModule : NancyModule
{
public GreetingModule(IGreeter greeter)
{
Get["/"] = x => greeter.Greet();
}
}
The above will work just fine and Greeter will have it's dependency on IGreetingMessageService satisfied at runtime
I have had a very similar issue, needing to "share" the container. The reason this is an issue is that my program runs as a service using Nancy self hosting to provide a REST API. My modules have dependencies which are injected by Nancy itself, but the other parts of the app which are not referenced from modules also need dependencies injected.
Multiple containers are not a sensible option here (or anywhere really), I need to share the container between Nancy and the rest of the app.
I simply did the following
(I'm using Autofac but I suspect that TinyIoC in similar)
public class Bootstrapper : AutofacNancyBootstrapper
{
private static readonly Lazy<ILifetimeScope> container = new Lazy<ILifetimeScope>(RegisterTypes);
public static ILifetimeScope Container => container.Value;
protected override ILifetimeScope GetApplicationContainer()
{
return container.Value;
}
// Create container and register my types
private static ILifetimeScope RegisterTypes()
{
var builder = new ContainerBuilder();
// Register all my own types.....
return builder.Build();
}
}
Then, in my main code, I can use the container myself
public class Program
{
public static void Main(string[] args)
{
// Resolve main service with all its dependencies
var service = Bootstrapper.Container.Resolve<Service>();
service.Run();
}
}
As my NancyHost is within the Service, the container is constructed (once) upon its first use in main, this static is then used when Nancy gets round to creating the Bootstrapper itself.
In an ideal world, I wouldn't really want a globally accessible container, normally it would be local to the main function.
In this particular case "not dealing with the container directly" is highly problematic:
public interface IFoo {}
public class Foo : IFoo { public Foo(string bar) {} }
Assume IFoo already is a constructor dependency of a Nancy module.
Note the Foo constructor's string dependency. I need to communicate to the container to use that constructor for an IFoo singleton, when encountered as a Nancy module dependency. I need to register that on the TinyIoC instance NancyFx uses, and pass in the actual value of bar.

nested methods testing using easy mock

i am facing a problem regarding class mocking in java.
I will explain the problem using dummy classes( to avoid project related security concerns)
We have a class Employee
public class Employee {
public int netSalary() {
int sal = totalSal() - 100;
return sal;
}
public int totalSal() {
// code to return value which is making db calls or remote calls
}
}
Now my problem is that how to test netSalary method without totalSal method being called
i have tried expect().andReturn() as well as suppress(method());
But both are not working
If this was done via MVC then your employee class should have a DAO that gives access to the DB. Inject a mocked version of the DAO that is called in totalSalary.
Per Comment:
This is based on the code you have above:
public class MyTest{
private class TestableEmployee extends Employee{
public int totalSal(){
return 55;
}
}
#Test
public void testIt(){
Employee employee = new TestableEmployee();
int netValue = employee.netSalary();
assertEquals(netValue, 55-100);
}
}
You can use Mockito. Mock the method:
when(employee.totalSal()).thenReturn(1000);

Testing mocked objects rhino mocks

I am new to RhinoMocks, and I am trying to write a test as shown
I have classes like these
public class A
{
public void methodA(){}
}
public class B
{
public void methodB(A a)
{
a.methodA();
}
}
And i am trying to test it like this
A a = MockRepository.GenerateMock<A>();
public void ShouldTest()
{
B b = new B();
b.methodB(a);
a.AssertWasCalled(x=>x.methodA());
a.VerifyAllExpectations();
}
But it is giving the error as shown:
System.InvalidOperationException : No expectations were setup to be verified, ensure that the method call in the action is a virtual (C#) / overridable (VB.Net) method call.
How do I test methodB then?? Can someone help??
Rhino mock creates proxy class when you call MockRepository.Generate *** method. This means that it extends your type. If you don't declare any abstraction you cannot make any derivation which is essential in any mocking framework.
You can do two things
Create an interface (better design)
Make the member virtual (this will allow RhinoMocks to derive from your type and create a proxy for the virtual member
Sample code
public interface IA { void methodA();}
public class A:IA{public void methodA() { }}
public class B
{
public void methodB(IA a)
{
a.methodA();
}
}
[TestFixture]
public class Bar
{
[Test]
public void BarTest()
{
//Arrange
var repo = MockRepository.GenerateMock<IA>();
//Act
B b = new B();
b.methodB(repo);
//Assert
repo.AssertWasCalled(a => a.methodA());
repo.VerifyAllExpectations();
}
}
You have concrete classes with no virtual methods and no interfaces. You can't mock anything.
Update:
Here's one way to do it:
public interface IA
{
void methodA();
}
public class A : IA
{
public void methodA(){}
}
public class B
{
public void methodB(IA a)
{
a.methodA();
}
}
Then use
IA a = MockRepository.GenerateMock<IA>();

Deserialization of ArrayList GWT

In my application I'm getting some data from a file located in the server. The data is stored in a text file (.obj), so I'm using an rpc to read the file and get the data. The file is read using a third party library http://www.pixelnerve.com/processing/libraries/objimport/ I'm sending the data to the client using ArrayLists, basicly I'm sending this: ArrayList[ArrayList[Vertex3dDTO]] where Vertex3dDTO is an serializable object with contains float parameters. ArrayList[Vertex3dDTO] is contained in another serializable class Face3dDTO, and ArrayList[Face3dDTO] is in the serializable class Group3dDTO.
package com.nyquicksale.tailorapp.shared;
import java.io.Serializable;
public class Vertex3dDTO implements Serializable {
float x,y,z;
public Vertex3dDTO(){
}
public Vertex3dDTO(float x, float y, float z){
this.x = x;
this.y = y;
this.z = z;
}
}
public class Face3dDTO implements Serializable {
ArrayList<Vertex3dDTO> vL = new ArrayList<Vertex3dDTO>();
Vertex3dDTO normal = new Vertex3dDTO();
Vertex3dDTO color = new Vertex3dDTO();
public Face3dDTO(){
}
public Face3dDTO(ArrayList<Vertex3dDTO> v) {
for(Vertex3dDTO v3dDTO : v){
vL.add(v3dDTO);
}
updateNormal();
}
public class Group3dDTO implements Serializable {
ArrayList<Face3dDTO> fL = new ArrayList<Face3dDTO>();
String name;
public Group3dDTO(){
}
public Group3dDTO(ArrayList<Face3dDTO> f) {
for(Face3dDTO f3dDTO : f){
fL.add(f3dDTO);
}
}
}
Now, everything is working well in development mode, but when I tested the application in hosted mode, everything I receive as response is: //OK[0,1, ["java.util.ArrayList/4159755760"],0,7]
So, I've been checked some other questions and seems the problem is about deserialization, but I've not found anything concrete.
The question is what do I have to do to get the app working well in hosted mode?
To successfully use RPC, your object needs to implement Serializable and should also have a default no arg constructor
Have you made sure this is a serialization problem? You can write a simple RPC test method to pass an array list of your DTO's over the wire in hosted mode.
If I were to bet money on a guess, I would say the problem is those array lists are sent empty in hosted mode. The .obj file read could be the problem. Perhaps in hosted mode the path of file doesn't match as in dev mode(different server configurations perhaps?), since file operations are in a try catch block an exception is most likely swallowed.
Long word short, Did you make sure those array lists are not sent empty in hosted mode?
Your object may well be Serializable, but that doesn't equate to something usable by Remote Procedure Calls. You need to implement Serializable, have a default contructor with no arguments (that calls super() if necessary), and a serial version ID, like so:
public class MyObject implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1796729355279100558L;
private Float someValue;
public MyObject() {
super();
}
public MyObject(Float someValue) {
super();
this.someValue = someValue;
}
public Float getSomeValue() {
return someValue;
}
public void setSomeValue(Float someValue) {
this.someValue = someValue;
}
}