Read Data from 'MSDB' System Table - c#
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
{
Related
Crestron Deserialize in C# and send array to Simpl+
Trying best how to take the following classes and deserialize a Json file to return each class values back to Simpl+. I am able to receive the Total value but anything in a list I am at a lost. public class Client { public string clientId { get; set; } public string locale { get; set; } public string location { get; set; } public string auxiliaryId { get; set; } public string description { get; set; } public string type { get; set; } public string typeDescription { get; set; } public Hardware hardware { get; set; } public Network network { get; set; } } public class Hardware { public string type { get; set; } public string softwareVersion { get; set; } public string serialNumber { get; set; } public string hardwareVersion { get; set; } public string model { get; set; } } public class Network { public string ip { get; set; } public string mac { get; set; } public object homepage { get; set; } public string dhcpSubnet { get; set; } } public class Result { public List<Client> clients { get; set; } public string total { get; set; } public int limit { get; set; } public int page { get; set; } } public class Root { public string jsonrpc { get; set; } public object id { get; set; } public Result result { get; set; } }
I was able to resolve this by adding the following to the foreach statement: args.MyIndex = (ushort)(rootObject.TriplePlayResult.clients.IndexOf(item) + 1);
Problem trying to deserialize a json with a model
I am trying to deserialize a json (using Newtonsoft.Json), i created the classes, but in json code there is a variable that i don't know if it is corrected or i don't know how to deserialize. I am getting a null exception on line : MessageBox.Show(root.matriculations._14000.name) private void btnImportaDados_Click(object sender, EventArgs e) { string getDataUrl = "https://xxx.xxx.com/api/matriculations/get.json?entity_code=14000"; try { using (var webClient = new System.Net.WebClient()) { var json = webClient.DownloadString(getDataUrl); var root = JsonConvert.DeserializeObject<Rootobject>(json); MessageBox.Show(root.matriculations._14000.name); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } public class Rootobject { public Matriculations matriculations { get; set; } } public class Matriculations { public _14000 _14000 { get; set; } } public class _14000 { public string entity_code { get; set; } public string name { get; set; } public string street { get; set; } public string local { get; set; } public string postal_code { get; set; } public string sub_postal_code { get; set; } public string phone1 { get; set; } public object phone2 { get; set; } public string email1 { get; set; } public object email2 { get; set; } public string entity_code_2 { get; set; } public string courseaction_ref { get; set; } public string courseaction_id { get; set; } public string course_code { get; set; } public string course { get; set; } public Billingorderplan[] billingorderplans { get; set; } } public class Billingorderplan { public string id { get; set; } public string paid { get; set; } public string date { get; set; } public object obs { get; set; } public object payment_doc_num { get; set; } public string value { get; set; } public string description { get; set; } public string entity_code { get; set; } public object paid_date { get; set; } } The result(json data) from the url is: {"matriculations":{"14000":{"entity_code":"14000","name":"Fabio Danilson Sivone Antonio","street":"Rua Dr. Pereira Jardim, Bl. 3 - 25 - 4 B","local":"Luanda","postal_code":"2685","sub_postal_code":"093","phone1":"923810539","phone2":null,"email1":"fabiodanilson1#hotmail.com","email2":null,"entity_code_2":"9957","courseaction_ref":"EPCE_01","courseaction_id":"1828","course_code":"EPCE","course":"Especializa\u00e7\u00e3o Avan\u00e7ada em Investiga\u00e7\u00e3o de Crime Econ\u00f3mico [E-learning]","billingorderplans":[{"id":"298","paid":"0","date":"2020-05-06","obs":null,"payment_doc_num":null,"value":"0.00","description":"Inscri\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"299","paid":"0","date":"2019-11-21","obs":null,"payment_doc_num":null,"value":"0.00","description":"1\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"300","paid":"0","date":"2019-12-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"2\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"301","paid":"0","date":"2020-01-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"3\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"302","paid":"0","date":"2020-02-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"4\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"303","paid":"0","date":"2020-03-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"5\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"304","paid":"0","date":"2020-04-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"6\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"305","paid":"0","date":"2020-05-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"7\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"306","paid":"0","date":"2020-06-08","obs":null,"payment_doc_num":null,"value":"0.00","description":"8\u00aa presta\u00e7\u00e3o","entity_code":"14000","paid_date":null},{"id":"16595","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null},{"id":"16596","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"45.00","description":"EExt - Teste","entity_code":"14000","paid_date":null},{"id":"16597","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null},{"id":"16598","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"45.00","description":"EExt - Teste","entity_code":"14000","paid_date":null},{"id":"16599","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null},{"id":"16601","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"45.00","description":"EExt - Teste","entity_code":"14000","paid_date":null},{"id":"16600","paid":"0","date":"2020-08-27","obs":null,"payment_doc_num":null,"value":"20.00","description":"EExt - Atividade","entity_code":"14000","paid_date":null}]}}} But that "14000" is a varible value depending from the parameter passed. How can i do it? Thank You.
Since 14000 cannot be a variable name you will have to resort to some manual intervention to capture that dynamic value. The cleanest way is to remove the Matriculations class and replace it with Dictionary<int, _14000> (or Dictionary<string, _14000>). public class Rootobject { public Dictionary<int, _14000> matriculations { get; set; } } This will ensure that the key is captured correctly even if it is a number. You can read the object from the dictionary's values as such: root.matriculations.Values.First().name. (Remember to import System.Linq for using .First().) For clarity you can rename _14000 to something more descriptive.
You do not have _14000 in returned JSON but 14000 under matriculations.
I am getting error while converting json to object
i am trying to convert JSON to object following is my json {"entity":"event","account_id":"acc_8yTsyb2WJOlcka","event":"payment.captured","contains":["payment"],"payload":{"payment":{"entity":{"id":"pay_AKR45WLH0g1ANu","entity":"payment","amount":100,"currency":"INR","status":"captured","order_id":"order_AKR41LsWIgOAB1","invoice_id":null,"international":false,"method":"netbanking","amount_refunded":0,"refund_status":null,"captured":true,"description":"Admission Fees","card_id":null,"bank":"SBIN","wallet":null,"vpa":null,"email":"xxxxx.xxxx#xxx.xxx","contact":"xxxxx","notes":{"address":"NA","merchant_order_id":"2516"},"fee":2,"tax":0,"error_code":null,"error_description":null,"created_at":1528367383}}},"created_at":1528367384} and the code I am trying to convert to object is jsonString = JsonConvert.SerializeObject(documentContents); RazorPayPayload desJsonString = JsonConvert.DeserializeObject<RazorPayPayload>(jsonString); and the classes where I want to deserialized public class RazorPayPayload { public string entity { get; set; } public string account_id { get; set; } public string events { get; set; } public List<string> contains { get; set; } public payments payload { get; set; } public string created_at { get; set; } } public class payments { public Entities payment { get; set; } } public class notes { public string address { get; set; } public string merchant_order_id { get; set; } public string source { get; set; } } public class Entities { public Entity entity { get; set; } } public class Entity { public string id { get; set; } public string entity { get; set; } public string amount { get; set; } public string currency { get; set; } public string order_id { get; set; } public string invoice_id { get; set; } public string international { get; set; } public string method { get; set; } public string amount_refunded { get; set; } public string refund_status { get; set; } public string captured { get; set; } public string description { get; set; } public string card_id { get; set; } public string bank { get; set; } public string wallet { get; set; } public string vpa { get; set; } public string email { get; set; } public string contact { get; set; } public notes notes { get; set; } public string fee { get; set; } public string tax { get; set; } public string error_code { get; set; } public string error_description { get; set; } } I am getting the error "Error converting value to type 'FeePayr_Razor_Webhook.RazorPayPayload'"
Have you tried changing: {"entity":"event","account_id":"acc_8yTsyb2WJOlcka","event": to {"entity":"event","account_id":"acc_8yTsyb2WJOlcka","events": That would better match your class definition. Or rename your class field to event.
There is a useful visual studio function for converting a json object to c# classes. Copy the JSON into the clipboard. (helps if the JSON object properties holds data, to determine the data type) Go to visual studio and place cursor where you'd like to paste in the c# classes. click edit => paste special => paste json as classes
PHP error with multiple levels of key-value JSON pairs
I am using multiple levels of JSON data coming into php from a C# application, as in: public class User_Group { public int ID_UserGroup { get; set; } public string Name_UserGroup { get; set; } public int UserID { get; set; } } public class User_Role { public int ID_User { get; set; } public string Role_User { get; set; } public string User_Role_Description { get; set; } public List<User_Group> UserGroup { get; set; } } public class Stand_Orte { public int ID { get; set; } public string Bezeichnung { get; set; } public List<Modul> modul { get; set; } } public class Modul { public string ID { get; set; } public string Seriennummer { get; set; } public string Bezeichnung { get; set; } public string StandortID { get; set; } public List<Mess_Kanal> MessKanal { get; set; } } public class Mess_Kanal { public string ID { get; set; } public string ModulID { get; set; } public List<LogMess_Daten> LogMessDaten { get; set; } } public class LogMess_Daten { public string KanalID { get; set; } public string Zeitstempel { get; set; } } public class RootObject { public int ID_Project { get; set; } public string Name_Project { get; set; } public int Receiver_ID { get; set; } public string Receiver_Name { get; set; } public int UserID { get; set; } public User_Role UserRole { get; set; } public Stand_Orte Standorte { get; set; } } I have an issue with accessing the 3rd level data elements. For Eg., I am able to get the values uptil Project-> Stand_Orte-> Modul. but after that Project-> Stand_Orte-> Modul-> MessKanal Throws an error in PHP as " Trying to get property of non-object ". I tried the following: $phpArray['project']->Standorte[0]->modul[0]->MessKanal[0]->ID $messkanals=$phpArray->Standorte->modul->MessKanal; And then used a "foreach ($messkanals as $messkanal)" to insert MessKanal data into MYSQL. it gives me the following errors respectively. Cannot use object of type stdClass as array Trying to get property of non-object does anyone have any idea? Thanks, Revathy
LINQ: Read an Excel file and then writing to database
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();