SQLite net with linq on Windows Phone 8.1 - c#

Suppose I have following table:
public class User
{
public User()
{
}
public User(string name, string pass)
{
addUser(name, pass);
}
public void addUser(string name, string pass)
{
//todo cryptography
this.login = name;
this.password = pass;
}
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
[Unique, MaxLength(20)]
public string login { get; set; }
[MaxLength(20)]
private string password { get; set; }
public string group { get; set; }
}
I have unique keyword in login field. If I add another person with same login, exception will be thrown or this insert command will be skiped?
What is a best way to get user name from User table?
To get all users depending on some name condition I use this example function for my test purpose.
public async void GetRow(string name)
{
var query = dbConnection.Table<User>().Where(x => x.login.Contains(name));
var result = await query.ToListAsync();
foreach (var item in result)
{
User u = item as User;
MessageDialog msgbox = new MessageDialog(u.login);
await msgbox.ShowAsync();
}
}
Suppose I want to get only 1 record from Users table based on a given name, what would be best way to do that.
I tried something like this:
from u in dbConection.Table<User> select u.Login where u.Login = name;
How to return from GetRow function described in 2 question user password? I can recieve only list of items, I search on the web and I find FirstOrDefault function but is there any better way to do it?
Edit:
ad 1. Throws exception
ad 2.This works only if record exists in table, in other case throws exception
var query = (from s in dbConnection.Table<User>() where s.login == name && s.password == password select s).FirstAsync();
User qr = query.Result;

I find solution. This is a simple validation function. Thank You for Your help.
try
{
var query = (from s in dbConnection.Table<User>() where s.login == name && s.password == password select s).FirstAsync();
User x = await query;
if (x != null) return true;
else return false;
}
catch (Exception)
{
return false;
}

var some_strings = new List<string> {"Szcz","epan"};
string first_string = some_strings.FirstOrDefault();
//first_string = "szcz";
some_strings = new List<string>();
first_string = some_strings.FirstOrDefault();
//first_string = null;
if (first_string != null)
// do your stuff here.
if you were dealing with Int's, then the default would have been zero. IF it's a custom class, it'll be whatever your default for the class is.

Related

Get all keys from combination of JArray and JObject

I'm new to JSON and looked at all the possible answers, but still not able to get it. Basically I'm getting the list of all users and storing it as string. Below is the result Json output string.
[{"Links":[],"RequestedObject":{"Id":181,"DisplayName":"User, Migration","FirstName":"Migration","MiddleName":null,"LastName":"User","LastLoginDate":"2008-01-10T11:04:00","UserName":"1564134","AccountStatus":2,"DomainId":null,"UpdateInformation":{"CreateDate":"2008-01-10T17:04:24.72","UpdateDate":"2011-10-07T16:35:51.74","CreateLogin":2,"UpdateLogin":2}},"IsSuccessful":true,"ValidationMessages":[]},{"Links":[],"RequestedObject":{"Id":16167,"DisplayName":"Xyz, Abc","FirstName":"Abc","MiddleName":null,"LastName":"Xyz","LastLoginDate":"2022-03-04T15:54:29.43","UserName":"1514834","AccountStatus":1,"DomainId":null,"UpdateInformation":{"CreateDate":"2022-03-04T15:53:14.817","UpdateDate":"2022-03-04T15:54:29.293","CreateLogin":14760,"UpdateLogin":11743}},"IsSuccessful":true,"ValidationMessages":[]}]
As you can see first part is JArray and then Jobject. My requirement is to get all "RequestedObject" that have "CreateDate" greater than or equal to CurrentDate. Is there a simple way to achieve this using linq instead of foreach loop. Here is code that I was able to put in from all other answers.
try
{
string text = System.IO.File.ReadAllText(#"H:\Test.txt");
DateTime previousRunTime = new DateTime(2022, 01, 31);
JArray jsonArray = JArray.Parse(text);
var jsonObjects = jsonArray.OfType<JObject>().ToList();
//var users1 = from item in jsonObjects.Children()["RequestedObject"].Value<string>()
// select item;
var abc = jsonObjects.Properties().Where(p => p.Name == "RequestedObject").Select(p => p.Value);
foreach(var q in abc)
{
Console.WriteLine(q.Value<string>("Id").ToString());
}
}
catch (Exception p)
{
Console.WriteLine(p.Message);
}
Looking for solution something like below
var users =
from item in jsonObjects["RequestedObject"]
where item["UpdateInformation"]["CreateDate"].Value<DateTime>() >= previousRunTime
select new UserDetails
{
UserName = item["UserName"].Value<string>(),
UserID = item["Id"].Value<string>(),
};
public class UserDetails
{
public string UserName { get; set; }
public string UserID { get; set; }
}
Thanks,
Prem
RequestedObject is a property on the objects in the array, not the array itself.
var users =
from item in jsonObjects
let obj = item["RequestedObject"]
where (DateTime)obj["UpdateInformation"]["CreateDate"] >= previousRunTime
select new UserDetails
{
UserName = (string)obj["UserName"],
UserID = (string)obj["Id"],
};
you need only one line code if you are using LINQ to JSON
List<UserDetails> users = jsonArray.Where(i => (DateTime)i["RequestedObject"]
["UpdateInformation"]["CreateDate"] >= previousRunTime)
.Select(i => i["RequestedObject"].ToObject<UserDetails>()).ToList();
class
public class UserDetails
{
[JsonProperty("UserName")]
public string UserName { get; set; }
[JsonProperty("Id")]
public string UserID { get; set; }
}

Issue with returning object from a function in asp.net MVC

i am little confused about my code:
Here is some function from my controller:
public void signIn(string userName, string userPass)
{
User user = new User();
user.getUser(userName , userPass);
if (user.userName != null)
{
Response.Redirect("/Home/Menu");
}
else
{
Response.Redirect("/Index/Index?Fail=" + "fail");
}
}
the " user.getUser" suppose to return a User object.. here is the code from my Model directory:
public class User
{
public ObjectId _id { get; set; }
public string userName { get; set; }
public string userPass { get; set; }
public User getUser(string name , string pass)
{
var client = new MongoClient("mongodb://localhost:27017");
var db = client.GetDatabase("testdb");
var coll = db.GetCollection<User>("user");
List<User> list = coll.Find(x => x.userName == name && x.userPass == pass).ToList<User>();
User uObj = new User();
uObj = list.FirstOrDefault();
return uObj;
}
}
when i am debugging the code i can see the uJob object contain values. but when the function end and i return to the controller i see that the user object contain only null values, and the condition - " if (user.userName != null)" is returning FALSE!.. instead of TRUE..
i would like to get some help. Thanks !
You have to assign it.
user = user.getUser(userName , userPass);
Either you assign the value returned by the getUser method in calling program like this
user = user.getUser(userName , userPass);
Or you change the code in Model like this
public class User
{
public ObjectId _id { get; set; }
public string userName { get; set; }
public string userPass { get; set; }
public void getUser(string name , string pass)
{
var client = new MongoClient("mongodb://localhost:27017");
var db = client.GetDatabase("testdb");
var coll = db.GetCollection<User>("user");
var user = coll.FirstOrDefault(x => x.userName == name && x.userPass == pass);
if(user != null)
{
this._id = user._id;
this.userName = user.userName;
this.userPass = user.userPass;
}
}
}
if you replace
if (user.userName != null)
with
if ( user.getUser(userName , userPass).userName != null)
wil works for you.

Get User Roles with ASP.net Identity and Web API

I am currently trying to get the given user's list of Roles and am having some trouble fitting this into the context we are using it in. I was able to get a list of all available roles with this API function earlier,
[HttpGet]
[Route("GetRoles")]
public async Task<ApiResponse<List<RoleViewModel>>> GetRoles()
{
try
{
//Get Roles
var roles = await (from r in _db.AspNetRoles
select new RoleViewModel { Id = r.Id, Name = r.Name}).ToListAsync();
return new ApiResponse<List<RoleViewModel>>{ Success = true, Result = roles };
}
catch(Exception ex)
{
return new ApiResponse<List<RoleViewModel>> { Success = false, Message = ex.Message };
}
}
But can't seem to figure out what I need to throw into this one to get a list of the roles for the user. We went with Entity Frameworks Code First from Existing Database approach and are pulling from those tables. Strangely though there is no AspNetUserRoles table since I guess it is just relating the two tables AspNetUsers and AspNetRoles. Anyway, here is the function in question,
[HttpGet]
[Route("GetUserRoles")]
public async Task<ApiResponse<List<RoleViewModel>>> GetUserRoles(string userName)
{
try
{
var userRoles = await (_db.AspNetUsers.FirstOrDefault(u => u.UserName == userName).AspNetRoles).ToListAsync();
}
catch (Exception ex)
{
return new ApiResponse<List<RoleViewModel>> { Success = false, Message = ex.Message };
}
}
The current error I am getting is that AspNetRole does not contain a definition for ToListAsync(). I think the async stuff is throwing me a little. And lastly here is the RoleViewModel for reference,
public class RoleViewModel
{
public string Id { get; set; }
[Required]
[StringLength(256)]
public string Name { get; set; }
}
And the ApiResponse class,
public class ApiResponse<TResult>
{
public bool Success { get; set; }
public string Message { get; set; }
public TResult Result { get; set; }
}
I feel like there should be a simple fix, but I just can't quite grasp what it is.
Just found the answer to my problem. The main thing I was missing was utilization of the User Manager which made things so much easier. Then I just had to fit things into the functions I had already defined. Here is the code.
[HttpGet]
[Route("GetUserRoles")]
public async Task<ApiResponse<List<RoleViewModel>>> GetUserRoles(string userName)
{
try
{
// Get the user in question
var aspUser = (from u in _db.AspNetUsers
where u.UserName == userName
select u).FirstOrDefaultAsync();
// Check if the user was found
if (aspUser == null)
{
throw new Exception("User was not found");
}
// Get the roles associated with that user
var userRoles = await UserManager.GetRolesAsync(aspUser.Result.Id.ToString());
// Setup a RoleViewModel list of roles and iterate through userRoles adding them to the list
List<RoleViewModel> roleList = new List<RoleViewModel>();
foreach (var u in userRoles)
{
var item = new RoleViewModel { Name = u };
roleList.Add(item);
}
return new ApiResponse<List<RoleViewModel>> { Success = true, Result = roleList };
}
catch (Exception ex)
{
return new ApiResponse<List<RoleViewModel>> { Success = false, Message = ex.Message };
}
}

Easiest way to use Dapper ORM

What is the easiest way to get the output of a Dapper ORM query into the data members of the class that provides the method for the query?
This is my code with a method A (ugly) and B (does not work):
public class MyLab_ClientRef
{
public int UserId { get; set; }
public string ClientId { get; set; }
// ... more fields ...
public bool GetUser(OracleConnection conn, int UserId, string ClientId)
{
bool Ok = false;
IEnumerable<MyLab_ClientRef> QueryResultRecords =
conn.Query<MyLab_ClientRef>(#"
SELECT *
FROM MyLab_ClientRef
WHERE UserId = :UserId
AND ClientId = :ClientId",
new { UserId = UserId, ClientId = ClientId });
if (QueryResultRecords.Count() == 1)
{
// Method A
MyLab_ClientRef Rec = QueryResultRecords.First(); // works
CopyRec(Rec, this); // ugly
// Method B
this = QueryResultRecords.First(); // avoids CopyRec, does not work
Ok = true;
}
return Ok;
}
private static void CopyRec(MyLab_ClientRef CR_From, MyLab_ClientRef CR_To)
{
CR_To.UserId = CR_From.UserId;
CR_To.ClientId = CR_From.ClientId;
}
}
I like to keep the record definition close to the query that gets the record, but don't like to implement a CopyRec method for every table class this way.
Is there no better way to implement this? I tried to write this = ... but that is not possible.
How to write a method B that is better than method A?
Following would not work:
this = QueryResultRecords.First();
Check following links for why:
Why can't I set "this" to a value in C#?
MSDN
As shown in the first link above, your best options remains that you return the MyLab_ClientRef from a given method, can make it static and use if for value or reference assignment, in this case either should yield same result
Check the following if this can be a cleaner implementation in your view:
public class MyLab_ClientRef
{
public int UserId { get; set; }
public string ClientId { get; set; }
// ... more fields ...
public static MyLab_ClientRef GetUser(OracleConnection conn, int UserId, string ClientId)
{
bool Ok = false;
var QueryResultRecords =
conn.Query<MyLab_ClientRef>(#"SELECT * FROM MyLab_ClientRef WHERE UserId = :UserId AND ClientId = :ClientId",new { UserId = UserId, ClientId = ClientId });
if(QueryResultRecords.Any())
return QueryResultRecords.First();
else
return null;
}
}
It can be called as:
var newClient = MyLab_ClientRef.GetUser(conn, UserId,ClientId);
It would be preferred though is the connection object is local to a method and is use in the using clock

ASP.NET how to get the currently logged in users name and ID from a SQL database

I am currently still a junior programmer and have taken over from a previous programmer and i am busy carrying on with his ASP.NET website. He has created his own login and i cant figure out how to display the currently logged in user into a ReadOnly Textbox.
The reason the textBox is readonly is because once a user has logged onto the website any data that is inserted into the SQL database gets added with the currently logged in userID but for Convenience the User name is shown in a readOnly textBox.
here is the Code for the login.aspx
protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
{
LoggedMember member = new LoggedMember();
if (LoginUser.UserName.Contains('#'))
{
member = Login.LogInContact(LoginUser.UserName, LoginUser.Password);
}
else
{
member = Login.LogInUser(LoginUser.UserName, LoginUser.Password);
}
if (member.ID != 0)
{
Session["LoggedMember"] = member;
FormsAuthentication.SetAuthCookie(member.UserName, true);
e.Authenticated = true;
Response.Redirect("~/pages/Monitor.aspx");
}
else
{
Session["LoggedMember"] = null;
e.Authenticated = false;
}
}
LoggedMember Class
public class LoggedMember
{
public int ID { get; set; }
public string UserName { get; set; }
public UserProfile Profile { get; set; }
}
Login Class
public class Login
{
public static LoggedMember LogInUser(string username, string password)
{
LoginContext db = new LoginContext();
User user = db.Users.Where(u => u.UserName == username && u.Password == password).SingleOrDefault();
LoggedMember member = new LoggedMember();
if (user != null)
{
if (user.UserID != 0)
{
member = new LoggedMember()
{
ID = user.UserID,
UserName = user.UserName
};
}
}
if (user != null)
{
member.Profile = UserProfile.GetUserProfileAndSettings((int)user.UserProfileID);
}
else
{
member.Profile = UserProfile.GetUserProfileAndSettings(0);
}
return member;
}
public static LoggedMember LogInContact(string username, string password)
{
LoginContext db = new LoginContext();
Contact contact = db.Contacts.Where(u => u.Email == username && u.Password == password).SingleOrDefault();
LoggedMember member = new LoggedMember();
if (contact.ContactID != 0)
{
member = new LoggedMember()
{
ID = contact.ContactID,
UserName = contact.FirstName + ' ' + contact.LastName
};
}
return member;
}
}
How would i go about loading the currently logged in userName into the ReadOnly textBox and once a record is added to the database to get the userID of the currently logged in user.
I am using C#,Sql server and linq
Thank you
Since the login code sets a forms-auth cookie, you should be able to use:
public static string GetUsername() {
var ident = System.Web.HttpContext.Current.User.Identity;
return ident.IsAuthenticated ? ident.Name : null;
}
It's very simple just assigning username to TextBox like
Textbox1.Text = username;
For getting the UserID of the Current Login User you need to call a select query like
Select UserId from tablename where username = "Pass username";
Your username must be unique otherwise you wil get multiple UserId from this query.
You need to use this type of scenario.
Hope you understand and works for you.

Categories

Resources