Retrieve data from remote sqlserver to android app - c#

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

Related

Unable to get a table data from SAP

This is a c# method that invokes SAP BAPI.
public Message ReleaseBapi(string orderNumber)
{
Message msg = new Message();
DataTable dt = new DataTable();
_ecc = ERPRfcDestination.InitialiseDestination();
try
{
IRfcFunction api = _ecc.Repository.CreateFunction("BAPI_PRODORD_RELEASE");
IRfcTable orderNumTable = api.GetTable("ORDERS");
orderNumTable.Insert();
IRfcStructure ItemData = orderNumTable.CurrentRow;
orderNumber = orderNumber.PadLeft(12,'0');
ItemData.SetValue("ORDER_NUMBER", orderNumber);
api.SetValue("ORDERS", orderNumTable);
BeginContext();
api.Invoke(_ecc);
//EndContext();
IRfcTable detReturnTable = api.GetTable("DETAIL_RETURN");//On this line I am getting RfcInvalidStateException
IRFCToDatatable convertToDT = new IRFCToDatatable();
dt = convertToDT.ToDataTable(detReturnTable, dt);
if (dt.Rows.Count > 0)
{
msg.Msg = "Order number " + orderNumber + " released";
msg.MsgType = "S";
}
else { RollbackAPI(); }
}
catch (Exception ex)
{
msg.MsgType = "D";
msg.Msg = ex.Message;
RollbackAPI();
}
finally
{
EndContext();
}
return msg;
}
I checked every other instances where similar line of code is written and on debugging I found that it works as expected. Above is the only place where I am getting this error although I was able to invoke the Rfc method.

How to post with async and await with HttpClient

I am writing a windows service to get some data from my database, then send it to my provider and get the response. I have some issues which make me simulate a console application to test my code.
Here is my code:
static async Task Main(string[] args)
{
send();
}
public static DataSet dataAccess()
{
DataSet ds = new DataSet();
ds.Tables.Add();
ds.Tables.Add();
ds.Tables[0].Columns.Add("id");
ds.Tables[0].Columns.Add("token");
ds.Tables[1].Columns.Add("token_id");
ds.Tables[1].Columns.Add("type");
ds.Tables[1].Columns.Add("value");
ds.Tables[0].Rows.Add("1", "token1");
ds.Tables[0].Rows.Add("2", "token2");
ds.Tables[1].Rows.Add("1", "t1", "v1");
ds.Tables[1].Rows.Add("1", "t1", "v2");
ds.Tables[1].Rows.Add("1", "t2", "v3");
ds.Tables[1].Rows.Add("2", "t2", "v4");
ds.Tables[1].Rows.Add("2", "t3", "v5");
ds.Tables[1].Rows.Add("2", "t3", "v6");
ds.Tables[1].Rows.Add("2", "t4", "v7");
ds.Relations.Add("rel_token", ds.Tables[0].Columns["id"], ds.Tables[1].Columns["token_id"]);
return ds;
}
private static async Task send()
{
DataSet ds;
DataTable dt;
while (true)
{
try
{
ds = dataAccess();
if (ds == null)
{
break;
}
List<Task> lst = new List<Task>();
foreach (DataRow dr in ds.Tables[0].Rows)
{
dt = dr.GetChildRows("rel_token").CopyToDataTable();
dt.Columns.Remove("token_id");
lst.Add(send_call((dr["token"]).ToString(), dt));
}
await Task.WhenAll(lst);
await Task.Delay(30000);
}
catch (HttpRequestException e)
{
string erMsg = e.Message;
}
}
}
private static HttpClient req { get; set; }
private static async Task send_call(string strToken, DataTable dt)
{
try
{
// DataTable to Json
string strJson = "";
foreach (DataRow dr in dt.Rows)
{
if (dt.Rows.IndexOf(dr) > 0)
{
strJson += ",";
}
strJson += "{";
foreach (DataColumn dc in dt.Columns)
{
if (dr.IsNull(dc))
{
continue;
}
if (dt.Columns.IndexOf(dc) > 0)
{
strJson += ",";
}
strJson += string.Format("\"{0}\":{1}{2}{1}",
dc.ColumnName,
dc.DataType == typeof(string) || dc.DataType == typeof(Guid) ? "\"" : null,
dc.DataType == typeof(bool) ? dr[dc].ToString().ToLower() : dr[dc]);
}
strJson += "}";
}
//
req.DefaultRequestHeaders.Add("token", strToken);
StringContent sc = new StringContent(strJson, Encoding.UTF8, "application/json");
HttpResponseMessage res = await req.PostAsync("my webhook url", sc);
string response = await res.Content.ReadAsStringAsync();
using (StreamWriter sw = new StreamWriter(#"C:\responseJson.txt", true, Encoding.UTF8))
{
sw.WriteLine(response);
}
}
catch (HttpRequestException e)
{
string strError = e.Message;
}
}
Code explanation:
I want to post each token child data separately which in each call,
header value is different.
Each time dataAccess() value is different, I just use a static data
for simulation.
Issues:
When I run the program I see no request in destination, so I start debugging and noticed the pointer will reach this line:
HttpResponseMessage res = await req.PostAsync("my webhook url", sc);
But the call wouldn't initiated and after that the pointer comes back at:
await Task.WhenAll(lst);
then comes to:
send();
And finished!
So the PostAsync method didn't work and due to that response didn't fill so the responseJson.txt didn't created.
Things I have tried:
Instead of send(); I used await send(); but I faced this error:
System.NullReferenceException: 'Object reference not set to an
instance of an object.
I have checked the strJson. The list converted to JSON properly.
I have checked my connection through another program, I could make
call to my webhook url.
Note: I had asked this question yesterday but because I explained it complicatedly I deleted that today and design a smaller one.
Create the HttpClient before trying to use it, by using the new keyword.
private static HttpClient req { get; set; } = new HttpClient();
public async Task Main()
{
await send();
}

Best way to get the error from a class method to web api call

I have a class that works in inserting the data correctly but this function is communicating with a webapi.
How do i return the exception information to the web api probably from a shared libary?
public void AddStockTransfer(StockTransfer item)
{
using (var connection = new SqlConnection(ConfigurationManager.AppSettings["DataConnectionLive"]))
{
connection.Open();
string insertQuery = #"
INSERT INTO[fuel].[StockTransfer]
([StockTransferGuid]
,[StockItemId]
,[Quantity]
,[SourceWarehouseId]
,[SourceBin]
,[TargetWarehouseId]
,[TargetBin]
,[DateTimeCreated]
,[DateTimeLastUpdated]
,[StockTransferStatus]
,[StatusMessage])
VALUES (#StockTransferGuid,#StockItemId,#Quantity,#SourceWarehouseId,#SourceBin,#TargetWarehouseId,#TargetBin,#DateTimeCreated,#DateTimeLastUpdated,#StockTransferStatus,#StatusMessage)";
var mydate = DateTime.Now;
var mydate2 = DateTime.Now;
var result = connection.Execute(insertQuery, new
{
item.StockTransferGuid,
item.StockItemId,
item.Quantity,
item.SourceWarehouseId,
item.SourceBin,
item.TargetWarehouseId,
item.TargetBin,
mydate,
mydate2,
item.StockTransferStatus,
item.StatusMessage
});
}catch (Exception ex)
{
logger.Warn("Connection string is " + connection.ConnectionString.ToString());
logger.Warn("Error occoured on add stock transfer funciton " + ex.Message.ToString());
}
}
}
I want to pass what the logger is seeing, and pass it to my web method.
[HttpPost]
public ActionResult Create(StockTransfer stockTrans)
{
try
{
database.AddStockTransfer(stockTrans);
}
catch (Exception ex)
{
logger.Warn("Error on Create ex");
}
return Json(true);
}

Passing JSON Data over TCP, Socket programming c#

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.

Array class not rendering into datagrid

The following application is not rendering the information that I am getting back from a web service into the datagrid. I know I am being able to connect to the webservice because I am getting the count for the class array. I am being able to get a Response.Write but when I try to pull all the information from the array class I haven't been able to see the elements nor to render the whole class into the data grid. What might be my issue? I am stuck with this one.
void LoadABCPhoneInfo()
{
PhoneTypeInfo[] PhoneInfo = GetPhoneInfo();
DataSet quoteDataSet = XmlString2DataSet(PhoneInfo.ToString());
//Here is NOT doing the databinding.
grdABC.DataSource = quoteDataSet;
grdABC.DataBind();
grdABC.Visible = true;
}
private PhoneTypeInfo[] GetPhoneInfo()
{
//string strGetPhoneInfo = String.Empty;
PhoneTypeInfo[] strGetPhoneInfo; //
try
{
OwnerAndReservation ownerAndReservationWS = new OwnerAndReservation();
strGetPhoneInfo = ownerAndReservationWS.GetPhoneTypes();
//GetPhoneTypesAsync()
//Here I can get the count for the array
Response.Write("GetPhoneInfo Length "+ strGetPhoneInfo);
}
catch (Exception ex)
{
//raise the error
string errorMessage = String.Format("Error while trying to connect to the Web Service. {0}", ex.Message);
throw new Exception(errorMessage);
}
//return the quote information
return strGetPhoneInfo;
}
private DataSet XmlString2DataSet(string xmlString)
{
//create a new DataSet that will hold our values
DataSet quoteDataSet = null;
//check if the xmlString is not blank
if (String.IsNullOrEmpty(xmlString))
{
//stop the processing
return quoteDataSet;
}
try
{
//create a StringReader object to read our xml string
using (StringReader stringReader = new StringReader(xmlString))
{
//initialize our DataSet
quoteDataSet = new DataSet();
//load the StringReader to our DataSet
quoteDataSet.ReadXml(stringReader);
}
}
catch
{
//return null
quoteDataSet = null;
}
//return the DataSet containing the stock information
return quoteDataSet;
}

Categories