value cannot be null with htmlagility pack selectnodes - html-agility-pack

I have error "Value cannot be null" when taking data from div with htmlagility pack,
my code is:
var varitem = doc.DocumentNode.SelectNodes("//*[#id='title']")
.SelectMany(x => x.Descendants("div"));
I tryed to chek if value is null with code:
if (object.ReferenceEquals(doc.DocumentNode.SelectNodes("//*[#id='title']")
.SelectMany(x => x.Descendants("div")), null))
but again I get same error.

Related

System.InvalidOperationException: 'Sequence contains no matching element'

May I know why that error keeps pointing to "String isEmailVerified ...."?
public JsonResult GetMemberCounts([FromBody] ChartFilterRequest filter)
{
DateTime startDate = DateTime.Parse(filter.MainFilter.First(m => m.Name == "startDate").Value as string);
DateTime endDate = DateTime.Parse(filter.MainFilter.First(m => m.Name == "endDate").Value as string);
String isEmailVerified = filter.MainFilter.First(m => m.Name == "isEmailVerified").Value as string;
var data = _dashboardComponent.GetMemberCount(startDate, endDate, isEmailVerified);
return new JsonResult(data);
}
Try using FirstOrDefault and LastOrDefault instead of First and Last, these methods will return the default value of the type they are invoked for if no elements match the lambda expression you provide as a parameter.
In your project, You just use filter.MainFilter.First(xxxx) to select the data, So if no elements match the lambda expression you provide as a parameter,First() will throw an exception, So here will report this error.

FirstOrDefault throws ArgumentnullException

My goal is to extract a specific record that has a parameter value specified by me. The data is taken from an external API.
My query looks like this:
var productId = productsResponse.Where(x => x.Parameters.Any(y => y.Values.Any(z => z.Equals(auctionTitle)))).FirstOrDefault();
And it works fine until where filters out all the records. Then the method aborts and debugging cannot continue.
The problem is:
System.ArgumentNullException: Value cannot be null
because source transferred to FirstOrDefault is null.
I also tried:
var productId = productsResponse.Where(x => x.Parameters.Any(y => y.Values.Any(z => z.Equals(auctionTitle)))).DefaultIfEmpty().First();
Please let me know what topic I should read because I have run out of ideas. I really care to understand where I am wrong.
This can be not an answer but try this construction:
var productId = productsResponse
.Where(x => x.Parameters.SelectMany(y => y.Values)
.Any(z => z == auctionTitle))
.FirstOrDefault();
Also if data came from external API, it may be needed more null check.
var productId = productsResponse
.Where(x => x.Parameters?.SelectMany(y => y.Values ?? Enumerable.Empty<Value>())
?.Any(z => z == auctionTitle) == true)
.FirstOrDefault();

What's wrong with my Kendo UI ClientTemplate code?

columns.Bound(e => e.CreateDate).ClientTemplate("# if (CreateDate != null){#"
+ #Html.Action("ChangeDate", "Home", new {date = "#= CreateDate #"}) +
"#} else if ((CreateDate) == null)" +
"{#-#}#");
The ChangeDate action add year to date, but I got the following error:
The parameters dictionary contains a null entry for parameter 'date' of non-nullable type 'System.DateTime' for method 'System.String ChangeDate(System.DateTime)'
as error says the date value is null .
If CreateDate can be null, you need to check for data.CreateDate instead.
columns.Bound(e => e.CreateDate).ClientTemplate("# if (data.CreateDate != null){#"
+ #Html.Action("ChangeDate", "Home", new {date = "#= CreateDate #"}) +
"#} else if ((data.CreateDate) == null)" +
"{#-#}#");

Get Attribute Value by LINQ

The HTML Source is as follows
<img id="itemImage" src="https://www.xyz.com/item1.jpg">
I am using the following LINQ query to get the SRC value (Image Link)
string imageURL = document.DocumentNode.Descendants("img")
.Where(node => node.Attributes["id"] != null && node.Attributes["id"].Value == "itemImage")
.Select(node => node.Attributes["src"].Value).ToString();
But the imageURL gives output as
System.Linq.Enumerable+WhereSelectEnumerableIterator`2[HtmlAgilityPack.HtmlNode,System.String]
The problem is casting it to string. Select() returns IEnumerable<T> so you are basically converting an enumerator to a string (as the error message says). Call First() or Single() or Take(1) in order to get a single element before casting it to a string.
.Select(node => node.Attributes["src"].Value).First().ToString();
Also, if there is a chance that the desired element is not present, FirstOrDefault() and SingleOrDefault() returns null rather then throwing an exception. In that case, I would recommend
var imageUlr = ... .Select(node => node.Attributes["src"].Value).FirstOrDefault();
if (imageUrl != null)
{
// cast it to string and do something with it
}
Add .DefaultIfEmpty(string.Empty)
.FirstOrDefault
string imageURL = document.DocumentNode.Descendants("img")
.Where(node => node.Attributes["id"] != null && node.Attributes["id"].Value == "itemImage")
.Select(node => node.Attributes["src"].Value)
.DefaultIfEmpty(string.Empty)
.FirstOrDefault()
.ToString();
Try adding FirstOrDefault():
string imageURL = document.DocumentNode.Descendants("img")
.Where(node => node.Attributes["id"] != null && node.Attributes["id"].Value == "itemImage")
.Select(node => node.Attributes["src"].Value)
.FirstOrDefault();

mvc3 assign anonymous types or workaround

I have a model that is used to modify a user's password and captures the date that the password has been changed. I am getting an error saying property or indexer anonymous type cannot be assigned to it is read only I get that error for both fields the password and CreateDate . I only know of 1 way to select multiple fields from entity and this is it..
var old= db.registration.Where(b => b.email == getid.email).Select
(s => new { s.password, s.CreateDate }).FirstOrDefault();
old.CreateDate = DateTime.Now();
old.password = new.password;
db.Entry(old).State = EntityState.Modified;
db.SaveChanges();
Is there a way that I can assign these new values without getting the error message or a workaround ?
Just select the default object and run with it
var old= db.registration.Where(b => b.email == getid.email).FirstOrDefault();
old.CreateDate = DateTime.Now();
old.password = new.password;
db.Entry(old).State = EntityState.Modified;
db.SaveChanges();
The error message you're getting is likely because you're assigning to the index of an anonymous type, ie.
s => new { s.password, s.CreateDate }
is anonymous and its indexed properties cant be assigned to

Resources