Web API controller returns empty JSON even if returned var is not empty - json

In my API, I have to return a json composed of 2 distinct objects, one is a unique entity and the other a list. When I return each separatly there is no problem, but when I try to return them as a single json, the result is empty, even though my var in the return ok(var) contains what is supposed to be returned.
The controller looks like this:
[System.Web.Mvc.HttpGet]
public IHttpActionResult GetOne(int id)
{
var x = Service.GetOne(id);
return Ok(x)
}
(If I put a breakpoint on the return line, I can see that x contains the single object and the list that I want in my json)
"Service" is where I merge the 2 objects by caling a model constructor that takes the single object and the list as input, it looks like this:
public class mergedObject
{
IEnumerable<SingleObject> y;
IEnumerable<ListObject> z;
public mergedObject GetOne(int Id)
{
mergedObject x = new mergedObject(RepoSingleObject.getOne(Id) a,
RepoList.GetAll(Id) b)
this.y = a
this.z = b
}
It calls the corresponding repository(which contains the sql query) for each object and I know this part is working, since like I said earlier, I can properly return each object individually.
The console returns absolutely no error, I did everything the same way as with the individual objects, except for the merging and when I use breakpoints everything seems to go fine, but yet, using postman to test it, I always get an empty return. Does anyone have an explanation?
EDIT
The controller is derived from ApiController + added full definition of the mergedObject class up there. I use IEnumerable even on the single object because I reuse some part of the code where this single element is in fact a list, so I figured it would only be a list of 1 element and wouldn't cause any problem.

Related

Return different values each time from jMockit expectation

I have a unit test where I am mocking java.net.URI class. Further, I am creating a jMockit NonStrictExpectation where I am expecting invocation of URI.getPath() and returning a particular string.
The code being tested invokes URI.getPath() twice, where I need to send a different string each time.
Here is my actual method under test:
public void validateResource() {
// some code
URI uri = new URI(link1.getHref());
String path1 = uri.getPath();
// some more code
uri = new URI(link2.getHref());
String path2 = uri.getPath();
}
Here is the unit test code:
#Mocked URI uri;
#Test
public void testValidateResource() {
new NonStrictExpectations() {
{
// for the first invocation
uri.getPath(); returns("/resourceGroup/1");
// for the second invocation [was hoping this would work]
uri.getPath(); returns("/resource/2");
}
};
myObject.validateResource();
}
Now, I want "/resource/2" to be returned from my expectation when the URI.getPath() is called second time. But it always hits the first expectation and returns "/recourceGroup/1". This is my problem.
How do I make it happen? I can't really use StrictExpectations due to a number of reasons, and will have to stick with NonStrictExpectations.
Seems like you just need to list uri.getPath() once, and use the varargs version of returns...something like this:
uri.getPath(); returns("/resourceGroup/1", "/resourceGroup/2");
This is according to the documentation, anyway...I have not tested it myself.
Multiple consecutive values to return can be recorded for an expectation, by calling the returns(v1, v2, ...) method. Alternatively, the same can be achieved by assigning the result field with a list or array containing the consecutive values.

string linq to entities error - json

I am trying to map various markers on google map with a info window. It is all working fine till I try to pass a string through the controller.
I get the error below:
"LINQ to Entities does not recognize the method 'System.String GetMainPhoto(Int32)' method, and this method cannot be translated into a store expression."
I have read this is mainly caused because ToString method or some other methods are not valid to use. But, I am not really sure how to correct this error in this case.
Basically, I have a db - PropertyPhoto that holds the filename of the pictures. GetMainPhoto basically looks up all the rows and returns the main pic file name.
public string GetMainPhoto(int id)
{
return db.PropertyPhotos.Single(p => p.PropertyId == id && p.MainPic == true).PhotoLocation;
}
Controller is as follows:
public ActionResult Map()
{
if (Request.IsAjaxRequest())
{
var properties = websiteRepository.FindAllProperties();
var jsonProperties = from property in properties
select new JsonProperty
{
PropertyId = property.PropertyId,
NoOfBedroom = property.NoOfBedrooms,
Price = property.Price,
Address1 = property.PropertyAddress.Address1,
MainPicSrc = websiteRepository.GetMainPhoto(property.PropertyId),
Latitude = property.PropertyAddress.Latitude,
Longitude = property.PropertyAddress.Longitude
};
return Json(jsonProperties.ToList(), JsonRequestBehavior.AllowGet);
}
else
{
return View();
}
}
Try to eagerly load the data first by calling .ToList() before projecting into an anonymous type, otherwise EF doesn't know how to translate the websiteRepository.GetMainPhoto call to SQL:
var properties = websiteRepository.FindAllProperties().ToList();
Be careful though. By doing this you might be experiencing the SELECT N+1 problem because for each element of the initial resultset you will be sending a SQL query to fetch the MainPicSrc property.
A better approach would be to perform this join directly by the database and don't use the websiteRepository.GetMainPhoto call.

How to always return a java.util.Vector

If the value in my control only have one value the following code will return a String, if there are more than one value the code will return a java.util.Vector.
getComponent("mycontrol").getValue();
I want this code to return a vector even if there is only one value.
I have seen several code snippets that converts my string to an Array, but I want to get back a vector.
There is no way to force a singular value to be returned as a java.util.vector (or Array for that matter). The only way would be to test to see if it is a vector, then build a vector if not. You could place it into a function and wrap the call into that... for example (this is untested code so you'll need to verify syntax, etc):
asVector(getComponent("mycontrol").getValue());
function asVector(obj) {
if (obj.constructor === java.util.Vector) {
return obj;
} else {
var x:java.util.Vector = new java.util.Vector();
x.add(obj);
return x;
}
}

AS3 - Returning a property of a class rather than the class itself

In ActionScript 3, there are some classes that will represent a value rather than the class itself. It's hard to explain properly what I mean, so take this example:
var str:String = "something";
var mc:MovieClip = new MovieClip();
trace(str); // something
trace(mc); // [object MovieClip]
You'll notice that the first trace outputs a value, rather than [object String]. Ontop of this, I can still make use of methods of String, like this:
var ar:Array = str.split('s');
Even though in a way you could almost read the above as:
"something".split('s');
I have a class AvLevelData that has some methods that deal with level data (which is essentially a String). At the moment there is a property data:String which represents the core level data.
The question I have is - can I replicate the behaviour of String in that when I trace or assign an instance of AvLevelData, the result is actually the String data.
For example, at the moment I need to go:
var levelData:AvLevelData = new AvLevelData();
trace(levelData.data);
To get the data. I instead want to be able to simply do the following:
var levelData:AvLevelData = new AvLevelData();
trace(levelData); // some level data string
Is this possible?
If you wan't your object to trace out your own fabricated string then you must implement a toString() function on your AvLevelData class.
In your example above, the MovieClip trace outputs: [Object MovieClip]; this comes from the default toString() implementation for Object (found on Object.prototype) . Note, you cannot override toString() as it only exists on the prototype of Object (remnants of the AS2/Javascript world), all you need to do is provide your own implementation with the same name. For instance:
public function toString():String {
return "MyCustomObjectString";
}
Some of the most basic types - String, int, Number, uint, Boolean, to name a few - are not classes / objects per se, they are primitives. In some languages there is a wrapper class available for some of these so they can be treated like objects, though Flash doesn't do this so much from my experience.
Probably the best way to answer your question is to make a toString() method for your AvLevelData class:
public function toString():String {
return data;
}
Any time you treat a class as a string (such as by putting it in trace()), flash (and many other languages) try to call toString() on the object. Typically this results in a string that's not helpful. But if you define your own toString() method, you can control what string gets output.
Another option is to simply do:
trace(AvLevelData.data);
Since that variable is a string, it should trace just fine.

What is the equivilant of C#'s generic Dictionary in ActionScript 3?

I want to have a collection of objects, which will be of a class I created called Server. A Server has a string property which is it's IP address, as well as many other pieces of data and objects.
I will have methods for adding and removing servers to this collection, and there will be a need to find a server by it's IP address occasionally. If I were doing this in C# I would use a Dictionary< where the IP string would be the key and the Server object would be the value. I could easily check to see if an item exists in the Dictionary before attempting to add it.
So my requirements are:
1. Ability to add items to the collection (I don't care where they go, front, back, middle)
2. Ability to remove items from anywhere in the collection.
3. Ability to determine if a particular IP address already exists in the collection.
4. Ability to get a reference to a Server object by it's IP.
Edit: Oh yes, I would like it to be strongly typed like the Vector... I guess it's not absolutely necesary, but would be nice.
So it seems like an associative arrays will give me what I need, except I'm not sure about how to do #3 or #4.
public var Servers:Object = new Object( );
public function AddServer(server:Server):void
{
//TODO:need to check if it exists first and throw an error if so
//(it's the caller's responsibility to call DoesServerExist first)
Servers[server.IP] = server;
}
public function RemoveServer(IP:string):void
{
//is it OK to attempt to delete an item if it doesn't already exist?
//do I need to check if it exists before doing delete?
delete Servers[IP];
}
public function DoesServerExist(IP:string):bool
{
//Do I loop through all the elements testing it's IP property?
//Or can I just do something like this?
if(Servers[IP] == null)
{
return false;
}
else
{
return true;
}
}
public function GetServer(IP:string):Server
{
return Servers[IP];//what is returned if this IP doesn't exist?
}
Call me goofy, but why not use the Dictionary class? That gets you everything except strong typing.
If you want strong typing then I'd say you need a custom container, which wraps up a Vector of Servers, and a Dictionary or associative array of IP strings that indexes into the Vector. Then you'd need to expose methods for access, test, insert and remove.
You can just use an array. Example:
var dict:Array = [];
var ip = "164.157.012.122"
dict[ip] = "Server name"
if (dict[ip] == "Server name"){
trace("Yay");
}
//membership
if (dict[ip]){
trace(ip + " is a member of dict");
} else {
trace (ip + " is not a member");
}
//removal:
dict[ip] = null;
AS3 does not really have a built in Dictionary class, unfortunately.