The timeout period ... IN LINQ C# - c#

While executing the down lines of my C# controller code I was getting
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding
I use linq to sql in my c#.and result show my report form.my reporter is rdlc.
I tried like set the connect Timeout = 0; also, but I get the same error.
How can I solve it?
please help me...thanks.
private void bt10_Click(object sender, EventArgs e)
{
{
Form3 frm3 = new Form3();
DataSet ds = new DataSet();
var DB = new DataClasses3DataContext();
var c1 = (from c in DB.A
join r in DB.A1
on c.DATE equals r.DATE
where c.B.Equals(int.Parse(txtSearch.Text))
&& (string.Compare(c.DATE.ToString(), txtEdate.Text) <= 0
&& string.Compare(c.DATE.ToString(), txtFdate.Text) >= 0)
&& (c.NO == r.NO)
&& (c.K == 10)
&& (c.A == 1)
&& (r.A == 2)
&& r.K != 10
select c).ToList();
dataGridView1.DataSource = c1;
DataSet2.ADataTable dt = new DataSet2.ADataTable();
foreach (A item in c1)
{
dt.Rows.Add(item.B, item.DATE, item.NO, item.K);
}
if (c1 == null)
{
MessageBox.Show("null");
}
else
{
ds.Tables.Add(dt);
ReportDataSource rds = new ReportDataSource();
frm3.reportViewer1.LocalReport.DataSources.Clear();
rds.Name = "DataSet3";
rds.Value = dt;
frm3.reportViewer1.LocalReport.DataSources.Add(rds);
frm3.reportViewer1.LocalReport.ReportEmbeddedResource = "P10.Report5.rdlc";
frm3.ShowDialog();
}
}
}

Don't "fix" timeouts by increasing them. Fix the underlying problem!
It's very likely that convertingc.DATE to string before comparing it causes the problem. This makes the expression non-sargable, i.e. any index on DATE is disabled. You should change this by parsing txtEdate.Text and txtFdate.Text first, and use the parsed values in the comparison (and also parse txtSearch first).
var edate = DateTime.Parse(txtEdate.Text);
var fdate = DateTime.Parse(txtFdate.Text);
var searchInt = int.Parse(txtSearch.Text);
...
where c.B == searchInt
&& c.DATE <= edate
&& c.DATE >= fdate
...
If this still doesn't help you should investigate proper indexing on the database tables. For such a relatively simple query you just shouldn't get a timeout.

Use CommandTimeout Property That adds to the default time out which is 30 seconds:
DB.CommandTimeout = 1 * 60; // Adds 1 Minute to the time out, so 1:30 minutes now
If this is a long running task, you might need to consider an async method.
For More : DataContext.CommandTimeout

Related

Lambda Expression doesn't work for filtering obj in a list

User select month, and dynamically 4 textbox + a button (save row) for each day will be drawn; every textbox has the textbox.Tag = day who refers.
When user click on save row I will it to select only the textboxes of the corresponding row (expecting 4 textboxes).
code that generate the textboxes:
foreach (DateTime day in monthDays)
{
var t1 = new TextBox();
t1.Location = new Point(Origin.X + 90, Origin.Y + 30 * Ycounter);
t1.Size = new Size(40, 25);
t1.MaxLength = 5;
t1.Tag = day;
AutoControls.Add(t1);
Controls.Add(t1);
I try this:
private void SaveButton_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
DateTime d = (DateTime)b.Tag;
List<TextBox> t = new List<TextBox>(AutoControls.OfType < TextBox());
//Autocontrols it's the list with ALL the dynamically generates controls in that form.
var g = t.Where(x => x.Tag == b.Tag); // expecting 4 textboxes, but returns 0
var g = t.Where(x => x.Tag == b.Tag).ToList(); // 0
var g = t.FindAll(x => x.Tag == b.Tag); //returns 0
Any help is very appreciated ^_^
You are comparing two object directly, and by default this will be done by references comparison.
// this for example will never be true, even if today is 20190613
// because they are 2 different instances
(object)new DateTime(2019, 06, 13) == (object)DateTime.Today
You want to compare the value of these date instead:
t.Where(x => x.Tag is DateTime date && date == d)
List<Control> RecordData = Controls.Cast<Control>().Where(x => x.Tag is DateTime date && date == d).ToList();
I've create this code starting from the suggestions of Xiaoy312 (Thanks ^^) and reading about Cast command on similar threads.

Select Query Count LINQ C# Unity Not Working Correctly

Could someone tell me why this query return a wrong value ?
First I generate 30 data at Player.estateagent. The Date must until 28/05.
System.DateTime Now = System.DateTime.Now;
System.DateTime thedate;
thedate = Now;
System.DateTime today = System.DateTime.Now;
for (int i = 1; i <= 30; i++) {
Player.estateagent.Add (new classBundle (thedate, false));
thedate = thedate.AddDays (1);
Debug.Log ("DATE : " + Player.estateagent [i - 1].Date);
}
int count = Player.estateagent.Where (j => {
return j.Complete == false && today.Date <= j.Date.Date;
}).Select (j=> j.Date.Date).Count ();
Debug.Log(count); // Here return 30, It must be 1
When i count i got 30 not 1. It should return 1 because i have query
where j.complete == false && today.Date <= j.Date.Date
Can someone explain what mistake that i done ?
Thanks
Yes, So far I have asked a wrong question. This is just misunderstood about the logic.
The code i am provide above is running without an error. And the logic is right too.
The result is right with 30.
But i want to have a result which Equal and Greater ( <= ) than the Player.estateagent => Date Compire to today date.
So i just need to do today.Date >= j.Date.Date.
Just like that.

Query upcoming birthdays

I'd like to query my customers for the ones, whose birthdays are yet to come.
I've tried this query, and it - of course - has failed breathtakingly:
Addresses.Where(adr => adr.DateOfBirth != null && adr.DateOfBirth.Value >
DateTime.Now).Take(15).ToList();
Of course this can't work properly (not if you're born in the future) and I'd like to know how I can query my Nullable<DateTime> without a year?
You can do it in one line like this:
context.Addresses.Where(adr => adr.DateOfBirth != null).OrderBy(adr => EntityFunctions.DiffDays(DateTime.Today, EntityFunctions.AddYears(adr.DateOfBirth, EntityFunctions.DiffYears(adr.DateOfBirth, DateTime.Today) + ((adr.DateOfBirth.Month < DateTime.Today.Month || (adr.DateOfBirth.Day <= DateTime.Today.Day && adr.DateOfBirth.Month == DateTime.Today.Month)) ? 1 : 0)))).Take(15).ToList();
Or in a more readable format:
var query = from adr in context.Addresses
where adr.DateOfBirth != null
let diffYears = EntityFunctions.DiffYears(adr.DateOfBirth, DateTime.Today)
let birthdayOccurred = adr.DateOfBirth.Month < DateTime.Today.Month || (adr.DateOfBirth.Day <= DateTime.Today.Day && adr.DateOfBirth.Month == DateTime.Today.Month)
let nextBirthdate = EntityFunctions.AddYears(adr.DateOfBirth, diffYears + (birthdayOccurred ? 1 : 0))
let daysToBirthdate = EntityFunctions.DiffDays(DateTime.Today, nextBirthdate)
orderby daysToBirthdate
select adr;
var result = query.Take(15).ToList();
I'm not sure you can do this as a one-liner. Certainly not with any degree of clarity.
The needed steps are:
Create an ordered list containing only the birthdates where the
month/day comes after today.
Create an ordered list containing only the birthdates where the month/day is before today.
Append the second list to the first one, you now have a single list, sorted in
birthday order.
Take the first 15.
I think the C# code would look something like this (You might need to add a List or two.)
var list1 = Addresses.Where(adr => adr.DateOfBirth != null && (adr.DateOfBirth.Value.Month > DateTime.Today.Month || (adr.DateOfBirth.Value.Month == DateTime.Today.Month && adr.DateOfBirth.Value.Day >= DateTime.Today.Day))).ToList();
var list2 = Addresses.Where(adr => adr.DateOfBirth != null && (adr.DateOfBirth.Value.Month < DateTime.Today.Month || (adr.DateOfBirth.Value.Month == DateTime.Today.Month && adr.DateOfBirth.Value.Day < DateTime.Today.Day))).ToList();
var fullList = list1.Add(list2);
Im not familiar with Linq, I'll try to help with some pseudocode.
Most important condition should look like this:
Date(CurrentDate.Year, DateOfBirth.Month, DateOfBirth.Day) >= CurrentDate
|| ' OR
Date(CurrentDate.Year + 1, DateOfBirth.Month, DateOfBirth.Day) >= CurrentDate
This will work 31 December too.
Alternative:
// consider this as pseudocode, I didnt tested that in C#
function GetNextBirthday(DateTime DateOfBirth)
{
int yearOfNextBirthday;
int birthdayMMDD = DateOfBirth.Month*100 + DateOfBirth.Day;
int todayMMDD = CurrentDate.Month*100 + CurrentDate.Day;
if (birthdayMMDD >= todayMMDD)
{
yearOfNextBirthday = CurrentDate.Year; // this year
}
else
{
yearOfNextBirthday = CurrentDate.Year + 1; // next year
}
DateTime nextBirthday;
// you have to write this line yourself, i dont remember how to make date from Y, M, D
nextBirthday = DateFromYMD(yearOfNextBirthday, DateOfBirth.Month, DateOfBirth.Day);
return nextBirthday;
}
Here is my entry for "one liner":
DateTime now = DateTime.Now;
var next15 =
from a in db.Addresses
where a.DateOfBirth != null
let diff = EntityFunctions.DiffSeconds(
EntityFunctions.AddYears(now, -EntityFunctions.DiffYears(a.DateOfBirth, now)),
a.DateOfBirth)
orderby diff >= 0 ? diff : diff + 366*24*60*60
select new a;
var res = next15.Take(15).ToList();
Just tested with SQL Database - and it works like charm ;)
Try something like this; (this is working - I've tested)
//A mock up value for comparison (as DayOfYear not supported in Linq)
int doy = DateTime.Today.Month * 31 + DateTime.Today.Day;
var results = Addresses.Where(a => a.DateOfBirth != null)
.OrderBy( a =>
(a.DateOfBirth.Value.Month * 31 + a.DateOfBirth.Value.Day) +
(a.DateOfBirth.Value.Month * 31 + a.DateOfBirth.Value.Day > doy ? 0 : 400 ))
.Take(15).ToList();
Here's the same solution as #Aducci but with nullable date and the DBFunctions, as EntityFunctions became deprecated.
pacientes = from paciente in pacientes
where paciente.Nascimento != null
let diffYears = DbFunctions.DiffYears(paciente.Nascimento, DateTime.Today)
let birthdayOccurred = paciente.Nascimento.Value.Month < DateTime.Today.Month
|| (paciente.Nascimento.Value.Day <= DateTime.Today.Day && paciente.Nascimento.Value.Month == DateTime.Today.Month)
let nextBirthdate = DbFunctions.AddYears(paciente.Nascimento, diffYears + (birthdayOccurred ? 1 : 0))
let daysToBirthdate = DbFunctions.DiffDays(DateTime.Today, nextBirthdate)
orderby daysToBirthdate
select paciente;

Grouping drop down list and applying them to a set of equations

I'm very new to using this site and to C# .Net so be gentle!
What is my project? I am creating a timesheet for my parents side business that doctors can fill out online. There are call hours and regular hours that I have created if statements for to equate the correct hours for both call and regular.
What am I trying to accomplish? I would like the user to click one submit button and have each group of drop down lists corresponding to each day run through the equations and give a total.
What is my question? How can I first off - group a set of Drop Down Lists and then - how would the code look to say something like "for some label(LabelMondayCALL.Text), use this group (DDL_In_Monday, DDL_OutBreak_Monday, etc.) of drop downs to find what the label would be."
Why do I want to do this? To avoid copy and pasting pages of code for each individual day and to try and keep things clean and simple for possible future changes.
Here is some code:
DateTime MondayDDL4 = DateTime.Parse(DDL_Out_Monday.SelectedValue);
DateTime MondayDDL3 = DateTime.Parse(DDL_InBreak_Monday.SelectedValue);
DateTime MondayDDL2 = DateTime.Parse(DDL_OutBreak_Monday.SelectedValue);
DateTime MondayDDL1 = DateTime.Parse(DDL_In_Monday.SelectedValue);
else if ((MondayDDL1 <= FromCompHours) & (MondayDDL4 <= FromCompHours)) //comp time earlier than 6:30
{
LabelMondayREG.Text = "00:00:00";//works
LabelMondayCALL.Text = MondayDDL4.Subtract(MondayDDL1).ToString();//works
if ((BreakStart != "00:00:00") & (BreakEnd != "00:00:00"))
{
LabelMondayREG.Text = "00:00:00";
String CompTimeBreakHours = (BreakEndDT.Subtract(BreakStartDT)).ToString();
LabelMondayCALL.Text = ((DateTime.Parse(LabelMondayCALL.Text)) - (DateTime.Parse(CompTimeBreakHours))).ToString();
}
}
Thanks for any help you can provide and please let me know if you see anything else that I could simplify, like I said I'm fairly new to this stuff.
Here is some more code and a picture of the actual site, but here is a little bit more of a description of what I'm doing: Basically these equations are deciding what time (Call hours or Regular Hours) the doctors break should be subtracted from, for one day of the week, from a row of drop down menus. However I would prefer not to copy this code for each set of drop down lists. So I wanted to know if there was a way to create an instance to have the call hours and regular hours labels use only the drop downs that correspond to the day they are labeled.
so MondayDDL1, 2, ,3 and 4 run through the equation and their answers fill in LabelMondayCall and LabelMondayReg
and then
TuesdayDDL1, 2, ,3 and 4 run through the equation and their answers fill in LabelTuesdayCall and LabelTuesdayReg
Never mind no image I don't have enough reputation
here is a bit of what the layout looks like though
mondayDDL1 mondayDDL2 mondayDDL3 mondayDDL4 LABELmondayREG LABELmondayCALL
tuesdayDDL1 tuesdayDDL2 tuesdayDDL3 tuesdayDDL4 LABELtuesdayREG LABELtuesdayCALL
protected void ButtonCalculate_Click(object sender, EventArgs e)
{
//DropDownList2.Items.Clear();
//DropDownList2.SelectedValue = null;
//DropDownList3.Items.Clear();
//DropDownList3.SelectedValue = null;
if (DDL_OutBreak_Monday.SelectedValue == "----")
{
DDL_OutBreak_Monday.SelectedValue = DateTime.Parse("00:00:00").ToShortTimeString();
}
if (DDL_InBreak_Monday.SelectedValue == "----")
{
DDL_InBreak_Monday.SelectedValue = DateTime.Parse("00:00:00").ToShortTimeString();
}
DateTime MondayDDL4 = DateTime.Parse(DDL_Out_Monday.SelectedValue);
DateTime MondayDDL3 = DateTime.Parse(DDL_InBreak_Monday.SelectedValue);
DateTime MondayDDL2 = DateTime.Parse(DDL_OutBreak_Monday.SelectedValue);
DateTime MondayDDL1 = DateTime.Parse(DDL_In_Monday.SelectedValue);
//DDL1 = DateTime.Parse(DDL_In_Tuesday.SelectedValue);// END POINT---------------------------END POINT
String BreakStart = DDL_OutBreak_Monday.SelectedValue;
String BreakEnd = DDL_InBreak_Monday.SelectedValue;
DateTime BreakStartDT = DateTime.Parse(BreakStart);
DateTime BreakEndDT = DateTime.Parse(BreakEnd);
DateTime FromCompHours = DateTime.Parse("6:30:00");
DateTime ToCompHours = DateTime.Parse("16:30:00");
Label1.Text = "";
Label2.Text = "";
Label3.Text = "";
LabelMondayREG.Text = "";
LabelMondayCALL.Text = "";
//int result = DateTime.Compare(DDL1, DDL2);
if ((MondayDDL1 <= FromCompHours) & (MondayDDL4 >= ToCompHours))//Comp time at both ends
{
Label2.Text = FromCompHours.Subtract(MondayDDL1).ToString(); //finds comp hours before 6:30 WORKS
Label3.Text = MondayDDL4.Subtract(ToCompHours).ToString(); //finds comp hours after 16:30 WORKS
LabelMondayREG.Text = ("10:00:00");
//LabelHolder.Text = (DateTime.Parse(Label2.Text)) + (DateTime.Parse(Label3.Text)).ToString(); //adds the two comp hours together
//TimeSpan SubtractReg = DDL2.Subtract(DDL1); //finds the difference of from minus to
DateTime To = DateTime.Parse(Label2.Text);//convert text to datetime of earlier time
DateTime From = DateTime.Parse(Label3.Text);//convert text to datetime of later time
LabelMondayCALL.Text = (To.TimeOfDay + From.TimeOfDay).ToString();
//LabelMondayCALL.Text = "10:00:00";
if ((BreakStartDT != DateTime.Parse("00:00:00")) & (BreakEndDT != DateTime.Parse("00:00:00")))
{
//DateTime MondayBreak = MondayDDL3.Subtract(MondayDDL2);
if ((MondayDDL2 <= FromCompHours) & (MondayDDL3 <= FromCompHours)) //Start before 6:30 end after 16:30 w/ break before 6:30
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(MondayDDL3.Subtract(MondayDDL2)).ToString();
//LabelMondayCALL.Text = "error1"; //(DateTime.Parse(LabelMondayCALL.Text)).ToString();
}
if ((ToCompHours >= MondayDDL2) & (MondayDDL2 >= FromCompHours) & (ToCompHours >= MondayDDL3) & (MondayDDL3 >= FromCompHours)) //Start before 6:30 end after 16:30 /w break between 6:30 and 16:30
{
LabelMondayREG.Text = TimeSpan.Parse(LabelMondayREG.Text).Subtract(MondayDDL3.Subtract(MondayDDL2)).ToString();
}
if ((MondayDDL2 >= ToCompHours) & (MondayDDL3 >= ToCompHours)) //Start before 6:30 end after 16:30 /w break after 16:30
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(MondayDDL3.Subtract(MondayDDL2)).ToString();
}
if ((MondayDDL2 <= FromCompHours) & (MondayDDL3 >= FromCompHours) & (MondayDDL3 <= ToCompHours))
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(FromCompHours.Subtract(MondayDDL2)).ToString();
LabelMondayREG.Text = TimeSpan.Parse(LabelMondayREG.Text).Subtract(MondayDDL3.Subtract(FromCompHours)).ToString();
}
if ((MondayDDL2 <= ToCompHours) & (MondayDDL2 >= FromCompHours) & (MondayDDL3 >= ToCompHours))
{
LabelMondayCALL.Text = TimeSpan.Parse(LabelMondayCALL.Text).Subtract(ToCompHours.Subtract(MondayDDL2)).ToString();
LabelMondayREG.Text = TimeSpan.Parse(LabelMondayREG.Text).Subtract(MondayDDL3.Subtract(ToCompHours)).ToString();
}
}

Only parameterless constructors and initializers are supported in LINQ to Entities while getting records using range dates

i have develop a small web application in that i want get the records from database using Entity frame work when get the records it showing error ..
Only parameterless constructors and initializers are supported in LINQ to Entities.
public void Bindloanpayment()
{
int loanpaymentid = Convert.ToInt32(Session["Loanid"].ToString());
int kr = 1998;
int km = 05;
int kdt = 02;
var query = from p in mortgageentity.Payments
join D in mortgageentity.Debit_Method on p.Debit_Method_ID equals D.Debit_Method_ID
join pt in mortgageentity.Payment_Type on p.Payment_Type_ID equals pt.Payment_Type_ID
where (p.Client_Pmt_Date >= new DateTime(kr, km, kdt)) && (p.Client_Pmt_Date <= new DateTime(1999, 8, 1)) && (p.Loan_ID == loanpaymentid)
select new
{
Pmt_ID=p.Pmt_ID,
Loan_ID=p.Loan_ID,
Client_Pmt_Date=p.Client_Pmt_Date,
MtgSvr_Pmt_Start_Date2=p.MtgSvr_Pmt_Start_Date2,
Debit_Method_Desc=D.Debit_Method_Desc,
Total_Debit_Amt=p.Total_Debit_Amt,
CreditAmt=p.CreditAmt,
LenderAmt=p.LenderAmt,
Payment_Type_Desc=pt.Payment_Type_Desc,
Return_Code=p.Return_Code,
Returned_Date=p.Returned_Date
};
grdPayments.DataSource = query.ToList();
grdPayments.DataBind();
}
Please help me how can i resolve this problem..
You could try creating the DateTime values first:
DateTime start = new DateTime(kr, km, kdt);
DateTime end = new DateTime(1999, 8, 1);
...
// In the query
where p.Client_Pmt_Date >= start
&& p.Client_Pmt_Date <= end
&& p.Loan_ID == loanpaymentid
That's only a guess as to what's going wrong, but it seems feasible...

Categories