Get a User Object by username field - c#

I've looked around and cannot figure out how to get a different user by their user name, something tells me this is not possible am I correct? I want the user to be capable of using Game Center or Google Play and not just Facebook as an id. That means I can register anyone I want as a user and then find their friends (without having to use FB). Should I just make a separate Table to store this info?
I have attached code below for what should work, can anyone give some insight in either my code or on why I cannot get "bob". I have tested this code against another table and I can get the rows.
The code falls through properly and I do get to the foreach but there are no results to iterate through
I have also tried "_User" but get
ArgumentException: Use the class-specific query properties for class _User
Parameter name: className
Any help here would be great I would like to avoid making another Table just for searching and doing relationships to other tables.
private void getParseObjectTest()
{
var query = ParseObject.GetQuery("User").WhereEqualTo("username", "bob");
query.FindAsync().ContinueWith(user =>
{
if (user.IsCanceled || user.IsFaulted)
{
Debug.Log("Can't get the user.... " + user.Exception.Message);
}
else
{
Debug.Log("Return was success time to iterate");
IEnumerable<ParseObject> results = user.Result;
foreach (var result in results)
{
string str = result.Get<string>("email");
Debug.Log("email: " + str);
}
}
});
}

In Unity you must use ParseUser.Query instead of ParseObject.Query when querying users.
https://parse.com/docs/unity_guide#users-querying

And if you can't do what wbdev said (because there is another bug triggered by using generic ParseQuery objects), you can create the non-generic query with new ParseQuery<ParseObject>("_User").

Related

NPOCO 'System.ArgumentException: An item with the same key has already been added.'

I am attempting to use NPoco to Query a stored procedure and retrieve a list of Phone numbers. Below is my code, but my issue is every time dc.QueryStoredProcedure is called I receive an error 'System.ArgumentException: An item with the same key has already been added.'
I have executed the sprocs without fail. I have attempted Google but I'm unable to find anything regarding Npoco and this error message. I'm stumped at this point. I've checked over PhoneNumber object just to be sure there was nothing duplicated.
Any pointers would be greatly appreciated! Thank you.
private List<PhoneNumber> GetPhoneNumberFromDL(int? MemberID, int? MemberIDPhoneNumber)
{
var TheList = new List<PhoneNumber>();
var parameters = new[]
{
new Parameter("MemberID", MemberID),
new Parameter("MemberIDPhoneNumber", MemberIDPhoneNumber)
};
using (var dc = this._DataProvider.AlphaDatabase())
{
var results = dc.QueryStoredProcedure<PhoneNumber>("phone_num_GET", parameters);
TheList.AddRange(results);
return TheList;
}
}
I found the issue. I went back over my PhoneNumber object, which I thought I had looked at previously, but missed a duplicate property. It appears there was an issue with case-sensitivity and the property name 6 years back. I removed the duplicate and it's working fine.

Dynamic LINQ - Entity Framework 6 - Update Records for Dynamic Select

C# rookie. Below is my code, been trying for hours now to get this to update some fields in my DB and tried many different implementations without luck.
// Select all fields to update
using (var db = new Entities())
{
// dbFields are trusted values
var query = db.tblRecords
.Where("id == " + f.id)
.Select("new(" + string.Join(",", dbFields.Keys) + ")");
foreach (var item in query)
{
foreach (PropertyInfo property in query.ElementType.GetProperties())
{
if (dbFields.ContainsKey(property.Name))
{
// Set the value to view in debugger - should be dynamic cast eventually
var value = Convert.ToInt16(dbFields[property.Name]);
property.SetValue(item, value);
// Something like this throws error 'Object does not match target type'
// property.SetValue(query, item);
}
}
}
db.SaveChanges();
}
The above code when run does not result in any changes to the DB. Obviously this code needs a bit of cleanup but i'm trying to get the basic functionality working. I believe what I might need to do is to somehow reapply 'item' back into 'query' but I've had no luck getting that to work no matter what implementation I try i'm always receiving 'Object does not match target type'.
This semi similar issue reaffirms that but isn't very clear to me since i'm using a Dynamic LINQ query and cannot just reference the property names directly. https://stackoverflow.com/a/25898203/3333134
Entity Framework will perform updates for you on entities, not on custom results. Your tblRecords holds many entities, and this is what you want to manipulate if you want Entity Framework to help. Remove your projection (the call to Select) and the query will return the objects directly (with too many columns, yes, but we'll cover that later).
The dynamic update is performed the same way any other dynamic assignment in C# would be, since you got a normal object to work with. Entity Framework will track the changes you make and, upon calling SaveChanges, will generate and execute the corresponding SQL queries.
However, if you want to optimize and stop selecting and creating all the values in memory in the first place, even those that aren't needed, you could also perform the update from memory. If you create an object of the right type by yourself and assign the right ID, you can then use the Attach() method to add it to the current context. From that point on, any changes will be recorded by Entity Framework, and when you call SaveChanges, everything should be sent to the database :
// Select all fields to update
using (var db = new Entities())
{
// Assuming the entity contained in tblRecords is named "ObjRecord"
// Also assuming that the entity has a key named "id"
var objToUpdate = new ObjRecord { id = f.id };
// Any changes made to the object so far won't be considered by EF
// Attach the object to the context
db.tblRecords.Attach(objToUpdate);
// EF now tracks the object, any new changes will be applied
foreach (PropertyInfo property in typeof(ObjRecord).GetProperties())
{
if (dbFields.ContainsKey(property.Name))
{
// Set the value to view in debugger - should be dynamic cast eventually
var value = Convert.ToInt16(dbFields[property.Name]);
property.SetValue(objToUpdate, value);
}
}
// Will only perform an UPDATE query, no SELECT at all
db.SaveChanges();
}
When you do a SELECT NEW ... it selects only specific fields and won't track updates for you. I think if you change your query to be this it will work:
var query = db.tblRecords.Where(x=>x.id == id);

Filtering LINQ Query against member object list

I have an application that I inherited from a coworker that tracks feedback cards. I also have a form that filters the cards that are displayed on a web page based upon a number of user entered filters. All of the filters work fine, except the filter that is applied against feedback details (service was fine/bad, room was clean/dirty, etc). These are stored in list of a member class in my card class.
Below is a set of snippets of each class.
public class Card {
public long ID { get; set; }
public List<Feedback> feedback { get; set; }
...
}
public class Feedback {
public long ID {get; set; }
...
}
public class CardFilter {
public ICollection<long> FeedBackDetails {get; set; }
...
}
...
public IQueryable<CardType > GetFeedbackQueryable<CardType>(CardFilter filter = null)
where CardType : Card
{
var data = Service.GetRepository<CardType>();
var CardQuery = data.All;
...
if (filter.FeedbackDetails != null && filter.FeedbackDetails.Count != 0)
{
cardQuery = cardQuery.Where(card => card.FeedbackValues)
.All(fbv => filter.FeedbackDetails.Contains(fbv.ID));
}
return cardQuery;
}
...
When I try the filter:
cardQuery = cardQuery.Where(card => card.FeedbackValues)
.All(fbv => filter.FeedbackDetails.Contains(fbv.ID));
It returns the 15 card instances without any feedback. If I use the filter:
cardQuery = cardQuery.Where(card => card.FeedbackValues)
.Any(fbv => filter.FeedbackDetails.Contains(fbv.ID));
Nothing is returned, even though I can look through the data and see the appropriate cards.
I'm new to LINQ, so I know I'm missing something. Please point me in the right direction here.
EDIT:
To give a little more background on this application, I'll be a bit more verbose. The Card table/Model has the information about the card and the person submitting it. By that I mean name or anonymous, address, location being commented upon and a few other basic facts. The feedback items are listed in another table and displayed on the web form and the user can check either positive or negative for each. There are three possible answers for each feedback detail; 0 (positive), 1 (negative) or nothing (no answer).
The Card Model has all of the basic card information as well as a collection of feedback responses. My filter that is giving me trouble is against that collection of responses. Each card can have from 0 to 52 possible responses which may not apply to all situations, so I need to see all cards that are about a specific situation (cleanliness, etc.) whether they are positive or negative. That is the purpose of this filter.
You can't use the all statement, the predicate for this statement is if all values are identical to the id.
In your where statement, which is a filter clause, are you not filtering any thing.
And you are comparing feedbackvalues with an id? Are they the same?
Can you post some more details about
Maybe try:
cardQuery = cardQuery.Where(card => filter. FeedbackDetails.Contains(card. Id/detsils))
.Select(se=> se).Tolist() ;
var ifExist = YourList.Any(lambda expression) checking if YourList<T> contains object whitch fulifill lambda expression . It's only return true or false. If you want to have list of objects you should use var YourNewList = YourList.Where(lambda expression).ToList().
Try this. Although I'm not entirely sure about your filter obj.
cardQuery = cardQuery.Query().Select(card => card.FeedbackValues).Where(fbv => filter.FeedbackDetails.Contains(fbv.ID));
I was able to solve this. All of the answers that were posted helped me in the right direction. I wish I could have flagged them all as the answer.
I ended up reworking my Feedback model slightly to include another identity field from the database. It duplicated existing date (bad design, I know. It wasn't mine), but had a unique name. Using the new field, I was able to apply an Any filter. I guess I was confusing LINQ with multiple fields named ID. Once I used FeedbackID, it worked fine.

Entity Framework - Handling a join with no records from join table

I searched vigorously for an answer to this, but I was unable to find (or understand) a solution. I have a query where I am joining to another table that may or may not have associated records. Here is the query:
var educationUniversity = result.new_educationUniversity.Select(c => new
{ c.majorDegree, c.dateEnd, c.dateStart, c.institutionName,
c.degreeProgramCompletionStatus, c.institutionAddress,
attachmentId = c.attachmentId ?? 0,
fileName = c.new_attachments.fileName ?? "No Attachment"}).ToList();
The first table is "new_educationUniversity" and it holds details of a user's college or university degree. The user may or may not have uploaded an attachment (which is stored in the "new_attachments" table). The attchmentID is the primary key in the "new_attachments" table and a foreign key in the "new_educationUniversity" table. EF sees the relationship.
I am binding the results to a repeater but the code fails on the line above if there is no related attachment. Everything works fine if there is an attachment or if I remove the reference to the fileName.
Above, I am handling if the fileName is NULL (or at least I am trying to), but I suspect my issue is that the record simply doesn't exist, which is different from NULL I guess. I've tried using something like: c.new_attachments.fileName.SingleOrDefault() or DefaultIfEmpty() with no luck.
As an analogy, imagine you have a CUSTOMERS table and an ORDERS table. You want to query the following:
-customer last name
-customer first name
-customer most recent order Id
However, you have registered customers who have never purchased anything. I'm sure I am doing something completely noobish, so any assistance is GREATLY appreciated. Thanks!
So you have a few things going on here:
You can get a null reference exception on your reference to c.new_attachments.fileName. If new_attachments is null, then this will throw an exception. Including the null-coalescing operator (the ??) won't help, because you're trying to access the property of something which can be null.
Unless you're lazy-loading (generally bad), then there's no reason for you to be trying to create a dynamically typed object to send to your repeater. Just pass the result.new_educationUniversity object directly.
What's the solution?
I'd create a partial class to add a new property to your new_educationUniversity class. Add a null-reference-safe property reference to determine the file name of the new_attachments property of new_educationUniversity. Then, bind the repeater to your new property. Something like:
public partial class new_educationUniversity {
public String AttachmentFileName {
get {
if (new_attachments == null)
return "";
else
return new_attachments.fileName;
}
}
}
The following line of code seems to be working.
var educationUniversity = result.new_educationUniversity.Select
(c => new { c.majorDegree, c.dateEnd, c.dateStart, c.institutionName,
c.degreeProgramCompletionStatus, c.institutionAddress, attachmentId = c.attachmentId ?? 0,
fileName = (c.new_attachments == null ? "***NO ATTACHMENT***" : c.new_attachments.fileName)}).ToList();
I don't fully understand what this line means:
fileName = (c.new_attachments == null ? "***NO ATTACHMENT***" : c.new_attachments.fileName)}
I assume it says "if nothing is there replace with the string "NO ATTACHMENT" otherwise use what is in the DB"
Is this acceptable? So far, so good. Thanks!

RavenDb store and retrieve class-less objects (json)

I'm writing a application where the user can write json-code and store that json code with an Id and a Collection. In other words, they specify an Id, a Collection (string; [a-zA-Z0-9]) and a Data (json, can be anything that is valid json).
Up til now I've been using RavenDb for this, cause I thought a document-database would be perfect, but I've had some problems with querying.
One of the objects that needs to be stored and queried is the following:
{
"network": "some_network",
"names": ["name1","name2"],
"data": {"values":[],"keys":[]}
}
This object should be stored with some Id that is either specified, or auto-generated (if null is given), and a Collection (must always be specified), and then I need to be able to query it based on Collection, network and a single name.
For instance, I have the code query('users', '{"network":"some_network","names":"name1"}'), and I need that code to return this object (and any other object that matches it).
Also, I'm ok with changing database, but the database needs to be able to run in-process (self-hosted), and to be able to run without admin-rights without installation (in other words, it can't bind to hostname/ip like wcf does).
How can I achieve something like this?
I found the answer to this:
public string Query(string dynIndexName, string query)
{
using (var session = store.OpenSession())
{
var q = new IndexQuery();
q.Query = query;
var result = session.Advanced.DatabaseCommands.Query("dynamic/" + dynIndexName, q, new string[0]);
return "[" + String.Join(",", result.Results.Select(r => r.ToString())) + "]";
}
}
Before calling the Query-method I convert the json-query-object into a Lucene-query that looks like this: (network:"some_network" AND names:"name1"), and use that as a query-parameter to the database. The whole class for storing and retrieving can be found here: https://github.com/Alxandr/RunJS/blob/master/src/AddIns/Storage/StorageMbro.cs

Categories