I'am new using C# and i have problem when using if inside "public object" method, this my code :
public object Login([FromBody] MailParameters data)
{
UmbracoDatabase db = ApplicationContext.DatabaseContext.Database;
var select = new Sql("SELECT UserID FROM Users where Email='" + data.Email + "';");
var ids = db.Fetch<listUsersChecks>(select);
if (ids)
{
var getByEncrypt = new Sql("SELECT * FROM Users where Email='" + data.Email + "' AND password='" + data.Password + "';");
var listue = db.Fetch<listUsers>(getByEncrypt);
}else{
var listue = "";
}
return listue;
}
the output is :
error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<LoginController.listUsersChecks>' to 'bool'
the error is in if(ids){ , how to solved this?
thanks
Look at the error message, if statement required a Boolean, but you feed in with a List. In this case, your ids is a list List<LoginController.listUsersChecks>
Since it's a list, you can check by counting number of item in this list:
if(ids.Count >0){} else{}
var ids = db.Fetch<listUsersChecks>(select);
This will give you a List<listUsersChecks> and an if condition needs a bool to evaluate if it should be executed or not.
If you want to execute the if statement when you have entries in your list you should use
if(ids.Count > 0)
{
//logic
}
Count is a property of List and gives the number of items in the list.
To make it even more clearer you could write this as well.
bool hasItems = ids.Count > 0;
if(hasItems)
{
//logic
}
You could use the Any method of LINQ as well.
Determines whether any element of a sequence exists or satisfies a
condition.
That would look like
if(ids.Any())
{
//logic
}
For more information have a look at 101 LINQ-Samples
not all your code paths return a value. you have to define your return object prior to the if statement and inside each branch just set it.and as for ids, it's not a valid boolean expression by itself, you may try ids.Any()
It looks like you are expecting C# to support "truthy" and "falsey" values like Javascript. In C#, there is no concept of "truthy" or "falsey". The expression in the if must evaluate to a boolean true or false. What you really want to do is use something like this Linq expression:
if(ids.Any())
{
...
}
Related
I am desperately trying to adapt an API from which I want to fetch a specific value out of an array and I can't seem capable of doing so.
Specifically, I am trying to fetch a custom field name and value out of the API where the name is Controller and the value is whatever the user gave it a value of (its a string value).
I order to get to this, I need to use what is called an IGame interface, which has several properties and methods within it. All of the properties are used with game proceeded with the name of the property. For example, game.title or game.Platform.
So, doing this.Controller.Text = game.Title; outputs the game title to the UI. So far, so good.
My problem comes when using the methods, whering the custom fields lie. I have to use GetAllCustomFields which has the syntax of ICustomField[] GetAllCustomFields(). The return value is ICustomField[] whose syntax in turn is public interface ICustomField with the properties of GameId, Name, Value.
Unfortunately, the API gives me no further information on actual usage so I'm left to try to figure it out but to no avail.
Here what i have so far:
public void OnSelectionChanged(FilterType filterType, string filterValue, IPlatform platform, IPlatformCategory category, IPlaylist playlist, IGame game)
{
if (game == null)
{
this.Controller.Text = "HellO!";
}
else
{
foreach (string field in game.GetAllCustomFields(ICustomField[Name]))
{
this.Controller.Text = "The " + Name + " is " + Value;
}
}
}
XAML
<Grid>
<TextBox x:Name="Controller" />
</Grid>
Can someone help me restructure the foreach so it actually works?
var controllerFields = game.GetAllCustomFields().Where(f => f.Name == "Controller");
foreach (var field in controllerFields)
{
this.Controller.Text = "The " + field.Name + " is " + field.Value;
}
Or if it is just one Controller-field:
Controller.Text = game.GetAllCustomFields()
.SingleOrDefault(f => f.Name == "Controller")
?.Value ?? "No controller here";
?.Value will return the value of the field if it was found. If not, that question mark will prevent to access .Value because it would lead to a NullReferenceException. By adding ?? "No controller here", you give a fallback which is returned if no Controller field was found. That opererator (?.) is called the null coalescing operator, if you don't know it yet.
In .NET WinForms C# app, I have a Dictionary<string, RefItemDetails> collection named listItems. I store data in it on start of the app. In a static class I have as follows:
// listItems is populated bt reading a file.
// No other operations are performed on it, except finding an item.
public static Dictionary<string, RefItemDetails> itemsList;
// Find RefItemDetails of barcode
public static RefItemDetails FindRefItem(string barcode)
{
RefItemDetails itemDet = null;
try
{
//if (itemsList.TryGetValue(barcode, out itemDet) == false)
// System.Diagnostics.Debug.WriteLine("Barcode " + barcode + " not found in Items");
//itemDet = itemsList.First(item => item.Key == barcode);//.First(item => item.Barcode == barcode);
if (itemsList.ContainsKey(barcode))
itemDet = itemsList[barcode];
}
catch (Exception)
{
itemDet = null;
}
return itemDet;
}
For retrieving an item from listItems in another class, I use :
refScannedItem = null;
// Get Unit Barcode & Search RefItem of it
refScannedItem = UtilityLibrary.FindRefItem(boxItem.UnitBarcode.Trim());
// Display BOX item details
refScannedItem.Barcode = boxItem.BoxBarcode.Trim();
refScannedItem.Description = "BOX of " + boxItem.Quantity + " " + refScannedItem.Description;
refScannedItem.Retail *= boxItem.Quantity;
refScannedItem.CurrentCost *= boxItem.Quantity;
Here what happens above is, I search for an item & I get it "refScannedItem" and I append the Description of it by "BOX of " + boxItem.Quantity + " " + refScannedItem.Description; . So if the original Description was "Aquafina", I make it "BOXof 10 Aquafina". The nest time I scan the same product, I find the product, but now its descrption has become "Box of 10 Aquafina", so my line of setting Description turns to "BOX of 10 BOX of 10 Aquafina". The same goes on like "BOX of 10 BOX of 10 BOX of 10 Aquafina" and so on.
As you cna see in my find code, I had initially used TryGetValue, then tried using LINQ, then tried using ContainsKey, but in all of them why does the value of listItem get updated.
I understand that as TryGetValue has out parameter, so the value is passed as a reference, and then it will be chnaged. But in listItems[key] also updates it !!! How can I avoid this to happen ? I had selected Dictionary collection for easy & fast searching, but this part gives a lot of problems and a big bug too on my app. I couldn't find nay solution where the receive the value but shouldn't be updated. All articles shows how to search & update it.
Kindly suggest a solution for the above. Any help is highly appreciated.
Thanks
You return a pointer to the item contained in your Dictionary, so it makes sense that any manipulations you make to this Object will be stored in the original Dictionary object.
What you want to do is, in FindRefItem, return a pointer to a copy of your RefItemDetails object.
An easy way to do this would be to write a new constructor.
Something like:
public RefItemDetails(RefItemDetails original)
{
this.Barcode = original.Barcode ;
this.Description = original.Description ;
this.Retail = original.Retail ;
this.CurrentCost = original.CurrentCost ;
//Set any other properties here
}
and then replace return itemDet; with return new RefItemDetails(itemDet);
I think you are going about this the wrong way.
You shouldn't have a writeable Description property that you update whenever the quantity changes.
Instead, I think you should have a separate Name property which contains the name of the item (e.g. Aquafina) and a dynamically-created readonly Description property like so:
public string Description
{
get
{
return string.Format("Box of {0} {1}", Quantity, Name);
}
}
Or something along similar lines.
This should do the trick:
if (!refScannedItem.Description.StartsWith("BOX of "))
{
refScannedItem.Description = "BOX of " + boxItem.Quantity + " " + refScannedItem.Description;
}
You are getting an object from a Dictionary - and then changing it, so of course it's properties will change in the Dictionary as well ... you haven't cloned it so why would you be taking a copy?
The solution is quite simply not to change the values of the item and use the amended text in a different way:
var amendedDescription = "BOX of " + boxItem.Quantity + " " + refScannedItem.Description;
Looks like you need to make a copy of the RefItemDetails to make modifications to after you get it back from the call to UtilityLibrary.FindRefItem(boxItem.UnitBarcode.Trim())
I'm still learning C# whilst building an MVC web app. Trying to find a way to create a list of values that were changed by a user during an edit operation.
Here's one way I have that would work:
public List<string> SaveVehicleTechnicalInformation(VehicleAssetTechnicalInformationViewModel editmodel)
{
// Create a list of fields that have changed
List<string> changes = new List<string>();
var record = db.VehicleAssetTechnicalInformations.Find((int)editmodel.RecordID);
if (editmodel.Make != null && editmodel.Make != record.Make)
{
changes.Add(" [Make changed from " + record.Make + " to " + editmodel.Make + "] ");
record.Make = editmodel.Make;
}
if (editmodel.Model != null && editmodel.Model != record.Model)
{
changes.Add(" [Model changed from " + record.Model + " to " + editmodel.Model + "] ");
record.Model = editmodel.Model;
}
return changes;
}
But... As you can tell, I am going to need to write an IF/ELSE statement for every single field in my database. There are about 200 fields in there. I'm also worried that it's going to take a long time to work through the list.
Is there some way to go through the list of properties for my object iteratively, comparing them to the database record, changing them if necessary and then outputting a list of what changed.
In pseudo code this is what I guess I am after:
foreach (var field in editmodel)
{
if (field != database.field)
{
// Update the value
// Write a string about what changed
// Add the string to the list of what changed
}
}
Because I'm still learning I would appreciate guidance/tips on what subject matter to read about or where I can independently research the answer. The gaps in my skill are currently stopping me from being able to even research a solution approach.
Thanks in advance.
You can try to use Reflection for your purposes. Something like this
var fields = editmodel.GetType().GetFields();
foreach (var item in fields)
{
if (item.GetValue(editmodel) == database.field)
{
// Update the value
// Write a string about what changed
// Add the string to the list of what changed
}
}
I think I have found the hint I was looking for...
System.Reflection
More specifically, the FieldInfo.GetValue() method.
I was previously unaware of what System.Reflection was all about, so I'll research this area further to find my solution.
I have the following code in C# using selenium:
private void SelectElementFromList(string label)
{
var xpathcount = selenium.GetXpathCount("//select");
for (int i = 1; i <= xpathcount; ++i)
{
string[] options;
try
{
options = selenium.GetSelectOptions("//select["+i+"]");
}
catch
{
continue;
}
foreach (string option in options)
{
if (option == label)
{
selenium.Select("//select[" + i + "]", "label=" + label);
return;
}
}
}
}
The problem is the line:
options = selenium.GetSelectOptions("//select["+i+"]");
When i == 1 this works, but when i > 1 the method return null ("ERROR: Element //select[2] not found"). It works only when i == 1.
I have also tried this code in JS:
var element = document.evaluate("//select[1]/option[1]/#value", document, null, XPathResult.ANY_TYPE, null);
alert(element.iterateNext());
var element = document.evaluate("//select[2]/option[1]/#value", document, null, XPathResult.ANY_TYPE, null);
alert(element.iterateNext());
Which print on the screen "[object Attr]" and then "null".
What am I doing wrong?
My goal is to iterate all "select" elements on the page and find the one with the specified label and select it.
This is the second most FAQ in XPath (the first being unprefixed names and default namespace.
In your code:
options = selenium.GetSelectOptions("//select["+i+"]");
An expression of the type is evaluated:
//select[position() =$someIndex]
which is a synonym for:
//select[$someIndex]
when it is known that $someIndex has an integer value.
However, by definition of the // XPath pseudo-operator,
//select[$k]
when $k is integer, means:
"Select all select elements in the document that are the $k-th select child of their parent."
When i == 1 this works, but when i > 1 the method return null ("ERROR:
Element //select[2] not found"). It works only when i == 1.
This simply means that in the XML document there is no element that has more than one select child.
This is a rule to remember: The [] XPath operator has higher precedence (priority) than the // pseudo-operator.
The solution: As always when we need to override the default precedence of operators, we must use brackets.
Change:
options = selenium.GetSelectOptions("//select["+i+"]");
to:
options = selenium.GetSelectOptions("(//select)["+i+"]");
Finally I've found a solution.
I've just replaced these lines
options = selenium.GetSelectOptions("//select["+i+"]");
selenium.Select("//select["+i+"]", "label="+label);
with these
options = selenium.GetSelectOptions("//descendant::select[" + i + "]");
selenium.Select("//descendant::select[" + i + "]", "label=" + label);
The above solution options = selenium.GetSelectOptions("(//select)["+i+"]"); doesn't worked for me but i tried to use css selectors.
I want to get username and password text box. I tried with css=input this gave me Username text box and when used css=input+input this gave me Password textbox.
along with this selectors you can use many things in combination.
here is the link from where i read.
I think this will help u to achieve your target.
Regards.
I have an IEnumerable of Lesson objects:
IEnumerable<Lesson> filteredLessons
I convert it to a List through the following method:
ToList();
But I want the returned list to contain only the first property, lessonid, not all the Lesson properties.
How can I get the data of specific property of the list instead of the objects?
You can select the value you want first, like this:
filteredLessons.Select(l => l.lessonId).ToList();
And you'll get a list of ID's
If you want to get the the specific row value from list using linq use the following code:
var name = from r in objClientList
where r.ClientCode == Convert.ToInt32(drpClientsInternal.Items[i].Value)
select r.IsInternalClient;
foreach (bool c in name)
{
if (c)
{
ClientNameInternal = ClientNameInternal + drpClientsInternal.Items[i].Text +", ";
drpClientsInternal.Items[i].Selected = true;
}
}