how to convert object's properties as list elements - c#

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

Related

C# - check if a custom list contains a username and if his password it's correct

Noob question! Need some help!
So I'm using GoogleSheets API to store user credentials.
I created a custom list with all the data of every user in the GoogleSheet, I need to verify if the data inserted by user matches something within the list.
I managed to check if the username matches, but how to check if the password matches that username?
##The class
public class ListadeJogadoresRegistados
{
public int id { get; set; }
public string nome { get; set; }
public string pwd { get; set; }
public int hiscore { get; set; }
}
##Building the list
private static List<ListadeJogadoresRegistados> GetListaJogadores()
{
var request = service.Spreadsheets.Values.Get(SpreadsheetID, range);
var response = request.Execute();
var values = response.Values;
var jogador = new List<ListadeJogadoresRegistados>();
foreach (var row in values)
{
jogador.Add(new ListadeJogadoresRegistados
{
id = Int32.Parse((string)row[0]),
nome = (string)row[1],
pwd = (string)row[2],
hiscore = Int32.Parse((string)row[3])
});
}
return jogador;
}
##Data validation
public static bool ValidarLogin(string username, string pwd)
{
var jogadores = GetListaJogadores();
ListadeJogadoresRegistados item = jogadores.Find(item => item.nome == username && item.pwd == pwd);
if (item != null) // check item isn't null
{
// it is logged in
}
return true;

restricting access to a dropdownlist in C#

Hello I have a 'RestrictAccessController' That looks like this
public class RestrictAccessController : Controller
{
private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
public ActionResult Index()
{
return View ();
}
}
[AttributeUsage(AttributeTargets.Method, AllowMultiple=true)]
public class RestrictAccessAttribute : ActionFilterAttribute
{
private PIC_Program_1_0Context db = new PIC_Program_1_0Context();
public AccessRestrictions restriction { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
// here's where we check that the current action is allowed by the current user
if (!IGT.canAccess(IGT.userId, restriction, false))
{
string url = IGT.baseUrl+"/Home/NotAllowed";
string msg = "This page requires " + IGT.DisplayEnum(restriction) + " access";
filterContext.Result = new RedirectResult("~/Home/NotAllowed?msg="+HttpUtility.HtmlEncode(msg));
}
}
And a Config model that looks like this
public enum AccessRestrictions
{
[Display(Name = "Disposal Orders")]
ModifyDisposalOrder,
[Display(Name = "Admin")]
Admin
}
public class userAccess
{
[Key]
public int ID { get; set; }
public AccessRestrictions restriction { get; set; }
public bool allow { get; set; }
public int userID { get; set; }
}
public class configDetails
{
public int ID {get; set;}
public string Name {get; set;}
public string Value {get;set;}
public bool deleted {get;set;}
public DateTime updateTime { get; set; }
}
public class Config
{
public int ID { get; set; }
[Display(Name = "Configuration Date")]
public DateTime TargetDate { get; set; }
[Display(Name = "Enable Access Restrictions")]
public bool restrictAccess { get; set; }
}
What I want to do is edit what my 'ChangeStatus' dropdown looks like based on whether they have the Admin access restriction or not. Here is the controller method that I want to edit
[RestrictAccess(restriction = AccessRestrictions.ModifyDisposalOrder)]
public ActionResult ChangeStatus(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
DisposalOrder disposalOrder = db.disposalOrders.Find(id);
if (disposalOrder == null)
{
return HttpNotFound();
}
switch (disposalOrder.Status)
{
case DOStatus.Pending:
ViewBag.statusList = new List<Object>
{
new {value = DOStatus.Pending, text = "Pending"},
new {value = DOStatus.Disposed, text = "Disposed" }
};
break;
case DOStatus.Disposed:
// if(restriction = AccessRestrictions.ModifyDisposalOrder)
ViewBag.statusList = new List<Object>
{
new {value = DOStatus.Pending, text = "Pending"},
new {value = DOStatus.Disposed, text = "Disposed" }
};
//else
//{
// new { value = DOStatus.Disposed, text = "Disposed" }
// };
break;
};
return View(disposalOrder);
}
Here is my Startup file
public class LdapAuthentication
{
private string _adUser = ConfigurationManager.AppSettings["ADUserName"];
private string _adPW = ConfigurationManager.AppSettings["ADPassword"];
private string _domain = ConfigurationManager.AppSettings["ADDomain"];
public LdapAuthentication() {
}
public string authenticate(string username, string pwd)
{
using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW)) {
//Username and password for authentication.
if (context.ValidateCredentials(username, pwd)) {
UserPrincipal user = UserPrincipal.FindByIdentity(context, username);
Internal internalUser = new Internal {
UserName = user.SamAccountName,
ContactName = user.DisplayName,
Email = user.UserPrincipalName
};
//Search if the user account already exists in the database
PIC_Program_1_0Context db = new PIC_Program_1_0Context();
Internal existing = db.Internals.Where(x => x.UserName == user.SamAccountName).FirstOrDefault();
// If it does not, create a new user account
if (existing == null) {
// add a new Internal entry for this user
existing = new Internal {
UserName = user.SamAccountName,
ContactName = user.DisplayName,
Email = user.UserPrincipalName
};
db.Internals.Add(existing);
db.SaveChanges();
// If it does exist, but some of the data does not match, update the data
} else if(existing != internalUser) {
existing.ContactName = internalUser.ContactName;
existing.Email = internalUser.Email;
db.SaveChanges();
}
return user.SamAccountName;
} else {
return null;
}
}
}
public UserPrincipal getUserPrincipal(string username)
{
using (var context = new PrincipalContext(ContextType.Domain, _domain, _adUser, _adPW))
{
return UserPrincipal.FindByIdentity(context, username);
}
}
Is it possible for me to accomplish this?
Ok, I think I understand your question now. You need to access the User's claims. MVC Controllers have this, half way, built in.
if (User.HasClaim("ClaimNameHere", "Admin"))
{
}
Solved by adding
if (IGT.canAccess(IGT.userId, AccessRestrictions.Admin, false))

Filling DataGridView from database

I have a DataGridView which I want to fill from my database. I got an empty DataGridView. Here's my script and what I tried :
private void listUser_Load(object sender, EventArgs e)
{
List<User> lesUsers = Passerelle.getUsers();
dgvUser.DataSource = lesUsers;
}
My class :
class User
{
private int id { get; set; }
private int level { get; set; }
private string name { get; set; }
private string password { get; set; }
private string email { get; set; }
public User(int idP, int levelP, string nameP, string passwordP, string emailP)
{
id = idP;
level = levelP;
name = nameP;
password = passwordP;
email = emailP;
}
}
And the way I got my data :
public static List<User> getUsers()
{
MySqlDataReader result = executerSelect("SELECT id, level, name, email, password FROM users");
List<User> users = new List<User>();
if(result != null)
{
while(result.Read())
{
int id = int.Parse(result[0].ToString());
int level = int.Parse(result[1].ToString());
string name = result[2].ToString();
string email = result[3].ToString();
string password = result[4].ToString();
users.Add(new User(id, level, name, password, email));
}
}
return (users.ToList());
}
I already tried with a binding source but I'm not able to link with my datagridview
Thanks for help
You need to assign lesUsers , instead of getUsers which is a method
List<User> lesUsers = Passerelle.getUsers();
dgvUser.DataSource = lesUsers ;
EDIT
check if you have public properties which would be used to display the contents of the Class as columns in the DataGridView

Convert FQL Results to custom class?

I am a fairly new C# programmer and am getting stuck on trying to convert FQL results into a custom class...for example, I am doing the following, but it seems like a lot of steps...I was just returning a datatable, but wanted the result to be strongly typed class collection. I'd appreciate any insights. I'm open to other ways of achieving similar results as well.
Thanks,
Chad
public class FacebookFriends
{
public string FriendID { get; set; }
public string FriendName { get; set; }
public string PicURLSquare { get; set; }
public string ProfileLink { get; set; }
//Gets your FB friends that are NOT currently using this application so you can invite them
public IEnumerable<FacebookFriends> GetFriendsNotUsingApp()
{
string strQuery = "SELECT uid, name, pic_square, link FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me()) AND NOT is_app_user";
FacebookSDKInterface objFQL = new FacebookSDKInterface();
dynamic objFNU = objFQL.FBFQL(strQuery);
//Construct the new, formated, merged datatable to store the results the way we want them
DataTable dtFriendsNotUsingApp = new DataTable();
dtFriendsNotUsingApp.Columns.Add("FriendID");
dtFriendsNotUsingApp.Columns.Add("FriendName");
dtFriendsNotUsingApp.Columns.Add("PicURLSquare");
dtFriendsNotUsingApp.Columns.Add("Link");
if (objFQL != null)
{
foreach (dynamic row in objFNU.data)
{
//Add New DataRow to new DataTable
DataRow drRow = dtFriendsNotUsingApp.NewRow();
//Get various values from original JSON Friend List returned
drRow["FriendID"] = row.uid;
drRow["FriendName"] = row.name;
drRow["PicURLSquare"] = row.pic_square;
drRow["Link"] = row.link;
//Add New Row to New Resulting Data Table
dtFriendsNotUsingApp.Rows.Add(drRow);
}
dtFriendsNotUsingApp.DefaultView.Sort = "FriendName";
}
IEnumerable<FacebookFriends> objFriendsListCollection = null;
var toLinq = from list in dtFriendsNotUsingApp.AsEnumerable()
select new FacebookFriends
{
FriendID = list["FriendID"].ToString(),
FriendName = list["FriendName"].ToString(),
PicURLSquare = list["PicURLSquare"].ToString(),
ProfileLink = list["ProfileLink"].ToString()
};
objFriendsListCollection = toLinq.OrderByDescending(p => p.FriendName);
return objFriendsListCollection;
} //Get FB Friends not already using this app
I belive this may help.
1st: I've never used the Facebook API, so I'm just using your code as an example.
2nd: As the method is inside the class, I've changed it to static. This way, you can use it by simply calling FacebookFriends.GetFriendsNotUsingApp(), instead of new FacebookFriends().GetFriendsNotUsingApp().
3rd The code:
public class FacebookFriends
{
public string FriendID { get; set; }
public string FriendName { get; set; }
public string PicURLSquare { get; set; }
public string ProfileLink { get; set; }
//Gets your FB friends that are NOT currently using this application so you can invite them
public static IEnumerable<FacebookFriends> GetFriendsNotUsingApp()
{
string strQuery = "SELECT uid, name, pic_square, link FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me()) AND NOT is_app_user";
FacebookSDKInterface objFQL = new FacebookSDKInterface();
dynamic objFNU = objFQL.FBFQL(strQuery);
List<FacebookFriends> friendsToReturn = new List<FacebookFriends>();
if (objFQL != null)
{
foreach (dynamic row in objFNU.data)
{
friendsToReturn.Add(new FacebookFriends()
{
FriendID = row.uid,
FriendName = row.name,
PicURLSquare = row.pic_square,
ProfileLink = row.link
}
);
}
}
return friendsToReturn;
} //Get FB Friends not already using this app
}
Hope this helps.
Regards
I have no experience with Facebook API or FQL as well, but by looking at your code objFNU.data appears to implement IEnumerable, hence you can use LINQ extension methods directly with it:
public class FacebookFriends
{
public string FriendID { get; set; }
public string FriendName { get; set; }
public string PicURLSquare { get; set; }
public string ProfileLink { get; set; }
//Gets your FB friends that are NOT currently using this application so you can invite them
public static IEnumerable<FacebookFriends> GetFriendsNotUsingApp()
{
string strQuery = "SELECT uid, name, pic_square, link FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1=me()) AND NOT is_app_user";
FacebookSDKInterface objFQL = new FacebookSDKInterface();
dynamic objFNU = objFQL.FBFQL(strQuery);
if (objFQL != null) // shouldn't you check objFNU for being null here instead?
{
IEnumerable<dynamic> objFNUdata = (IEnumerable<dynamic>)objFNU.data; // explicit cast might not be necessary
return objFNUdata.Select(row => new FacebookFriends()
{
FriendID = row.uid,
FriendName = row.name,
PicURLSquare = row.pic_square,
ProfileLink = row.link
}).OrderByDescending(p => p.FriendName);
}
else
{
return new List<FacebookFriends>();
}
} //Get FB Friends not already using this app
}
In the end, this worked best for me. Thanks to both, and especially #DarmirArh for all his help in getting this to work.
try
{
FacebookSDKInterface objFQL = new FacebookSDKInterface();
dynamic objFNU = objFQL.FBFQL(strQuery);
if (objFNU != null) // shouldn't you check objFNU for being null here instead?
{
IEnumerable<dynamic> objFNUdata = (IEnumerable<dynamic>)objFNU.data; // explicit cast might not be necessary
IEnumerable<FacebookFriends> objMyFriends =
from row in objFNUdata
select new FacebookFriends()
{
FriendID = row.uid,
FriendName = row.name,
PicURLSquare = row.pic_square,
ProfileLink = row.profile_url
};
objMyFriends = objMyFriends.OrderBy(p => p.FriendName);
return objMyFriends;
}
else
{
return new List<FacebookFriends>();
}
}
catch (Exception ex)
{
return new List<FacebookFriends>();
}

How to get values from a list<class>

I have these classes, which i want to use it to login, to check if the email and password is the same, then it will redirect to the respective page.
public class Account
{
public Account(){}
public int accID { get; set; }
public string emailAddress { get; set; }
public string password { get; set; }
public string name { get; set; }
public string company { get; set; }
public string position { get; set; }
public string department { get; set; }
public string mobileNo { get; set; }
public string officeNo { get; set; }
}
public static SADataReader DoSelectQuery(String sql)
{
SAConnection myConnection = new SAConnection(DB_STR);
//open the connection
myConnection.Open();
//Create a command object.
SACommand myCommand = myConnection.CreateCommand();
//Specify a query.
myCommand.CommandText = sql;
//Create a DataReader for the command
SADataReader reader = myCommand.ExecuteReader();
return reader;
}
public static List<Account> getAllAccountFromReader(SADataReader reader){
List<Account> results = new List<Account>();
while (reader.Read())
{
int accID = reader.GetInt32(0);
string emailAddress = reader.GetString(1);
string password = reader.GetString(2);
string name = reader.GetString(3);
string company = reader.GetString(4);
string position = reader.GetString(5);
string department = reader.GetString(6);
string mobileNo = reader.GetString(7);
string officeNo = reader.GetString(8);
Account Accounts = new Account();
Accounts.accID = accID;
Accounts.emailAddress = emailAddress;
Accounts.password = password;
Accounts.name = name;
Accounts.company = company;
Accounts.position = position;
Accounts.department = department;
Accounts.mobileNo = mobileNo;
Accounts.officeNo = officeNo;
results.Add(Accounts);
}
return results;
}
public static List<Account> getAllAccounts()
{
//Specify a query.
string sql = "SELECT accountID,emailAddress,password,name,company,position,department,mobileNo,officeNo FROM account";
SADataReader reader = DoSelectQuery(sql);
List<Account> results = getAllAccountFromReader(reader);
return results;
}
.CS file to check for fields
protected void btnSubmit_Click(object sender, EventArgs e)
{
string email = tbEmail.Text;
string password = tbPW.Text;
List<Account> getAccounts = MinuteDB.getAllAccounts();
// Session["getAllAccount"] = getAccounts;
if(email ==?? && password == ??)
{
//Session["name"] = name.ToString();
//Session["ID"] = Convert.ToInt32(accID.ToString());
Response.Redirect("HomePage.aspx");
}
else if (email == "" && password == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Please enter Login and Password!');", true);
}
else
{
ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Wrong Login Or Password!');", true);
}
}
How do i retrieve the email and password from the List getAccounts so that i can check for if (email == email from the list account && password == password from list account) ??
Try LINQ/extension methods.
var account = MinuteDB.getAllAccounts()
.Where(p=> p.emailAddress==email && p.password==password)
.FirstOrDefault();
if(account!=null)
{
Session["id"]=account.accID;
Session["name"]=account.name;
Response.Redirect("~/other_page.aspx");
}
Write following code in other_page.aspx to read session key-value.
int id=0;
string name="";
if(Session["id"]!=null)
id=int.Parse(Session["id"].ToString());
if(Session["name"]!=null)
name=Session["name"];
PS: Do not store password in the List<T>. You may assign Account object reference to the Session.
e.g
if(account!=null)
{
Session["account"]=account;
Response.Redirect("~/other_page.aspx");
}
and to retrieve the account value from session:
Account account=Session["account"] as Account;
if(account!=null)
{
//read the property value of Account
}
Are you wanting to find the email in the list of accounts and check the password entered matches? If so, superficially you just loop through each along the lines of:
private bool isPasswordValid(string email, string password)
{
foreach (Account account in Accounts)
{
if (account.emailAddress != email)
continue;
return (account.password == password);
}
return false;
}
You could alternatively return a Dictionary<string, Account> to simplify and speed up the search.
Update
So instead of the following line:
if(email ==?? && password == ??)
Insert
if (isPasswordValid(email, password))
// it is valid
else
// it is not valid, redirect
This assumes the getAccounts variable is accessible to isPasswordValid. In your current code it would not be visible, so you might want to pass it in as a parameter.

Categories