Issue
I have a xamarin forms app and a REST web api created using ASP.net. The web api is running on the remote server. In that web api, I have classes for my database queries. I need to pass the server address, username, password and database name as connection string from my xamarin app to that particular class. How to serialize both the connection string and the object together?
My database query
public void addSalesReport(string connstr, SalesReport salesreport)
{
MySqlConnection myconn = new MySqlConnection(connstr);
string d = salesreport.Date.ToString("yyyy-MM-dd");
String sqlstr = "INSERT INTO salesreport (ID,sDate,ColorCopy,BwCopy,4RPrints,Misc,ExternalOrder,TotalSales,BwWastage,ColorWastage,Remarks) VALUES ('" + salesreport.ID + "','" + d + "'," + salesreport.ColorCopy + "," + salesreport.BwCopy + "," + salesreport.p4rPrint + "," + salesreport.Misc + ","+salesreport.ExternalOrder+","+salesreport.TotalSales+","+salesreport.BwWastage+","+salesreport.ColorWastage+",'"+salesreport.Remarks+"')";
MySqlCommand cmd = new MySqlCommand(sqlstr, myconn);
myconn.Open();
cmd.ExecuteNonQuery();
myconn.Close();
myconn.Dispose();
}
Control to post data to Mysql db
[HttpPost]
[Route("api/SalesReport", Name = "salesReport")]
public void PostUpdate([FromBody]string connstr , SalesReport value)
{
SalesDBConn db = new SalesDBConn();
db.addSalesReport(connstr, value);
}
Data service class in my Xamarin app
public async void addSalesReport(string connstr, SalesReport salesReport)
{
var conn = JsonConvert.SerializeObject(connstr);
var contentstr = new StringContent(conn, Encoding.UTF8, "application/json");
var data = JsonConvert.SerializeObject(salesReport);
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://myserverdomain.com/api/SalesReport", contentstr, content);
}
Solution
At first, we will have to introduce a new class which will act as wrapper container for your two inputs. Now whenever we serialize the class, both the inputs will get serialized together:
public class DataToPost
{
public string ConnectionString { get; set; }
public SalesReport SalesReportData { get; set; }
}
Then change the addSalesReport method as shown in the code snippet below:
public async void addSalesReport(string connstr, SalesReport salesReport)
{
HttpClient client = new HttpClient();
var objectDataToPost = new DataToPost { ConnectionString = connstr, SalesReportData = salesReport };
var data = JsonConvert.SerializeObject(objectDataToPost);
var content = new StringContent(data, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://myserverdomain.com/api/SalesReport", content, CancellationToken.None);
}
Answered By - RBT
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.