I have problem when copy query linq to same datatable.
DataTable dt_result = filterkontrak.CopyToDataTable();
var query = from q in dt_result.AsEnumerable()
select new
{
ChassisNo = q.Field<string>("ChassisNo"),
Engineno = q.Field<string>("Engineno"),
BuiltYear = q.Field<string>("ManufactureYear"),
VehicleType = q.Field<string>("VehicleType"),
PlatNo = q.Field<string>("LicensePlate"),
Type = q.Field<string>("Type"),
ContractNo = q.Field<string>("Brand"),
ContractDate = q.Field<string>("ContractNo"),
TglGenerate = q.Field<string>("ContractDate"),
FileName = q.Field<string>(FileName),
Status = q.Field<string>("1"),
CreatorID = q.Field<string>(UserId),
LastUserId = q.Field<string>(UserId)
};
DataTable dt_result2 = query.AsEnumerable();
SqlBulkCopy bulkCopy = new SqlBulkCopy(conn.SqlCon());
bulkCopy.DestinationTableName = "TEMP_VMF_LogAssetMngmt";'
Error:
The type 'AnonymousType#1' cannot be used as type parameter 'T' in the
generic type or method
'System.Data.DataTableExtensions.CopyToDataTable(System.Collections.Generic.IEnumerable)'.
Couldy anybody improve my code ?
Related
I try to count line in my SQL query.
It works without parameter. For example, if I assign directly FIOForm = 'SmithJJ'. I really don't understand what I'm doing wrong.
Exception: the SqlParameter is already contained by another SqlParameterCollection
int kolNar = 0;
System.Data.SqlClient.SqlParameter Name = new System.Data.SqlClient.SqlParameter("#Name", System.Environment.UserName);
var pushStat = db.Database.SqlQuery<Reestr>("select * from Reestr where FIOForm = #Name and Status = 'Executed'", Name);
foreach (var u in pushStat)
{
kolNar = pushStat.Count();
}
if (kolNar > 0)
MessageBox.Show(kolNar.ToString());
I suppose you can call:
Dispose();
before
System.Data.SqlClient.SqlParameter Name = new System.Data.SqlClient.SqlParameter("#Name", System.Environment.UserName);
i have 'created date' and 'closed date' in my file and i'm converting it in json so i have that dates in json.
in my method i have two parameter like from date and to date and i want to count particular column data of my file between from date and to date.so how can we write code to fetch it using linq.
i tried this...
public JsonResult StatusDerails(DateTime from,DateTime to)
{
string csvurl = WebConfigurationManager.AppSettings["csvfileurl"];
var lines = System.IO.File.ReadAllLines(csvurl).Skip(1);
List<Product> prdt = new List<Product>();
foreach (string line in lines)
{
Product c1 = new Product();
var split = line.Split(',');
c1.ID = Int32.Parse(split[0]);
c1.Area_Path = split[1];
c1.IterationPath = split[2];
c1.State = split[3];
c1.Reason = split[4];
c1.Priority = Int32.Parse(split[5]);
c1.Severity = split[6];
c1.Tags = split[7];
c1.Title = split[8];
c1.CreatedDate = split[9];
c1.CreatedBy = split[10];
c1.ResolvedDate = split[11];
c1.ResolvedBy = split[12];
c1.ClosedDate = split[13];
c1.AssignedTo = split[14];
prdt.Add(c1);
}
//var list = prdt.GroupBy(a=>a.AreaPath).Select(a=>new UIproduct() {
var productName = prdt.Select(a => a.Area_Path).Distinct();
List<StatusDetail> statusdetail = new List<StatusDetail>();
foreach (var Name in productName)
{
StatusDetail sd = new StatusDetail();
sd.CarryOver = prdt.Where(a => a.CreatedDate >= from.Date.ToString() && a.ClosedDate <= to.Date.ToShortDateString
}
return Json(statusdetail, JsonRequestBehavior.AllowGet);
}
The comparison of DateTime as string will not be a good option and that wont gives you the exact result, So I recommend you to change the type of CreatedDate and ClosedDate to DateTime. and compare two DateTime values in linq. I think instead of splitting json for creating object of certain types you can use json converters.
Fix for your scenario:
c1.CreatedDate = DateTime.Parse(split[9]);
c1.ClosedDate = DateTime.Parse(split[13]);
Don't forget to change the type in the class, Now its fine to use the linq as like the following:
sd.CarryOver = prdt.Where(a => a.CreatedDate >= from.Date && a.ClosedDate <= to.Date);
I'm attempting to take a list of Contacts that are retrieved from an OleDB query, add them to a List and then load the List into a DataTable. When I count the number of items in the list it results in the correct number (27000).
However, when I count the number of rows in the DataTable, it results in 0. After doing this I want to write the DataTable to CSV using FileHelpers, however the CSV file is empty.
This is the code I am using;
var listOfContacts = new List<Contact>();
using (OleDbConnection dbfCon = new OleDbConnection(dbfConstr))
{
dbfCon.Open();
var dbfCmd = new OleDbCommand(#"SELECT ct_id, ct_cmpid, ct_empid,
ct_pplid, ct_cntid, ct_pplnm, ct_date, ct_time, ct_type, ct_doneby, ct_desc
FROM contacts", dbfCon);
using (var myReader = dbfCmd.ExecuteReader())
{
while (myReader.Read())
{
var newContact = new Contact()
{
ContactID = Convert.ToInt32(myReader[0]),
CompanyID = Convert.ToInt32(myReader[1]),
EmployeeID = Convert.ToInt32(myReader[2]),
PersonID = Convert.ToInt32(myReader[3]),
ContractID = Convert.ToInt32(myReader[4]),
PersonName = myReader[5].ToString(),
ContactDate = Convert.ToDateTime(myReader[6]),
ContactTime = Convert.ToDateTime(myReader[7]),
TypeOfContact = myReader[8].ToString(),
ContactMadeBy = myReader[9].ToString(),
ContactDescription = myReader[10].ToString(),
};
listOfContacts.Add(newContact);
}
}
DataTable dTable = new DataTable();
dTable.Columns.Add("ContactID");
dTable.Columns.Add("CompanyID");
dTable.Columns.Add("EmployeeID");
dTable.Columns.Add("PersonID");
dTable.Columns.Add("ContractID");
dTable.Columns.Add("PersonName");
dTable.Columns.Add("ContactDate");
dTable.Columns.Add("ContactTime");
dTable.Columns.Add("TypeOfContact");
dTable.Columns.Add("ContactMadeBy");
dTable.Columns.Add("ContactDescription");
MessageBox.Show(listOfContacts.Count.ToString());
foreach (var contact in listOfContacts)
{
var newRow = dTable.NewRow();
newRow["ContactID"] = contact.ContactID;
newRow["CompanyID"] = contact.CompanyID;
newRow["EmployeeID"] = contact.EmployeeID;
newRow["PersonID"] = contact.PersonID;
newRow["ContractID"] = contact.ContractID;
newRow["PersonName"] = contact.PersonName;
newRow["ContactDate"] = contact.ContactDate;
newRow["ContactTime"] = contact.ContactTime;
newRow["TypeOfContact"] = contact.TypeOfContact;
newRow["ContactMadeBy"] = contact.ContactMadeBy;
newRow["ContactDescription"] = contact.ContactDescription;
}
MessageBox.Show(dTable.Rows.Count.ToString());
You can see the two MessageBox that result in the numbers, am I loading the Data into the DataTable incorrectly?
You have to add the new row to the DataTable:
foreach (var contact in listOfContacts)
{
var newRow = dTable.NewRow();
newRow["ContactID"] = contact.ContactID;
newRow["CompanyID"] = contact.CompanyID;
newRow["EmployeeID"] = contact.EmployeeID;
newRow["PersonID"] = contact.PersonID;
newRow["ContractID"] = contact.ContractID;
newRow["PersonName"] = contact.PersonName;
newRow["ContactDate"] = contact.ContactDate;
newRow["ContactTime"] = contact.ContactTime;
newRow["TypeOfContact"] = contact.TypeOfContact;
newRow["ContactMadeBy"] = contact.ContactMadeBy;
newRow["ContactDescription"] = contact.ContactDescription;
dTable.Rows.Add(newRow); // YOU NEED THIS LINE TO ADD THE NEWROW TO DATATABLE
}
In your foreach loop add this at the end :
dTable.Rows.Add(newRow);
In my code below I am having issue on this line:
transactiongetalert = serv.GetAlertThresholdCall(AcctNo));
The error: cannot implicitly convert type.... from... to
Models.xmlGetResponse c = new Models.xmlGetResponse();
var serv = new SelfServiceServices();
string _xmlString = serv.GetLoggedUserAccessAccount(loggedusersession.LoggedSessionId);
XmlDocument x = new XmlDocument();
x.LoadXml(_xmlString);
string AcctNo;
var accts = x.GetElementsByTagName("AccountNumber");
var GlobalListOfTranAlerts = new List<AlertResponse>();
List<AlertResponse> transactiongetalert = new List<AlertResponse>();
foreach (XmlElement a in accts)
{
AcctNo = a.InnerText;
transactiongetalert = serv.GetAlertThresholdCall(AcctNo));
GlobalListOfTranAlerts.AddRange(transactiongetalert);
}
return View(GlobalListOfTranAlerts);
Please who can help me out; Thanks in advance.
Declaration: AlertResponse SelfServiceServices.GetAlertThresholdCall(string AccountNo) where SelfServiceServices is a public class
Detailed Error: Cannot implicitly convert type ‘Namespace.WebServiceConnect.AlertResponse’ to ‘System.Collections.Generic.List’
Hi to get associated records from campaignlist_association in ms crm 2013. Tried tons of different variations.
This is last one:
System.Guid campaignId = ((EntityReference)entity.Attributes["regardingobjectid"]).Id;
var list = (from c in EntityCon.CampaignSet
join l in EntityCon.ListSet on c.campaignlist_association equals l.campaignlist_association
where c.CampaignId == campaignId select c).First();
The error message
The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'Join'
indicates that the types of the properties used with the equals expression must match, e.g. that they are both Int32 or Guid.
Make sure that the type l.campaignlist_association is the same as the type c.campaignlist_association.
I would use code as follows to get the associated entity records. Change the column set as per your requirement.
private EntityCollection GetAssociatedEntityItems(string relationshipName, string relatedEntityName, string entityName, Guid entityId)
{
EntityCollection result = null;
QueryExpression query = new QueryExpression();
query.EntityName = relatedEntityName;
query.ColumnSet = new ColumnSet(false);
Relationship relationship = new Relationship();
relationship.SchemaName = relationshipName;
relationship.PrimaryEntityRole = EntityRole.Referencing;
RelationshipQueryCollection relatedEntity = new RelationshipQueryCollection();
relatedEntity.Add(relationship, query);
RetrieveRequest request = new RetrieveRequest();
request.RelatedEntitiesQuery = relatedEntity;
request.ColumnSet = new ColumnSet(true);
request.Target = new EntityReference
{
Id = entityId,
LogicalName = entityName
};
RetrieveResponse response = (RetrieveResponse)serviceProxy.Execute(request);
RelatedEntityCollection relatedEntityCollection = response.Entity.RelatedEntities;
if (relatedEntityCollection.Count > 0)
{
if (relatedEntityCollection.Values.Count > 0)
{
result = (EntityCollection)relatedEntityCollection.Values.ElementAt(0);
}
}
return result;
}