I'm developing an application in windows form,I have json data in my mysql database ,column = data
'{"money":0,"goal":0,"advantage":0}'
I'm trying to pull this data into tags in the form,label1.text="money";label2.text="goal";label3.text="advantage";
I could not find enough resources like this and I am inexperienced in this regard.
I uploaded the Json nouget package to my form.
output ='{"money":0,"goal":0,"advantage":0}'
How can I get json data as I want.
Thanks for your help.
MySqlConnection baglan = new MySqlConnection("Server=localhost;Database=json;user=root;Pwd=;");
private void Form1_Load(object sender, EventArgs e)
{
baglan.Open();
MySqlCommand kom = new MySqlCommand("SELECT * FROM player_accounts", baglan);
int count = Convert.ToInt32(kom.ExecuteScalar());
if (count != 0)
{
MySqlDataReader oku = kom.ExecuteReader();
while (oku.Read())
{
listBox1.Items.Add(oku["data"].ToString());
}
baglan.Close();
}
}
If the JSON data is always the same, the 1st thing I would create is a model class to house the data in C# land.
So, something like this::
public class Data
{
public decimal money { get; set; }
public int goal { get; set; }
public int advantage { get; set; }
}
Then, in your function, I would convert the JSON data to this new object and return from the function. For this you will need to go to nuget and install Newtonsoft.Json
Now you can write something like this:
var dbData = JsonConvert.DeserializeObject<Data>(oku["data"]);
instead of your line:
listBox1.Items.Add(oku["data"].ToString());
The function would look something like this:
private List<Data> GetDatabaseData()
{
var resultList = new List<Data>();
MySqlConnection baglan = new MySqlConnection("Server=localhost;Database=json;user=root;Pwd=;");
baglan.Open();
MySqlCommand kom = new MySqlCommand("SELECT * FROM player_accounts", baglan);
int count = Convert.ToInt32(kom.ExecuteScalar());
if (count != 0)
{
MySqlDataReader oku = kom.ExecuteReader();
while (oku.Read())
{
var data JsonConvert.DeserializeObject<Data>(ku["data"].ToString());
resultList.Add(data);
}
baglan.Close();
}
return resultList;
}
You can then use the function like this:
var dataList = GetDatabaseData();
foreach( var item in dataList )
{
listBox1.Items.Add(item.money);
}
Related
I have an app that checks the data on the server (json) and the database. I want when the id on json is not the same as the id on the database, it will insert all data with unequal id into the database.
Code:
var sqlpath = System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "ebookstore.db");
this.DataContextChanged += (s, e1) => { UpdateViewModel = DataContext as ViewModels.UpdateViewModel; };
string idDb = #"SELECT id FROM books where parent_folder_id = 2 and title like '%guru%'";
var IDdb = objConnUpdate.Prepare(idDb);
IDdb.Step();
iddb = IDdb[0].ToString();
IDDB = Convert.ToInt32(iddb.ToString());
ConnectionProfile connections = NetworkInformation.GetInternetConnectionProfile();
{
try
{
Downloading.IsOpen = true;
string urlPath1 = "https://.../fetch/k13G";
var httpClient1 = new HttpClient(new HttpClientHandler());
httpClient1.DefaultRequestHeaders.TryAddWithoutValidation("KIAT-API-KEY", "...*");
var values1 = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("halaman", "1"),
new KeyValuePair<string, string>("limit", "20"),
};
var response1 = await httpClient1.PostAsync(urlPath1, new FormUrlEncodedContent(values1));
response1.EnsureSuccessStatusCode();
string jsonText1 = await response1.Content.ReadAsStringAsync();
JsonObject jsonObject1 = JsonObject.Parse(jsonText1);
JsonArray jsonData1 = jsonObject1["data"].GetArray();
foreach (JsonValue groupValue in jsonData1)
{
JsonObject groupObject = groupValue.GetObject();
string ID = groupObject["id"].GetString();
BukuUpdate file1 = new BukuUpdate();
file1.ID = ID;
int intID = Convert.ToInt32(file1.ID);
if (intID != IDDB)
{
string jumlahidDb = #"SELECT COUNT(id) FROM books where parent_folder_id = 2 and id > " + IDDB + " and title like '%guru%'";
var jumlahIdDB = objConnUpdate.Prepare(jumlahidDb);
jumlahIdDB.Step();
if (jumlahiddb < jumlahbuku)
{;
if (nama == "Kelas_01_SD_")
{
DownloadBukuK2013G(url);
string K2013GUpdate = #"INSERT INTO books (id,title,folder_id,identifier,parent_folder_id) SELECT " + intID + ",'" + namaFile + ".pdf',34,'" + namaFile +
".pdf',2 WHERE not exists (select id AND title AND folder_id AND identifier AND parent_folder_id FROM books WHERE id=" + intID + " and title='" + namaFile +
".pdf' AND folder_id=34 and identifier='" + namaFile + ".pdf' and parent_folder_id=2)";
var K2013GQuery = objConnUpdate.Prepare(K2013GUpdate);
K2013GQuery.Step();
}
BukuUpdate.cs:
public class BukuUpdate
{
public string ID { get; set; }
}
Database:
I did not succeed in implementing it. How to handle it?
But if I use the code in my previous post, it only shows the first id in the database
You getting the first id by this code line iddb = IDdb[0].ToString(); for using. Actually the id list is saved in idDb variable.
I want if the id on json is not the same as the id on the database, then the data will be added to the database. If the same, then do nothing.
For this, you may just get all the ids from the database, and compare with the new income record from Json one by one. From your code snippet I'm not sure what's the Nuget package you're using for Sqlite, but the newest official tutorial using Microsoft.Data.SQLite package. I also strongly recommended you to use Microsoft.Data.SQLite package by following the official tutorial. By this way, the insert sample code may like this:
public sealed partial class MainPage : Page
{
private void btngettest_Click(object sender, RoutedEventArgs e)
{
List<String> ids = sqlhelp.GetData();
string idfromjson = "2";
foreach (string id in ids)
{
if (id != idfromjson)
{
//do insert operation
}
else
{
//do nothing
}
}
}
}
public class sqlhelp
{
public static void InitializeDatabase()
{
...
}
public static List<String> GetData()
{
List<String> entries = new List<string>();
using (SqliteConnection db =
new SqliteConnection("Filename=sqliteSample.db"))
{
db.Open();
SqliteCommand selectCommand = new SqliteCommand
("SELECT id from MyTable", db);
SqliteDataReader query = selectCommand.ExecuteReader();
while (query.Read())
{
entries.Add(query.GetString(0));
}
db.Close();
}
return entries;
}
Since your code snippet contains a lot of your own logic that I didn't give changes on your original code snippet. Please kindly reference my simple code which may be more clearly to know.
I am using MYSQL, WinForms and c#
I have a requirement when I next to get data from my database and export to a text file but each entry needs to be a specific length regardless of the information the database brings in -where data is less than total amount required, empty spaces are to follow it.
E.g First Name could bring in Sam or Samatha but I need to export to be 8 characters in length
"Sam " (8 total characters)
"Samatha "(8 total characters)
this is the function that I am using - any help would be greatly appreciated
public MySqlDataReader RunQueryTextFile(string query, string s1,string pathName)
{
MySqlConnection conDataBase = new MySqlConnection(connString);
MySqlCommand cmdDatabase = new MySqlCommand(query, conDataBase);
MySqlDataReader myReader;
StreamWriter sw = new StreamWriter(#pathName);
conDataBase.Open();
myReader = cmdDatabase.ExecuteReader();
while (myReader.Read())
{
sw.WriteLine (myReader[s1].ToString());
}
sw.Close();
conDataBase.Close();
return myReader;
}
use PadRight
int totalLength = 8;
myString.PadRight(totalLength, " ").
You trying to write procedural code. Think objects. I would do something like this
// create enum - how to pad
public enum PadStyle
{
Right
Left
}
// create attribute class
public class PaddingAttribute : Attribute
{
public int TotalLen {get;set;}
public PadStyle Style {get;set;}
public char PadChar {get;set;}
public int Order {get;set;}
}
// Create class record base - this one knows how to get properties, read attributes and pad values into one string
public class RecordBase
{
protected string CreateRecordProtected()
{
// here you
// 1 - use reflection to get properties
// 2 - use reflection to read PaddingAttribute from properties
// 3 - pad property values using data in PaddingAttribute
// 4 - concatenate record
// something like
var result = o.GetPropeties().Where(...).Select(...padding logic...);
return string.Join("", result);
// padding logic = string.PadRight or string.PadLeft
}
}
Read here how to deal with attribute classes
// Create class record - this one corresponds to your DB
public class Record : RecordBase
{
private const string _fn_FiedName = "firstName";
private const string _ln_FiedName = "lastName";
public Record(IDataReader r)
{
FirstName = r[_fn_FiedName];
LastName = r[_ln_FiedName];
}
[Padding(TotalLen = 15, Style = PadStyle.Right, PadChar = " ", Order = 1)]
public string FirstName{get;set;}
[Padding(TotalLen = 20, Style = PadStyle.Right, PadChar = " ", Order = 2)]
public string LastName {get;set;}
public override string ToString()
{
return base.CreateRecordProtected();
}
And now, your code with some mods
var recList = new List<Record>();
using (var conn = new MySqlConnection(connString))
{
using (var cmd = new MySqlCommand(query, conn))
{
conn.Open();
using (var reader = cmdDatabase.ExecuteReader())
{
while (reader.Read())
{
recList.Add(new Record(reader));
}
}
}
conn.Close();
}
if (!recList.Any()) // System.Linq
return;
IEnumerable<string> textFileRecords = recList.Select(x => x.ToString());
File.WriteAllLines(pathName, textFileRecords); // System.IO
Now, you have some decent reusable code.
NOTE: if data amount is huge, you can append right in while
var rec = new Record(reader);
rec.ToString() // append this
hello i try to create an object named 'gerant'
class gerant
{
public double CIN_GERANT, NUM_TEL_GERANT, MOBILE_GERANT;
public string NOM_GERANT, PRENOM_GERANT, ADRESSE__GERANT, MAIL_GERANT, VILLE_GERANT;
public int CP_GERANT;
public DateTime DATE_GERANT;
public gerant(double _Cin_gerant, string _Nom_Gerant, string _Prenom_Gerant, string _Adresse_Gerant, double _Num_Tel_Gerant, string _Mail_Gerant, double _Mobile_Gerant, int _cp_gerant, string _ville_gerant, DateTime _date_gerant)
{
this.CIN_GERANT = _Cin_gerant;
this.NOM_GERANT = _Nom_Gerant;
this.PRENOM_GERANT = _Prenom_Gerant;
this.ADRESSE__GERANT = _Adresse_Gerant;
this.NUM_TEL_GERANT = _Num_Tel_Gerant;
this.MAIL_GERANT = _Mail_Gerant;
this.MOBILE_GERANT = _Mobile_Gerant;
this.CP_GERANT = _cp_gerant;
this.VILLE_GERANT = _ville_gerant;
this.DATE_GERANT = _date_gerant;
}
public gerant getinfogerant()
{
gerant gerer = null;
string sql_gerant = "select CIN,NOM,PRENOM,ADRESS_PERSONNEL,NUM_TEL,MAIL,MOBILE,CP_GERANT,VILLE_GERANT,DATE_CIN from GERANT";
connexion connect = new connexion();
OleDbConnection connection = connect.getconnexion();
// try
//{
connection.Open();
OleDbCommand cmd = new OleDbCommand(sql_gerant, connection);
OleDbDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
gerer = new gerant(reader.GetDouble(0),
reader.GetString(1),
reader.GetString(2),
reader.GetString(3),
reader.GetDouble(4),
reader.GetString(5),
reader.GetDouble(6),
reader.GetInt32(7),
reader.GetString(8),
reader.GetDateTime(9)
);
}
connection.Close();
return gerer;
}
}
but when i try to fill my combobox with gerant i try to insert this code
foreach(Modele.gerant ligne in liste_gerant)
{
}
but i make this error for me
foreach statement cannot operate on variables of type 'gerant' because 'gerant' does not contain a public definition for 'GetEnumerator'
how can i resolve that?
Based on your comments. The gerant class is not a collection of any sort, and your getinfogerant doesn't return a collection.
So, the problem is that you are trying to iterate over a single value.
From the query You use in getinfogerant I guess you want it to get all "gerant" in your db, not just one?
However now you're just returning the first. You should change its return type to List and turn the if (reader.Read()) into a while loop to fill the list, then return the whole list at the end.
I'm trying to format XML from a MySQL query to emulate what a client frontend is expecting for input. I have no control over what the client requires, so I have to match what I've gotten from Wireshark captures. I am not married to the idea of adding columns to the dataset to do this, and I can probably just do a search and replace for the additions to the XML, however, I have a large number of very similar, yet different queries & outputs to write, and I'd prefer to do something that scales well. Unfortunately it'll be throw away code because when I write the new front end client for this, we won't be tracking a lot of the data the current legacy system does like client IP address, or the supposedly unique "ActionID" both of which you'll see referenced below, nor will I have to do anything with XML, it'll all be MySQL driven queries.
My output should be in a form like this:
<PCBDatabaseReply>
<SearchResult>
<SBE_PCB_Data PCBID="53">
<Termination ActionID="97DF" User="UName:192.168.255.255" Date="2012-09-26T13:15:51" PCBID="53">
<Reason>Other</Reason>
</Termination>
</SBE_PCB_Data>
</SearchResult>
</PCBDatabaseReply>
The results from my query look like this:
EventType User Date PCBID Reason
Termination UName 2012-09-26T13:15:51 53 Other
My output XML currently looks like this:
<PCBDatabaseReply>
<Termination User="UName" Date="2012-09-26T13:15:51" PCBID="53">
<EventType>Termination</EventType>
<Reason>Other</Reason>
</Termination>
</PCBDatabaseReply>
Using this code:
string mysqlConnection = "server=server;\ndatabase=database;\npassword=password;\nUser ID=user;";
MySqlConnection connection = new MySqlConnection(mysqlConnection);
connection.Open();
string command = "SELECT eventtypes.EventType, events.User, DATE_FORMAT(events.DateTime,'%Y-%m-%dT%T') AS Date, pcbid.PCBID, getReasons.ItemValue AS Reason " +
"FROM events " +
"INNER JOIN pcbid ON events.PCBID = pcbid.PCBID " +
"INNER JOIN eventtypes " +
"ON events.EventType_ID = eventtypes.EventType_ID " +
"LEFT JOIN getReasons " +
"ON getReasons.Event_ID = events.Event_ID " +
"WHERE eventtypes.EventType = 'termination'";
//create fake "ActionID"
var random = new Random();
string ActionID = String.Format("{0}\"{1:X4}\"", "ActionID=", random.Next(0xffff));
MySqlDataAdapter adapter = new MySqlDataAdapter(command, connection);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
//change upper level node name to what's expected in client-speak
dataSet.DataSetName = "PCBDatabaseReply";
//change first child node name to client-speak eventType
dataSet.Tables[0].TableName = dataSet.Tables[0].Rows[0][0].ToString();
StringWriter writer = new StringWriter();
var ds1 = dataSet.Tables[0];
DataColumn dcEventType = ds1.Columns[0];
DataColumn dcUser = ds1.Columns[1];
DataColumn dcDate = ds1.Columns[2];
DataColumn dcPCBID = ds1.Columns[3];
dcEventType.ColumnMapping = MappingType.Element;
dcUser.ColumnMapping = MappingType.Attribute;
dcDate.ColumnMapping = MappingType.Attribute;
dcPCBID.ColumnMapping = MappingType.Attribute;
dataSet.Tables[0].WriteXml(writer, true);
Console.WriteLine(writer.ToString());
I need to inject several things
At the top beneath <PCBDatabaseReply>:
<SearchResult>
<SBE_PCB_Data PCBID="53">
In the Termination tag: (from the fake ActionID in the code)
ActionID="0xnnnn" & append ":192.168.255.255" to the end of the user name
And then close with the appropriate tags:
</SBE_PCB_Data>
</SearchResult>
I have tried adding a dummy column for the "SBE_PCB_Data" tag, which didn't work.
DataColumn dcSBE_PCB_Data = new DataColumn("SBE_PCB_Data", System.Type.GetType("System.String"), "SBE_PCB_Data", MappingType.Element);
dcSBE_PCB_Data.DefaultValue = "SBE_PCB_Data";
//add to the dataset
dataSet.Tables[0].Columns.Add(dcSBE_PCB_Data);
//move it to the zeroth position
dcSBE_PCB_Data.SetOrdinal(0);
This just makes it show up as:
<SBE_PCB_Data>SBE_PCB_Data</SBE_PCB_Data>
I need it to wrap around the rest of the XML as an ancestor node.
How best to inject the XML I need into the results?
EDIT: refactored according to excellent example below
**EDIT: updated with final code
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Xml.Linq;
using MySql.Data.MySqlClient;
namespace TerminationResults
{
public class SearchResult
{
//all possible event detail tags (test items are excluded)
public string EventType { get; set; }
public string User { get; set; }
public string Date { get; set; }
public string PCBID { get; set; }
public string EAReason { get; set; }
public string ETReason { get; set; }
public string Notes { get; set; }
public string Reason { get; set; }
public string SBEJobNumber { get; set; }
public string SBEModelNumber { get; set; }
public string SBEPN { get; set; }
public string SBESerialNumber { get; set; }
//create fake IP address since we no longer track it
public string UserAndIP
{
get { return String.Format("{0}:192.168.255.255", User); }
set {}
}
//create fake actionID since the originals weren't inserted into the database because they weren't unique.
public string ActionId
{
get { return String.Format("{0:X4}", new Random().Next(0xffff)); }
set {}
}
}
internal class Program
{
private static void Main(string[] args)
{
var searchResults = GetSearchResults();
var xml = TransformList(searchResults);
Console.WriteLine(xml);
Console.ReadLine();
}
public static IEnumerable<SearchResult> GetSearchResults()
{
List<SearchResult> searchResults = new List<SearchResult>();
try
{
const string mysqlConnection = #"server=server;
database=database;
password=password;
User ID=username;";
MySqlConnection conn = new MySqlConnection(mysqlConnection);
conn.Open();
using (conn)
{
string cmd = #"SELECT eventtypes.EventType, events.User,
DATE_FORMAT(events.DateTime,'%Y-%m-%dT%T') AS Date,
pcbid.PCBID,
getEAReasons.ItemValue AS EAReason,
getETReasons.ItemValue AS ETReason,
getReasons.ItemValue AS Reason,
getNotes.ItemValue AS Notes,
getSBEJobNumbers.ItemValue AS SBEJobNumber,
getSBEModelNumbers.ItemValue AS SBEModelNumber,
getSBEPNs.ItemValue as SBEPN,
getSBESerialNumbers.ItemValue as SBESerialNumber
FROM events
INNER JOIN pcbid ON events.PCBID = pcbid.PCBID
INNER JOIN eventtypes
ON events.EventType_ID = eventtypes.EventType_ID
LEFT JOIN getEAReasons
ON getEAReasons.Event_ID = events.Event_ID
LEFT JOIN getETReasons
ON getETReasons.Event_ID = events.Event_ID
LEFT JOIN getReasons
ON getReasons.Event_ID = events.Event_ID
LEFT JOIN getNotes
ON getNotes.Event_ID = events.Event_ID
LEFT JOIN getSBEJobNumbers
ON getSBEJobNumbers.Event_ID = events.Event_ID
LEFT JOIN getSBEModelNumbers
ON getSBEModelNumbers.Event_ID = events.Event_ID
LEFT JOIN getSBEPNs
ON getSBEPNs.Event_ID = events.Event_ID
LEFT JOIN getSBESerialNumbers
ON getSBESerialNumbers.Event_ID = events.Event_ID
WHERE eventtypes.EventType = 'termination'";
try
{
using (MySqlDataAdapter adapter = new MySqlDataAdapter(cmd, conn))
{
DataSet dataSet = new DataSet();
adapter.Fill(dataSet);
DataTable ds = dataSet.Tables[0];
for (int row = 0; row < ds.Rows.Count; row++ )
{
SearchResult result = new SearchResult()
{
EventType = ds.Rows[row]["EventType"].ToString(),
User = ds.Rows[row]["User"].ToString(),
Date = ds.Rows[row]["Date"].ToString(),
PCBID = ds.Rows[row]["PCBID"].ToString(),
EAReason = ds.Rows[row]["EAReason"].ToString().Any() ? ds.Rows[row]["EAReason"].ToString() : null,
ETReason = ds.Rows[row]["ETReason"].ToString().Any() ? ds.Rows[row]["ETReason"].ToString() : null,
Notes = ds.Rows[row]["Notes"].ToString().Any() ? ds.Rows[row]["Notes"].ToString() : null,
Reason = ds.Rows[row]["Reason"].ToString().Any() ? ds.Rows[row]["Reason"].ToString() : null,
SBEJobNumber = ds.Rows[row]["SBEJobNumber"].ToString().Any() ? ds.Rows[row]["SBEJobNumber"].ToString() : null,
SBEModelNumber = ds.Rows[row]["SBEModelNumber"].ToString().Any() ? ds.Rows[row]["SBEModelNumber"].ToString() : null,
SBEPN = ds.Rows[row]["SBEPN"].ToString().Any() ? ds.Rows[row]["SBEPN"].ToString() : null,
SBESerialNumber = ds.Rows[row]["SBESerialNumber"].ToString().Any() ? ds.Rows[row]["SBESerialNumber"].ToString() : null
};
searchResults.Add(result);
}
}
}
catch (MySqlException ex)
{
Console.WriteLine(ex);
}
catch(Exception ex)
{
Console.WriteLine(ex);
}
}
}
catch (MySqlException ex)
{
Console.WriteLine(ex);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
return searchResults;
}
public static XElement TransformSearchResult (SearchResult result)
{
return new XElement("SBE_PCB_Data",
new XAttribute("PCBID", result.PCBID),
new XElement(result.EventType,
new XAttribute("ActionID", result.ActionId),
new XAttribute("User", result.UserAndIP),
new XAttribute("Date", result.Date),
new XAttribute("PCBID", result.PCBID),
result.EAReason == null ? null : new XElement("EAReason", result.EAReason),
result.ETReason == null ? null : new XElement("ETReason", result.ETReason),
result.Reason == null ? null : new XElement("Reason", result.Reason),
result.Notes == null ? null : new XElement("Note", result.Notes),
result.SBEJobNumber == null ? null : new XElement("SBEJobNumber", result.SBEJobNumber),
result.SBEModelNumber == null ? null : new XElement("SBEModelNumber", result.SBEModelNumber),
result.SBEPN == null ? null : new XElement("SBEPN", result.SBEPN),
result.SBESerialNumber == null ? null : new XElement("SBESerialNumber", result.SBESerialNumber)
)
);
}
public static XElement TransformList (IEnumerable<SearchResult> listOfResults)
{
return new XElement("PCBDatabaseReply",
new XElement("SearchResult",
from r in listOfResults
select TransformSearchResult(r)));
}
}
}
Had to do some tweaking to get this to run, but the concept is sound, and I like that it's extensible. It doesn't quite give the right output yet, but I can tweak that as well.
Ok, Let's refactor this.
Lets not try and do this directly from your dataset, you are trying to do to many things in your method here, it's messy hard to maintain and very hard to unit test.
The first thing we should do is create a SearchResult class that we can work with more easily, this is also a convenient place to put in our Business rules (Ip added to User and random ActionId) it also means that we can easily mock up data into this class without having to hit the database, we can then test our transform logic as a unit test, not an integration test (which are slower, and have more dependencies)
public class SearchResult
{
public string EventType {get ;set;}
public string User {get ; set;}
public DateTime Date {get;set;}
public int PCBID {get;set;}
public string Reason {get;set;}
public string UserAndIP
{
get
{
return String.Format("{0}:192.168.255.255",User);
}
}
public string ActionId
{
get
{
return String.Format("{0:X4}", new Random().Next(0xffff));
}
}
}
So lets rewrite the query to now populate a list of SearchResult's instead of a dataset
public IEnumerable<SearchResult> GetSearchResults()
{
using(var conn = GetYourConnection())
{
conn.open();
using(var cmd = conn.CreateCommand())
{
cmd.CommandText = GetYourQueryString();
using(var reader = cmd.ExecuteReader())
{
while(reader.Read())
{
var result = new SearchResult
{
.... populate from reader...
}
yield return result;
}
}
}
}
}
So now that we have a SearchResult class and a query method that gives us a list of them, lets transform that to your required XML.
Firstly, I'll make some assumtions that are not 100% clear from your question. (if these are not correct, it will be easy enough to modify)
I'll assume that we are creating a search result tag for each search
result returned from our query. And that these will be contained in
the PCBDatabaseReply tag.
The xml tag "Termination" is the value of the Event Type, so I'll
assume that tag should be the EventType value.
Lets use Linq to XML to create the XML from the list of SearchResults
Firstly We'll create a method that transforms individual SearchResults (the contents of the SearchResult tag)
public XElement TransformSearchResult(SearchResult result)
{
return new XElement("SearchResult",
new XElement("SBE_PCB_Data", new XAttribute("PCBID", result.PCBID)),
new XElement(result.EventType,
new XAttribute("ActionID", result.ActionId),
new XAttribute("User", result.UserAndIP),
new XAttribute("Date", result.Date),
new XAttribute("PCBID", result.PCBID)),
new XElement("Reason", result.Reason));
}
Secondly we'll create the method to transform the list
public XElement TransformList(IEnumerable<SearchResult> listOfResults)
{
return new XElement("PCBDatabaseReply",
from r in listOfResults
select TransformSearchResult(r));
}
Now our main calling method simply becomes...
var searchResults = GetSearchResults();
var xml = TransformList(searchResults);
I am trying to do a tracker application in wp8. I want to save the values in database using Sqlite. All the values r working (time, distance and pace). After pressing Stop button, I want the values to be posted in a table view using Sqlite as u can see in the second screen. Any good suggestions or links are appreciated. Thank u.
Try this nokia developer site here.
Gives you a small tutorial how to use sqlite on windows phones.
This piece of code gives you the answer?
private void Insert_Click_1(object sender, RoutedEventArgs e)
{
// Create a new task.
Task task = new Task()
{
Title = TitleField.Text,
Text = TextField.Text,
CreationDate = DateTime.Now
};
/// Insert the new task in the Task table.
dbConn.Insert(task);
/// Retrieve the task list from the database.
List<Task> retrievedTasks = dbConn.Table<Task>().ToList<Task>();
/// Clear the list box that will show all the tasks.
TaskListBox.Items.Clear();
foreach (var t in retrievedTasks)
{
TaskListBox.Items.Add(t);
}
}
hm, i see this is a retrieval piece of code. Maybee this site helps you further.
The following example is an insert:
public void Initialize()
{
using ( var db = new SQLite.SQLiteConnection( _dbPath ) )
{
db.CreateTable<Customer>();
//Note: This is a simplistic initialization scenario
if ( db.ExecuteScalar<int>(
"select count(1) from Customer" ) == 0 )
{
db.RunInTransaction( () =>
{
db.Insert( new Customer() {
FirstName = "Jon", LastName = "Galloway" } );
db.Insert( new Customer() {
FirstName = "Jesse", LastName = "Liberty" } );
} );
}
else
{
Load();
}
}
}
I'm assuming your table is.
public class HistoryTable
{
public string date { get; set; }
public string time { get; set; }
public double pace { get; set; }
public double distance { get; set; }
}
Insert values using this statement.
string date = DateTime.Now.ToShortDateString();
string time = DateTime.Now.ToShortTimeString();
double pace = 16;
double distance = 4;
SQLiteConnection conn = new SQLiteConnection(System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Database.sqlite"));
conn.Execute("Insert into HistoryTable values(?,?,?,?)", date, time, pace, distance);
Fetch your data as below statement, I'm assuming that you know how to bind the data in listbox if there is need. I'm taking the values in textbox.
SQLiteConnection conn = new SQLiteConnection(System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Database.sqlite"));
var result = conn.Table<HistoryTable>();
foreach (var val in result)
{
TimeSpan pace = TimeSpan.FromMinutes(val.pace);
TextBoxDate.Text = val.date;
TextBoxTime.Text = val.time;
TextBoxPace.Text = pace.Minutes + ":" + pace.Seconds;
TextBoxDistance.Text = val.distance + " Km";
}
The reason why I used Pace as double because I can use this double value as total minutes and can be changed as timespan(in minutes and seconds). For any other queries you can ask any time.
To get exactly the same format as you ask in your question you should use like this also.
string date = string.Format("{0:00}.{1:00}.{2:00}", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year);
string time = DateTime.Now.ToString("HH:mm:ss");
double pace = 16.5;
double distance = 4;
SQLiteConnection conn = new SQLiteConnection(System.IO.Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "Database.sqlite"));
conn.Execute("Insert into HistoryTable values(?,?,?,?)", date, time, pace, distance);
At the time of fetching info, please change the above steps by this.
TextBoxDistance.Text = string.Format("{0:0.00}Km", val.distance);