Change value in try c# - c#

I have a function which sends a Vector3 pos to a robot via RestSharp and the response of the POST call looks like this:
{present_effector_pos: true/false}
I want to parse the true or false and return it as boolean.
public bool postEffectroPos(Vector3 pos, float speed_n)
{
var client = new RestClient("http://"+robotIP);
var request = new RestRequest("/present/effector_position_with_speed.json", Method.POST) { RequestFormat = RestSharp.DataFormat.Json };
effectorPos a = new effectorPos();
a.x = pos.x;
a.y = pos.z;
a.z = pos.y;
a.speed = speed_n;
request.AddBody(a);
bool move = false;
try
{
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
string[] tmp = response.Content.Split(':');
string t = tmp[1].Remove(tmp[1].Length - 1);
move = bool.Parse(t);
Debug.Log(move);
}
else
{
Debug.Log(response.StatusCode);
}
});
}
catch (Exception error)
{
Debug.Log(error);
}
return move;
}
But no matter to what value the variable move is changed in the if clause through parsing the method always returns false.

Related

Splitting ReadOnlySequence into lines then ReadOnlySequence by delimiters

I am trying to split the following chunked memory into ReadOnlySequence<char> by newline \n and then delimiters (in this example of ").
I have the partially working (by lines) code below which when I tweak I get exceptions, and currently have the incorrect output of: hello, fun, one.
I believe my issues are with my use of ReadOnlySequence.Slice() and SequencePosition, as this seems linked to the position of the starting sequence, and not the start of the sliced ReadOnlySequence (at least as I understand).
I am kindly seeking advice towards a corrected example of the below, so that we get the expected:
hello, much, fun, done.
using System;
using System.Buffers;
namespace NotMuchFunYet
{
class Program
{
static void Main(string[] args)
{
var buffer = GetExampleBuffer();
while (TryReadLine(ref buffer, out var line))
{
while (GetString(ref line, out var token))
{
Console.WriteLine(token.ToString());
}
}
}
private static ReadOnlySequence<char> GetExampleBuffer()
{
Chunk<char> startChnk;
var currentChnk = startChnk = new Chunk<char>(new ReadOnlyMemory<char>("\"hello\".\"mu".ToCharArray()));
currentChnk = currentChnk.Add(new ReadOnlyMemory<char>("ch\".".ToCharArray()));
currentChnk = currentChnk.Add(new ReadOnlyMemory<char>("\"fun\"".ToCharArray()));
currentChnk = currentChnk.Add(new ReadOnlyMemory<char>("\n\"done\"\n".ToCharArray()));
return new ReadOnlySequence<char>(startChnk, 0, currentChnk, currentChnk.Memory.Length);
}
private static bool TryReadLine(ref ReadOnlySequence<char> buffer, out ReadOnlySequence<char> line)
{
var position = buffer.PositionOf('\n'); // Look for a EOL in the buffer.
if (position == null)
{
line = default;
return false;
}
line = buffer.Slice(0, position.Value); // Skip the line + the \n.
buffer = buffer.Slice(buffer.GetPosition(1, position.Value));
return true;
}
public static bool GetString(ref ReadOnlySequence<char> line, out ReadOnlySequence<char> property)
{
var start = line.PositionOf('"');
if (start == null)
{
property = default;
return false;
}
property = line.Slice(start.Value.GetInteger() + 1);
var end = property.PositionOf('"');
if (end == null)
{
property = default;
return false;
}
property = property.Slice(0, end.Value);
line = line.Slice(line.GetPosition(1, end.Value));
return true;
}
}
class Chunk<T> : ReadOnlySequenceSegment<T>
{
public Chunk(ReadOnlyMemory<T> memory) => Memory = memory;
public Chunk<T> Add(ReadOnlyMemory<T> mem)
{
var segment = new Chunk<T>(mem) { RunningIndex = RunningIndex + Memory.Length };
Next = segment;
return segment;
}
}
}
Changing the first property fetch in GetString() method resolves this, from:
property = line.Slice(start.Value.GetInteger() + 1);
To:
property = line.Slice(line.GetPosition(1, start.Value));
Giving the code:
using System;
using System.Buffers;
namespace NowMuchFun
{
class Program
{
static void Main(string[] args)
{
var buffer = GetExampleBuffer();
while (TryReadLine(ref buffer, out var line))
{
while (GetString(ref line, out var token))
{
Console.WriteLine(token.ToString());
}
}
}
private static ReadOnlySequence<char> GetExampleBuffer()
{
Chunk<char> startChnk;
var currentChnk = startChnk = new Chunk<char>(new ReadOnlyMemory<char>("\"hello\".\"mu".ToCharArray()));
currentChnk = currentChnk.Add(new ReadOnlyMemory<char>("ch\".".ToCharArray()));
currentChnk = currentChnk.Add(new ReadOnlyMemory<char>("\"fun\"".ToCharArray()));
currentChnk = currentChnk.Add(new ReadOnlyMemory<char>("\n\"done\"\n".ToCharArray()));
return new ReadOnlySequence<char>(startChnk, 0, currentChnk, currentChnk.Memory.Length);
}
private static bool TryReadLine(ref ReadOnlySequence<char> buffer, out ReadOnlySequence<char> line)
{
var position = buffer.PositionOf('\n'); // Look for a EOL in the buffer.
if (position == null)
{
line = default;
return false;
}
line = buffer.Slice(0, position.Value); // Skip the line + the \n.
buffer = buffer.Slice(buffer.GetPosition(1, position.Value));
return true;
}
public static bool GetString(ref ReadOnlySequence<char> line, out ReadOnlySequence<char> property)
{
var start = line.PositionOf('"');
if (start == null)
{
property = default;
return false;
}
// property = line.Slice(start.Value.GetInteger() + 1);
// REPLACE WITH BELOW:
property = line.Slice(line.GetPosition(1, start.Value));
var end = property.PositionOf('"');
if (end == null)
{
property = default;
return false;
}
property = property.Slice(0, end.Value);
line = line.Slice(line.GetPosition(1, end.Value));
return true;
}
}
class Chunk<T> : ReadOnlySequenceSegment<T>
{
public Chunk(ReadOnlyMemory<T> memory) => Memory = memory;
public Chunk<T> Add(ReadOnlyMemory<T> mem)
{
var segment = new Chunk<T>(mem) { RunningIndex = RunningIndex + Memory.Length };
Next = segment;
return segment;
}
}
}

Problem with the SDK Azure for FACE API With FileStream picture

We try to use the sdk to use the cognitives services of Microsoft. We use the Interface IFaceOperatiosn which inside there's a method to send a picture by stream like:DetectWithStreamWithHttpMessagesAsync. When we try to use it, we reach a APIErrorException which the message is Bad request but don't know where is the problem so there's our code:
public async Task<List<FaceAPI.Face>> DetectFace(string picture)
{
try
{
Stream img = new FileStream(picture, FileMode.Open);
var res = await detect.DetectWithStreamWithHttpMessagesAsync(img);
List<FaceAPI.Face> result = new List<FaceAPI.Face>();
for (int i = 0; i < res.Body.Count; i++)
{
result.Add(new FaceAPI.Face { Age = (double)res.Body[i].FaceAttributes.Age, Bald = res.Body[i].FaceAttributes.Hair.Bald > 0.5 ? true : false, Beard = res.Body[i].FaceAttributes.FacialHair.Beard > 0.5 ? true : false, Gender = res.Body[i].FaceAttributes.Gender.Value.Equals(Gender.Male) ? true : false, Glasses = res.Body[i].FaceAttributes.Glasses.Value.Equals(GlassesType.NoGlasses) ? false : true, Hair = res.Body[i].FaceAttributes.Hair.HairColor.ToString(), Moustache = res.Body[i].FaceAttributes.FacialHair.Moustache > 0.5 ? true : false,Rectangle=new System.Drawing.Rectangle { X = res.Body[i].FaceRectangle.Left, Y = res.Body[i].FaceRectangle.Top, Height = res.Body[i].FaceRectangle.Height, Width = res.Body[i].FaceRectangle.Width } });
}
return result;
}
catch (APIErrorException e)
{
Debug.WriteLine(e.Message);
return null;
}
catch (SerializationException e)
{
Debug.WriteLine(e.Message);
return null;
}
catch (ValidationException e)
{
Debug.WriteLine(e.Message);
return null;
}
}
Normally it returns a list of Face.
You need to put a wich attribute you want retrieve for the detection like this:
var requiredFaceAttributes = new FaceAttributeType[] {
FaceAttributeType.Age,
FaceAttributeType.Hair,
FaceAttributeType.Gender,
FaceAttributeType.Smile,
FaceAttributeType.FacialHair,
FaceAttributeType.Glasses
};
var res = await detect.DetectWithStreamWithHttpMessagesAsync(picture,true,true,requiredFaceAttributes);

Error when pulling from database to create objects after successful creation

Let me start by apologizing for the complexity of this post. hopefully I am missing something simple but in order to find out I have to make a lengthy explanation.
I'm building a staff tracking app that allows users to draw polygons on a map. The polygon is used as a zone. If the device location is inside the zone it will set them to one status such as "In" and then set them to another status like "Out" when they leave. I'm using several nugets; SQLite, TK.CustomMap, PopupPlugin, to accomplish as much of this as possible in the Shared Project. The SQLite data model is based on the structure of the remote database for the solution which also has a desktop application, web app, and many other interfaces so that structure must be maintained.
The tables involved in this operation are Zones, ZonePoints and StatusClass. When the Zone is saved the Points of the TK.Polygon are saved into the points table. The Statuses assigned to the in and out status of the Zone are assigned to the zone as is the zone name.
The process works this way - first the user clicks on a button to add the zone. This creates a new zone, saves it to the database and gets its id from the table. For now, the ZoneSys (Primary Key in the remote db) is also set to the id although when the API is ready this will be Auto Incremented in the remote db. Here is that command and the objects it references. I did not include the database method definitions given that they work on the first time through, but if anyone thinks they will help solve this riddle please let me know -
public static List<Position> ActiveZonePositions = new List<Position>();
public static int ActiveZoneID;
public static Zone ActiveZone;
public static int PointCount;
public static bool NewZoneOpen = false;
public Command<EventArgs> OpenNewZone
{
get
{
return new Command<EventArgs>(async e =>
{
NewZoneOpen = true;
PointCount = 0;
ActiveZonePositions.Clear();
Zone ZoneToAdd = new Zone
{
Contactsys = MobileUser.ContactSys,
ZoneTypeSys = 1,
OrganizationSys = MobileUser.OrganizationSys,
ZoneName = null
};
ActiveZoneID = await AddZoneToDBAsync(ZoneToAdd);
ZoneToAdd.ID = ActiveZoneID;
ZoneToAdd.ZoneSys = ActiveZoneID;
await AddZoneToDBAsync(ZoneToAdd);
ActiveZone = await App.Database.GetZoneAsync(ActiveZoneID);
});
}
}
As the user click points in the map the polygon is drawn using those positions and those positions are also used to create points which are added to a static list. Here is the MapClicked_Command -
public Command<Position> MapClickedCommand
{
get
{
return new Command<Position>(async position =>
{
if (NewZoneOpen)
{
bool isPointInPolygon = IsPointInAnyPolygon(position);
if (isPointInPolygon)
{
var action = await Application.Current.MainPage.DisplayActionSheet(
"Region Collides with Another Region",
"Cancel",
null,
"Try Again",
"Close Zone Editor");
if (action == "Close Zone Editor")
{
await RemoveZoneAsync(ActiveZoneID);
}
if (action == "Try Again")
{
return;
}
}
else if (!isPointInPolygon)
{
ActiveZonePositions.Add(position);
}
if (ActiveZonePositions.Count == 2)
{
ZonePolyLine.LineCoordinates = ActiveZonePositions;
_lines.Remove(ZonePolyLine);
_lines.Add(ZonePolyLine);
}
else if (ActiveZonePositions.Count == 3)
{
ActiveZonePositions.Add(position);
_lines.Remove(ZonePolyLine);
TKPolygon poly = new TKPolygon
{
StrokeColor = System.Drawing.Color.CornflowerBlue,
StrokeWidth = 2f,
Color = System.Drawing.Color.CornflowerBlue
};
foreach (Position pos in ActiveZonePositions)
{
poly.Coordinates.Add(pos);
}
_polygons.Add(poly);
_currentPolygon.Clear();
_currentPolygon.Add(poly);
currentPolygonRendering = true;
}
else if (ActiveZonePositions.Count > 3)
{
ActiveZonePositions.Add(position);
TKPolygon poly = new TKPolygon
{
StrokeColor = System.Drawing.Color.CornflowerBlue,
StrokeWidth = 2f,
Color = System.Drawing.Color.CornflowerBlue
};
foreach (Position pos in ActiveZonePositions)
{
poly.Coordinates.Add(pos);
}
_polygons.Remove(_polygons.Last());
_polygons.Add(poly);
_currentPolygon.Clear();
_currentPolygon.Add(poly);
}
var pin = new TKCustomMapPin
{
Position = new TK.CustomMap.Position(position.Latitude, position.Longitude),
Title = string.Format("Pin {0}, {1}", position.Latitude, position.Longitude),
IsVisible = true,
IsDraggable = true,
ShowCallout = true
};
_pins.Add(pin);
await CreatePointAsync(position);
PointCount++;
}
else if (EditZoneOpen)
{
ActiveZonePositions.Add(position);
var poly = _polygons[0];
poly.Coordinates.Clear();
foreach (Position pos in ActiveZonePositions)
{
poly.Coordinates.Add(pos);
}
_polygons.Remove(_polygons.Last());
_polygons.Add(poly);
_currentPolygon.Clear();
_currentPolygon.Add(poly);
var pin = new TKCustomMapPin
{
Position = new TK.CustomMap.Position(position.Latitude, position.Longitude),
Title = string.Format("Pin {0}, {1}", position.Latitude, position.Longitude),
IsVisible = true,
IsDraggable = true,
ShowCallout = true
};
_pins.Add(pin);
await CreatePointAsync(position);
PointCount++;
}
});
}
}
Here is the CreatePointAsyncMethod -
public async Task CreatePointAsync(TK.CustomMap.Position position)
{
var zone = await RetrieveZoneAsync(ActiveZoneID);
Model.Point PointToAdd = new Model.Point
{
ZoneSys = zone.ZoneSys,
PointName = "",
Latitude = position.Latitude,
Longitude = position.Longitude,
PointOrder = PointCount + 1
};
ActiveZonePoints.Add(PointToAdd);
}
Here is the IsPointInAnyPolygon method that checks against the list of polygons to ensure the point clicked is not inside any of them as well as its supporting methods.
private bool IsPointInAnyPolygon(Position position)
{
bool inBounds = false;
for (var i = 0; i < ZonePolygons.Count(); i++)
foreach (ZonePolygon zpoly in ZonePolygons)
{
TKPolygon tkpoly = zpoly.Zpolygon;
inBounds = IsPointInPolygon(position, tkpoly.Coordinates);
if (inBounds)
{
ActiveZoneID = zpoly.ID;
return inBounds;
}
}
return inBounds;
}
private bool IsPointInPolygon(TK.CustomMap.Position position, List<Position> coords)
{
int intersectCount = 0;
for (int j = 0; j < coords.Count() - 1; j++)
{
if (j+1 >= coords.Count())
{
if (rayCastIntersect(position, coords[j], coords[0]))
{
intersectCount++;
}
} else if (rayCastIntersect(position, coords[j], coords[j + 1]))
{
intersectCount++;
}
}
return ((intersectCount % 2) == 1); // odd = inside, even = outside;
}
private bool rayCastIntersect(TK.CustomMap.Position position, TK.CustomMap.Position vertA, TK.CustomMap.Position vertB)
{
double aY = vertA.Latitude;
double bY = vertB.Latitude;
double aX = vertA.Longitude;
double bX = vertB.Longitude;
double pY = position.Latitude;
double pX = position.Longitude;
if ((aY > pY && bY > pY) | (aY < pY && bY < pY)
| (aX < pX && bX < pX))
{
return false; // a and b can't both be above or below pt.y, and a or
// b must be east of pt.x
}
double m = (aY - bY) / (aX - bX); // Rise over run
double bee = (-aX) * m + aY; // y = mx + b
double x = (pY - bee) / m; // algebra is neat!
return x > pX;
}
Upon clicking the save button a popup opens that allows the user to give the Zone a name, define the statuses it will be assigned and the points are added to the database. There is a ZoneSys column in the Points table which allows the points to be matched to their respective zones when retrieved. This is done withe the UpdateZone command
public Command<EventArgs> UpdateZone
{
get
{
return new Command<EventArgs>(async e =>
{
Zone zone = await App.Database.GetZoneAsync(ActiveZoneID);
zone.ZoneName = ZoneParameters.ZoneName;
zone.StatusSys = ZoneParameters.InStatus.StatusSys;
zone.OutOfZoneStatusSys = ZoneParameters.OutStatus.StatusSys;
await AddZoneToDBAsync(zone);
if (MapPage.SaveZoneInfoPopupPageOpen)
{
SavePointsOnExit();
MapPage.SaveZoneInfoPopupPageOpen = false;
}
});
}
}
The UpdateZone command calls the SavePointsOnExit method
private async void SavePointsOnExit()
{
ActiveZonePoints.OrderBy(o => o.PointOrder);
for (var i = 0; i < ActiveZonePoints.Count(); i++)
{
Model.Point PointToAdd = new Model.Point();
PointToAdd = ActiveZonePoints[i];
ActivePointID = await AddPointToDBAsync(PointToAdd);
PointToAdd.ID = ActivePointID;
PointToAdd.PointSys = ActivePointID;
await AddPointToDBAsync(PointToAdd);
}
try
{
Zone zone = await RetrieveZoneAsync(ActiveZoneID);
}
catch
{
await Application.Current.MainPage.DisplayActionSheet("no zone returned", "database error", "cancel");
}
try
{
Zone zone = await RetrieveZoneAsync(ActiveZoneID);
await CreateZonedPolygonAsync(zone);
}
catch
{
await Application.Current.MainPage.DisplayActionSheet("Could not create ZonePolygon", "object error", "cancel");
}
ActiveZonePoints.Clear();
ActiveZonePositions.Clear();
NewZoneOpen = false;
ClearPins();
PointCount = 0;
PopulatePoints();
}
In addition to saving the points to the db the SaveZonePointsOnExit method also creates the ZonePolygon and adds it to an observable collection using the CreateZonedPolygonAsync method -
private async Task<ZonePolygon> CreateZonedPolygonAsync(Zone zone)
{
int StatusSys = zone.StatusSys;
var status = await App.Database.GetStatusBySysAsync(StatusSys);
int OutStatusSys = zone.OutOfZoneStatusSys;
var outStatus = await App.Database.GetStatusBySysAsync(OutStatusSys);
var points = await App.Database.GetZonePointsAsync(zone.ZoneSys);
ZonePolygon zonePolygon = new ZonePolygon
{
ID = zone.ID
};
TKPolygon poly = new TKPolygon();
foreach (Model.Point point in points)
{
poly.Coordinates.Add(new Position(point.Latitude, point.Longitude));
}
poly.Color = Color.FromHex(status.ColorCode);
poly.StrokeColor = Color.Firebrick;
poly.StrokeWidth = 5f;
_polygons.Add(poly);
ZonePolygons.Add(zonePolygon);
return zonePolygon;
}
So far all of this works to a point. I have been successful in creating the first Polygon. I don't run into a problem until I attempt to create a second Zone. When I click on the AddZone button a second time that works fine but when I click on the map to begin creating the second zone a nullreference exception occurs.
Given that the first zone is created without issue I think the problem must be arising from something that occurs when the IsPointInAnyPolygon method no longer immediately returns false because the ZonePolygons list is no longer empty. So something about the retrieving of zones from the database to check against is the problem or possibly adding coordinates when the TKPolygon is created. I don't know what has a null reference. I would think that since I am creating the Zones directly from the database that all the objects would be saved properly and their previous references wouldn't matter. I'm very stuck on this.
TL;DR there is an issue with either the CreateZonedPolygonAsync Method or the IsPointInAnyPolygon method
I figured this out. I feel rather silly because I have been stuck on this for several hours spread out over a couple of weeks. Kept coming back to it and couldn't figure it out. The issue was that in the CreateZonedPolygonAsync method I never assigned the TKPolygon created via points to the ZonePolygon object being created. So when I tried to reference it it didn't exist. All that existed was the ID. Can't believe I missed this for this long.
Of course now I'm having brand new problems but at least this is fixed.
All I had to do was add zonePolygon.Zpolygon = poly; as shown here and it works now
private async Task<ZonePolygon> CreateZonedPolygonAsync(Zone zone)
{
int StatusSys = zone.StatusSys;
var status = await App.Database.GetStatusBySysAsync(StatusSys);
int OutStatusSys = zone.OutOfZoneStatusSys;
var outStatus = await App.Database.GetStatusBySysAsync(OutStatusSys);
var points = await App.Database.GetZonePointsAsync(zone.ZoneSys);
ZonePolygon zonePolygon = new ZonePolygon
{
ID = zone.ID
};
TKPolygon poly = new TKPolygon();
foreach (Model.Point point in points)
{
poly.Coordinates.Add(new Position(point.Latitude, point.Longitude));
}
poly.Color = Color.FromHex(status.ColorCode);
poly.StrokeColor = Color.Firebrick;
poly.StrokeWidth = 5f;
zonePolygon.Zpolygon = poly;
_polygons.Add(poly);
ZonePolygons.Add(zonePolygon);
return zonePolygon;
}

Unity crashes at Get- Call in RestSharp

I use RestSharp to send post and get calls to a robot which is connected via LAN through a switch with my computer. My get call:
public Vector3 getEffectorPos()
{
var c = new RestClient("http://" + robotIP);
var r = new RestRequest("/present/effector_position.json", Method.GET);
List<String> queryResult = c.Execute<List<String>>(r).Data;
string[] tmp = queryResult[0].Split('[', ']');
Vector4 x = parseStringToFloat4(tmp[2]);
Vector4 y = parseStringToFloat4(tmp[4]);
Vector4 z = parseStringToFloat4(tmp[6]);
Vector3 pos = new Vector3(x.w, y.w, z.w);
effPos.setPos(x.w, y.w, z.w);
effPos.cos = x.x;
effPos.sin = -x.y;
return pos;
}
Because the robot has the static ip 192.168.200.99 I have to switch to a static ip adress in the .200 subnet every time I want to run the project. When I first started the project I would get an error like NullReference or Bad Gateway if the robot was not connected.
But now if I forget to switch from dynamic ip to a static one and the programm can't connect to the robot Unity crashes. And afterwards even if I switch back to a static ip Unity proceeds to crash and it seems like nothing helps but waiting and after some time it will just work again without me doing anything.
It seems like I don't have the same problem with the post call:
public bool postEffectroPos(Vector3 pos, float speed_n)
{
var client = new RestClient("http://" + robotIP);
var request = new RestRequest("/present/effector_position_with_speed.json", Method.POST) { RequestFormat = RestSharp.DataFormat.Json };
effectorPos a = new effectorPos();
a.x = pos.x;
a.y = pos.y;
a.z = pos.z;
a.speed = speed_n;
request.AddBody(a);
bool move = false;
try
{
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
string[] tmp = response.Content.Split(':');
string t = tmp[1].Remove(tmp[1].Length - 1);
move = bool.Parse(t);
//Debug.Log(move);
}
else
{
Debug.Log(response.StatusCode);
}
});
}
catch (Exception error)
{
Debug.Log(error);
}
return move;
}
The post call is async but I didn't figure out yet how to a return a value with async(returns always zero or false, depending on type) and I need the return value of the get call.

How can I return both types of data in an action inside my controller?

So, I have an ActionResult inside my controller that is supposed to grab the existing values from my database and return the parameters to the view.
My method is called ReadMeasurements and it grabs Angle and point data.I want to return both angle and point data if it exists/not null.
I noticed the way I have it set up right now, I am only returning my angle data because when angle data and point data is not null, the code only returns the angle data and not the point data.
How can I return both angle and point data inside my method?
Here's my code:
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public ActionResult ReadMeasurements([DataSourceRequest] DataSourceRequest request, string viewType)
{
JsonResult json = new JsonResult();
List<AngleData> angledata = UserSession.GetValue(StateNameEnum.Planning, ScreenName.Planning.ToString() + "Angles" + viewType, UserSessionMode.Database) as List<AngleData>;
List<PointData> pointData = UserSession.GetValue(StateNameEnum.Planning, ScreenName.Planning.ToString() + "Points" + viewType, UserSessionMode.Database) as List<PointData>;
if (angledata != null)
{
List<PlanningViewParam> angles = new List<PlanningViewParam>();
foreach (AngleData i in angledata)
{
string col = "#" + ColorTranslator.FromHtml(String.Format("#{0:X2}{1:X2}{2:X2}", (int)(i.color.r * 255), (int)(i.color.g * 255), (int)(i.color.b * 255))).Name.Remove(0, 2);
int angleVal = (int)i.angleValue;
angles.Add(new PlanningViewParam()
{
Color = col,
Label = "Angle",
Value = angleVal,
Number = i.angleNumber
});
}
return json = Json(angles.ToDataSourceResult(request, i => new PlanningViewParam()
{
Color = i.Color,
Label = i.Label,
Value = i.Value,
Number = i.Number
}), JsonRequestBehavior.AllowGet);
}
if (pointData != null)
{
List<PlanningViewParam> points = new List<PlanningViewParam>();
foreach (PointData f in pointData)
{
string col = "#" + ColorTranslator.FromHtml(String.Format("#{0:X2}{1:X2}{2:X2}", (int)(f.color.r * 255), (int)(f.color.g * 255), (int)(f.color.b * 255))).Name.Remove(0, 2);
string pointAnglesVal = f.pointAnglesValue;
points.Add(new PlanningViewParam()
{
Color = col,
Label = "Points",
ValueTwo = pointAnglesVal,
Number = f.pointNumber
});
}
return json = Json(points.ToDataSourceResult(request, f => new PlanningViewParam()
{
Color = f.Color,
Label = f.Label,
Value = f.Value,
Number = f.Number
}), JsonRequestBehavior.AllowGet);
}
return null;
}
Create a type that holds them both and return that instead:
public class PointAndAngle
{
public Point Point { get; set; }
public Angle Angle { get; set; }
}
var pAndA = new PointAndAngle { Point = p, Angle = a };
return Json(pAndA);
You could do it with an anonymous type if you wanted too:
return Json(new { Point = p, Angle = a});
ok, if you `return' from a function then, the function ends and you get an output. you need to concate both data types into an object that you can return.
try something like
public class data
{
public AngleData angle {get; set;}
public PointData point { get; set;}
}
Return a object of type data in your function.

Categories