C# get Image Url from JSON response [duplicate]

This question already has an answer here:

I am writing a C# app that is supposed to get event data from JSON

Assuming my JSON response looks like below, how do I get the city_name, image url, date and list of owner names from the response? In JSON below, image could be null and so could be owners.

Also, how would I download the image and show it in my Image control?

{
  "total_items": "24",
  "page_number": "1",
  "page_size": "10",
  "page_count": "3",
  "events": {
    "event": [
      {
        "url": "",
        "id": "event-1",
        "city_name": "Seattle",
        "description": "car show event",
        "image": { <-- THIS COULD BE NULL, HOW TO HANDLE NULL VALUE?
          "thumb": {
            "width": "32",
            "url": "/carshow.jpg",
            "height": "32"
          }
        },
        "date": "2015-12-09 13:20:20",
        "owners": { <-- THIS COULD BE NULL OR MULTIPLE OWNERS, HOW TO GET ALL OWNERS NAMES?
          "owner": [
            {
              "name": "John Doe",
              "id": "O12",
              "bio": "fast track racer"
            },
            {
              "name": "Tom Tomasson",
              "id": "O513",
              "bio": "fines collector"
            }
          ]
        },
      },
      {
        "url": "",
        "id": "event-2",
        "city_name": "Blaine",
        "description": "toyota event",
        "image": null, <-- NO IMAGE IS PROVIDED
        "date": "2015-12-09 13:20:20",
        "owners": null, <-- NO OWNER IS PROVIDED
      },
      {...}
    ]
  }
}

Thanks

How to define a class whose properties change in runtime? [duplicate]

This question already has an answer here:

I have a class called Attributes

public class Attributes
{
    public string Length { get; set; }
    public string Size { get; set; }
    public string Color { get; set; }
    public string Material { get; set; }
    public string Diameter { get; set; }
}

This class is populated from a call to a web service that returns JSON. The web service returns a different set of attributes each time and it is not possible to define all the attributes at compile time as this could run into thousands.

What is the best way to model such a class in c#?

Deserialize array of JSON objects to c# anonymous [duplicate]

This question already has an answer here:

Any ideas how to achieve this?
I have no problem deserializing a single json object like to c# anonymous type

 string json = @"{'Name':'Mike'}";

to

 var definition = new { Name = ""};

with

var result = JsonConvert.DeserializeAnonymousType(json, definition);

but when I have

string jsonArray = @"[{'Name':'Mike'}, {'Name':'Ben'}, {'Name':'Razvigor'}]";

I am stuck.
Thanks!

Duplicated Records Being Returned by Web API Method

I have created what I thought to be a simple controller selecting on a database view. However, the first record is returned multiple times in the JSON result. For example, when filtering using Odata, 7 different records are expected however, 7 of the same record are being returned.

Here is the controller code:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using MyAPI.WebAPI.Models;
using System.Web.OData;
using System.Security.Principal;
using System.Web;

namespace MyAPI.WebAPI.Controllers
{
    public class MyViewController : ApiController
    {
        private MyEntities db = new MyEntities();

        // GET
        [EnableQuery] // Enables OData query integration
        public IHttpActionResult GetMetrics()
        {
            return Ok(db.ViewResults.AsQueryable());
        }
    }
}

When using a breakpoint on the return statement, I can see where all 4000 results are being returned in the query and the OData seems to be filtering only the 7 records I need but when it is sent via JSON string it is duplicated.

Has anyone experienced anything like this?

Asp.Net Web Api trailing / causing odata query to fail

I am using HttpClient to query the WebApi controller using the below code:

        var uri = new Uri(url);
        var message = new HttpRequestMessage(method, uri);
        if (content != null) message.Content = new StringContent(content, Encoding.UTF8, "application/json");

        var client = new HttpClient();
        if (content != null) Debug.WriteLine($"Payload:\n {content}");
        var response = await client.SendAsync(message);
        return response;

The generated Url is as below:
http://localhost:9333/api/roles?$filter=%20Name%20eq%20’Some%20Role’/

Note the trailing ‘/’. This causes the OData Validation (code below) to fail:

    [HttpGet]
    [Route("")]
    public async Task GetRoles(ODataQueryOptions options)
    {
        GuardForODataException(options);

        var filteredResults = await _roleService.GetRolesAsync(options);
        return Ok(filteredResults);

    }

    public void GuardForODataException(ODataQueryOptions options)
    {
        try
        {
            var validationSettings = new ODataValidationSettings();
            options.Validate(validationSettings);
        }
        catch (Exception e)
        {

            var result =
                new ValidationFailedResult(
                    Request,
                        new ValidationResultModel(
                            new ValidationResult(
                                new List { new ValidationFailure("", "Odata Query is invalid") })));

            throw new HttpResponseException(result.ExecuteAsync(default(CancellationToken)).Result);
        }
    }

The exception I am getting is

“An identifier was expected at position 9.”

If however, I remove the trailing /, then the odata query returns the expected results.

I wasn’t able to find much on how to construct a HttpRequestMessage without the / at the end. Has anyone encountered this before?

Modify odata results after query

I have an ASP.NET Web API app using Entity Framework and Odata.

I would like to modify the results of a query when using a GET… currently, within the controller, you effectively just pass the EntityFramework data entities back to the Odata handlers…

[EnableQuery]
public IQueryable GetLineItem()
{
    return db.myEntities;
}

It’s simple to prepend whatever query Odata passes into this by simply returning a subset

return db.myEntity.Where(myEntity => myEntity.Name == "Bob")

Odata will add whatever is in the $filter querystring parameter to the expression passed in here and you get the subset of these results.

However, I would like to iterate over the results once the query executes and the SQL results are parsed into entity objects.

I have tried creating a wrapper that implements the IQueryable interface and hooking into the GetEnumerator methods and the same for the IProvider and hooking into the execute method. Odata doesn’t seem to be using either one of these.

Is there a way to do this?

Can ASP.NET Web API OData Return Non-Collection Properties?

I have the following class:

    public class WeeklyReport
    {
        public IEnumerable DailyReports { get; set; }

        public int? TotalReport
        {
            get
            {
                return DailyReports.Sum(x => x.ReportId);
            }
        }

        public string Title
        {
            get
            {
                return "Weekly Report";
            }
        }
    }

    public class DailyReport
    {
        public string Office { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }
        public string ReportTo { get; set; }
        public DateTime Collection { get; set; }
        public int? Leads { get; set; }
    }

In one of my method in OData controller, I return IQueryable of WeeklyReport.
However, when the OData endpoint is queried, the returned JSON looks something like:

{
"odata.metadata": "http://localhost:546/odata/$metadata#WeeklyReports",
"value": [
    {
        "DailyReports": [
            {
                "Office": "002",
                "Name": "First Last",
                "Type": 10,
                "ReportTo": "00002",
                "Collection": "2014-03-18T00:00:00",
                "Leads": null
            },
            {
                "Office": "002",
                "Name": "Agent, ",
                "Type": 10,
                "ReportTo": "00002",
                "Collection": "2014-03-18T00:00:00",
                "Leads": null
            }
        ]
    },
    {
        "DailyReports": [
            {
                "Office": "002",
                "Name": "First Last",
                "Type": 10,
                "ReportTo": "00002",
                "Collection": "2014-03-18T00:00:00",
                "Leads": null
            },
            {
                "Office": "002",
                "Name": "Agent, ",
                "Type": 10,
                "ReportTo": "00002",
                "Collection": "2014-03-18T00:00:00",
                "Leads": null
            }
        ]
    }
]

Is there a way to set ASP.NET Web API OData to return WeeklyReport.TotalReport and WeeklyReport.Title as well?

Thanks!

OData queries and types other than IQueryable in ASP.NET Web API

I am building an ASP.NET Web API application that returns an Atom or an RSS feed. To do this, it builds a System.ServiceModel.Syndication.SyndicationFeed and a custom MediaTypeFormatter is responsible for handling the HTTP Accept Header, converting the SyndicationFeed to either an Atom10FeedFormatter or an Rss20FeedFormatter, and streaming the result to the response stream. So far, so good.

My controller looks something like this:

    public class FeedController : ApiController
    {
        public HttpResponseMessage Get()
        {
            FeedRepository feedRepository = new FeedRepository();
            HttpResponseMessage successResponseMessage = new HttpResponseMessage(feedRepository.GetSyndicationFeed());
            return successResponseMessage;
        }
    }

What I would like to do is make use of the built-in OData querying to filter my feed, but changing the return type of the Get() method to IQueryable obviously will not work since a SyndicationFeed does not implement IQueryable.

Is there a way to use the built in OData querying on the IEnumerable property on the SyndicationFeed?

How to get Process Finish Button event in Dynamics CRM?

I am using Dynamics 365 online instance to integrate sales process. I have one condition where I need to change the Probability field value to 100 when user clicks on Finish button in Close Process Stage.

enter image description here

I have done some research and found that (OnProcessStatusChange event) can help to get business process flow status change (statuses: Active, Finished, or Aborted)

Ref Link: OnProcessStatusChangeEvent

I have checked this by adding this to form OnLoad event like below, but nothing happens.

Xrm.Page.data.process.addOnProcessStatusChange(setProbablityOnFinish);

Is there any other solution?

How can I tell if user is moving to next or previous stage of business process flow when OnStageChange event is fired in Dynamic 365 Online?

I’m writing a JS script to intercept and do some additional validations when user moved to the next stage of business process flow in Dynamic 365 Online.

I’m binding my function to OnStageChange event of Dynamic 365, but that event is not only fired when a user moved to next stage but also when he moved back to previous stage as well.

Is the any way to tell if the user is moving to the next or the previous stage?

How do I sort a dictionary by value?

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.

I can sort on the keys, but how can I sort based on the values?

Note: I have read Stack Overflow question How do I sort a list of dictionaries by values of the dictionary in Python? and probably could change my code to have a list of dictionaries, but since I do not really need a list of dictionaries I wanted to know if there is a simpler solution.

Sort ArrayList of custom Objects by property

I read about sorting ArrayLists using a Comparator but in all of the examples people used compareTo which according to some research is a method for Strings.

I wanted to sort an ArrayList of custom objects by one of their properties: a Date object
(getStartDay()). Normally I compare them by item1.getStartDate().before(item2.getStartDate()) so I was wondering whether I could write something like:

public class CustomComparator {
    public boolean compare(Object object1, Object object2) {
        return object1.getStartDate().before(object2.getStartDate());
    }
}

public class RandomName {
    ...
    Collections.sort(Database.arrayList, new CustomComparator);
    ...
}

Sort list of class objects in c# [duplicate]

This question already has an answer here:

I want to sort list of class objects.

class tocka
{
Point t;
double kut;
int redkotiranja;

public tocka(Point _t, double _kut, int _redkotiranja)
{
t = _t;
kut = _kut;
redkotiranja = _redkotiranja;
}
}

Here is the list:

List tocke= new List();
tocka a = new tocka(new Point(0, 1), 10, 1);
tocke.Add(a);
tocka b = new tocka(new Point(5, 1), 10, 1);
tocke.Add(b);
tocka c = new tocka(new Point(2, 1), 10, 1);
tocke.Add(c);
tocka d = new tocka(new Point(1, 1), 10, 1);
tocke.Add(d);
tocka ee = new tocka(new Point(9, 1), 10, 1);
tocke.Add(ee);

I want to sort list tocke by t.X

How I do that in C#?

How do I order by lastname? [duplicate]

This question already has an answer here:

How do I order my list with people alphabetical? I have the people randomly in a list but I want it to be alpabetical ordered. How do I do that?

Here is my code:

@if (ViewBag.Roles.CanModify)
{

Sleep naar een groep om deze toe te voegen

}

How to Sort a List by a property in the object

I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class:

List objListOrder = new List();
GetOrderList(objListOrder); // fill list of orders

Now I want to sort the list based on one property of the Order object, for example I need to sort it by the order date or order id.

How can i do this in C#?

How can I sort a list of objects by a member of each object? [duplicate]

This question already has an answer here:

class candle
{
    public DateTime date { get; set; }
    public double open { get; set; }
    public double high { get; set; }
    public double low { get; set; }
    public double close { get; set; }     
}
List candleList = new List();

Assuming I have added many candles to candeList, How can I then sort candleList by date?

Also, how can I remove all duplicate entries from candleList?

Thank you

LINQ's Distinct() on a particular property

I am playing with LINQ to learn about it, but I can’t figure out how to use Distinct when I do not have a simple list (a simple list of integers is pretty easy to do, this is not the question). What I if want to use Distinct on a list of an Object on one or more properties of the object?

Example: If an object is Person, with Property Id. How can I get all Person and use Distinct on them with the property Id of the object?

Person1: Id=1, Name="Test1"
Person2: Id=1, Name="Test1"
Person3: Id=2, Name="Test2"

How can I get just Person1 and Person3? Is that possible?

If it’s not possible with LINQ, what would be the best way to have a list of Person depending on some of its properties in .NET 3.5?

Using LINQ to remove elements from a List

Say that I have LINQ query such as:

var authors = from x in authorsList
              where x.firstname == "Bob"
              select x;

Given that authorsList is of type List, how can I delete the Author elements from authorsList that are returned by the query into authors?

Or, put another way, how can I delete all of the firstname’s equalling Bob from authorsList?

Note: This is a simplified example for the purposes of the question.

remove object from the list if certain statement is true [duplicate]

This question already has an answer here:

using linq I want to check certain condition, if that condition is met I want to remove that object from the list

pseudo code

if any object inside cars list has Manufacturer.CarFormat != null
delete that object

if (muObj.Cars.Any(x => x.Manufacturer.CarFormat != null))
{
    ?
}

remove all strings from list containing certain substring

I’ve got a list of strings called albumList
the string has this structure: abc,abc,abc,abc,abc
I ask the user to search an album to delete; if the album is found, it will be deleted from the list. There could be more than one album with the same name to be deleted from the list.

 private void searchAlbumName(string search)
        {
            string[] cellVal;
            foreach (string x in albumList)
            {
                cellVal = x.Split(',');
                if (cellVal[0].ToString().Equals(search))
                {
                    //do delete here
                }
            }
        }

I’m not sure how to remove every album with the search name

Lambda or LinQ expression to remove certain objects from List

I have a cart.Lines List and want to remove all items where quantity == 0

This is a list that holds collection of CartLine objects:

public class Cart
{
    private IList lines = new List();
    public IList Lines { get { return lines; } set { lines = value; } }
}   

public class CartLine
{
    Product Product {get; set;}
    int Quantity {get; set;}

}

So something like:

cart.Lines.RemoveAll(x => x.Quantity == 0)

I only get Remove and RemoveAt, not RemoveAll !

Also can’t remove in a foreach loop, get error:
Collection was modified; enumeration operation may not execute.

I have now managed to do it with this code, surely there must be something more efficient ?

var myList = cart.Lines.ToList();
myList.RemoveAll(x => x.Quantity == 0);
cart.Lines = myList;

Okay Problem solved!Thanks guys, this here does it:

cart.Lines = cart.Lines.Where(x => x.Quantity != 0);

Remove items in one IList<> from another IList<> [duplicate]

This question already has an answer here:

Sorry to post such basic questions, I’m new to LINQ and am trying to figure out the best way to do this short of looping through each IList.

I have 2 ILists<> with of custom dto objects. I want to remove all the matching items from on list that are in the other.

IList list1 = itemsbl.GetBestItems();
IList list2 = itemsbl.GetWorstItems();

I need to remove all the items in list1 from list2. I have been looking at the Except() method but apparently i need my ItemsDTO class to override the GetHashCode and Equals methods for that to work, but i am having trouble finding some examples of this.

Could someone please show me the best way to remove list1 from list2?

Thanks again

Using LINQ to remove elements from a List

Say that I have LINQ query such as:

var authors = from x in authorsList
              where x.firstname == "Bob"
              select x;

Given that authorsList is of type List, how can I delete the Author elements from authorsList that are returned by the query into authors?

Or, put another way, how can I delete all of the firstname’s equalling Bob from authorsList?

Note: This is a simplified example for the purposes of the question.

Removing items in List using LINQ [duplicate]

This question already has an answer here:

I have a List of type some entity

List

public class OrderLine
{
   public string productCode;
   public int quantity;


}

i need to remove items from the above List if the productCode is equal to some products.

List ProductsToBeExcluded = new List(){"1234","1237"};

so, from List i need to remove products which are equal to 1234 and 1237

i have tried

  1. create a List from List using

      List OrderLines = GetOrderLines();
      var ol = from o in OrderLines
            select o.ProductCode;
    

2.

  List ProductsToBeExcluded = new List(){"1234","1237"};
   var filtered = OrderLines.Except(ProductsToBeExcluded);

how do I proceed further in removing

thanks

Remove an item from a LINQ collection

I think I am putting my question correctly 🙂

I am querying the database using LINQ to retrieve some data. Please find the code below.

var leadtasktype = _context.LeadTypeTaskTypes.Where(l => l.LeadTypeId == item.Value);

foreach(LeadTypeTaskType l in leadtasktype){
    if (l.TaskTypeId == 21)
    {
        //I need to remove an item which has the tasktype id 21
    }
}

As I mentioned in the comments, I need to remove items from the leadtasktype based on my if condition. How do I do this?

Remove Item have same key in List C# [duplicate]

This question already has an answer here:

I have a List n Objects.
In n Objects have some object that they have same Id.
Example List = {t1, t2, t3, t4, t5....,t10}.

assuming that:

t1.Id = t5.id

So i want to remove t5 from that List.

Who can help me plz.

In this question: using LINQ to remove objects within a List you know that object duplicates (ex: “bob”), but in my question, in this List, i don’t know any object duplicate before.

Multiple “order by” in LINQ

I have two tables, movies and categories, and I get an ordered list by categoryID first and then by Name.

The movie table has three columns, ID, Name, and CategoryID.
The category table two has columns, ID, and Name.

I tried something like the following, but it didn’t work.

var movies = _db.Movies.OrderBy( m => { m.CategoryID, m.Name })