how do i access the class list value - c#

I have a class which populates without a problem from a rest server and it binds
the class is
namespace SavRMobile.AccessToken
{
public class AccessTokenModel
{
public User user { get; set; }
}
public class User
{
public Accesstoken[] accessTokens { get; set;}
}
public class Accesstoken
{
public string appId { get; set; }
public string value { get; set; }
}
}
there will only ever be 1 token that i need to retrieve. I dont know why the developers made it into a list? anyways i want to access the accesstoken.value property.. it get returned as an array.. I cant seem to get the value even in a foreach it will not let me. or should i just grad the index of [0] but not sure what the approach is?

You can try like this:
AccessTokenModel receivedAccessTokens = new AccessTokenModel();
if (receivedAccessTokens.user.accessTokens.Length > 0)
{
string appID = receivedAccessTokens.user.accessTokens[0].appId;
string value = receivedAccessTokens.user.accessTokens[0].value;
}
In the definition of the class accessTokens is defined as an array of Accesstoken so you have to access their values based on the index. It is always better to check for the Array Length/items count before accessing a value based on the index. so above code will do that checking as well as retrieving the values for appId and value.

You can call it like this:
if(RecievedAccessToken.User.accessTokens.Length > 0)
{
ReceivedAccessToken.User.accessTokens[0].value;
}
Hope it helps!

Get spesific Index value
if(recievedAccessToken.User.Accesstoken.Length > 0)
{
recievedAccessToken.User.Accesstoken[0].value
}
or
//Check `length`
AccessTokenModel tokens = recievedAccessToken.User.Accesstoken[0];
Return result List
AccessTokenModel receivedAccessTokens = new AccessTokenModel();
foreach (AccessTokenModel act in recievedAccessToken)
{
receivedAccessTokens.Add(act);
}

Related

ASP.NET Core MVC ViewBag always get zero or NULL from other class

I got this problem when I receive values from a class that use ExecuteAsync.
For example check tempPrice, this nullable var continue to change every second fraction and it's never zero. Other va are props and can be true, false or null... I always get null.
The following is the action method of a specified controller:
public IActionResult Index()
{
ViewBag.tempPrice = _Strategy.TempPrice.ToString().Replace(".", ",");
ViewBag.TradingPair = _Strategy.Symbol;
ViewBag.StopOrderPrice = _Order.StopPriceSpotOrder.ToString().Replace(".", ",");
ViewBag.CurrentTradePrice = _Trade.LastPublicTrade.ToString().Replace(".", ",");
return View();
}
These are parts of codes where i get values , just for example...
public class OrdersFunctions
{
public string ClientOrderId { get; set; }
public string Id { get; set; }
public string Symbol { get; set; }
public string Side { get; set; }
public string Status { get; set; }
}
Only where I manually set the value during app testing (for example)
public string Symbol { get; set; } = "ETHBTC";
I can get the correct value.
As you can see in the screenshot, every value is set to zero, or null, but in the class that contain vars, are all valued.
I supposed it was a problem of services Singleton, Transient, etc... but in any case I set them, I always have this problem (with or without interfaces).
Can someone help me?
EDIT :
As results from the following pic, you can see that all my values, during task operation, are OK. ONLY when i pass the values by contructor in this controller, all values go zero to or null.
The pic show that _trade var has Side value filled in main logic class, but it pass a null value to Controller class
I have used this contructor, but nothing... always zero...
public StrategyController(IOptions<StrategyManager> sm, IOptions<TradeFunctions> trade, IOptions<OrdersFunctions> order )
{
_Strategy = sm.Value;
_Order = order.Value;
_Trade = trade.Value;
}

Get the value of the property of the object whose name begins with a number

I'm fetching data from website that returns me an object in a string like this:
{
index: 1,
commentNumber: 20,
feedComments: {
3465665: {
text: "I do not agree",
likeRatio: 0
},
6169801: {
text: "Hello",
likeRatio: 12
},
7206201: {
text: "Great job!",
likeRatio: 5
}
}
}
I want to work with this as an object, that's pretty easy to do, I'll just do this:
string objectString = GetData(); // Artificial GetData() method
dynamic data = JObject.Parse(objectString);
And now I can easily get all properties I want from this object using dynamic
The problem is pretty obvious now, I want to get properties, whose name starts with number (the object data structure I fetch is just designed that way). But property/field names you get from object cannot begin with a number.
int commentNumber = data.commentNumber; // Works fine
string commentText = data.feedComments.3465665.text; // Obviously won't compile
Is there any way to do this?
Note that I want to work with data I fetch as it was an object, I know I get get the comment text right from the string that GetData() method returns using some regex or something, but that's something I want to avoid.
You should really be parsing the JSON into concrete C# classes. Dynamic is slow and vulnerable to runtime errors that are hard to detect.
The comments will go into a Dictionary. For example:
public class Root
{
public int Index { get; set; }
public int CommentNumber { get; set; }
public Dictionary<long, FeedComment> FeedComments { get; set; }
}
public class FeedComment
{
public string Text { get; set; }
public int LikeRatio { get; set; }
}
And deserialise like this:
var result = JsonConvert.DeserializeObject<Root>(objectString);
Now you can access the comments very easily:
var commentText = result.FeedComments[3465665].Text

Get property value of object in an list

I want to get an property value from an object that is in a list and put it into textbox.text
Below i have an example of my code:
The object:
public class Incident
{
public int Incident_id { get; set; }
public string Description { get; set; }
public string Caller { get; set; }
}
Below is my code in my form class:
List<Incident> incidentById = new List<Incident>();
incidentById = db.GetIncidentById(ID);
when my list is filled i want to put the string Caller into an textbox somewhat like below:
textBoxCaller.Text = incidentById[1].Caller;
I'm stuck at this point so i hope someone can help me out.
Thanks!
EDIT:
public List<Incident> GetIncidentById(int id)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("IncidentLog")))
{
var output = connection.Query<Incident> ($"select * from Incidents where Incident_id like #id", new { id = "%id%" }).ToList();
return output;
}
}
I wasn't passing the right value into my query
this did the trick!
What you want is $"select * from Incidents where Incident_id = #id", new { id }
do you want first value should go?
check like.
if(incidentById.Count>0)
{
textBoxCaller.Text = incidentById.First().Caller;
}
// or you can join all Caller in list like
if(incidentById.Count>0)
{
textBoxCaller.Text = string.join(",",incidentById.Select(x=>x.Caller));
}
The issue that you are facing is that you are trying to access the second element in the list when there are not two or more elements in the list. If you are trying to access the first element in the list, then you could do either
textBoxCaller.Text = incidentById[0].Caller;
or
textBoxCaller.Text = incidentById.First().Caller;
If you do in fact want the second element of the list, then you should be checking to verify that it's length is at least two:
if(incidentById.Count >= 2)
{
...
}
Finally, as mentioned in a comment, you should rename GetIncidentById to something that makes clear it is returning a list, like GetIncidentsById or something similar.

Check to see if value exists in list - better way than a loop?

I have the following class data structure:
public class clsUser
{
public string userid { get; set; }
public List<OrgPermission> orgs { get; set; }
}
public class OrgPermission
{
public string Org { get; set; }
public string SubOrg {get;set;}
public List<string> type { get; set; }
}
List<string> type can have values such as "admin", "user", "superuser", etc.
so each user can have multiple org-suborg combinations with multiple user roles to each.
orgs and suborgs in the user class can be written out like so: 56% (which means they can see everything that starts with 56)
I want to check if the user has access to org-suborg combination on a page of type "Admin"
right now I am doing it with a loop, which works, like so:
foreach (OrgPermission userOrg in user.orgs) {
if ((ddlOrg.SelectedValue.StartsWith(userOrg.Org.Trim('%'))) && (ddlSubOrg.SelectedValue.StartsWith(userOrg.SubOrg.Trim('%')))) {
if (userOrg.type.Contains("Admin"))
btnSubmitToProd.Enabled = true;
else
btnSubmitToProd.Enabled = false;
break; //break out of the loop if the org-sub org match is found
}
}
is there a better way to do this to get rid of the loop maybe? or am I doing it right?
It sounds like you want:
string orgValue = ddlOrg.SelectedValue;
string subOrgValue = ddlSubOrg.SelectedValue;
btnSubmitToProd = user.orgs
.Any(org => orgValue.StartsWith(org.Org.Trim('%')) &&
subOrgValue.StartsWith(org.SubOrg.Trim('%')) &&
org.type.Contains("Admin"));
You can use Enumerable.Any:
var userIsAdmin = user.orgs.Any(uo => uo.type.Any(uot => uot == "Admin"));
I am not sure about using any inbuild method but i still go by your way , any code will at the end will use the foreach logic only , There is no magic way. Even using for in place of foreach will be much faster. I will still vote the way you are doing because it will give you more power in hand. Using any method like LINQ is fine but for loop is the best one.

c# -> javascript, Json decoding misses property

I have a c# object (below) that I'm trying to send to my javascript.
My problem is, that while I can iterate over the items in the list, I can't get to the string-property ('Period').
Referencing the object in JS shows no property at all. After Json-encoding in c#, I can still see the property just before returning it to caller (hovering over the result variable in below function):
[OutputCache(Duration = 0, VaryByParam = "None")]
public JsonResult GetRankingList() {
Response.ContentType = "text/javascript";
var user = _userService.GetUserByPrincipal(User);
// Note, we do this while the user waits as we need to make progress in repeated calls to get the compared ranking list.
_businessLogicServiceMaintenance.PerformMaintenanceSteps();
//TODO: Replace with userid (Guid)
var rankingList = _presenterService.GetRankingListForDisplay(user);
if (rankingList == null)
return Json("");
var result = Json(rankingList);
return result;
}
How on earth can I get past this? Any comments appreciated!
Yours, Anders, Denmark,
public class RankingListForDisplay : List<RankingListLine>
{
public string Period { get; set; }
}
Thanks for taking your time - I found a solution.
I changed above implementation of RankingListForDisplay to the one below. For some reason json likes it way better ;-)
public class RankingListForDisplay
{
public List<RankingListLine> Lines { get; set; }
public string Period { get; set; }
public RankingListForDisplay()
{
Lines = new List<RankingListLine>();
Period = "<Unspecified>";
}
}

Categories

Resources