I have created a desktop software server system, which accepts string from client and insert into database, here is the server code
public class TcpServer
{
public TcpListener _server;
public Boolean _isRunning;
Data_connection dbobject = new Data_connection();
SQLiteConnection SQLconnect = new SQLiteConnection();
Window win;
public DataTable dt_stored;
public List<string> connected_users;
public TcpServer(int port,Window _win)
{
win = _win;
_server = new TcpListener(IPAddress.Any, port);
connected_users = new List<string>();
_server.Start();
_isRunning = true;
SQLconnect.ConnectionString = dbobject.datalocation();
Thread th = new Thread(listenClients);
th.Start();
//listenClients();
}
public void listenClients()
{
while (_isRunning)
{
try
{
// wait for client connection
TcpClient newClient = _server.AcceptTcpClient();
// client found.
// create a thread to handle communication
Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
t.Start(newClient);
}catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public void HandleClient(object obj)
{
// retrieve client from parameter passed to thread
TcpClient client = (TcpClient)obj;
StreamWriter sWriter = new StreamWriter(client.GetStream(), Encoding.ASCII);
StreamReader sReader = new StreamReader(client.GetStream(), Encoding.ASCII);
// reads from client stream
string sData = sReader.ReadLine();
if (!string.IsNullOrEmpty(sData))
{
//store to sqlite database
insertToDB(sData, 0);
string[] arr = sData.Split(',');
//add name to list
connected_users.Add(arr[0]);
//select all students from the DB
SelectAllStudents();
////show
//MessageBox.Show(sData);
// to write data back.
string allnames = convertDtNamesToString();
sWriter.WriteLine(allnames);
sWriter.Flush();
}
}
private string convertDtNamesToString()
{
string data = "";
foreach(DataRow row in dt_stored.Rows)
{
data = data +row[1].ToString()+",";
}
return data;
}
public void SelectAllStudents()
{
if (SQLconnect.State != ConnectionState.Open)
{
SQLconnect.Open();
}
SQLiteCommand cmd = new SQLiteCommand("select * from Students", SQLconnect);
SQLiteDataAdapter da = new SQLiteDataAdapter();
dt_stored = new DataTable();
da.SelectCommand = cmd;
da.Fill(dt_stored);
if (SQLconnect.State != ConnectionState.Closed)
{
SQLconnect.Close();
}
}
private void insertToDB(string sData,int n)
{
if(n>20)
{
MessageBox.Show("Error inserting data");
return; ;
}
if (SQLconnect.State != ConnectionState.Open)
{
SQLconnect.Open();
}
//create students table if not exist
try
{
SQLiteCommand SQLcommand = new SQLiteCommand();
SQLcommand = SQLconnect.CreateCommand();
SQLcommand.CommandText = "CREATE TABLE IF NOT EXISTS Students" + "( Name TEXT, Phone TEXT, Address Text, Passport Text);";
SQLcommand.ExecuteNonQuery();
SQLcommand.Dispose();
// MessageBox.Show("Table Created");
//insert student
string[] data = sData.Split(',');
SQLiteCommand cmd = new SQLiteCommand();
cmd = SQLconnect.CreateCommand();
cmd.CommandText = "insert into Students values (#_name,#_phone,#_address,#_passport)";
cmd.Parameters.AddWithValue("#_name", data[1]);
cmd.Parameters.AddWithValue("#_phone", data[2]);
cmd.Parameters.AddWithValue("#_address", data[3]);
cmd.Parameters.AddWithValue("#_passport", data[4]);
cmd.ExecuteNonQuery();
cmd.Dispose();
}
catch (Exception ex)
{
n++;
Thread.Sleep(200);
insertToDB(sData,n);
}
finally
{
if (SQLconnect.State != ConnectionState.Closed)
{
SQLconnect.Close();
}
}
//MessageBox.Show("Data Inserted");
}
}
And i have a client sofwtare, which also send data to the server to insert into databse, and here is the code also
class Client
{
private TcpClient _tcpclient;
private StreamReader _sReader;
private StreamWriter _sWriter;
public static List<string> lst_storeddata = new List<string>();
private Boolean _isConnected;
string name;
string phone;
string address;
string passport;
public Client(string _name, string _phone, string _address, string _passport)
{
//server ip
String ipAddress = "127.0.0.1";
//String ipAddress = "192.168.43.15";
//port number
int portNum = 8585;
try
{
_tcpclient = new TcpClient();
_tcpclient.Connect(ipAddress, portNum);
name = _name;
phone = _phone;
address = _address;
passport = _passport;
HandleCommunication();
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public void HandleCommunication()
{
_sReader = new StreamReader(_tcpclient.GetStream(), Encoding.ASCII);
_sWriter = new StreamWriter(_tcpclient.GetStream(), Encoding.ASCII);
string clientData = Environment.MachineName+","+name + "," + phone + "," + address + "," + passport;
_sWriter.WriteLine(clientData);
_sWriter.Flush();
// receive data
String sDataIncomming = _sReader.ReadLine();
lst_storeddata = (sDataIncomming.Split(',')).ToList();
_sWriter.Close();
_tcpclient.Close();
}
}
My challenge now is, i don't know how to go about it, sending JSON data through network, instead of string array.
Please help.
Json serialization turns an object into a string representation of the object. If your existing code works ok then you can serialize any POCO into a string and reuse it.
The de facto standard json serialization library for C# is Json.NET usually referenced via the Newtonsoft.json nuget package.
Related
Below is my Connectionstring and sucessfully read the data. It will return total rows of my data.
private static async Task<List<OperatorErrorTransaction>> GetDevIndex()
{
try
{
var currentConnectionDev = new CurrentConnection(Configuration["ConnectionStrings:Default"], currentRequest);
Console.WriteLine("\nPress the Enter key to exit the application...\n");
var response = await currentConnectionDev.DbConnection.QuerySafeAsync<OperatorErrorTransaction>(GenerateGetDatabaseIndexQuery());
return response.ToList();
}
catch (Exception ex)
{
return new List<OperatorErrorTransaction>();
}
}
private static string GenerateGetDatabaseIndexQuery()
{
return #"SELECT * FROM test.operator_error_transaction";
}
Below is the csv CreateFile function. Right now i looking a way how to implement mysql data into the csv file.
public static void CreateFile(List<OperatorErrorTransaction> result)
{
string myFileName = String.Format("{0:yyyy-MM-dd-HHmm}{1}", DateTime.Now, ".csv");
string myFullPath = Path.Combine("D:\\", myFileName);
using (var mem = new MemoryStream())
using (StreamWriter writer = File.CreateText(myFullPath))
using (var csvWriter = new CsvWriter(writer))
{
csvWriter.Configuration.Delimiter = ";";
csvWriter.WriteField(result);
csvWriter.NextRecord();
writer.Flush();
var result1 = Encoding.UTF8.GetString(mem.ToArray());
Console.WriteLine(result1);
}
}
I have created a class for the variables as well such as public string BetId { get; set; } etc...
I have these codes for receiving sms from my gsm modem. It works but I want the messages to be viewed on a listbox or textbox. Can someone help me on how to do this?
public void Read()
{
gsmPort.WriteLine("AT+CMGF=1"); // Set mode to Text(1) or PDU(0)
Thread.Sleep(1000); // Give a second to write
gsmPort.WriteLine("AT+CPMS=\"SM\""); // Set storage to SIM(SM)
Thread.Sleep(1000);
gsmPort.WriteLine("AT+CMGL=\"ALL\""); // What category to read ALL, REC READ, or REC UNREAD
Thread.Sleep(1000);
gsmPort.Write("\r");
Thread.Sleep(1000);
string response = gsmPort.ReadExisting();
if (response.EndsWith("\r\nOK\r\n"))
{
Console.WriteLine(response);
// add more code here to manipulate reponse string.
}
else
{
// add more code here to handle error.
Console.WriteLine(response);
}
This is how I communicate with my modem using these codes. It works but only on console. I want add these to my winform
class GSMsms
{
private SerialPort gsmPort = null;
private bool IsDeviceFound { get; set; } = false;
public bool IsConnected { get; set; } = false;
public GSMsms()
{
gsmPort = new SerialPort();
}
public GSMcom[] List()
{
List<GSMcom> gsmCom = new List<GSMcom>();
ConnectionOptions options = new ConnectionOptions();
options.Impersonation = ImpersonationLevel.Impersonate;
options.EnablePrivileges = true;
string connString = $#"\\{Environment.MachineName}\root\cimv2";
ManagementScope scope = new ManagementScope(connString, options);
scope.Connect();
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_POTSModem");
ManagementObjectSearcher search = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection collection = search.Get();
foreach (ManagementObject obj in collection)
{
string portName = obj["AttachedTo"].ToString();
string portDescription = obj["Description"].ToString();
if (portName != "")
{
GSMcom com = new GSMcom();
com.Name = portName;
com.Description = portDescription;
gsmCom.Add(com);
}
}
return gsmCom.ToArray();
}
I have a problem while trying to send elements from dataGridView to the form, where I edit the whole row.
The function catches the error and displays it as "Invalid attempt to read when no data is present", but the problem is that I have rows inserted in the database, so row is not empty.
Here is the code:
private void urediIzbranoKnjigoToolStripMenuItem_Click(object sender, EventArgs e)
{
string naslovKnjige = "";
string avtorKnjige = "";
string datumIzdaje = "";
string kategorijaID = "";
string zalozbaID = "";
string knjiznicaID = "";
string statusID = "";
this.urejanje = false;
try
{
this.stavekSQL = "SELECT naslovKnjige, avtorKnjige, datumIzdaje, kategorijaID, zalozbaID, knjiznicaID, statusID FROM Knjiga WHERE ID=#ID";
this.izvediSQL = new SqlCommand(this.stavekSQL, this.povezavaDB);
this.izvediSQL.Parameters.AddWithValue("#ID", this.zadnjiIzbran);
this.povezavaDB.Open();
this.reader = this.izvediSQL.ExecuteReader();
this.reader.Read();
naslovKnjige = this.reader["naslovKnjige"].ToString();
avtorKnjige = this.reader["avtorKnjige"].ToString();
datumIzdaje = this.reader["datumIzdaje"].ToString();
kategorijaID = this.reader["kategorijaID"].ToString();
zalozbaID = this.reader["zalozbaID"].ToString();
knjiznicaID = this.reader["knjiznicaID"].ToString();
statusID = this.reader["statusID"].ToString();
this.reader.Close();
this.urejanje = true;
}
catch (Exception ex)
{
MessageBox.Show("Napaka pri izvajanju: " + ex.Message);
}
finally
{
this.povezavaDB.Close();
if (this.urejanje)
{
UrediKnjigo uredi = new UrediKnjigo(this, this.zadnjiIzbran, naslovKnjige, avtorKnjige, datumIzdaje, kategorijaID, zalozbaID, knjiznicaID, statusID);
uredi.ShowDialog();
}
}
}
I want to display data from my remote sql-server in my android app. I am using web-service. I am able to connect and to insert but not to display with JSON.
This is the code from web-service
public DataTable RequestDetails(string request_name)
{
DataTable requestDetails = new DataTable();
requestDetails.Columns.Add(new DataColumn("Request ID", typeof(String)));
requestDetails.Columns.Add(new DataColumn("Date", typeof(String)));
if(dbConnection.State.ToString() == "Closed")
{
dbConnection.Open();
}
string query = "select ID_Requests,request_date from Requests where request_by='" + request_name + "'";
SqlCommand command = new SqlCommand(query, dbConnection);
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
requestDetails.Rows.Add(reader["Request ID"], reader["Date"]);
}
}
reader.Close();
dbConnection.Close();
return requestDetails;
}
This is the android code:
protected class AsyncLoadDeptDetails extends
AsyncTask<DeptTable, JSONObject, ArrayList<DeptTable>> {
ArrayList<DeptTable> deptTable = null;
#Override
protected ArrayList<DeptTable> doInBackground(DeptTable... params) {
// TODO Auto-generated method stub
RestAPI api = new RestAPI();
try {
JSONObject jsonObj = api.RequestDetails(params[1].getName());
JSONParser parser = new JSONParser();
deptTable = parser.parseDepartment(jsonObj);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("AsyncLoadDeptDetails", e.getMessage());
}
return deptTable;
}
#Override
protected void onPostExecute(ArrayList<DeptTable> result) {
// TODO Auto-generated method stub
for (int i = 0; i < result.size(); i++) {
data.add(result.get(i).getNo() + " " + result.get(i).getName());
}
adapter.notifyDataSetChanged();
Toast.makeText(context, "Loading Completed", Toast.LENGTH_SHORT).show();
}
}
And the JSONParser code:
public ArrayList<DeptTable> parseDepartment(JSONObject object)
{
ArrayList<DeptTable> arrayList=new ArrayList<DeptTable>();
try {
JSONArray jsonArray=object.getJSONArray("Value");
JSONObject jsonObj=null;
for(int i=0;i<jsonArray.length();i++)
{
jsonObj=jsonArray.getJSONObject(i);
arrayList.add(new DeptTable(jsonObj.getInt("Request ID"), jsonObj.getString("Date")));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.d("JSONParser => parseDepartment", e.getMessage());
}
return arrayList;
}
I would use Fiddler or something similar and have a look at the data being returned. I've always had trouble returning a .NET Datatable from a service, so if it were me I would convert the datatable to JSON before sending. This has been discussed on several posts before, but here's a great answer:
https://stackoverflow.com/a/17398078/3299157
I am new to MySQL database, I am using Visual Studio C# to connect to my database. I have got a following select method. How can I run it to check if it is working?
EDITED The open and close connection methods
//Open connection to database
private bool OpenConnection()
{
try
{
// connection.open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, your application's response based
//on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server.");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
Select method which is in the same class as the close and open connection as shown above
public List<string>[] Select()
{
string query = "SELECT * FROM Questions";
//Create a list to store the result
List<string>[] list = new List<string>[3];
list[0] = new List<string>();
list[1] = new List<string>();
list[2] = new List<string>();
list[3] = new List<string>();
list[4] = new List<string>();
list[5] = new List<string>();
list[6] = new List<string>();
list[7] = new List<string>();
//Open connection
if (this.OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
list[0].Add(dataReader["id"] + "");
list[1].Add(dataReader["difficulty"] + "");
list[2].Add(dataReader["qustions"] + "");
list[3].Add(dataReader["c_answer"] + "");
list[4].Add(dataReader["choiceA"] + "");
list[5].Add(dataReader["choiceB"] + "");
list[6].Add(dataReader["choiceC"] + "");
list[7].Add(dataReader["choiceD"] + "");
}
//close Data Reader
dataReader.Close();
//close Connection
this.CloseConnection();
//return list to be displayed
return list;
}
else
{
return list;
}
}
This method is in a separate class which has got all the database connection settings. Now that I want to call this method from my main class to test it to see if it's working, how can I do this?
You should create an object instance of that DB class and then call the Select() method.
So, supposing that this DB class is named QuestionsDB you should write something like this:
QuestionDB questionDAL = new QuestionDB();
List<string>[] questions = questionDAL.Select();
However, before this, please correct this line
List<string>[] list = new List<string>[8]; // you need 8 lists for your db query
You could check if you have any record testing if the first list in your array list has more than zero elements.
if(questions[0].Count > 0)
... // you have read records.
However, said that, I will change your code adding a specific class for questions and using a list(of Question) instead of an array of list
So, for example, create a class like this
public class Question
{
public string ID;
public string Difficulty;
public string Question;
public string RightAnswer;
public string AnswerA;
public string AnswerB;
public string AnswerC;
public string AnswerD;
}
and change your select to return a List(of Question)
List<Question> list = new List<Question>;
......
while (dataReader.Read())
{
Question qst = new Question();
qst.ID = dataReader["id"] + "";
qst.Difficulty = dataReader["difficulty"] + "";
qst.Question = dataReader["qustions"] + "";
qst.RightAnswer = dataReader["c_answer"] + "";
qst.AnswerA = dataReader["choiceA"] + "";
qst.AnswerB = dataReader["choiceB"] + "";
qst.AnswerC = dataReader["choiceC"] + "";
qst.AnswerD = dataReader["choiceD"] + "";
list.Add(qst);
}
return list;
You can test whether the method works by writing a unit test for it. A good unit testing frame work is Nunit. Before you call this you must create and open a connection to the DB:
//Open connection
if (this.OpenConnection() == true)
{
as the other person said, you will want to fix the lists up.