I am trying to figure out how to obtain the objectId from an query. What i am trying to accomplish is that I want to know if a object with a specific username and password exists in my class and then if yes, get the objectId and save it in my Unity game!
Here is how I am trying to do so with no luck:
void OnClick(){
PrimeAI.ShowSpinner();
LoginUsername = GameObject.Find("UsernameLogin").GetComponent<UIInput>().value;
LoginPassword = GameObject.Find("PasswordLogin").GetComponent<UIInput>().value;
var query = ParseObject.GetQuery("Players")
.WhereEqualTo("playername", LoginUsername)
.WhereEqualTo("password", Constant.Md5Sum(LoginPassword));
query.CountAsync().ContinueWith(t => {
int count = t.Result;
if(count == 1){
GetUserData(LoginUsername);
} else {
LoginError = true;
}
});
}
public void GetUserData(string UserName){
var query = ParseObject.GetQuery("Players")
.WhereEqualTo("playername", UserName);
query.FindAsync().ContinueWith(t => {
IEnumerable<ParseObject> results = t.Result;
OnlyOnce = true;
foreach (var result in results) {
print("Here: "+result["objectId"]);
}
});
}
It works fine until the foreach loop... How can I accomplish this and what am i doing wrong?
Any help is appreciated :-)
Do a Find rather than a CountAsync. Then just access the objectID from the returned object. If you are concerned about moving the whole object when you don't need it, use selectKeys to select only the attributes you want.
-Bob
foreach (var result in results) {
print("Here: "+ result.objectId);
}
Related
My recursive function is
private dynamic FillRecursive(List<AllAccounts> flatObjects, Guid accountID)
{
List<AllAccounts> recursiveObjects = new List<AllAccounts>();
foreach (var item in flatObjects.Where(x => x.ParentID.Equals(accountID)))
{
recursiveObjects.Add(new AllAccounts
{
AccountID = item.AccountID ,
Children = FillRecursive(flatObjects, item.AccountID)
});
}
return recursiveObjects;
}
When I send request to this function from postman it stops the running program in Visual Studio Code. Kindly help me resolve this issue. Thanks
Test if this work
private dynamic FillRecursive(List<AllAccounts> flatObjects, Guid accountID, List<AllAccounts> recursiveObjects=null)
{
if(recursiveObjects==null)
recursiveObjects = new List<AllAccounts>();
foreach (var item in flatObjects.Where(x => x.ParentID.Equals(accountID)))
{
recursiveObjects.Add(new AllAccounts
{
AccountID = item.AccountID ,
Children = FillRecursive(flatObjects, item.AccountID,recursiveObjects)
});
}
return recursiveObjects;
}
Im facing performance issue in below code in multiple foreach loops. First im getting a list of ReturnDetails and then based on detail id get the HandlingInfo object. Then based on value of action, update the ReturnsDetail Object again.
It take more than a minute for loading 3000 records of ReturnsDetail. While debugging locally, it runs for infinite amount of time.
Please let me know in anyway i can refactor this code .
Thanks for your help.
lstReturnsDetail = dcReturnsService.GetReturnDetailsInfo(header_id);
List<HandlingInfo> lstHandlingInfo = null;
foreach (ReturnsDetail oReturnsDetail in lstReturnsDetail)
{
using (DCReturns_Entities entities = new DCReturns_Entities())
{
lstHandlingInfo = entities.HandlingInfoes.Where(f => f.detail_id == oReturnsDetail.id).ToList();
if(lstHandlingInfo != null)
{
foreach (HandlingInfo oHandlingInfo in lstHandlingInfo)
{
if (oHandlingInfo.action == "DST")
{
oReturnsDetail.destroy += Convert.ToInt32(oHandlingInfo.qty);
}
else if (oHandlingInfo.action == "SHP")
{
oReturnsDetail.to_shop += Convert.ToInt32(oHandlingInfo.qty);
}
else if (oHandlingInfo.action == "RBX")
{
oReturnsDetail.in_stock += Convert.ToInt32(oHandlingInfo.qty);
}
}
}
}
oReturnsDetail.received_qty = oReturnsDetail.destroy + oReturnsDetail.to_shop + oReturnsDetail.in_stock;
}
dgReturnsDetail.DataSource = lstReturnsDetail.OrderByDescending(g => g.id).ToList();
Session[DCReturnsConstants.Returns_Detail_Entity] = lstReturnsDetail;
dgReturnsDetail.DataBind();
this is su-do code! but you should get the jist.
//modify this to return all of them into mem, and then filter on this...
//if it can not be done here then do below..
var lstReturnsDetail = dcReturnsService.GetReturnDetailsInfo(header_id);
//then create a list here which fetches all,
List<[type]> somelist
List<int> listId = lstReturnsDetail.select(x=>x.id).tolist();
using (var db = new DCReturns_Entities())
{
somelist = db.HandlingInfoes.Where(f => listId.Contains( f.detail_id)).ToList();
}
foreach (ReturnsDetail oReturnsDetail in lstReturnsDetail)
{
//performance issue is here
//using (DCReturns_Entities entities = new DCReturns_Entities())
//{
// lstHandlingInfo = entities.HandlingInfoes.Where(f => f.detail_id == oReturnsDetail.id).ToList();
//}
//insead fetach all before, into mem and filter from that list.
var lstHandlingInfo = somelist.Where(f => f.detail_id == oReturnsDetail.id).ToList();
//code ommited for reaablity
}
//code ommited for reaablity
Good day, I've been fiddling around with the Eventlog method, and with fiddling around I was able to count how many entry.replacementstrings[5] aka usernames would be there.
public int countUsers { get; set; }
public string User { get; set; }
public Users(int count, string name)
{
countUsers = count;
User = name;
}
public void getCountUsers()
{
number = 0; //
UserList = new ObservableCollection<Users>();
EventLog myNewLog = new EventLog();
myNewLog.Log = "Security";
foreach (EventLogEntry entry in myNewLog.Entries)
{
if (entry.InstanceId == 4624 && entry.TimeWritten.Date == DateTime.Today)
{
if (UserList.Count > 0)
{
bool check = false;
foreach (var user in UserList)
{
if (user.User == entry.ReplacementStrings[5])
{
user.countUsers += 1;
check = true;
}
}
if (!check)
{
Users u = new Users(1, entry.ReplacementStrings[5]);
UserList.Add(u);
}
}
else
{
Users u = new Users(1, entry.ReplacementStrings[5]);
UserList = new ObservableCollection<Users>();
UserList.Add(u);
}
}
}
}
public void counter()
{
var totalUsers = UserList.Sum(user => user.countUsers);
foreach (var user in UserList)
{
Console.WriteLine("There has been {0} users on {1}", user.countUsers, DateTime.Today.ToShortDateString());
}
}
Is what I currently have. What I now want to be able to do is, add a regex to the writeline so it doesn't count the user SYSTEM.
I was able to do it with but that would print out every individual user, but instead I want the general/global idea of how many people were online at said date.
So I need to know how to do it with getting rid of the for each loop, and just getting the user.countUsers.
foreach (var user in UserList)
{
Regex User = new Regex(#"SYSTEM");
Match match = User.Match(user.User);
if (!match.Success)
{}
}
I now don't know how to call the variable so my regex works. Anyone know how to fix it, maybe possibly without a regex?
(Side note: I also need help with the fact that the EventLog is 2x, when it should be 1 by the ones that are legit. I would need to see how I would filter that)
You don't need to use Regex since the string you want to exclude is literal, you can use Linq:
foreach (var user in UserList.Where(u => u.User != "SYSTEM"))
{
Console.WriteLine("There has been {0} users on {1}", user.countUsers, DateTime.Today.ToShortDateString());
}
I am fairly new to Parse and are trying to switch to parse from an php/mysql solution. I am making a multiplayer game with Unity3D in which you can play one on one. My issue concerns the game menu. One game consists of 3 objects. 1 main game object (class:Games) and then 2 player objects (class:GamePlayers). These 2 objects have 2 different references/relations to other objects. 1 to the gameObjectId and one to the playerObjectId (class:Players). I have not used the pointer or relation for this course I am not sure how to use them?
Now, to get all the games a player is involved in I call the GamePlayers class to find all objects in which the current players objectId is.
void getGames(string playerObjectId){
var query = ParseObject.GetQuery("GamePlayers")
.WhereEqualTo("playerObjectId", playerObjectId);
query.FindAsync().ContinueWith(t => {
if (t.IsFaulted){
} else {
IEnumerable<ParseObject> results = t.Result;
foreach (var result in results) {
getGameData(result.Get<string>("gameObjectId"), playerObjectId, result.Get<string>("playerTiles"), result.Get<int>("playerTurn"));
}
}
});
}
From this I call another method (getGameData) in which I would like to get the game data and opponent game data for each game.
void getGameData(string gameObjectId, string playerObjectId, string playertiles, int playerTurn){
string bagtiles = "";
string tabletiles = "";
string newtiles = "";
int lastdraw = 0;
int sqlid = 0;
string oppObjectId = "";
string oppDataReturn = "";
var query = ParseObject.GetQuery("Games")
.WhereEqualTo("objectId", gameObjectId);
query.FindAsync().ContinueWith(t => {
if (t.IsFaulted){
} else {
IEnumerable<ParseObject> results = t.Result;
foreach (var result in results) {
bagtiles = result.Get<string>("bagtiles");
tabletiles = result.Get<string>("tabletiles");
newtiles = result.Get<string>("newtiles");
sqlid = result.Get<int>("sqlId");
}
}
});
query = ParseObject.GetQuery("GamePlayers")
.WhereEqualTo("gameObjectId", gameObjectId)
.WhereNotEqualTo("playerObjectId", playerObjectId);
query.FindAsync().ContinueWith(t => {
if (t.IsFaulted){
} else {
IEnumerable<ParseObject> results = t.Result;
foreach (var result in results) {
oppObjectId = result.Get<string>("playerObjectId");
lastdraw = result.Get<int>("lastDraw");
}
}
});
}
Now, all I am missing is the opponents playerdata e.g. username etc.
var query = ParseObject.GetQuery("Players")
.WhereEqualTo("objectId", oppObjectId);
query.FindAsync().ContinueWith(t => {
if (t.IsFaulted){
} else {
IEnumerable<ParseObject> results = t.Result;
foreach (var result in results) {
oppName = result.Get<string>("username");
}
}
});
I though about running yet another method but it seems like this could be done more effectually and maybe in one query?!?
At the end I add each game to my gamelist like so:
if(playerTurn == 0){
myturn.Add(gameObjectId+"^"+sqlid+"^"+bagtiles+"^"+tabletiles+"^"+newtiles+"^"+playertiles+"^"+lastdraw+"^"+oppObjectId);
} else if(playerTurn == 1){
theirturn.Add(gameObjectId+"^"+sqlid+"^"+bagtiles+"^"+tabletiles+"^"+newtiles+"^"+playertiles+"^"+lastdraw+"^"+oppObjectId);
} else if(playerTurn > 1){
finnished.Add(gameObjectId+"^"+sqlid+"^"+bagtiles+"^"+tabletiles+"^"+newtiles+"^"+playertiles+"^"+lastdraw+"^"+oppObjectId);
}
Hope this makes sense and somebody can guide me in the right direction. I am not an expert in C# but am learning ;-)
Thanks in advance :-)
Details
I have 2 tables (Procedures, Surgeons) with a lookup table (ProcSurg) to create a many to many relationship.
scar_Requests scar_Procedures scar_ProcSurg scar_Surgeons
------------- --------------- ------------- -------------
RequestID <> ProcedureID <> ProcedureID(fk) <> SurgeonID
... RequestID SurgeonID(fk) ...
...
A single request can have multiple procedures and each procedure can have multiple surgeons.
Everything saves correctly until I have 2 procedures each that share the same Surgeon.
Error: InvalidOperationException was unhandled
The relationship between the two objects cannot be defined because they are attached to different ObjectContext objects.
I separated out the code for saving this part of the record to try to isolate my problem..
Addprocedures is a class that contains 1 Procedure and a list of Surgeons
class Procedure
{
public scar_Procedures Procedure { get; set; }
public List<scar_Surgeons> Surgeons { get; set; }
public void RemoveSurgeon(int SurgeonID)
{
Surgeons.Remove(Surgeons.Where(x => x.SurgeonID == SurgeonID).FirstOrDefault());
}
public Procedure()
{
Surgeons = new List<scar_Surgeons>();
}
}
Saving code: using DBContext
private void SaveProcSurg()
{
using (MCASURGContext db2 = new MCASURGContext())
{
foreach (Procedure p in AddProcedures)
{
if (p.Procedure.RequestID == 0)
{
p.Procedure.RequestID = ReqID;
}
p.Procedure.scar_Surgeons.Clear();
foreach (scar_Surgeons s in p.Surgeons)
{
if (db2.ChangeTracker.Entries<scar_Surgeons>().Where(x => x.Entity.SurgeonID == s.SurgeonID).FirstOrDefault() == null)
{
db2.scar_Surgeons.Attach(s);
}
p.Procedure.scar_Surgeons.Add(s);
}
if (p.Procedure.ProcedureID == 0)
{
db2.scar_Procedures.Add(p.Procedure);
db2.Entry(p.Procedure).State = System.Data.Entity.EntityState.Added;
}
else
{
db2.scar_Procedures.Attach(p.Procedure);
db2.Entry(p.Procedure).State = System.Data.Entity.EntityState.Modified;
}
}
db2.SaveChanges();
}
}
I've tried several different ways of saving the record and this is the closest I've come to doing it correctly.
I feel like it has something to do with the way I'm attaching the surgeons to the entity and then to the procedure. Any help, idea's or suggestions on where I can find an answer would be great!
I've been searching google endlessly for over a week and I've been trying to wrap my mind around what exactly Entity Framework is doing but I'm still pretty new to this.
Edited 9/24/2013
Sorry this is the complete code snippet from the comments section with the req variable included
//Internal variable
private scar_Requests req;
private List<Procedure> AddProcedures = new List<Procedure>();
//Gets a scar_Request from the DB
private void GetRequest()
{
using (MCASURGContext db = new MCASURGContext())
{
req = db.scar_Requests.Include("scar_Procedures.scar_Surgeons").Include("scar_Status").Include("scar_Users.scar_Service").Where(x => x.RequestID == ReqID).FirstOrDefault();
foreach (scar_Procedures p in req.scar_Procedures) { AddProcedures.Add(new Procedure() { Proc = p, Surgeons = p.scar_Surgeons.ToList() }); }
}
}
Keeping with good form I'll post my answer since I think I figured it out. Maybe it will help someone in the future.
I completely re-wrote the saving and cut out a lot of useless code that I was using before and less calls to the DB. There was other methods that I didn't post above that saved other parts of the record that I condensed into a single method.
Basically I get the record and its joined tables from the DB and iterate through all the fields/joined tables that need to be updated and save it back to the DB. (Seems super obvious now but I tried this way before and I must have had something wrong because it didn't work the first few times I tried it this way.)
I don't know if its 100% correct or written up to normal coding standards and I still have some final tweaking to do before its completely done.
private void SaveProcSurg()
{
using (MCASURGContext db2 = new MCASURGContext())
{
//Get Record from DB
scar_Requests sReq = db2.scar_Requests.Include("scar_Users").Include("scar_Status").Include("scar_Procedures.scar_Surgeons").Where(x => x.RequestID == ReqID).FirstOrDefault();
//Update Record fields
sReq.CreationDate = req.CreationDate == null ? DateTime.Now : req.CreationDate = req.CreationDate;
sReq.DateOfSurgery = dtpDateOfSurgery.Value;
sReq.IsDeleted = false;
sReq.IsScheduled = false;
sReq.LatexAllergy = cbLatexAllergy.Checked;
sReq.ModifiedDate = DateTime.Now;
sReq.MRN = txtMRN.Text;
sReq.PatientName = txtPatientName.Text;
foreach (RadioButton rb in gbPatientType.Controls) if (rb.Checked == true) sReq.PatientType = rb.Text;
sReq.PreOpDiagnosis = txtPreOpDiag.Text;
sReq.PrimarySurgeon = txtPrimarySurgeon.Text;
sReq.PrivateComment = txtPrivateComment.Text;
sReq.PublicComment = txtPublicComment.Text;
sReq.RequestID = ReqID;
sReq.StatusID = req.StatusID;
sReq.UserID = req.UserID;
//Update Users/Status
sReq.scar_Users = db2.scar_Users.Where(x => x.UserID == sReq.UserID).FirstOrDefault();
sReq.scar_Status = db2.scar_Status.Where(x => x.StatusID == req.StatusID).FirstOrDefault();
//Attach to DBContext
db2.scar_Requests.Attach(sReq);
//Update Procedures
foreach (Procedure p in AddProcedures)
{
scar_Procedures pro = sReq.scar_Procedures.Where(x => x.ProcedureID == p.Proc.ProcedureID && p.Proc.ProcedureID != 0).FirstOrDefault();
if (pro != null)
{
pro.EnRecovery = p.Proc.EnRecovery;
pro.IsPrimary = p.Proc.IsPrimary;
pro.Laterality = p.Proc.Laterality;
pro.OrthoFastTrack = p.Proc.OrthoFastTrack;
pro.ProcedureID = p.Proc.ProcedureID;
pro.ProcedureText = p.Proc.ProcedureText;
pro.RequestID = ReqID;
pro.Site = p.Proc.Site;
}
else
{
pro = new scar_Procedures();
pro.EnRecovery = p.Proc.EnRecovery;
pro.IsPrimary = p.Proc.IsPrimary;
pro.Laterality = p.Proc.Laterality;
pro.OrthoFastTrack = p.Proc.OrthoFastTrack;
pro.ProcedureID = p.Proc.ProcedureID;
pro.ProcedureText = p.Proc.ProcedureText;
pro.RequestID = ReqID;
pro.Site = p.Proc.Site; ;
pro.scar_Requests = sReq;
}
//Update Surgeons
pro.scar_Surgeons.Clear();
foreach (scar_Surgeons s in p.Surgeons)
{
pro.scar_Surgeons.Add(db2.scar_Surgeons.Where(x=> x.SurgeonID == s.SurgeonID).FirstOrDefault());
}
}
//Set State and Save
db2.Entry(sReq).State = System.Data.Entity.EntityState.Modified;
db2.SaveChanges();
}
}