Child Node set to 0 - c#

I am encountering a weird issue that I am not sure how to resolve. The issue I am encountering is when I update a single node in the firebase realtime database, another node that has an integer value is also updated and set to 0.
.
I also tried the following approach in my User Class so that the child node does not update when targeting other values. This does work when updating other values and the age value in the realtime database. However, when I attempt to upload a new user, the child node age is not uploaded to the realtime database.
public int? age;
The following code is my approach to update the realtime database using JSON.Net.
public static void UpdateUserInfo(string userId, string nodeUpdate, string valueUpte, UpdateUserInfoCallback callback)
{
User user = new User();
user.email = valueUpte;
string json = JsonConvert.SerializeObject(user, Newtonsoft.Json.Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Debug.Log("UpdateUserInfo Method");
var updateRequest = new RequestHelper {
Uri = $"{databaseURL}users/{userId}.json",
Method = "PATCH",
ContentType = "application/json-path+json"
};
updateRequest.BodyString = json;
RestClient.Request(updateRequest).Then(response => {
EditorUtility.DisplayDialog("Status", response.StatusCode.ToString(), "Ok");
}).Catch(err =>
{
var error = err as RequestException;
EditorUtility.DisplayDialog("Error Response", error.Response, "Ok");
});
}
Also here is my user class:
[Serializable] // This makes the class able to be serialized into a JSON
public class User
{
public string name;
public string userName;
public string team;
public string pswrd;
public string email;
public string birthDate;
public int age;
public User(string name, string userName, string team, string pswrd, string email, string birthDate, int age)
{
this.name = name;
this.userName = userName;
this.team = team;
this.pswrd = pswrd;
this.email = email;
this.birthDate = birthDate;
this.age = age;
}
public User(){
}
}
Is there a better approach? Or am I missing something that needs to be added? Any help would be appreciated.

Related

Checking if an object is on the list I created [duplicate]

This question already has answers here:
how to check if List<T> element contains an item with a Particular Property Value
(7 answers)
Closed 1 year ago.
I am making a code that registers a number of parameters and then checks if these parameters are already in the list, in the case, for example, I want to check if an Email is in this list, how can I do this check?
List<Professional> lprofessional = new List<Professional>();
public int role_id = 1;
public string First_name { get; set; }
public string Last_name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Description { get; set; }
public Professional(int role_id, string firstname, string lastname, string email, string phone, string description) {
this.First_name = firstname;
this.Last_name = lastname;
this.Email = email;
this.Phone = phone;
this.Description = description;
}
public void Create()
{
Professional pro = new Professional(role_id, First_name, Last_name, Email, Phone, Description);
if (lprofessional.Contains(email)//Here is the check maybe...
{
lprofessional.Add(pro);
role_id++;
}
}
if (lprofessional.Any(p => p.Email == email))
{
// already in the list
}
else
{
// not yet in the list
}
Alternatively:
var p = lprofessional.FirstOrDefault(p => p.Email == email);
if (p is object)
{
//already in the list, and you can use "p" to see or change other properties
}
else
{
// not in the list
}
I know there are also newer options using pattern matching to do this in even less code, but I've not yet incorporated pattern matching into my own workflow.
var email = "test#test.com";
var listElement = lprofessional.Where(x=> x.Email.Equals(email)).FirstOrDefault();
if(listElement != null)
{
//some code
}
or
var email = "test#test.com";
var result = lprofessional.Any(x => x.Email.Equals(email));
if( result)
{
//some code here
}

RawJsonValues in Unity & Firebase

Some problems with the SetRawJsonValueAsync. When I use the code from documentation:
public class User
{
public string username;
public string email;
public User()
{
}
public User(string username, string email)
{
this.username = username;
this.email = email;
}
}
private void writeNewUser(string userId, string name, string email)
{
User user = new User(name, email);
string json = JsonUtility.ToJson(user);
mDatabaseRef.Child("users").Child(userId).SetRawJsonValueAsync(json);
}
Then firebase automatically converts it to the tree of values. Ok. But when i'm trying to get them back:
public void get_data()
{
mDatabaseRef.Child("users").Child(userId).GetValueAsync().ContinueWithOnMainThread(task => {
if (task.IsCompleted)
{
Debug.Log("completed");
string json = task.Result.Value;
User user = JsonUtility.FromJson<User>(json);
Debug.Log(user.username);
}
});
}
it stops and doesn't print username. Why? Or how i need to get json raws?
The issue here is task.Result.Value is a C# interpretation of the value in the database. I believe it should be a IDictionary<string, object> given the code that you posted.
What you want is task.Result.GetRawJsonValue():
public void get_data()
{
mDatabaseRef.Child("users").Child(userId).GetValueAsync().ContinueWithOnMainThread(task => {
if (task.IsCompleted)
{
Debug.Log("completed");
string json = task.Result.GetRawJsonValue();
User user = JsonUtility.FromJson<User>(json);
Debug.Log(user.username);
}
});
}

How to create register and log in form with XML in C#?

New to coding!
How can I get my register form to add the user's details instead of rewriting them everytime? And how can I get my log in form to loop through the XML file to find a matching username and password?
The code that I have does 2 things:
It rewrites the XML file instead of updating it.
It duplicates data.
Here is my User class:
public class User
{
public string fname;
public string lname;
public string username;
public string password;
public string Fname
{
get { return fname; }
set { fname = value; }
}
public string Lname
{
get { return lname; }
set {lname = value; }
}
public string Username
{
get { return username; }
set { username = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
public User() { }
public User (string fname, string lname, string username, string password)
{
this.fname = fname;
this.lname = lname;
this.username = username;
this.password = password;
}
}
Here is the sign up form code:
public partial class sign_up_form : Form
{
public sign_up_form()
{
InitializeComponent();
}
private void btn_create_Click(object sender, EventArgs e)
{
User users = new User();
users.fname = txt_fname.Text;
users.lname = txt_lname.Text;
users.username = txt_username.Text;
users.password = txt_password.Text;
XmlSerializer xs = new XmlSerializer(typeof(User));
using(FileStream fs = new FileStream("Data.xml", FileMode.Create))
{
xs.Serialize(fs, users);
}
}
}
This is the XML file:
<?xml version="1.0"?>
-<User xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<fname>asdf</fname>
<lname>asdf</lname>
<username>asdf</username>
<password>asdf</password>
<Fname>asdf</Fname>
<Lname>asdf</Lname>
<Username>asdf</Username>
<Password>asdf</Password>
</User>
I do not have any code for the log in form but it only has 2 text boxes (user and pass) and a log in button.
Any advice is appreciated.

Linq Query Filed

I am to get List user by using Linq query. I have local to encrypt the user password but when initialized local class filed to entity model class field, it's showing the following error ...
cannot convert from 'HalifaxWCFProject.PasswordEncrypt.UserLogin' to 'HalifaxWCFProject.HalifaxDatabaseEntities' HalifaxWCFProjet
Here is my Local Class.
[DataContract]
public class UserLogin
{
string id;
string username;
string password;
string email;
[DataMember]
public string Id
{
get { return id; }
set { id = value; }
}
[DataMember]
public string Username
{
get { return username; }
set { username = value; }
}
[DataMember]
public string Password
{
get { return password; }
set { password = value; }
}
[DataMember]
public string Email
{
get { return email; }
set { email = value; }
}
}
}
Here is the Method ..
[OperationContract]
[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/GetAllStudent/")]
List<UserLogin> GetAllStudent();
Here is Implementation of the method .
public List<UserLogin> GetAllStudent()
{
var query = (from a in ctx.tblUsers
select a).Distinct();
List<HalifaxDatabaseEntities> userList = new List<HalifaxDatabaseEntities>();
query.ToList().ForEach(rec =>
{
userList.Add( new UserLogin
{
Id =Convert.ToString(rec.Id),
Username = rec.Username,
Password = rec.Password,//Error on this line
Email = rec.Email
});
});
return userList;
}
}
What is the solution. Any help would be appreciated.
You have incorrectly declared your variable type for the userList variable. Make life easier (and your code more readable) by just using the var keyword.
However, better yet for readability reasons, use a Select to create your new types.
var query = (from a in ctx.tblUsers select a).Distinct();
var result = query.Select(rec => new UserLogin
{
Id = Convert.ToString(rec.Id),
Username = rec.Username,
Password = rec.Password,
Email = rec.Email
});
return result.ToList();
You could collapse it further too if you want by not even bothering with the query and result variables.
Also, the Distinct seems like it wouldn't make a difference here since you're already selecting from a single table.
This line:
List<HalifaxDatabaseEntities> userList = new List<HalifaxDatabaseEntities>();
needs to be:
List<UserLogin> userList = new List<UserLogin>();

How do I manipulate an object's properties after it has been added to a List in C#

Say I have a class like this:
class public Person
{
public string firstName;
public string lastName;
public string address;
public string city;
public string state;
public string zip;
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
And let's further say I create a List of type Person like this:
List<Person> pList = new List<Person>;
pList.Add(new Person("Joe", "Smith");
Now, I want to set the address, city, state, and zip for Joe Smith, but I have already added the object to the list. So, how do I set these member variables, after the object has been added to the list?
Thank you.
You get the item back out of the list and then set it:
pList[0].address = "123 Main St.";
You can keep a reference to your object around. Try adding like this:
List<Person> pList = new List<Person>;
Person p = new Person("Joe", "Smith");
pList.Add(p);
p.address = "Test";
Alternatively you can access it directly through the list.
pList[0].address = "Test";
You can get the first item of the list like so:
Person p = pList[0]; or Person p = pList.First();
Then you can modify it as you wish:
p.firstName = "Jesse";
Also, I would recommend using automatic properties:
class public Person
{
public string firstName { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zip { get; set; }
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
You'll get the same result, but the day that you'll want to verify the input or change the way that you set items, it will be much simpler:
class public Person
{
private const int ZIP_CODE_LENGTH = 6;
public string firstName { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public string city { get; set; }
public string state { get; set; }
private string zip_ = null;
public string zip
{
get { return zip_; }
set
{
if (value.Length != ZIP_CODE_LENGTH ) throw new Exception("Invalid zip code.");
zip_ = value;
}
}
public Person(string firstName, string lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
}
Quite possibly not the best decision to just crash when you set a property here, but you get the general idea of being able to quickly change how an object is set, without having to call a SetZipCode(...); function everywhere. Here is all the magic of encapsulation an OOP.
You can access the item through it's index. If you want to find the last item added then you can use the length - 1 of your list:
List<Person> pList = new List<Person>;
// add a bunch of other items....
// ....
pList.Add(new Person("Joe", "Smith");
pList[pList.Length - 1].address = "....";
Should you have lost track of the element you're looking for in your list, you can always use LINQ to find the element again:
pList.First(person=>person.firstName == "John").lastName = "Doe";
Or if you need to relocate all "Doe"s at once, you can do:
foreach (Person person in pList.Where(p=>p.lastName == "Doe"))
{
person.address = "Niflheim";
}

Categories