I'm writing an app and I'm trying to get data out of an existing database. I succeeded in importing the database and addressing it correctly using this tutorial. When I try to execute a query, my object are empty.
This is my code
public void TestDB() {
using (var conn = new SQLite.SQLiteConnection(dbPath))
{
var cmd = new SQLite.SQLiteCommand (conn);
cmd.CommandText = "select * from totem";
var r = cmd.ExecuteQuery<Totem> ();
tekst.Text = r[0].Title;
}
}
}
public class Totem
{
[PrimaryKey, AutoIncrement]
public string TotemId { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public string Synonyms { get; set; }
}
According to debug, r is a list and it contains 395 entries (the number of entries there are in Totem), but the Totem objects are empty as you can see:
Does anyone know how to initialize them?
Thanks in advance.
Related
I have a .Json URL that contains Json format data.
HTTPS://XXXX/fetch-transaction?fromdate=2020-10-13&toDate=2020-10-20 (Not working just an example)
[
{
"orderId": 110,
"consignmentNumber": "TEST",
"itemNumbers": [
"TEST"
],
"country": "UK",
"orderType": "ORDER_HOME_DELIVERY",
"paymentTransactionId": "395611",
"priceInOre": 5900,
"paidAt": "2020-10-16 10:51:08",
"orderNumber": "7000067718",
"articleName": "SOUTH-2"
}
]
I would like to insert data into a SQL server table and wonder if it's possible to use SQL server and t-SQL directly here or should I go for VS and C#?
If C# is the preferred choice can someone pleae guide me on how I would accomplish it?
I have created a Console application in Visual studio (however it might be a better solution to use something els then to create a command line applcation?) or guide me in the right direction.
You can try the following code to get the value from the json txt and transfer it to the sql server table.
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
class Program
{
static void Main(string[] args)
{
string json = File.ReadAllText("D:\\test1.txt");
List<Example> list = JsonConvert.DeserializeObject<List<Example>>(json);
string strcon = #"Connstr";
SqlConnection connection = new SqlConnection(strcon);
connection.Open();
string sql = "Insert into JsonData(orderId,consignmentNumber,itemNumbers,country,orderType,paymentTransactionId,priceInOre,paidAt,orderNumber,articleName) values(#orderId,#consignmentNumber,#itemNumbers,#country,#orderType,#paymentTransactionId,#priceInOre,#paidAt,#orderNumber,#articleName)";
SqlCommand command = new SqlCommand(sql, connection);
foreach (Example item in list)
{
command.Parameters.AddWithValue("#orderId", item.orderId);
command.Parameters.AddWithValue("#consignmentNumber", item.consignmentNumber);
command.Parameters.AddWithValue("#itemNumbers", item.itemNumbers.First());
command.Parameters.AddWithValue("#country", item.country);
command.Parameters.AddWithValue("#orderType", item.orderType);
command.Parameters.AddWithValue("#paidAt", item.paidAt);
command.Parameters.AddWithValue("#paymentTransactionId", item.paymentTransactionId);
command.Parameters.AddWithValue("#priceInOre", item.priceInOre);
command.Parameters.AddWithValue("#articleName", item.articleName);
command.Parameters.AddWithValue("#orderNumber", item.orderNumber);
}
command.ExecuteNonQuery();
connection.Close();
}
}
public class Example
{
public int orderId { get; set; }
public string consignmentNumber { get; set; }
public List<string> itemNumbers { get; set; }
public string country { get; set; }
public string orderType { get; set; }
public string paymentTransactionId { get; set; }
public int priceInOre { get; set; }
public string paidAt { get; set; }
public string orderNumber { get; set; }
public string articleName { get; set; }
}
Final result:
Edit:
var json = new WebClient().DownloadString("URL");
I am using Entity Framework 5.0 and I created my database from model. The below is the screenshot of the edmx diagram.
I am working towards to a below structure of data:
On given Client ID give me list of Theader which belongs to that ClientID and its TReports so I modeled my models as below:
public class TReportHeaderModel
{
public int ID { get; set; }
public int ClientID { get; set; }
public string THeaderTitle { get; set; }
public int RowNumber { get; set; }
public IList<TReportModel> TReports { get; set; }
}
public class TReportModel
{
public int ID { get; set; }
public string TReportName { get; set; }
public string URL { get; set; }
public int RowNumber { get; set; }
}
So when I query to get Theaders and its each report for given clientID:
I am listing the headers first for given clientID:
public IList<TReportHeaderModel> GetHeadersByClient(int ClientID)
{
using (var connection = new TReportEntitiesConnection())
{
var clientHeaders= (from st in connection.THeaders
where ClientID == st.ClientID
select new TReportHeaderModel
{
ID=st.ID,
THeaderTitle=st.THeaderTitle,
RowNumber=st.RowNumber
}).ToList();
return (clientHeaders);
}
}
And then to get the list of reports for each title and this is where I am stuck--->
public IList<TReportModel> GetChildReportsByHeader(int THeaderID)
{
using (var connection = new TReportEntitiesConnection())
{
// ....
}
}
Instead of separating it by get the headers by client first and then get the report by header id, is it possible to combine it in one method? sorry for the confusing explanation but I am new to LINQ Query so please understand.
The below is the ideal structure for the UI implemetation:
Client ID =2
Header 1
TReportName
URL
Header 2
TReportName
URL
is it possible to combine it in one method?
If I understand you correctly, this is what you're looking for:
using (var connection = new TReportEntitiesConnection())
{
var clientHeaders = (
from st in connection.THeaders
where ClientID == st.ClientID
select new TReportHeaderModel
{
ID=st.ID,
THeaderTitle = st.THeaderTitle,
RowNumber = st.RowNumber,
Reports = from r in st.TReports
select new TReportModel
{
ID = r.ID,
TReportName = r.TReportName,
URL = r.URL,
RowNumber = r.RowNumber,
}
}
).ToList();
}
return clientHeaders;
Note that for this to work, TReportHeaderModel.TReports should be IEnumerable<TReportModel>.
Normally I would suggest you separate the methods for getting your data and transforming your data into DTOs like this (And usually I have the connection defined at the class level, not at the method level because I will reuse the connection many times, and I prefer keeping my data accesses as lazy as possible):
TReportEntitiesConnection conn = new TReportEntitiesConnection();
Then I will create extension methods like so:
public static class MyExtensions
{
public IQueryable<THeader> ByClientId(this IQuerable<THeader> conn, int ClientID)
{
return conn
.Include(h=>h.Reports)
.Where(h=>h.ClientID==ClientID);
}
public TReportHeaderModel ToDto(this THeader t)
{
return new TReportHeaderModel
{
ID=t.ID,
ClientID=t.ClientID,
THeaderTitle=t.THeaderTitle,
RowNumber=t.RowNumber,
Reports=t.Reports.ToDto()
};
}
public TReportModel ToDto(this TReport r)
{
return new TReportModel
{
ID=r.ID,
TReportName=r.TReportName,
URL=r.URL,
RowNumber=r.RowNumber
};
}
public IEnumerable<TReportHeaderModel> ToDto(this IEnumerable<THeader> h)
{
return h.Select(x=>x.ToDto());
}
public IEnumerable<TReportModel> ToDto(this IEnumerable<TReport> r)
{
return r.Select(x=>x.ToDto());
}
}
Then you can use it like so:
var result=conn.THeaders.ByClientId(200).ToDto();
If you prefer not having your connection at the module level, that is easy too:
using(var connection = new TReportEntitiesConnection())
{
var result=connection.THeaders.ByClientId(200).ToDto();
}
(or use AutoMapper and skip all the manual Dto conversions)
I have a web service that fetches data from a database table and adds it to a custom list, and I now need to send that data into a listbox in a windows form, but I don't seem to be able to do it, the web service is referenced in the winform app,and I'm using another methods from that same web service in that app,so I don't think its a problem with the reference or the web service itself, I just can't add the data into the listbox, can someone tell me what I'm doing wrong?
The method:
public List<SLA_ClassLibrary.SLA_Class.ReadAtm> ReadAtm()
{
var AtmReadList = new List<SLA_ClassLibrary.SLA_Class.ReadAtm>();
using (SqlConnection Conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SLAdb"].ConnectionString))
{
using (Conn)
{
Conn.Open();
string SQLReadAtm = "Select * from ATM;";
SqlCommand ReadAtmCmd = new SqlCommand(SQLReadAtm, Conn);
SqlDataReader reader = ReadAtmCmd.ExecuteReader();
while (reader.Read())
{
AtmReadList.Add(new SLA_ClassLibrary.SLA_Class.ReadAtm
{
idatm = reader.GetInt32(reader.GetOrdinal("IDATM")),
District_Region = reader.GetString(reader.GetOrdinal("District_Region")),
Local = reader.GetString(reader.GetOrdinal("Local")),
IsUp = reader.GetBoolean(reader.GetOrdinal("IsUp"))
});
}
}
return AtmReadList;
}
}
This is the code for the winform regarding the method
ServiceConsumer.UsersMethodsSoapClient CheckAtms = new ServiceConsumer.UsersMethodsSoapClient();
listBox1.Items.Add(CheckAtms.ReadAtm());
And the class that I'm using to create the custom list
public class ReadAtm
{
public int idatm { get; set; }
public string District_Region { get; set; }
public string Local { get; set; }
public bool IsUp { get; set; }
}
I have obtained the list of data from database in the following way
List<MakerCheckerModel> mkckdata = new List<MakerCheckerModel>();
var dataContext = new PetaPoco.Database("MessageEntity");
mkckdata = dataContext.Query<MakerCheckerModel>(PetaPoco.Sql.Builder.Append("Select * from MakerChecker1")).ToList();
The data comes in mkckdata. My model is of the following way.
public class MakerCheckerModel
{
public int MakerCheckerId { get; set; }
public string OldJson { get; set; }
public string NewJson { get; set; }
public string ModelName { get; set; }
}
Now I want to put the value obtained in OldJson and NewJson of mkckdata in new List type of model variables so that I can manipulate it further.I want something like this.
List<MakerCheckerModel> oldDataList = new List<MakerCheckerModel>();
oldDataList.Add(mkckdata.OldJson));
But this is not allowed here. PLease help me how to do this.
I have a table called Activity (Mobile service), and i add a query in reading:
Azure Script:
function read(query, user, request)
{
var param = request.parameters.UserLocation;
if(param)
{
var sql = "Select TOP 10 [NewsItemUrl], count(1) as CounterNews FROM [MobileServiceExtra].[ACTIVITY] WHERE [UserLocation] = ? GROUP BY [NewsItemUrl] ORDER BY CounterNews Desc";
mssql.query(sql,param, {success: function(results) {request.respond(statusCodes.OK, results);}});
}
//request.execute();
}
Client side:
public class ACTIVITY
{
public int Id { get; set; }
[JsonProperty(PropertyName = "UserLocation")]
public string _UserLocation { get; set; }
[JsonProperty(PropertyName = "NewsItemUrl")]
public string _NewsItemUrl { get; set; }
[JsonProperty(PropertyName = "NewsItemTitle")]
public string _NewsItemTitle { get; set; }
[JsonProperty(PropertyName = "NewsItemPublisher")]
public string _NewsItemPublisher { get; set; }
}
If I do the query in sql, I get 2 columns CounterNews and NewsItemUrl and where the Last is the number of times to repeat the url. However, I dont know how to get the data in column "CounterNews", i mean, when i want to get the query, i get to do with the Activity table (class) and obviously returns me the data correctly, but only NewsItemUrl column and the other fields are empty.
Client side:
private MobileServiceCollection<ACTIVITY, ACTIVITY> TopReadCollectionActivity;
private IMobileServiceTable<ACTIVITY> ACTIVITYTable = App.MobileService.GetTable<ACTIVITY>();
private async void LoadTop10()
{
var dict = new Dictionary<string, string>
{
{ "UserLocation", "United States" },
};
try
{
TopReadCollectionActivity = await ACTIVITYTable.WithParameters(dict).ToCollectionAsync();
}
catch (Exception ex)
{
string err = ex.Message;
}
}
if i create a class (table too)"Top10", azure give a error, because the table doen't exist. and
not want to create a new table.
how to get the query only two fields CounterNews and NewsItemUrl?
Perhaps you should just query the table directly using the OData support. This way your not confined to the structure of your table. Take a look at this for reference.
http://msdn.microsoft.com/en-us/library/windowsazure/jj677199.aspx