get/set Accessors the correct scope - c#

i created a class called ProfileHelper, and I can't seem to get my get/set accessors correct; instead, I'm getting red lines on both get and set. Here is the code I am trying to use:
public static String UserName(string columnName)
{
get
{
using (SqlConnection cn = new SqlConnection(SiteConfig.ConnectionString))
{
string sSql = ("SELECT UserName , LoweredUserName FROM aspnet_Users WHERE UserId = #UserId");
using (SqlCommand cm = new SqlCommand(sSql, cn))
{
cm.Parameters.AddWithValue("#UserId", Membership.GetUser().ProviderUserKey.ToString());
cn.Open();
using (SqlDataReader rd = cm.ExecuteReader())
{
while (rd.Read())
{
return columnName;
}
rd.Close();
}
cn.Close();
}
}
return columnName;
}
set
{
using (SqlConnection cn = new SqlConnection(SiteConfig.ConnectionString))
{
string sSql = ("UPDATE [aspnet_ Users] SET UserName = #UserName, LoweredUserName = #LoweredUserName WHERE UserId = #UserId");
using (SqlCommand cm = new SqlCommand(sSql, cn))
{
cm.Parameters.AddWithValue("#UserId", Membership.GetUser ().ProviderUserKey.ToString());
cn.Open();
cm.ExecuteNonQuery();
cn.Close();
}
}
}
}

That's a method, not a property. Only properties have get and set accessors. Pick one.
public static String UserName(string columnName) // this implies a method
{
get // this implies a property
{

Syntax is basically:
private string userName;
public string UserName // no parameter here!
{
get { return this.userName; }
set { this.userName = value; } // value is a keyword
}
Alternatively, auto-property do the backing field for you:
public string UserName { get; set; } // equivalent
public string MyExternallyReadOnly { get; private set; } // setter is private
You should not fiddle around with SQL connections in properties. Access to properties should be fast and reliable. Consider replacing it by methods to make it clear that this is actually a longer-enduring action with external dependencies (which is more likely to fail):
public string GetUserName() { }
public void UpdateUserName() {}

You should make a pair of methods, GetUserName(string columnName) and SetUserName(string columnName, string value). This is the preferred approach when it will probably take a while, e.g. because you're making a DB connection, and lets you easily have a parameter.
public static String UserName(string columnName) is the signature for a method. public static String UserName would be a property. Properties have get/set accessors, methods do not. You need to change this. Properties do not allow arguments, except for indexed properties, which can't be static (e.g. used like myObj[someColumnName], declared like public string this[string columnName]). If you're expecting to access the property like var something = ProfileHelper.UserName;, just use a property.

Related

JSON Object Empty when is Serialize it C#?

I am using the following Code
public class GetTabelRealizari : ControllerBase
{
public class Realizare
{
String user;
String denumire;
String incasari;
public Realizare(String user, String denumire, String incasari)
{
this.user = user;
this.denumire = denumire;
this.incasari = incasari;
}
public String getUser()
{
return user;
}
public void setUser(String user)
{
this.user = user;
}
public String getDenumire()
{
return denumire;
}
public void setDenumire(String denumire)
{
this.denumire = denumire;
}
public String getIncasari()
{
return incasari;
}
public void setIncasari(String incasari)
{
this.incasari = incasari;
}
}
[HttpPost]
public string Post([FromBody] string[] value)
{
//SSMS connection
string connectionString = "Data Source=DESKTOP-QKC0G7V;Initial Catalog=Restaurant_gest;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
List<Realizare> realizari = new List<Realizare>();
double incasari;
String incasariString;
SqlCommand command = new SqlCommand("SELECT Users.Username," +
" Tip_Nota_Plata.Denumire," +
" sum(Nota_plata.Suma) as Incasari" +
" from Users" +
" INNER JOIN Nota_plata" +
" INNER JOIN Comandas" +
" ON Nota_plata.Id_comanda = Comandas.Id" +
" ON Comandas.User_Id = Users.Id" +
" INNER JOIN Tip_Nota_Plata" +
" ON Tip_Nota_Plata.Id = Nota_plata.Id_tip_nota" +
" Group by Username, Tip_Nota_Plata.Denumire", connection);
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
incasari = (double)reader["Incasari"];
incasariString = incasari.ToString("#.##");
realizari.Add(new Realizare(reader["Username"].ToString(), reader["Denumire"].ToString(), incasariString));
}
}
return JsonConvert.SerializeObject(realizari);
//return "salut";
}
}
And I am receiving an empty JsonObject. Why?
[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]
I keep trying to make it work and I cannot. The list has the objects, i can test it with Console.Writeline(realizari[0].getDenumire()) and it works. I can also serialize a list of strings, it just doesn`t work for objects.
Because the object has no serializable properties.
I'm going to guess you are a Java developer based on this:
String user;
public String getUser()
{
return user;
}
public void setUser(String user)
{
this.user = user;
}
C# has "properties" which, while they compile down to methods very similar to this, the syntax in C# is a bit different. All of the above code can be simplified to a property:
public String User { get; set; }
The usage then becomes simpler as well, allowing for assignments instead of calling a method:
someObject.User = someUser;
In cases where you want to add logic to your getter/setter, you can expand the "auto implemented property" above into a manual one:
private string user;
public string User
{
get { return user; }
set { user = value; }
}
The get and set syntax still tells the compiler that this is a property, but within those blocks you can write any method logic you like. (In the setter value is a keyword for the value being assigned to the property.)

C# - MySql - Best way to convert data from MySqlDataReader to different models

I have experience in working and fixing bugs with existing code bases that implement MySql code, but have to design a new program from scratch at my new job. I am not sure what is the best way to return data from MySqlDataReader to my custom models. Please advise!
Here's what I have,
Folder structure:
Models (folder)
Metadata.cs
User.cs
MySqlDb.cs
Metadata.cs: Reresents data from metadata table
public class Metadata
{
public int Id { get; set; }
public string Title { get; set; }
public string Sku { get; set; }
public bool IsLive { get; set; }
}
User.cs: Represents data from user table
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}
MySqlDb.cs
using MySql.Data;
using MySql.Data.MySqlClient;
public class MySqlDb
{
public MySqlConnection Connection { get; set;}
public MySqlDb(string connectionString)
{
Connection = new MySqlConnection(connectionString);
}
public List<Metadata> RunSelectQueryForMetadata(string query)
{
var rdr = new MySqlCommand(query, Connection).ExecuteReader();
var metadata = new List<Metadata>();
using (rdr)
{
while(rdr.Read())
{
metadata.Add(
new Metadata {
Id = rdr["id"],
Title = rdr["title"],
Sku = rdr["sku"],
IsLive = rdr["islive"],
});
} // while
} // using
return metadata;
} // public void RunSelectQuery(string query)
} // public class MySqlDb
If I try to get Users data, I am thinking of writing another method (RunSelectQueryForUsers). I would like to avoid writing different methods for different tables. I am not sure how to use one method for retrieving data from different tables with different data structures and typecast them to the Model I want.
Any help is greatly appreciated!!
One way is to use micro-orm such as Dapper which is a simple object mapper built for .Net. Dapper extends the IDbConnection by providing useful extension methods to query your database.
Example of implementing dapper within your current menthod:
public List<Metadata> RunSelectQueryForMetadata(string query)
{
var metadata = new List<Metadata>();
try // implement proper error handling
{
Connection.Open();
metadata = Connection.Query<Metadata>(query).ToList();
Connection.Close();
}
catch(Exception ex)
{
// error here
}
return metadata;
}
Some useful links:
Dapper Github
Dapper Tutorial
Converting it to generic method: (not tested right now)
public List<T> RunSelectQuery<T>(string query)
{
try // implement proper error handling
{
Connection.Open();
metadata = Connection.Query<T>(query).ToList();
Connection.Close();
}
catch(Exception ex)
{
// error here
}
return metadata;
}
and use something like this below:
List<Metadata> myMetadata = RunSelectQuery<Metadata>(query);
I prefer a pattern more like this:
public class MySqlDb
{
//1. This should not be public!
// Keeping it private forces other code to go through your public methods,
// rather than using the connection directly.
// Even better if the class knows how to read the string from a
// config rile rather than accepting it via the constructor.
//2. Don't save a connection object for re-use.
// ADO.Net has a connection pooling feature that works when you
// create new objects for most queries
private string ConnectionString { get; set;}
public MySqlDb(string connectionString)
{
ConnectionString = connectionString;
}
//1. Use IEnumerable instead of List
// ...don't pull all of the results into memory at the same time until/unless you really have to.
//2. Methods that accept query strings should also accept parameters.
// Otherwise you are forced to build sql strings in insecure crazy-vulnerable ways
public IEnumerable<Metadata> RunSelectQueryForMetadata(string query, IEnumerable<MySqlParameter> parameters)
{
using (var cn = new MySqlConnection(ConnectionString))
using (var cmd = new MySqlCommand(query, cn))
{
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
cn.Open();
using(var rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
yield return new Metadata {
Id = rdr["id"],
Title = rdr["title"],
Sku = rdr["sku"],
IsLive = rdr["islive"],
};
}
rdr.Close();
}
}
}
}
Ultimately, the ideal is for the RunSelectQuery__() method to be generic and private, and for public methods to not accept SQL statements. The goal is to force all SQL in your program to live in the MySqlDb class. Each query has a method that accepts specific typed inputs, and returns typed output. The reason you have that goal is to make it easy to manage your database access and easy to audit that all of your SQL code is safely using parameters (and not vulnerable to sql injection attacks! ). You want something like this:
//updated to remove the earlier explanatory comments
// and show example methods for isolating SQL from the rest of the application.
public class MySqlDb
{
private string ConnectionString { get; set;}
private string ReadConnectionStringFromConfigFile()
{
//TODO
throw NotImplementedException();
}
public MySqlDb()
{
ConnectionString = ReadConnectionStringFromConfigFile();
}
//This is now PRIVATE and generic, and allows for parameterized queries
private IEnumerable<T> RunSelectQuery(string query, Func<IDataReader, T> translateRecord, IEnumerable<MySqlParameter> parameters)
{
using (var cn = new MySqlConnection(ConnectionString))
using (var cmd = new MySqlCommand(query, cn))
{
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
cn.Open();
using(var rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
yield return translateRecord(rdr);
}
rdr.Close();
}
}
}
////// Example methods showing how to use the generic method above
// These methods are the only public part of your class
public MetaData GetMetaDataById(int ID)
{
string sql = "SELECT * FROM MetatData WHERE ID= #ID";
var parameters = new List<MySqlParameters> {
new MySqlParameter() {
ParameterName = "#ID",
MySqlDbType = MySqlDbType.Int32,
Value = ID
}
};
return RunSelectQuery<MetaData>(sql, parameters, r =>
new Metadata {
Id = r["id"],
Title = r["title"],
Sku = r["sku"],
IsLive = r["islive"],
}).FirstOrDefault();
}
public IEnumerable<MetaData> GetAllMetaData()
{
string sql = "SELECT * FROM MetatData";
return RunSelectQuery<MetaData>(sql, null, r =>
new Metadata {
Id = r["id"],
Title = r["title"],
Sku = r["sku"],
IsLive = r["islive"],
});
}
public User GetUserByID(int ID)
{
string sql = "SELECT * FROM User WHERE ID= #ID";
var parameters = new List<MySqlParameters> {
new MySqlParameter() {
ParameterName = "#ID",
MySqlDbType = MySqlDbType.Int32,
Value = ID
}
};
return RunSelectQuery<User>(sql, parameters, r =>
new Metadata {
Id = r["id"],
UserName = r["UserName"],
Age = r["Age"],
Address = r["Address"],
}).FirstOrDefault();
}
public User GetUserByUsername(string UserName)
{
string sql = "SELECT * FROM User WHERE Username= #UserName";
var parameters = new List<MySqlParameters> {
new MySqlParameter() {
ParameterName = "#UserName",
MySqlDbType = MySqlDbType.VarChar,
Size = 20, //guessing at username lenght
Value = UserName
}
};
return RunSelectQuery<User>(sql, parameters, r =>
new Metadata {
Id = r["id"],
UserName = r["UserName"],
Age = r["Age"],
Address = r["Address"],
}).FirstOrDefault();
}
public IEnumerable<User> FindUsersByAge(int Age)
{
string sql = "SELECT * FROM User WHERE Age = #Age";
var parameters = new List<MySqlParameters> {
new MySqlParameter() {
ParameterName = "#Age",
MySqlDbType = MySqlDbType.Int32,
Value = Age
}
};
return RunSelectQuery<User>(sql, parameters, r =>
new Metadata {
Id = r["id"],
UserName = r["UserName"],
Age = r["Age"],
Address = r["Address"],
});
}
}
In larger applications, you abstract this further into a separate project, with a private class for the lower-level methods that are private here, and a public class for each of the object types you use via that database. You might even go full-blown service-oriented architecture, where you get all your data via web service calls, and only the service layer talks directly to any database.
Of course, at this level you can also use a mirco-ORM like Dapper. Micro-ORMs will help you avoid re-writing the same mapping code over and over, and also help more with the INSERT/UPDATE side of data operations. Their goal is to take over as much of the boilerplate code for you as they can.
The advantage of a micro-ORM over a full ORM is it keeps you closer to the SQL. This is a good thing. Full-blown ORMs like Entity Framework or NHibernate effectively force you to learn a whole new language on top of the SQL, while mostly limiting you to basic SQL statements that often lose the advantages from the "relational" part of a relational database. Eventually, you often end up needing to understand and write complex raw SQL anyway to optimize performace. Micro-ORMs try to offer a happy-medium... taking away as much of the boiler plate code needed to talk to a database as they can, while still leaving you to write your own SQL.
While not tailored to using MySql and straight up sql, the below code snippets provide a means to do what you're asking using generics. Could use some improvements though...
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Data.General
{
public abstract class DataObject
{
protected abstract void Initialize(IDataRecord dataRow);
private static string _connectionString = "";
/// <summary>
/// Loads a single data object from the results of a stored procedure.
/// </summary>
protected static T ReadObject<T>(string procedureName, SqlParameter[] sqlParameters, Type dataType)
{
DataObject returnItem = null;
using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString()))
using (SqlCommand command = BuildCommand(sqlConnection, procedureName, sqlParameters))
{
sqlConnection.Open();
//Execute the reader for the given stored proc and sql parameters
using (IDataReader reader = command.ExecuteReader())
{
//If we get no records back we'll still return null
while (reader.Read())
{
returnItem = (DataObject)Activator.CreateInstance(typeof(T));
returnItem.Initialize(reader);
break;
}
}
}
//Return our DataObject
return (T)Convert.ChangeType(returnItem, dataType);
}
/// <summary>
/// Reads a collection of data objects from a stored procedure.
/// </summary>
protected static List<T> ReadObjects<T>(string procedureName, SqlParameter[] sqlParameters)
{
//Get cached data if it exists
List<T> returnItems = new List<T>();
T dataObject;
using (SqlConnection sqlConnection = new SqlConnection(GetConnectionString()))
using (SqlCommand command = BuildCommand(sqlConnection, procedureName, sqlParameters, null))
{
sqlConnection.Open();
//Execute the reader for the given stored proc and sql parameters
using (IDataReader reader = command.ExecuteReader())
{
//If we get no records back we'll still return null
while (reader.Read())
{
dataObject = (T)Activator.CreateInstance(typeof(T));
(dataObject as DataObject).Initialize(reader);
returnItems.Add(dataObject);
}
}
}
//Return the DataObjects
return returnItems;
}
/// <summary>
/// Builds a SQL Command object that can be used to execute the given stored procedure.
/// </summary>
private static SqlCommand BuildCommand(SqlConnection sqlConnection, string procedureName, SqlParameter[] sqlParameters, SqlTransaction sqlTransaction = null)
{
SqlParameter param;
SqlCommand cmd = new SqlCommand(procedureName, sqlConnection);
if (sqlTransaction != null)
{
cmd.Transaction = sqlTransaction;
}
cmd.CommandType = CommandType.StoredProcedure;
// Add SQL Parameters (if any)
foreach (SqlParameter parameter in sqlParameters)
{
param = new SqlParameter(parameter.ParameterName, parameter.DbType);
param.Value = parameter.Value;
cmd.Parameters.Add(param);
}
return cmd;
}
private static string GetConnectionString()
{
return _connectionString;
}
public static void SetConnectionString(string connectionString)
{
_connectionString = connectionString;
}
}
}
namespace Data.Library
{
public class Metadata : General.DataObject
{
protected Data.Model.Metadata _metaData;
public Data.Model.Metadata BaseModel
{
get { return _metaData; }
set { _metaData = value; }
}
//Typically I have properties in here pointing to the Data.Model class
protected override void Initialize(System.Data.IDataRecord dataRow)
{
_metaData = new Model.Metadata();
_metaData.Id = Convert.ToInt32(dataRow["Id"].ToString());
_metaData.Title = (dataRow["Title"].ToString());
_metaData.Sku = (dataRow["Sku"].ToString());
_metaData.IsLive = Convert.ToBoolean(dataRow["IsLive"].ToString());
}
public static Metadata ReadByID(int id)
{
return General.DataObject.ReadObject<Metadata>("dbo.s_MetadataGet", new[] { new SqlParameter("#ID", id) },
typeof(Metadata));
}
public static Metadata[] ReadBySku(string sku)
{
List<Metadata> metaDatas = General.DataObject.ReadObjects<Metadata>("dbo.s_MetadataGetBySku", new[] { new SqlParameter("#Sku", sku) });
return metaDatas.ToArray();
}
}
}
namespace Data.Model
{
public class Metadata
{
public int Id { get; set; }
public string Title { get; set; }
public string Sku { get; set; }
public bool IsLive { get; set; }
}
}

How to get a specific string out of a database with C# using a parameter that can change in layer model

I need to make a helpdesk form for my end of year task and I'm stuck.
The task requires me to load the solution of a specific problem that the user selects via a combobox. My implementation needs to separated into layers like business persist and so on.
The code that I wrote to solve this didn't work (EXPLAIN WHY HERE). I have made a few attempts at it and have included them below.
First Attempt:
For my first attempt, I have written the following code to load the solution to the selected problem from the database:
public List<HelpDesk> getOplossing()
{
List<HelpDesk> lijst = new List<HelpDesk>();
MySqlConnection conn = new MySqlConnection(_connectionstring);
MySqlCommand cmd = new MySqlCommand("SELECT Oplosing from tblhelpdesk where Probleem = #probleem" , conn);
cmd.Parameters.Add(new MySqlParameter("#probleem",
getProbleem().ToString()));
conn.Open();
MySqlDataReader datareader = cmd.ExecuteReader();
while (datareader.Read())
{
HelpDesk hlpdsk = new HelpDesk(
datareader["Oplosing"].ToString());
lijst.Add(hlpdsk);
}
conn.Close();
return lijst;
}
And in the controller I called it like this:
public List<HelpDesk> getOplossing()
{
return _persistcode.getOplossing();
}
Attempt 2:
This is what I wrote for my second attempt.
public string getOplossing()
{
MySqlConnection conn = new MySqlConnection(_connectionstring);
MySqlCommand cmd = new MySqlCommand("SELECT Oplosing from tblhelpdesk", conn);
conn.Open();
string oplossing;
oplossing = cmd.ExecuteScalar().ToString();
conn.Close();
return oplossing;
}
Again in the controller:
public string getOplossing()
{
return _persistcode.getOplossing();
}
My entire HelpDesk class:
And the class HelpDesk looks like this: (I provided the whole class so you guys can have a gander at all the problem :/ )
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GPDeBruykerSander_Domain.Business
{
public class HelpDesk
{
private int _id;
private Boolean _categorie; //Hardware= True en Software= False
private DateTime _datumProbleem;
private string _probleem;
private DateTime _datumOplossing;
private string _oplossing;
public int ID
{
get { return _id; }
set { _id = value; }
}
public override string ToString()
{
return Probleem;
}
public Boolean Categorie
{
get { return _categorie; }
set { _categorie = value; }
}
public DateTime DatumProbleem
{
get { return _datumProbleem; }
set { _datumProbleem = value; }
}
public string Probleem
{
get { return _probleem; }
set { _probleem = value; }
}
public DateTime DatumOplossing
{
get { return _datumOplossing; }
set { _datumOplossing = value; }
}
public string Oplossing
{
get { return _oplossing; }
set { _oplossing = value; }
}
public HelpDesk (int id, Boolean categorie, DateTime datumProbleem, string probleem, DateTime datumOplossing, string oplossing)
{
_id = id;
_categorie = categorie;
_datumProbleem = datumProbleem;
_probleem = probleem;
_datumOplossing = datumOplossing;
_oplossing = oplossing;
}
public HelpDesk(Boolean categorie, DateTime datumProbleem, string probleem, DateTime datumOplossing, string oplossing)
{
_categorie = categorie;
_datumProbleem = datumProbleem;
_probleem = probleem;
_datumOplossing = datumOplossing;
_oplossing = oplossing;
}
public HelpDesk(DateTime datumProbleem, Boolean categorie, string probleem)
{
_datumProbleem = datumProbleem;
_categorie = categorie;
_probleem = probleem;
}
public HelpDesk(DateTime datumOplossing, string oplossing)
{
_datumOplossing = datumOplossing;
_oplossing = oplossing;
}
public HelpDesk(string probleem)
{
_probleem = probleem;
}
}
}
I hope somebody can help me find the solution because I'm stuck :/
You were closer to solving your problem in your first attempt, so I will help you with that. But since you haven't actually provided any reasons as to why your code doesn't work (errors thrown by the application, etc.), I can only take a stab at potential issues I see in your code.
Looking at your MySQL query: SELECT Oplosing from tblhelpdesk where Probleem = #probleem, I would say that you are missing quotes around #probleem. So this query should look like this:
SELECT Oplosing from tblhelpdesk where Probleem = '#probleem'
I would also make the following suggestions:
Suggestion 1: Make getProbleem() method actually return a string, so you don't have to call ToString() on it. You haven't provided the implementation of this method so I can only assume the return type is not a string. If the return type is a string the ToString() is completely redundant here.
Suggestion 2:
I would also suggestion is that you pass the problem string as a parameter to getOplossing(), so that the database code is encapsulated better. For example:
public List<HelpDesk> getOplossing(string probleem)
{
...
cmd.Parameters.Add(new MySqlParameter("#probleem", probleem));
...
}
And your controller will call it like so:
public List<HelpDesk> getOplossing()
{
string probleem = getProbleem().ToString();
return _persistcode.getOplossing(probleem);
}

How to return a List in c#

Below I have a method I am trying to create. The overall objective of the method is to create a list, open a database in SQL, and convert that information to a string. The problem though I am having is returning all the data. I understand for a method to work you need a return statement of some sort, however when I try to return the list, it keeps telling me
Cannot implicitly convert type 'System.Collections.Generic.List(Namespace).MyHome' to '(namespace).MyHome
So my question to you all is, can I return the list, or will I have to create another variable to return, or am I trying to return the wrong thing entirely?
Below is the method I am working on. For explanation, this method is using a class I created that holds the credentials for the data I am trying to get.
private static MyHome GetUserDataFromMyHome(string username)
{
List<MyHome> myHomeInformation = new List<MyHome>();
using (SqlConnection connection = new SqlConnection(Properties.Settings.Default.MyHomeConnectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = #"SELECT USER_NAME, EMAIL, FIRST_NAME, LAST_NAME, TRAVELER_UID FROM DATA_BASE";
connection.Open();
SqlDataReader reader = sqlError.ExecuteReader();
while (reader.Read())
{
MyHome userInformation = new MyHome();
foreach (MyHome item in myHomeInformation)
{
userInformation.myHomeUserName = Utilities.FromDBValue<string>(reader["USER_NAME"]);
userInformation.myHomeEmail = Utilities.FromDBValue<string>(reader["EMAIL"]);
userInformation.myHomeFirstName = Utilities.FromDBValue<string>(reader["FIRST_NAME"]);
userInformation.myHomeLastName = Utilities.FromDBValue<string>(reader["LAST_NAME"]);
userInformation.myHomeTravelerUID = Utilities.FromDBValue<string>(reader["TRAVELER_UID"]);
myHomeInformation.Add(userInformation);
}
}
}
return myHomeInformation;
}
Here is the class that holds the credentials:
class MyHome : IEnumerable<MyHome>
{
public string myHomeUserName { get; set; }
public string myHomeEmail { get; set; }
public string myHomeFirstName { get; set; }
public string myHomeLastName { get; set; }
public string myHomeTravelerUID { get; set; }
}
Replace
private static MyHome GetUserDataFromMyHome(string username)
with
private static List<MyHome> GetUserDataFromMyHome(string username)
the return type should be a list of objects and not just a object
A List<MyHome> is not a MyHome. If you want your function to return a List<MyHome>, declare it as such.
You have to declare the return type of the function to be a List of MyHome.
private static List<MyHome> GetUserDataFromMyHome(string username)
Otherwise whatever is calling this is expecting to get one instance of MyHome.

How to create a single object and use values in different events?

I am creating a program with two forms(register and view).
The view form will read a single record from a table(database), and then you can edit or delete the record. I am creating a class for this program, and for one of the constructors it will get the search ID, First name and last name from the view form and then there is a method which will search through the table for the record(using search ID, OR firstname and lastname) and will assign the variables inside the class, and I want to use THOSE variables for my edit and delete methods, but the problem is when I try to create a public object of the class which would be used across all my events, using 'this' keyword, it says that this doesn't exist in the current context, but whenever I create an object in each event it will recognize 'this' keyword, but I won't be able to use the class variables assigned from the search method. This is my constructor and search method for the class
public ASystem(searchSHD search)
{
searchHID = search.searchHID;
search_FName = search.searchFName;
search_LName = search.searchLName;
}
public String searchHID;
public String search_FName;
public String search_LName;
public String HID;
public String First_Name;
public String Full_Name;
public String query;
public String Last_Name;
public String PhoneNum;
public String Country;
public String DOB;
public String Experience;
public void Search()
{
using (OleDbConnection db_connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\KAZEM\Documents\Hairsalon\employees.accdb;
Persist Security Info=False;"))
{
if (searchHID == "")
{
query = "SELECT * FROM Hairdresser where First_Name = #FName AND Last_Name = #LName";
}
else
{
query = "SELECT * FROM Hairdresser where HID = #HID";
}
using (OleDbCommand db_command = new OleDbCommand(query, db_connection))
{
db_command.Parameters.Add("#HID", searchHID);
db_command.Parameters.Add("#FName", search_FName);
db_command.Parameters.Add("#LName", search_LName);
db_connection.Open();
OleDbDataReader reader = db_command.ExecuteReader();
reader.Read();
HID = reader.GetValue(0).ToString();
First_Name = reader.GetString(1);
Last_Name = reader.GetString(2);
Full_Name = First_Name + " " + Last_Name;
Country = reader.GetString(4);
PhoneNum = reader.GetString(5);
DOB = (Convert.ToDateTime(reader.GetValue(3))).ToString();
Experience = reader.GetValue(6).ToString();
}
}
}
you can create your own event through creating a class which is derived of EventArgs, that like:
class yourEventArgs:EventArgs
{
public yourEventArgs(object yourValues)
{
Value = yourValues;
}
//Create your properties like below
public object Value { get; set; }
}
after that you need to create an eventhandler:
public event EventHandler<yourEventArgs> YourEventName;
for raising the event you use:
if(YourEventName!=null)
{YourEventName(this,new yourEventArgs(yourValue));}
then you can add to your eventhandler your method through (the code which should be executed if you raise the event)
YourEventName+=((object o,yourEventArgs e)=> {/*-Insert Code here-*/});
//or
YourEventName+=on_yourEvent;
private void on_yourEvent(object o,yourEventArgs e)
{
/*-Insert your Code here- */
}
I hope that's what you want.

Categories

Resources