Linq Query Filed - c#

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>();

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
}

Child Node set to 0

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.

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 convert object's properties as list elements

I am trying to get all data from DB and display it in a table using ajax and stored procedure.
public List<string> ShowDetailsFromDB()
{
using (adoHelper = new AdoHelper(connectionString))
{
List<string> users = new List<string>();
string procedureName = "GetDetails";
SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
while (dataReader.Read())
{
User user = new User();
user.userId = dataReader[1] as string;
user.password = dataReader[2] as string;
user.userName = dataReader[3] as string;
user.address = dataReader[4] as string;
user.email = dataReader[5] as string;
user.phone = dataReader[6] as string;
//here I want to assign each object property as list element
}
return users;
}
}
Below are two ways to generate a list of strings from the properties of a User instance.
internal class User
{
public string userId { get; set; }
public string password { get; set; }
public string userName { get; set; }
public string address { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string[] GetProperties()
{
return new string[]
{
userId,
password,
userName,
address,
email,
phone
};
}
static PropertyInfo[] properties = typeof(User).GetProperties();
public string[] GetPropertiesAuto()
{
return properties.Select((prop) => prop.GetValue(this) as string).ToArray();
}
}
The above can be used in your code quite simply, although you have to return a list of string array to get all the properties for all the users.
static public List<string[]> ShowDetailsFromDB()
{
using (var adoHelper = new AdoHelper(connectionString))
{
List<string[]> users = new List<string[]>();
string procedureName = "GetDetails";
SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
while (dataReader.Read())
{
var user = new User
{
userId = dataReader[1] as string,
password = dataReader[2] as string,
userName = dataReader[3] as string,
address = dataReader[4] as string,
email = dataReader[5] as string,
phone = dataReader[6] as string
};
//here I want to assign each object property as list element
users.Add(user.GetPropertiesAuto());
}
return users;
}
}
You can do it easy using a List of Users.
public class User
{
public string userId { get; set; }
}
public List<User> ShowDetailsFromDB()
{
using (adoHelper = new AdoHelper(connectionString))
{
List<User> users = new List<User>();
string procedureName = "GetDetails";
SqlDataReader dataReader = adoHelper.ExecuteDataReaderByProcedure(procedureName);
while (dataReader.Read())
{
User user = new User
{
userId = dataReader[1] as string
};
users.Add(user);
//here I want to assign each object property as list element
}
return users;
}
}
Please tell me if it works

SQLiteConnection Query

I'm trying to select data from Database using SQLiteConnection. It's an UWP application.
public class ResumeModel
{
public List<User> Users { get; set; } = new List<User>();
public ResumeModel()
{
using (var connection = new SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), App.path))
{
try
{
object query = connection.Query<User>("Select * From User", null);
if(query != null)
{
Users = (List <User>) query;
}
} catch(Exception ex)
{
Debug.Write(ex.ToString());
}
}
}
}
I'm getting the exception: "Object reference not set to an instance of an object"
Here is my User class:
public class User
{
[SQLite.Net.Attributes.PrimaryKey, SQLite.Net.Attributes.AutoIncrement]
public int userID { get; set; }
public String username { get; set; }
public User()
{ }
public User(int userID, string name)
{
this.userID = userID;
this.username = name;
}
}
Does anyone know what I'm doing wrong?
Thanks
You are not bringing single User. You are selecting "*".
Also you are not passing any parameters. So Instead of Null remove that altogether.
I also see you are checking if query != null you don't have to do that. If there is no data, you will receive count as 0
So your query should be
List<User> query = connection.Query<User>("Select * From User");
Try storing your userID entries and your username entries into seperate, but index related lists. Then loop through and initialize a User object for each of the entries of these two lists as your constructor parameters.
List<int> userIDs = connection.Query<int>("Select userID From User order by userIDs");
List<string> userNames = connection.Query<string>("Select userName From User order by userIDs");
List<User> Users = new List<User>();
for (int i = 0; i < userIDs.Count(); i++)
{
User addition = new User(userIDs[i], userNames[i]);
Users.add(addition);
}
The order by clause is to ensure the indexes of the two queries match.

Categories