Union with System.Linq.IQueryable get errors - c#

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);

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));

XML-mapping to SQL-server

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

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>()
};

MVC 4 DateTime? on model removal on edit

I have model which as a nullable Date field. Everything works as expected except in the circumstance where I am editing the model and I want to remove the date. Then validation is triggered:
How do I allow removal while also keeping validation on a partially filled in date? Is worth mentioning that are using a custom EditorTemplate:
Here is the code for the editor template:
#model DateTime?
#{
var months = new[] {
new { Value = "", Display="" },
new { Value = "1", Display = "01-Jan" },
new { Value = "2", Display = "02-Feb" },
new { Value = "3", Display = "03-Mar" },
new { Value = "4", Display = "04-Apr" },
new { Value = "5", Display = "05-May" },
new { Value = "6", Display = "06-Jun" },
new { Value = "7", Display = "07-Jul" },
new { Value = "8", Display = "08-Aug" },
new { Value = "9", Display = "09-Sep" },
new { Value = "10", Display = "10-Oct" },
new { Value = "11", Display = "11-Nov" },
new { Value = "12", Display = "12-Dec" }
};
var monthSelect = new SelectList(months, "Value", "Display", Model.HasValue ? Model.Value.Month.ToString() : "");
var days = new List<String>();
days.Add("");
days.AddRange(Enumerable.Range(1, 31).Select(s => s.ToString()));
var daySelect = new SelectList(days.Select(x => new KeyValuePair<string, string>(x, x)), "Key", "Value", Model.HasValue ? Model.Value.Day.ToString() : "");
}
#Html.DropDownList("Month", monthSelect)
#Html.DropDownList("Day", daySelect)
#Html.TextBox("Year", (Model.HasValue ? Model.Value.ToString("yyyy") : string.Empty), new { style="width:75px;" })
The code on the edit view is dead simple:
#Html.EditorFor(model => model.MyDate)

Ext.net gridview columns getting distorted in IE 8

i'm generating EXT.NET gridview dynamically as below,
public GridPanel GetGridView()
{
return new GridPanel
{
Border = false,
ID = "grd",
Cls = "x-grid-custom",
StyleSpec = "margin-top:7px; margin-left:-2px",
Scroll = ScrollMode.Both,
OverflowX = Overflow.Auto,
EnableColumnHide = false,
ColumnLines = true,
ForceFit = false,
//Width = 1100,
EmptyText = "No rows to display",
Store = { this.CreateTabularStore() },
ColumnModel =
{
Columns = {
new DateColumn {ID="ED", Text = "Effective Date",Wrap = true,DataIndex = "ED",Format="dd MMM yyyy",Groupable = true, Html="<i class='prfl_unfilter_icon' onclick='return ShowGridFilter(this);'></i>" ,Width = 110},
new Column {ID="PRICE", Text = "Price",DataIndex = "PRICE",Groupable = true, Html="<i class='prfl_unfilter_icon' onclick='return ShowGridFilter(this);'></i>" ,Width = 70},
new Column {ID="CURRENCY", Text = "Currency",DataIndex = "CURRENCY",Groupable = true, Html="<i class='prfl_unfilter_icon' onclick='return ShowGridFilter(this);'></i>" ,Width = 80},
new Column {ID="OFFICIAL",Text = "Official Price",DataIndex = "OFFICIAL",Groupable = true, Html="<i class='prfl_unfilter_icon' onclick='return ShowGridFilter(this);'></i>" ,Width = 100},
new DateColumn {ID="MARKETED_EFFECTIVE_DATE", Text = "Marketed Effective Date",DataIndex = "MARKETED_EFFECTIVE_DATE",Format="dd MMM yyyy",Groupable = true, Html="<i class='prfl_unfilter_icon' onclick='return ShowGridFilter(this);'></i>" ,Width = 100},
new Column {ID="MARKETING_DESC", Text = "Marketed",DataIndex = "MARKETING_DESC",Groupable = true, Html="<i class='prfl_unfilter_icon' onclick='return ShowGridFilter(this);'></i>" ,Width = 80},
new DateColumn {ID="DISCONTINUED_TS", Text = "Date Discontinued",DataIndex = "DISCONTINUED_TS",Format="dd MMM yyyy",Groupable = true, Html="<i class='prfl_unfilter_icon' onclick='return ShowGridFilter(this);'></i>" ,Width = 100},
}
},
Features = {
new Grouping(){HideGroupedHeader=false }
},
View = { new Ext.Net.GridView() { LoadMask = true, LoadingText = "Loading..." } }
};
}
below is how i defined store in a method named CreateTabularStore():
Store store;
Model model;
store = new Store();
store.ID = "StorePD";
model = new Model();
model.Fields.AddRange(new ModelField[] {
new ModelField("ED",ModelFieldType.Date),
new ModelField("PRICE", ModelFieldType.Float),
new ModelField("CURRENCY"),
new ModelField("OFFICIAL"),
new ModelField("MARKETED_EFFECTIVE_DATE",ModelFieldType.Date),
new ModelField("MARKETING_STATUS_DESC"),
new ModelField("DISCONTINUED_TS",ModelFieldType.Date)
}
);
when i filter grid with DateColumn filter, grid columns are rendering distorted in IE 8 Browser as shown in the image below

Categories