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;
}
Related
I'm deserializing a JSON using Newtonsoft for my Xamarin application, I am facing some issue when deserializing DateTime.
I have tried using the same code on asp.net C#, and storing the data into a dataset. The C# gave me the right output. However when it goes to Xamarin form, it produces the wrong output.
Expected result should be 2/4/2019 12:00:00 AM.
I have no idea how the 4/1/2019 4:00:00PM came from.
Wrong output using Xamarin
Right output using C#
using Xamarin
public List<GetFleet> GetDefaults(string xUserID)
{
string inJson =
List<GetFleet> tempList = new List<GetFleet>();
try
{
Uri serverUri2 = new Uri(inJson.ToString());
string rs2 = RequestGeoHttpAsString(serverUri2);
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(rs2);
DataTable dataTable = dataSet.Tables["Table1"];
foreach (DataRow row in dataTable.Rows)
{
tempList.Add(new GetFleet
{
FleetID = row["registrationNumber"].ToString(),
FleetName = row["Location"].ToString(),
FleetIgnition = row["Ignition"].ToString(),
FleetFuel1 = row["sFuel1"].ToString(),
FleetStartTime = row["startTime"].ToString()
});
}
}
catch (Exception ex)
{
string exe = ex.Message;
}
return tempList;
}
using C#
protected void Page_Load(object sender, EventArgs e)
{
string url =
Uri serverUri2 = new Uri(url.ToString());
string rs2 = RequestGeoHttpAsString(serverUri2);
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(rs2);
DataTable dataTable = dataSet.Tables["Table1"];
string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
Response.Write(json);
}
public string RequestGeoHttpAsString(Uri address)
{
string result = "";
// Create the web request
HttpWebRequest request = System.Net.WebRequest.Create(address) as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Read the whole contents and return as a string
result = reader.ReadToEnd();
}
return result;
}
I used another alternative solution on this matter.
I converted the date into string/VARCHAR in backend.
When it returns in JSON, it would be in text.
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 want to add data at the end of existing data in resource file on the click of button in windows form.
I have a windows form with 3 text boxes -
text_box1: Name
text_box2: Value
text_box3: Comments
and a button named as Save.
code for button:
private void button1_Click(object sender, EventArgs e)
{
myMethod.Create(textBox1.Text, textBox2.Text, textBox3.Text);
}
Method to add data in resource file:
public class myMethod
{
public static void Create(string myName, string myValue, string myComment)
{
try
{
ResXResourceReader resxReader = new ResXResourceReader(#"D:\Validator_Tool\resx\resx\myres.resx");
resxReader.UseResXDataNodes = true;
IDictionaryEnumerator data = resxReader.GetEnumerator();
while (data.MoveNext())
{
ResXResourceWriter resxWriter = new ResXResourceWriter(#"D:\Validator_Tool\resx\resx\myres.resx");
var node = new ResXDataNode(myName, myValue);
node.Comment = myValue;
resxWriter.AddResource(node);
resxWriter.Close();
}
}
catch (FileNotFoundException caught)
{
MessageBox.Show("Source: " + caught.Source + " Message: " + caught.Message);
}
}
}
Please help me in this problem to add data in resource file because with this code my data is overwrite with existing data but I want my data should append at the end of the existing data.
This code giving me exception too while using IDictionaryEnumerator exception is:
System.InvalidOperationException
This is a snippet, to add a new line to your resx and keep the old records:
var reader = new ResXResourceReader("filename");
var node = reader.GetEnumerator();
var writer = new ResXResourceWriter("filename");
while (node.MoveNext())
{
writer.AddResource(node.Key.ToString(), node.Value.ToString());
}
var newNode = new ResXDataNode("name", "value");
writer.AddResource(newNode);
writer.Generate();
writer.Close();
This will re-write your old lines and add your new line.
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.
I am programming a client program that calls a webmethod but when I get the return data there are missing values on some of the fields and objects.
The webmethod in turn is calling a WCF method and in the WCF method the return data is fine. But when it is passing to the webservice the return data is missing.
Is there any way to fix this problem?
This is my client code calling the webservice:
ReLocationDoc query = new ReLocationDoc();
query.PerformerSiteId = 1;
query.PerformerUserId = 1;
query.FromStatus = 10;
query.ToStatus = 200;
ReLocationDoc doc = new ReLocationDoc();
ServiceReference1.QPSoapClient service = new QPSoapClient();
try {
service.GetRelocationAssignment(query, out doc);
string test = doc.Assignment.Id.ToString();
} catch(Exception ex) {
MessageBox.Show(ex.Message);
}
The webmethod code is here:
[WebMethod]
return m_reLocationClient.GetRelocationAssignment(query, out reLocationDoc);
}
And at last the WCF code:
public ReLocationResult GetRelocationAssignment(ReLocationDoc query, out ReLocationDoc reLocationDoc) {
try {
LOGGER.Trace("Enter GetRelocationAssignment().");
ReLocationResult result = reLocationCompactServiceClient.GetRelocationAssignment(out reLocationDoc, query);
if(reLocationDoc.Assignment == null || reLocationDoc.Assignment.CurrentStatus == STATUS_FINISHED) {
ReLocationDoc newQuery = new ReLocationDoc();
newQuery.Assignment = new AssignmentDoc();
newQuery.Assignment.EAN = DateTime.Today.ToString();
newQuery.PerformerSiteId = QPSITE;
newQuery.PerformerUserId = QPUSER;
reLocationDoc.AssignmentStatus = m_settings.ReadyStatus; ;
result = reLocationCompactServiceClient.CreateReLocationAssignment(out reLocationDoc, newQuery);
}
return result;
} finally {
LOGGER.Trace("Exit GetRelocationAssignment().");
}
}
The GetRelocationAssignment:
public ReLocationResult GetRelocationAssignment(ReLocationDoc query, out ReLocationDoc reLocationDoc) {
try {
LOGGER.Trace("Enter GetRelocationAssignment().");
ReLocationDoc doc = new ReLocationDoc();
ReLocationResult result = new ReLocationResult();
new Database(Connection).Execute(delegate(DBDataContext db) {
User user = GetVerifiedUser(db, query, MODULE_ID);
SiteModule siteModule = SiteModule.Get(db, query.PerformerSiteId, MODULE_ID);
Status status = Status.Get(db, query.FromStatus, query.ToStatus, 0);
Status startStatus = Status.Get(db, query.FromStatus, 0);
Status endStatus = Status.Get(db, query.ToStatus, 0);
IQueryable<Assignment> assignments = Assignment.GetAssignmentsWithEndStatus(db, siteModule, endStatus);
assignments = Assignment.FilterAssignmentStartStatus(assignments, startStatus);
foreach(Assignment assignment in assignments) {
LOGGER.Debug("Handling assignment: " + assignment.Id);
result.Status = true;
AssignmentDoc assignmentDoc = FillAssignmentDoc(assignment);
//ReLocationDoc doc = new ReLocationDoc();
AssignmentStatus sts = assignment.AssignmentStatus.OrderByDescending(ass => ass.Id).First();
assignmentDoc.CurrentStatus = sts.Status.Zone;
Status currentStatus = sts.Status;
IList<Item> items = assignment.Items.ToList();
IList<ItemDoc> itemDocs = new List<ItemDoc>();
foreach(Item item in items) {
ItemDoc itemDoc = FillItemDoc(item);
ItemDetail itemDetail;
if(ItemDetail.TryGet(db, item.Id, out itemDetail)) {
ItemDetailDoc itemDetailDoc = FillItemDetailDoc(itemDetail);
itemDoc.Details = new ItemDetailDoc[1];
Event eEvent = null;
if(Event.GetEvent(db, itemDetail, currentStatus, out eEvent)) {
EventDoc eventDoc = FillEventDoc(eEvent);
itemDetailDoc.Events = new EventDoc[1];
if(eEvent.LocationId.HasValue) {
Location location = null;
if(Location.TryGet(db, eEvent.LocationId.Value, out location)) {
eventDoc.Location = new LocationDoc();
eventDoc.Location = FillLocationDoc(location, db);
}
}
itemDetailDoc.Events[0] = eventDoc;
}
itemDoc.Details[0] = itemDetailDoc;
}
itemDocs.Add(itemDoc);
}
assignmentDoc.Items = itemDocs.ToArray();
doc.Assignment = assignmentDoc;
}
}, delegate(Exception e) {
result.Message = e.Message;
});
reLocationDoc = doc;
return result;
} finally {
LOGGER.Trace("Exit GetRelocationAssignment().");
}
}
In all this code the return data is fine. It is loosing data only when passing to the webmetod.
Enter code here.
Also, the ordering of the XML tags in the message makes difference - I had a similar problem about maybe two years ago, and in that case parameter values were dissappearing during transmission because the sending part ordered the tags differently than what was defined in the schema.
Make surethe XML tags are being accessed with the same casing at either end. if the casing is not the same then the value won't be read.
You should check it all message are sending back from your webservice. Call your webservice manually and check its response.
If all data is there, probably your webservice reference is outdated; update it by right-clicking your webservice reference and choose "Update"
If your data don't came back, your problem is probably related to webservice code. You should check your serialization code (if any) again, and make sure all returned types are [Serializable]. You should check if all return types are public as it's mandatory for serialization.
As noted per John Saunders, [Serializable] isn't used by XmlSerializer.