C# web service get data from sql server - c#

I connected SQL server database and I using username and password value return xml boolean true. But I want to get sicilKod value according to the results of the username query. How can I do it?
This returning boolean value according to username and password
[WebMethod]
public bool login(string unamePI, string passPI)
{
DataTable mytable = new DataTable();
bool mydeger = false;
mytable = GetTableWithQueryParams("select * from UYE where USERNAME ={0} and PASSWORD={1}", unamePI, passPI);
if (mytable.Rows.Count > 0)
{
mydeger = true;
}
else
{
return mydeger;
}
string de = mytable.Rows[0].ToString();
return mydeger;
}
Database connect:
public static DataTable GetTableWithQueryParams(string SQLCommandText, params object[] myParametres)
{
string aConnectionString = "Data Source = ..; Initial Catalog = mydatabase; Persist Security Info = True; User ID = ..; Password = ..";
SqlConnection SqlConn = new SqlConnection(aConnectionString);
SqlCommand MyCommand = new SqlCommand("", SqlConn);
DataTable MyTable = new DataTable();
try
{
int i = 0;
SqlConn.Open();
foreach (object MyObject in myParametres)
{
if (SQLCommandText.Contains("{" + i.ToString() + "}"))
{
SQLCommandText = SQLCommandText.Replace("{" + i.ToString() + "}", "#Prm" + i.ToString());
MyCommand.Parameters.AddWithValue("Prm" + i.ToString(), MyObject);
i++;
}
}
MyCommand.CommandText = SQLCommandText;
SqlDataReader MyReader = MyCommand.ExecuteReader();
MyTable.Load(MyReader);
SqlConn.Close();
MyReader.Dispose();
}
catch (Exception ex)
{
throw new Exception(SQLCommandText + "\n" + ex.Message);
}
finally
{
SqlConn.Dispose();
MyCommand.Dispose();
}
return MyTable;
}

change your method to this.
public string login(string unamePI, string passPI)
{
DataTable mytable = new DataTable();
string result = "";
mytable = GetTableWithQueryParams("select * from UYE where USERNAME ={0} and PASSWORD={1}", unamePI, passPI);
if (mytable.Rows.Count > 0)
{
result = string.Format("Welcome {0}", mytable.Rows[0]["sicilKod"].ToString());
}
return result;
}
then check if login method return value is empty or not.

Related

Load data from database to string

I'm trying at the moment to get an information from a database and want to save it in a string, but yeah not sure about how really to do it right.
This is my code, where I open the LoadSql function:
public void LoadData(string KNR, string WNR, String filter)
{
// WHERE
const string sqlTemplate = "SELECT KUNDENAUFTRAGSNR FROM MESSFELD.AUSSTANDSDATEN WHERE FTNR = '" + txt_Barcode_read.Text + "'";
string sql = string.Format(sqlTemplate, filter);
Database cdb = new Database();
// try to connect and cancel on error
if (!cdb.Open("**********", "*********"))
{
SetStatusText("Datenbank ist nicht verfügbar.");
return;
}
WNR = cdb.LoadSql(sql);
cdb.Close();
}
And here is the LoadSQL function:
public DataTable LoadSql(string sql)
{
try
{
OracleCommand command = new OracleCommand(sql, _con);
command.InitialLONGFetchSize = -1;
OracleDataReader rdr = command.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr);
return dt;
}
catch
{
return null;
}
}
For the moment the LoadSQL is saving in datatable, how to change for saving the number in the string WNR?
You can re-write your LoadSQL function to something like this :
public string LoadSql(string sql)
{
try
{
OracleCommand command = new OracleCommand(sql, _con);
command.InitialLONGFetchSize = -1;
OracleDataReader rdr = command.ExecuteReader();
rdr.Read();
if(rdr.HasRows)
return rdr.GetString(0);
else
return "";
}
catch
{
return null;
}
}

Splitting my SQL class to support multi connection and stored procedure

I need to create the best architecture for my app to manage my different connections (two) and the stored procedure.
So far I have created one SQL class and do not handle the two connections : I have mixed methods and functions which can be called regardless of the connection (and can crash).
How do I create a Connection class and a DAL ?
My SQL connection class :
namespace GripPicture.Data
{
class Sqlmap
{
static string RmSynchro = "ConnectionRmSynchro";
static string PascomPhoto = "ConnectionPascomPhoto";
private string config;
private OleDbConnection _lConnection = new OleDbConnection();
private OleDbConnection OleConnection
{
get
{
if (_lConnection.State != ConnectionState.Open)
{
if (_lConnection.State != ConnectionState.Connecting)
{
_lConnection.OpenAsync();
}
}
return _lConnection;
}
set { _lConnection = value; }
}
public Sqlmap(bool pIsPascom = false)
{
config = pIsPascom ? ConfigurationManager.AppSettings[PascomPhoto] : ConfigurationManager.AppSettings[RmSynchro];
OleConnection = new OleDbConnection(config);
}
private void Connection()
{
OleConnection.OpenAsync();
}
public int ExcuteUpdate(string pQuery)
{
// Check if connection is closed
OleDbCommand command = new OleDbCommand(pQuery, OleConnection);
return command.ExecuteNonQuery();
}
// This function should reside in your SQL-class.
public IEnumerable<T> ExecuteQueryForList<T>(string pQuery)
{
List<T> items = new List<T>();
Type type = typeof(T);
var data = ExecuteDataTable(pQuery);
foreach (DataRow row in data.Rows)
{
// Object have a constructor with a Datarow
T item = (T)Activator.CreateInstance(typeof(T), row);
PascomPhotoDo element = (PascomPhotoDo)Activator.CreateInstance(typeof(PascomPhotoDo), row);
if ((items.Cast<PascomPhotoDo>()).Any((elem => elem.NumeroContact == element.NumeroContact)))
{
LogHelper.Log("Doublons dans la liste Id Pascom " + element.NumeroContact + " " + element.FirstName + " Atlas " + element.IdParticipantAtlas);
//Console.WriteLine("Doublon dans liste : " + element.NumeroContact + " " + element.FirstName + " Atlas " + element.IdParticipantAtlas);
}
items.Add(item);
}
return items;
}
private DataTable ExecuteDataTable(string pQuery)
{
OleDbDataAdapter dp1 = new OleDbDataAdapter(pQuery, OleConnection);
DataSet ldataSet = new DataSet();
dp1.Fill(ldataSet, "table");
return ldataSet.Tables[0];
}
#region PASCOM
public byte[] GetPictureFromPascom(int pNumeroContact)
{
byte[] lDataPicture = null;
OleDbCommand command = new OleDbCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "itsp_Photo_GetPhotoByContact";
command.Connection = OleConnection;
command.Parameters.Add("#numero_contact", OleDbType.Integer).Value = pNumeroContact;
command.CommandTimeout = 15000;
try
{
lDataPicture = (byte[])command.ExecuteScalar();
}
catch (Exception e)
{
LogHelper.Log("Fail to get picture \n" + " Id Pascom " + pNumeroContact + " " + e.Message);
}
return lDataPicture;
}
public void InsertPictureToDatabase(PascomPhotoDo pPascomPhoto)
{
OleDbCommand command = new OleDbCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "itsp_Photo_CreatePhotoContact";
command.Connection = OleConnection;
command.Parameters.Add("#idContact", OleDbType.Integer).Value = pPascomPhoto.NumeroContact;
command.Parameters.Add("#photo", OleDbType.Binary).Value = pPascomPhoto.PhotoByteReduced;
command.Parameters.Add("#source", OleDbType.VarChar).Value = "blabla";
command.Parameters.Add("#idSalonOrganise", OleDbType.VarChar).Value = "blabla";
command.Parameters.Add("#IdParticipantAtlas", OleDbType.VarChar).Value = pPascomPhoto.IdParticipantAtlas;
command.CommandTimeout = 15000;
try
{
int data = command.ExecuteNonQuery();
}
catch (Exception e)
{
LogHelper.Log(LogTarget.File, "Fail to insert in database", e);
}
}
}
#endregion
}
Then I use my SQL connection by declaring a new object like so :
_sqlRmSynchro = new Sqlmap();
_sqlPascom = new Sqlmap(true);
As you can see I can call some specific function from the wrong connection string...
What do I need ? A DAL ? What does it look like ?

Unable to fetch data from phpMyadmin using data table

I am creating a hotel management system, in which i am supposed to fetch the room for a specific reason. I am fetching room_NO from booking table using tourist_CNIC field from the same table. But i always get 0, instead of getting proper room number, which i have assigned to all of the rooms. Bellow is my code:
private int Fetch_Room()
{
int number = 0;
try
{
String str = "SELECT room_NO FROM booking WHERE tourist_CNIC='" + cnic.Content.ToString() + "'";
MySqlDataAdapter da = new MySqlDataAdapter(str, con);
DataTable dt = new DataTable();
da.Fill(dt);
foreach(DataRow row in dt.Rows)
number = Convert.ToInt32(row.ItemArray[0]);
return number;
}
catch (Exception x) { MessageBox.Show("Error: " + x.Message); return number; }
}
You can use MySqlDataReader for this case. try below solution
rivate int Fetch_Room()
{
int number = 0;
try
{
String str = "SELECT room_NO FROM booking WHERE tourist_CNIC='" + cnic.Content.ToString() + "'";
MySqlCommand cmd = new MySqlCommand(str, con);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
number = (int)rdr.GetValue(0);
}
return number;
}
catch (Exception x) { MessageBox.Show("Error: " + x.Message); return number; }
}

C# Error using Base64 convert on hash

Basically I am getting a saved hash (converted to base64) from an access database and comparing it (after converting it back) with another and should return true if they match, but for some reason it returns false. There is data in the database. I think the problem occurs when the hash is converted back from base64. Can anyone see what I am doing wrong?
private static bool MatchSHA(byte[] p1, byte[] p2)
{
bool result = false;
if (p1 != null && p2 != null)
{
if (p1.Length == p2.Length)
{
result = true;
for (int i = 0; i < p1.Length; i++)
{
if (p1[i] != p2[i])
{
result = false;
break;
}
}
}
}
return result;
}
private static byte[] GetSHA(string userID, string password)
{
SHA256CryptoServiceProvider sha = new SHA256CryptoServiceProvider();
return sha.ComputeHash(System.Text.Encoding.ASCII.GetBytes(userID + password));
}
public void RunTest()
{
string userId = "test";
string password = "Password";
string enteredPassword = "Password";
var hashedPassword = GetSHA(userId, password);
string encodedPassword = Convert.ToBase64String(hashedPassword);
try
{
string connString = (#"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=|DataDirectory|Password.accdb");
OleDbConnection conn = new OleDbConnection(connString);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = #"SELECT * FROM [Users] WHERE [UserId] = #UserId";
cmd.Parameters.AddWithValue("#UserId", userId);
OleDbDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
var compareHash = Convert.FromBase64String(dbReader["Password"].ToString());
errorLabel.Text = "Hash from DB: " + dbReader["Password"].ToString();
if (MatchSHA(compareHash, GetSHA(userId, enteredPassword)))
{
loginLabel.Text = "EnteredPassword. True";
}
else
{
loginLabel.Text = "EnteredPassword. False";
}
}
conn.Close();
}
catch (OleDbException obe)
{
errorLabel.Text = obe.ToString();
}
}

How to select a value with results from another column

i am using C# and i need to develop a check system for a mysql user and password.
So far what ive come up with is this and the error i get is that it is the wrong syntax...
public bool VerifyUser(string username, string password)
{
string returnValue = "";
string Query = "SELECT Pass FROM Base_Character WHERE User='" + username + "'";
MySqlCommand verifyUser = new MySqlCommand(Query, this.sqlConn);
try
{
verifyUser.ExecuteNonQuery();
MySqlDataReader myReader = verifyUser.ExecuteReader();
while (myReader.Read() != false)
{
returnValue = myReader.GetString(0);
}
myReader.Close();
}
catch (Exception excp)
{
Exception myExcp = new Exception("Could not verify user. Error: " +
excp.Message, excp);
throw (myExcp);
}
if (returnValue == password)
{
return false;
}
else
{
return true;
}
}
ExecuteNonQuery is for DELETE, INSERT and UPDATE. Whenever you want data returned as rows from database, use ExecuteReader
Your query should check the username and password together, if they exist in one record then the row is returned else nothing is returned.
You still need more to learn about coding/database programming using .Net
public bool VerifyUser(string username, string password)
{
bool returnValue = false;
string Query = "SELECT 1 FROM Base_Character WHERE User='" + username + "' AND pass='"+password+"'";
try
{
MySqlCommand command = new MySqlCommand(Query, this.sqlConn);
MySqlDataReader myReader = command.ExecuteReader();
if(myReader.Read())
{
returnValue = true;
}
myReader.Close();
}
catch (Exception excp)
{
throw;
}
return returnValue;
}
You should probably not throw a custom exception since you are using boolean
if(VerifyUser("user123", "******"))
{
//Congratulations
}
else
{
//Unable to log you in
}
Thanks guys, but this calls for a custom encryption that mysql cant hold or process, my main error was ovrlooking the executenonquery(), so i had to make the code like this:
if (AuthorizeTools.Encrypt.Password(Database.getPassword) != Password) //Password is already encrypted
Then set the mysql function to:
public string getPassword(string username)
{
string returnValue = "";
string Query = "SELECT Pass FROM Base_Character where (User=" +
"'" + username + "') LIMIT 1";
MySqlCommand checkUser = new MySqlCommand(Query, this.sqlConn);
try
{
checkUser.ExecuteNonQuery();
MySqlDataReader myReader = checkUser.ExecuteReader();
while (myReader.Read() != false)
{
returnValue = myReader.GetString(0);
}
myReader.Close();
}
catch (Exception excp)
{
Exception myExcp = new Exception("Could not grab password: " +
excp.Message, excp);
throw (myExcp);
}
return (returnValue);
}

Categories

Resources