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);
}
});
}
Related
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.
I have this class:
public class Userinfo
{
public Userinfo()
{
}
public static async Task<List<Information>> Login(string Username, string Password)
{
string str = "https://somesite.com/log.php";
string[] cID = new string[] { "act=qwjFpPXuGexZBHDJEreZrAUH&CID=", "&username=", Username, "&password=", Password };
string str1 = string.Concat(cID);
using (WebClient webClient = new WebClient())
{
webClient.Proxy = null;
webClient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string str2 = webClient.UploadString(str, str1)
var result = JsonConvert.DeserializeObject<List<Information>>(str2);
return result;
}
}
}
Which returns this JSON
[{"username":"fakeuser","email":"fakeemail#outlook.com","plan":"1","activationdate":"18\/12\/20","terminationdate":"18\/01\/21"}]
What I want to do is set in another form the data inside the result variable in labels so they can display the actual content. The problem is that if I debug the code the variable seems to be empty. If I make a break and hover the mouse over the variable it doesn't show anything and it doesn't even appear on the variable list. So, what am I doing wrong?
This is the code I have in the form where I have the labels:
private async void Filldata()
{
var result = await Userinfo.Login("username", "password");
label11.Text = result.Select(x => x.username).FirstOrDefault();
label18.Text = result.Select(x => x.email).FirstOrDefault();
label19.Text = result.Select(x => x.plan).FirstOrDefault();
label20.Text = result.Select(x => x.activationdate).FirstOrDefault();
label21.Text = result.Select(x => x.terminationdate).FirstOrDefault();
}
And here is my class where I deserialize the JSON:
public class Information
{
public string username { get; set; }
public string email { get; set; }
public string plan { get; set; }
public string activationdate { get; set; }
public string terminationdate { get; set; }
}
I think it's worth mentioning that the classes are separate. Userinfo and Information are their own classes.
What am I missing and how can I solve this?
Posted again because I haven't been able to solve this.
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.
I have two pages. The first page is a registration page where the user creates a user name and password. The second page is a log in page, where the user enters their user name and password. I want to validate that the two match, on the front-end. I stored the user name and password in a session and am not using a database. This isn't working and I'm unsure why:
protected void Button1_Click(object sender, EventArgs e)
{
List<Information> downloadList = (List<Information>)Session["DownloadList"];
foreach (Information obj1 in downloadList)
{
newName = String.Format("{0}", obj1.name);
newPassword = String.Format("{0}", obj1.email);
}
if(newName != TextBoxUserNameMatch.Text)
{
LabelLoginError.Text = "You Must Enter the Correct User Name";
}
else if(newPassword != TextBoxPasswordMatch.Text)
{
LabelLoginError.Text = "You Must Enter the Correct Password";
}
else
{
Response.Redirect("DownloadPage.aspx");
}
}
Can anyone tell me where I'm going wrong here? Here is the class information:
public class Information
{
public String name { get; set; }
public String email { get; set; }
public String phone { get; set; }
public String zip { get; set; }
public String state { get; set; }
public String login { get; set; }
public String password { get; set; }
public String reenter { get; set; }
public Information(String name, String email, String phone, String zip, String state, String login, String password, String reenter)
{
this.name = name;
this.email = email;
this.phone = phone;
this.zip = zip;
this.state = state;
this.login = login;
this.password = password;
this.reenter = reenter;
}
}
Here is the code behind my Registration page:
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack)
{
Information download1 = new Information("", "", "", "", "", "", "", "");
Session["Info1"] = download1;
DropDownListState.Items.Add(download1.name);
}
}
protected void ButtonRegister_Click(object sender, EventArgs e)
{
String name = TextBoxName.Text;
String email = TextBoxEmail.Text;
String phone = TextBoxPhone.Text;
String zip = TextBoxZip.Text;
String state = DropDownListState.SelectedItem.Text;
String login = TextBoxLogIn.Text;
String password = TextBoxPassword.Text;
String reenter = TextBoxReenter.Text;
if(Session["DownloadList"] == null)
{
List<Information> downloadList = new List<Information>();
Session["DownloadList"] = downloadList;
}
Information obj1 = new Information(name, email, phone, zip, state, login, password, reenter);
List<Information> downloadList2 = (List<Information>)Session["DownloadList"];
downloadList2.Add(obj1);
Session["DownloadList"] = downloadList2;
Response.Redirect("Confirmation.aspx");
I believe these parts are working correctly because on my final page I have it printing out the user's name and email and that is working correctly.
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>();