I am taking rows from an Excel file using LinqToExcel and then writing to SQLServer using LINQToSQL. It DID create records in the database but with null values. I wonder if I need to map the Mac object(linqtoexcel) to the HSD_TELE_INSTALLs object? I don't think I am too far off since it inserted records. Relevant code is below. Thanks in advance.
//LINQ
var macs = from x in excel.Worksheet<Mac>(sheet)
select x;
//ITERATE WITH LINQ RESULTS
foreach (var x in macs)
{
HSD_TELE_INSTALL myRecord = new HSD_TELE_INSTALL();
db.HSD_TELE_INSTALLs.InsertOnSubmit(myRecord);
db.SubmitChanges();
}
public class Mac
{
public string REGION { get; set; }
public string MACID { get; set; }
public string HOUSEKEY { get; set; }
public string HOUSENUM { get; set; }
public string STREET { get; set; }
public string UNIT { get; set; }
public string ADDRESS2 { get; set; }
public string COMMUNITY { get; set; }
public string STATE { get; set; }
public string ZIPCODE { get; set; }
public string TECHNICIAN { get; set; }
public string JOBNO { get; set; }
public string JOBTYPE { get; set; }
public string CLOSEDATE { get; set; }
public string CLOSETIME { get; set; }
public string COMMENTS { get; set; }
public string MGT { get; set; }
public string COMPLETIONCODE { get; set; }
public string TCRSN { get; set; }
You're creating a new uninitialized object of type HSD_TELE_INSTALL and then you're submitting it to DB.
You should initialize it somehow from x. Something like:
HSD_TELE_INSTALL myRecord = new HSD_TELE_INSTALL(){SomeField=x.SomeField /*etc...*/ };
db.HSD_TELE_INSTALLs.InsertOnSubmit(myRecord);
db.SubmitChanges();
Related
I want to check if some items are same in a list based on a item present in the list.
List<ProductDetailDTO> productDTOs;
The ProductDetailDTO is -
public class ProductDetailDTO
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public byte[] Image { get; set; }
public string Description { get; set; }
public string Brand { get; set; }
public string GUID { get; set; }
public string VariantName { get; set; }
public string VariantValue { get; set; }
public decimal Price { get; set; }
}
Now, I want to display all VariantName and VariantValue with the same GUIDs together.
How can I achieve this?
try with this
productDTOs.GroupBy(x => x.GUID,(key,item) => new
{
VariantName= item.Select(y=>y.VariantName),
VariantValue = item.Select(y => y.VariantValue),
}).ToList()
I have this code snippet from my method. It should write all parts of the list test.E_id, but it writes nothing. I don't know what i do wrong.
string jsonText = File.ReadAllText(jsonFilePath);
Execution test = JsonConvert.DeserializeObject<Execution>(jsonText);
foreach (string eID in test.E_id)
{
Console.WriteLine(eID);
}
This is my Execution class, besides the writing of the strings is working fine.
public class Execution
{
public string Usr_id { get; private set; }
public string Patient_id { get; private set; }
public List<string> E_id { get; private set; }
public List<string> E_title { get; private set; }
public List<string> E_description { get; private set; }
public List<string> E_date { get; private set; }
public List<string> E_delete { get; private set; }
public Execution(string usr_id, string patient_id, List<string> e_id, List<string> e_title, List<string> e_description,
List<string> e_date, List<string> e_delete)
{
Usr_id = usr_id;
Patient_id = patient_id;
E_id = e_id;
E_title = e_title;
E_description = e_description;
E_date = e_date;
E_delete = e_delete;
}
}
And here is the json file i want to read from:
{
"usr_id":"573",
"patient_id":"170510024",
"executions":[
{
"id":"SF70H",
"title":"Verbandswechsel",
"description":"Verband des rechten Armes wechseln",
"date":"2017-07-28T12:00:00.000Z",
"delete":false
},
{
"id":"SF18H",
"title":"Physiotherapie",
"description":"Beweglichkeit des Knies wiederherstellen",
"date":"2017-07-28T14:00:00.000Z",
"delete":false
}
]
Maybe anyone knows what i do wrong and can help me to find my mistake.
}
Your problem is that your JSON and the code don't match with each other. You have lists for single fields, you have wrong names, etc.
Use this C# which maps to your JSON (generated from json2csharp.com):
public class Execution
{
public string id { get; set; }
public string title { get; set; }
public string description { get; set; }
public DateTime date { get; set; }
public bool delete { get; set; }
}
public class Test
{
public string usr_id { get; set; }
public string patient_id { get; set; }
public List<Execution> executions { get; set; }
}
Then use this C# code:
Test test = JsonConvert.DeserializeObject<Test>(jsonText);
Your code structure does not match your JSON-structure. Since you already knew the structure of the JSON file, there's a handy tool in Visual Studio to help you generate code from that.
Select the JSON structure in the file -> Ctrl+C -> Visual Studio -> Edit -> Paste Special -> Paste JSON as classes.
This gives following result:
public class Rootobject
{
public string usr_id { get; set; }
public string patient_id { get; set; }
public Execution[] executions { get; set; }
}
public class Execution
{
public string id { get; set; }
public string title { get; set; }
public string description { get; set; }
public DateTime date { get; set; }
public bool delete { get; set; }
}
Now you can decorate it with JsonProperty attributes and make the names to the C# standards:
public class Rootobject
{
[JsonProperty("usr_id")]
public string UserId { get; set; }
[JsonProperty("patient_id")]
public string PatientId { get; set; }
[JsonProperty("executions ")]
public Execution[] Executions { get; set; }
}
public class Execution
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("datee")]
public DateTime Date { get; set; }
[JsonProperty("delete")]
public bool Delete { get; set; }
}
This code worked fine:
public class ExecutionOrder
{
public string Usr_id { get; set; }
public string Patient_id { get; set; }
public List<Execution> Executions { get; set; }
public ExecutionOrder(string usr_id, string patient_id, List<Execution> executions)
{
Usr_id = usr_id;
Patient_id = patient_id;
Executions = executions;
}
}
public class Execution
{
public string E_id { get; set; }
public string E_title { get; set; }
public string E_description { get; set; }
public string E_date { get; set; }
public bool E_delete { get; set; }
public Execution(string e_id, string e_title, string e_description, string e_date, bool e_delete)
{
E_id = e_id;
E_title = e_title;
E_description = e_description;
E_date = e_date;
E_delete = e_delete;
}
}
But now I have another problem, i want to read the strings and the bool from the Execution object and print it in the CommandWindow. I can print the Usr_id and the Patient_id without any problems, and the bool from the object is also shown. But it doesn't print the strings. Is it the right way to read the strings out of the object?
ExecutionOrder test = JsonConvert.DeserializeObject<ExecutionOrder>(jsonText);
test.Executions.ForEach(delegate(Execution exec)
{
Console.WriteLine(test.Usr_id);
Console.WriteLine(test.Patient_id);
Console.WriteLine(exec.E_id);
Console.WriteLine(exec.E_title);
Console.WriteLine(exec.E_description);
Console.WriteLine(exec.E_date);
Console.WriteLine(exec.E_delete);
Console.WriteLine();
});
I want to parse a JSON data dynamically and read its key and their values without serializing it in a concrete class because the JSON data can be different time to time. But for the initial testing one sample data is like this . In this data I want to get property values and if the JSON data aslo contains complex structure I also want to read child property values also How to do that in C#.
{"id":4877891717,"email":"rvp#insync.com","accepts_marketing":true,"created_at":"2017-03-24T08:39:56+01:00","updated_at":"2017-04-10T09:40:42+02:00","first_name":"Robin","last_name":"Van Persie","orders_count":8,"state":"disabled","total_spent":"2320.00","last_order_id":4434634693,"note":"","verified_email":true,"multipass_identifier":null,"tax_exempt":true,"phone":"+3225551212","tags":"","last_order_name":"#1116","addresses":[{"id":5143111941,"first_name":"Robin","last_name":"Van Persie","company":"InSync","address1":"CB 28, El Solo Road","address2":"CB 28, El Solo Road","city":"Brussels","province":"EU","country":"Belgium","zip":"123456","phone":"12345678","name":"Robin Van Persie","province_code":null,"country_code":"BE","country_name":"Belgium","default":true}],"default_address":{"id":5143111941,"first_name":"Robin","last_name":"Van Persie","company":"InSync","address1":"CB 28, El Solo Road","address2":"CB 28, El Solo Road","city":"Brussels","province":"EU","country":"Belgium","zip":"123456","phone":"12345678","name":"Robin Van Persie","province_code":null,"country_code":"BE","country_name":"Belgium","default":true}}
I am trying this way. But after geiing tiken what I will do.
foreach (JObject token in jObject.Children())
{}
Thanks
You can use NewtonsoftJson library to parse without creating concrete class
dynamic parseJson = JsonConvert.DeserializeObject("your json");
and get the value using below code like...
string Id=parseJson.Id.Value
I have tested it and it's working for me
you have two options(as far as i know). you can generate a class acording to your json string then parse the result in it. like this:
public class Address
{
public long id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address1 { get; set; }
public string address2 { get; set; }
public string city { get; set; }
public string province { get; set; }
public string country { get; set; }
public string zip { get; set; }
public string phone { get; set; }
public string name { get; set; }
public object province_code { get; set; }
public string country_code { get; set; }
public string country_name { get; set; }
public bool #default { get; set; }
}
public class DefaultAddress
{
public long id { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address1 { get; set; }
public string address2 { get; set; }
public string city { get; set; }
public string province { get; set; }
public string country { get; set; }
public string zip { get; set; }
public string phone { get; set; }
public string name { get; set; }
public object province_code { get; set; }
public string country_code { get; set; }
public string country_name { get; set; }
public bool #default { get; set; }
}
public class RootObject
{
public long id { get; set; }
public string email { get; set; }
public bool accepts_marketing { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public int orders_count { get; set; }
public string state { get; set; }
public string total_spent { get; set; }
public long last_order_id { get; set; }
public string note { get; set; }
public bool verified_email { get; set; }
public object multipass_identifier { get; set; }
public bool tax_exempt { get; set; }
public string phone { get; set; }
public string tags { get; set; }
public string last_order_name { get; set; }
public List<Address> addresses { get; set; }
public DefaultAddress default_address { get; set; }
}
then parse it(using json.net) like this:
var jObject=JsonConvert.DeserializeObject<RootObject>(responseString);
or you can use dynamic object and deal with json result at runtime. like this:
var jObject=JsonConvert.DeserializeObject(responseString);
foreach (JObject token in jObject.Children)
You can use NewtonsoftJson library to parse data easily
dynamic x = Newtonsoft.Json.JsonConvert.DeserializeObject(Jsondata);
foreach (var product in x) {
Messagebox.show(product.data.ToString());
}
I am new to C#. I have successfully consumed the Mailchip API with a simple console app. I am pulling in relevant data and I have successfully used a JSON deserializer on the returned data (Newtonsoft.Json via NuGet). What I need to find is the best way to place the data into variables which I can then pass to a stored procedure to save the data. I know SQL and I know how to pass variables to a stored procedure in C# (connection strings and such).
What I don't know is how to parse through the deserialized data and then place each value into a variable or something I can pass to SQL. I know this is a vague question so here is the current code.
Class MailChimpAPIClient.cs:
//Declare the API Key
public const string APIKey = "My API Key Here";
public static void APIGet(string url)
{
//Syncronious Consumption
var syncClient = new WebClient();
syncClient.Headers.Add(APIKey);
var content = syncClient.DownloadString(url);
//Deseralize the Json String
MailChimpData data = JsonConvert.DeserializeObject<MailChimpData>(content);
}
Class: MailChimpData.cs:
[DataContract]
public class MailChimpData
{
[DataMember]
public List<Unsubscribes> unsubscribes { get; set; }
[DataMember]
public string campaign_id { get; set; }
[DataMember]
public List<Link2> _links { get; set; }
[DataMember]
public int total_items { get; set; }
[DataMember]
public Link link { get; set; }
[DataMember]
public MergeFields mergefields { get; set; }
[DataMember]
public Stats stats { get; set; }
[DataMember]
public Location location { get; set; }
[DataMember]
public List<Member> members { get; set; }
[DataMember]
public string list_id { get; set; }
}
//Unsubscribe Data
public class Link
{
public string rel { get; set; }
public string href { get; set; }
public string method { get; set; }
public string targetSchema { get; set; }
public string schema { get; set; }
}
public class Unsubscribes
{
public string email_id { get; set; }
public string email_address { get; set; }
public string timestamp { get; set; }
public string reason { get; set; }
public string campaign_id { get; set; }
public string list_id { get; set; }
public List<Link> _links { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string href { get; set; }
public string method { get; set; }
public string targetSchema { get; set; }
public string schema { get; set; }
}
//List Data
public class MergeFields
{
public string FNAME { get; set; }
public string LNAME { get; set; }
}
public class Stats
{
public double avg_open_rate { get; set; }
public int avg_click_rate { get; set; }
}
public class Location
{
public double latitude { get; set; }
public double longitude { get; set; }
public int gmtoff { get; set; }
public int dstoff { get; set; }
public string country_code { get; set; }
public string timezone { get; set; }
}
public class Member
{
public string id { get; set; }
public string email_address { get; set; }
public string unique_email_id { get; set; }
public string email_type { get; set; }
public string status { get; set; }
public MergeFields merge_fields { get; set; }
public Stats stats { get; set; }
public string ip_signup { get; set; }
public string timestamp_signup { get; set; }
public string ip_opt { get; set; }
public string timestamp_opt { get; set; }
public int member_rating { get; set; }
public string last_changed { get; set; }
public string language { get; set; }
public bool vip { get; set; }
public string email_client { get; set; }
public Location location { get; set; }
public string list_id { get; set; }
public List<Link> _links { get; set; }
}
Program.cs:
class Program
{
static void Main(string[] args)
{
MailChimpApiClient.APIGet("Custom URL Here");
}
}
So when I run this and look in the Autos window of VS2013 I see this:
members: Count = 4 System.Collections.Generic.List
[0] {MailChimpAPI.Member} MailChimpAPI.Member
_links: Count = 8 System.Collections.Generic.List
email_address: email address here string
email_client: string
email_type: html string
id: (ID Here) string
ip_opt: (IP Here) string
ip_signup: string
language: string
last_changed: 9/16/15 19:31 string
list_id: (List ID Here) string
location: {MailChimpAPI.Location} MailChimpAPI.Location
member_rating: 3 int
merge_fields {MailChimpAPI.MergeFields} MailChimpAPI.MergeFields
stats: {MailChimpAPI.Stats} MailChimpAPI.Stats
status: unsubscribed string
timestamp_opt: 9/16/15 19:26 string
timestamp_signup: string
unique_email_id: (Unique Email ID Here) string
vip: FALSE bool
[1] {MailChimpAPI.Member}: MailChimpAPI.Member
[2] {MailChimpAPI.Member}: MailChimpAPI.Member
[3] {MailChimpAPI.Member}: MailChimpAPI.Member
Raw View
So for each member (0-3), I need to pull each fields value (Field names in bold) into a variable and save it to a database. I just don't know how to parse through each member.
I know this is a long question for a simple C# problem, but if you can remember way back to the beginning of the post I stated "I am new to C#"
Thanks in advance.
In my application I want to retrieve blind_copy_recipients from system table 'sysmail_mailitems' from database 'MSDB' in SQL Server 2012. I am using Entity Framework in a C# web application to query databases. I created a class for sysmail_mailitems and method to read data from it. But it actually created a new table outside of system tables with this name. My goal is not to create a table but just to read from existing table. Can anyone please guide me on how could I do it?
Code:
public class sysmail_mailitem
{
[Key]
public Int32 mailitem_id { get; set; }
public Int32 profile_id { get; set; }
public String recipients { get; set; }
public String copy_recipients { get; set; }
public String blind_copy_recipients { get; set; }
public String subject { get; set; }
public String from_address { get; set; }
public String reply_to { get; set; }
public String body { get; set; }
public String body_format { get; set; }
public String importance { get; set; }
public String sensitivity { get; set; }
public String file_attachments { get; set; }
public String attachment_encoding { get; set; }
public String query { get; set; }
public String execute_query_database { get; set; }
public Boolean? attach_query_result_as_file { get; set; }
public Boolean? query_result_header { get; set; }
public Int32? query_result_width { get; set; }
public String query_result_separator { get; set; }
public Boolean? exclude_query_output { get; set; }
public Boolean? append_query_error { get; set; }
public DateTime send_request_date { get; set; }
public String send_request_user { get; set; }
public Int32? sent_account_id { get; set; }
public Byte? sent_status { get; set; }
public DateTime? sent_date { get; set; }
public DateTime last_mod_date { get; set; }
public String last_mod_user { get; set; }
}
public String GetMailRecipients(Int32 mailItemId)
{
using(MSDBContext _db = new MSDBContext())
{
var query = (from mailItems in _db.MailItems
where mailItems.mailitem_id == mailItemId
select mailItems).FirstOrDefault();
try
{
return query.blind_copy_recipients;
}
catch (NullReferenceException) { }
return "N/A";
}
}
public class MSDBContext : DbContext
{
public MSDBContext() : base("msdb") { }
public DbSet<sysmail_mailitem> MailItems { get; set; }
}
In the end I came up with executing raw sql command using ExecuteStoreQuery to retrieve data from MSDB.
Code:
public String GetMailRecipients(Int32 mailItemId)
{
using(context _db = new context())
{
var obj = ((IObjectContextAdapter)_db).ObjectContext;
return obj.ExecuteStoreQuery<String>("SELECT blind_copy_recipients FROM msdb.dbo.sysmail_mailitems WHERE mailitem_id = {0}", mailItemId).FirstOrDefault();
}
}
If you want to do it the initial way you tried, using DBSet etc you can do that. Your issue is that you called the class sysmail_mailitem when the table name is sysmail_mailitems (with an s). So you would have to annotate the actual table name above the class like this:
[Table("sysmail_mailitems")]
public class sysmail_mailitem
{