XML-mapping to SQL-server - c#

I want to map a xml file to a SQL Server table.
This is what I've done so far:
XmlTextReader reader = new XmlTextReader("navetout.xml");
XmlNodeType type;
while (reader.Read())
{
type = reader.NodeType;
if(type == XmlNodeType.Element)
{
}
}
//using Entity framework
static void writeToDatabase()
{
BumsEntities _bums = new BumsEntities();
_bums.Seamen.Add(new Seamen
{
PersonalIdentityNumber = "",
ReferedCivicRegistrationNumber = "",
UnregistrationReason = "",
UnregistrationDate = "",
MessageComputerComputer = "",
GivenNameNumber = "",
FirstName = "",
MiddleName = "",
LastName = "",
NotifyName = "",
NationalRegistrationDate = "",
NationalRegistrationCountyCode = "",
NationalRegistrationMunicipalityCode = "",
NationalRegistrationCoAddress = "",
NationalRegistrationDistributionAddress1 = "",
NationalRegistrationDistributionAddress2 = "",
NationalRegistrationPostCode = "",
NationalRegistrationCity = "",
NationalRegistrationNotifyDistributionAddress = "",
NationalRegistrationNotifyPostCode = "",
NationalRegistrationNotifyCity = "",
ForeignDistrubtionAddress1 = "",
ForeignDistrubtionAddress2 = "",
ForeignDistrubtionAddress3 = "",
ForeignDistrubtionCountry = "",
ForeignDate = "",
BirthCountyCode = "",
BirthParish = "",
});
_bums.SaveChanges();
}
The code above is the database columns. What I want to be able to do is to load the xml file and insert the tags into the columns. The problem is that I don't know how to "translate" the xml tags to the database columns.. Can anyone help me out?

This is not the entire code, however should help :
XmlTextReader reader = new XmlTextReader("navetout.xml");
DataSet ds = new DataSet("XML Data");
ds.ReadXml(reader);
// Create Database Connection here
foreach(DataTable dt in ds.Tables){
//save datatable to database - You can use SqlBulkCopy
}
Saving DataTable to database

Related

Create dynamic object from a JSON disregarding null fields

I need to consume a method that the input parameter is a dynamic object, but I feed the object through a received JSON
Dynamic Builder:
public static dynamic PayChargeObject()
{
var body = new
{
payment = new
{
banking_billet = new
{
customer = new
{
name = "",
email = "",
cpf = "",
birth = "",
phone_number = "",
address = new
{
street = "",
number = "",
neighborhood = "",
zipcode = "",
city = "",
complement = "",
state = "",
},
juridical_person = new
{
corporate_name = "",
cnpj = "",
}
},
expire_at = "",
discount = new
{
type = "",
value = 0
},
conditional_discount = new
{
type = "",
value = 0,
until_date = ""
},
message = ""
}
}
};
return body;
}
My JSON Data:
{
"payment": {
"banking_billet": {
"customer": {
"name": "person name",
"email": "personnamez#gerencianet.com.br",
"cpf": "94271564656",
"birth": "1977-01-15",
"phone_number": "41991234567"
},
"expire_at": "2019-12-12"
}
}
Note that json will not always have all available fields in the object filled, but the method I need to consume does not accept null values in the fields, and my problem is this, when deserializing JSON in the dynamic object, the fields not used in JSON are created as null in the dynamic object
JSON Convert and Method call:
var obj = JsonConvert.DeserializeAnonymousType(MyJSON, PayChargeObject())
dynamicMethod.PayCharge(obj);
Dynamic Object with null fields on Debug
How can I solve this problem?
With help of #dbc solution:
replace:
var obj = JsonConvert.DeserializeAnonymousType(MyJSON, PayChargeObject())
dynamicMethod.PayCharge(obj);
with:
dynamicMethod.PayCharge(JObject.Parse(MyJSON));

Union with System.Linq.IQueryable get errors

i am trying to use union as follows :
var query1 = from c in dc.Hotel_Meals_TBLs
where c.CHDLunch != "0" && c.CHDLunch != ""
select new
{
SERVICE_CODE = c.HotelCodeID,
SERVICE_NAME = c.HotelName,
ROOM_CATEGORY = "",
ROOM_TYPE = "",
VARIANCE_NAME = "CHILDLUNCH",
MARKET = "WW",
CONTRACT_BUSINESS_YEAR = "2014/2015",
CONTRACT_START_DATE = "01/11/2014",
CONTRACT_END_DATE = "30/10/2015",
TYPE = "CHILD POLICY",
CURRENCY = c.CurrencyCode,
PERIOD_NAME = "",
PERIOD_START_DATE = "",
PERIOD_END_DATE = "",
PRICE = c.Lunch,
PERCENTAGE = c.CHDLunch + "%",
NUM_TO_STAY = "",
NUM_TO_PAY = "",
PENALTY_TIME_LIMIT = "",
PENALTY_NO_DAY_BEFORE = "",
CHILD_REFERENCE = "",
TEXT = c.ChildPolicy
};
var query2 = from c in dc.Hotel_Meals_TBLs
from d in dc.HotelPeriod_TBLs
from f in dc.HotelRoom_TBLs
where c.HotelCodeID == d.HotelCodeID && c.HotelCodeID == f.HotelCodeID && f.DBL_HighSeason != 0 && d.PeriodName == "High"
select new
{
SERVICE_CODE = c.HotelCodeID,
SERVICE_NAME = c.HotelName,
ROOM_CATEGORY = f.RoomName,
ROOM_TYPE = "DBL",
VARIANCE_NAME = "",
MARKET = "WW",
CONTRACT_BUSINESS_YEAR = "2014/2015",
CONTRACT_START_DATE = "01/11/2014",
CONTRACT_END_DATE = "30/10/2015",
TYPE = "COST",
CURRENCY = c.CurrencyCode,
PERIOD_NAME = d.PeriodName,
PERIOD_START_DATE = d._From,
PERIOD_END_DATE = d._To,
PRICE = f.SGL_LowSeason,
PERCENTAGE = "",
NUM_TO_STAY = "",
NUM_TO_PAY = "",
PENALTY_TIME_LIMIT = "",
PENALTY_NO_DAY_BEFORE = "",
CHILD_REFERENCE = "",
TEXT = ""
};
var result = query1.Union(query2);
and i got this errors:
'System.Linq.IQueryable<AnonymousType#1>' does not contain a definition for 'Union' and the best extension method overload 'System.Linq.ParallelEnumerable.Union<TSource>(System.Linq.ParallelQuery<TSource>, System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments
Instance argument: cannot convert from 'System.Linq.IQueryable<AnonymousType#1>' to 'System.Linq.ParallelQuery<AnonymousType#2>'
truly i used this method many times without get errors...do you have any idea what is wrong in this query?
The error message indicates that .NET thinks those two anonymous types are different. In order for two anonymous types to be the same they must have the same number of properties with the same names and types. I've gone through your property list and they appear to have the same names in the same order. However, it's possible you've got different types in these areas:
Type 1
PERIOD_START_DATE = ""
PERIOD_END_DATE = ""
PRICE = c.Lunch,
TEXT = c.ChildPolicy
Type 2
PERIOD_START_DATE = d._From
PERIOD_END_DATE = d._To
PRICE = f.SGL_LowSeason
TEXT = ""
Make sure that d._From, d._To, and c.ChildPolicy are all strings and that c.Lunch and f.SGL_LowSeason are the same type (e.g. maybe one is an int and the other is a decimal).
You have to create one ViewModel with all the properties you want and assign all the values to the viewmodel properties and in both the query the select statement will be like :
select new ViewModel{
ViewmodelProperties = Value,
};
Like:
var query1 = from c in dc.Hotel_Meals_TBLs
where c.CHDLunch != "0" && c.CHDLunch != ""
select new ViewModel
{
SERVICE_CODE = c.HotelCodeID,
SERVICE_NAME = c.HotelName,
ROOM_CATEGORY = "",
ROOM_TYPE = "",
VARIANCE_NAME = "CHILDLUNCH",
MARKET = "WW",
CONTRACT_BUSINESS_YEAR = "2014/2015",
CONTRACT_START_DATE = "01/11/2014",
CONTRACT_END_DATE = "30/10/2015",
TYPE = "CHILD POLICY",
CURRENCY = c.CurrencyCode,
PERIOD_NAME = "",
PERIOD_START_DATE = "",
PERIOD_END_DATE = "",
PRICE = c.Lunch,
PERCENTAGE = c.CHDLunch + "%",
NUM_TO_STAY = "",
NUM_TO_PAY = "",
PENALTY_TIME_LIMIT = "",
PENALTY_NO_DAY_BEFORE = "",
CHILD_REFERENCE = "",
TEXT = c.ChildPolicy
};
var query2 = from c in dc.Hotel_Meals_TBLs
from d in dc.HotelPeriod_TBLs
from f in dc.HotelRoom_TBLs
where c.HotelCodeID == d.HotelCodeID && c.HotelCodeID == f.HotelCodeID && f.DBL_HighSeason != 0 && d.PeriodName == "High"
select new ViewModel
{
SERVICE_CODE = c.HotelCodeID,
SERVICE_NAME = c.HotelName,
ROOM_CATEGORY = f.RoomName,
ROOM_TYPE = "DBL",
VARIANCE_NAME = "",
MARKET = "WW",
CONTRACT_BUSINESS_YEAR = "2014/2015",
CONTRACT_START_DATE = "01/11/2014",
CONTRACT_END_DATE = "30/10/2015",
TYPE = "COST",
CURRENCY = c.CurrencyCode,
PERIOD_NAME = d.PeriodName,
PERIOD_START_DATE = d._From,
PERIOD_END_DATE = d._To,
PRICE = f.SGL_LowSeason,
PERCENTAGE = "",
NUM_TO_STAY = "",
NUM_TO_PAY = "",
PENALTY_TIME_LIMIT = "",
PENALTY_NO_DAY_BEFORE = "",
CHILD_REFERENCE = "",
TEXT = ""
};
var result = query1.Union(query2);

Initialize array with a mix of with hard-coded and generated values

This code which initializes an array with two hard-coded values is working perfectly fine:
var db = new GoogleGraph {
cols = new ColInfo[] {
new ColInfo { id = "", label = "Date", pattern ="", type = "string" },
new ColInfo { id = "", label = "Attendees", pattern ="", type = "number" }
}.ToList(),
rows = new List<DataPointSet>()
};
db.cols.AddRange(listOfValues.Select(p => new ColInfo { id = "", label = p, type = "number" }));
This code which attempts to add some dynamically generated values is not working:
var db = new GoogleGraph {
cols = new ColInfo[] {
new ColInfo { id = "", label = "Date", pattern ="", type = "string" },
new ColInfo { id = "", label = "Attendees", pattern ="", type = "number" },
listOfValues.Select(p => new ColInfo { id = "", label = p, type = "number" })
}.ToList(),
rows = new List<DataPointSet>()
};
How can I correctly implement the above snippet?
You can't pass an IEnumerable<T> to an initializer of T[] like that.
You can do what you want by putting the hard-coded objects in their own collection, then concatenating the dynamic ones:
var db = new GoogleGraph {
cols =
new ColInfo[] {
new ColInfo { id = "", label = "Date", pattern ="", type = "string" },
new ColInfo { id = "", label = "Attendees", pattern ="", type = "number" }
}
.Concat(listOfValues.Select(p =>
new ColInfo { id = "", label = p, type = "number" }))
.ToList(),
rows = new List<DataPointSet>()
};

get Contacts based on Account in SugarCRM REST API in C# .Net

i want to retrieve all contacts based on account in sugarcrm rest api using C# .net
i have tried
json = serializer.Serialize(new
{
session = sessionId,
module_name = "accounts",
query = "",
order_by = "",
offset = "0",
select_fields = "",
link_name_to_fields_array = "",
max_results = "2000",
deleted = 0
});
values = new NameValueCollection();
values["method"] = "get_entry_list";
values["input_type"] = "json";
values["response_type"] = "json";
values["rest_data"] = json;
response = client.UploadValues(sugarUrl, values);
responseString = Encoding.Default.GetString(response);
var accountsList = serializer.Deserialize<Dictionary<string, dynamic>>(responseString);
i am able to get all accounts and contacts but i am not getting relations between them i.e which contact belong to which account
Thanks for help in advance
UPDATE :
object[] linkNameToFieldsArray = new object[1]
{
new object[2, 2]
{
{ "name", "contacts" },
{ "value", new string[2]
{ "id", "last_name"
}
}
};
json = serializer.Serialize(new
{
session = sessionId,
module_name = "accounts",
query = "",
order_by = "",
offset = "0",
select_fields = "",
link_name_to_fields_array = linkNameToFieldsArray , ***//just added this to get related records***
max_results = "2000",
deleted = 0
});
values = new NameValueCollection();
values["method"] = "get_entry_list";
values["input_type"] = "json";
values["response_type"] = "json";
values["rest_data"] = json;
response = client.UploadValues(sugarUrl, values);
responseString = Encoding.Default.GetString(response);
var accountsList = serializer.Deserialize<Dictionary<string, dynamic>>(responseString);
Assuming a SugarCRM 6.4 or 6.5 system and API version REST v4_1...
I don't know the C#/.NET syntax/lingo, but 'link_name_to_fields_array' needs to be an array with keys of module names (e.g. "Contacts") and values that are arrays of the fields you want. The JSON would look like this:
{
"session":"asdfasdfsrf9ebp7jrr71nrth5",
"module_name":"Accounts",
"query":"",
"order_by":null,
"offset":0,
"select_fields":[
"id",
"name"
],
"link_name_to_fields_array":[
{
"name":"contacts",
"value":[
"id",
"last_name"
]
}
],
"max_results":"2",
"deleted":false
}
Also - I wrote this to help non PHP-devs interact with this version of the API, since documention is largely PHP based. You may find it useful: https://gist.github.com/matthewpoer/b9366ca4197a521a600f

How to create an Crystal Report from a XML (XML is from a Web Service) in C#

I want to know how can i create an crystal report from a XML (XML is from a Web Service), I read in some tutorials that it needs to locate the file and drag the fields in the report, but how about a XML from a Web Service?
Here is the code how I get the XML from a Web Service
var doc = XDocument.Parse(trx.GetCardTrx("xxxxx", "xxxx", "xxx", "", dateTimePicker1.Text, dateTimePicker2.Text, "", "", "", "", "", "", "", "", "", "", "", "FALSE", "", "", "", "", "", "", "", "", "", "", ""));
MessageBox.Show(doc.ToString());
So this code return this kind of values (From MessageBox.Show(doc.ToString())
And here is the code for the selected values that should be in the report
var summary = from r in doc.Descendants("TrxDetailCard")
select new
{
Account_Type = r.Element("Account_Type_CH").Value,
Captured = r.Element("Captured").Value,
Trans_Type_ID = r.Element("Trans_Type_ID").Value,
Acct_Num_CH = r.Element("Acct_Num_CH").Value,
Tip_Amt_MN = r.Element("Tip_Amt_MN").Value,
Total_Amt_MN = r.Element("Total_Amt_MN").Value,
Date_DT = r.Element("Date_DT").Value,
};
And What I want to happen is that to create a report using Crystal Reports with this values, not all values. Selected values only. How can I possibly do this? Any ideas will be a big help Thank you :D
This has not been tested but can you try something like the following
using System.Xml;
using System.Xml.Linq;
var doc = XDocument.Parse(trx.GetCardTrx("xxxxx", "xxxx", "xxx", "", dateTimePicker1.Text, dateTimePicker2.Text, "", "", "", "", "", "", "", "", "", "", "", "FALSE", "", "", "", "", "", "", "", "", "", "", ""));
var data = new DataSet();
var context = new XmlParserContext(null, new XmlNamespaceManager(new NameTable()), null, XmlSpace.None);
var reader = doc
data.ReadXml(reader);
var report = new ReportDocument();
report.SetDataSource(data);
this.crystalReportViewer1.ReportSource.ReportSource = report;
The Idea in theory should work but you can reference something similar from this link
XML-based Crystal Report not updating child objects on refresh

Categories