I'm trying to make a search functionality. The code below says that if Port, Status and TIN are not null then query the database.
E.g 1. If User has chosen the port and status but not the TIN then the
TIN should not be included when searching the database.
E.g 2. If User has chosen the port only then the Status and TIN should
not be included when searching the database.
Code
int Port = Convert.ToInt32(Request.QueryString["Port"]);
var Status = Request.QueryString["Status"];
var TIN = Request.QueryString["TIN"];
List<Transaction> QueriedTransactionList;
QueriedTransactionList = db.Transactions.ToList();
TransactionViewModel TransactionViewModel = new TransactionViewModel();
List<TransactionViewModel> TransactionDataList = QueriedTransactionList.Select(x => new TransactionViewModel{
TTransactionID = x.TTransactionID,
BatchID = x.BatchID,
TransactionDateTime = x.TransactionDateTime,
TransactionStatus = x.TransactionStatus,
TaxPayerName = x.Card.TaxPayer.TaxPayerName,
TaxPayerEmail = x.Card.TaxPayer.TaxPayerEmail,
TaxPayerTIN = x.Card.TaxPayer.TaxPayerTIN,
DispatchBy = x.User.UserName,
DestinationPort = x.Card.Port.PortName,
BatchCards = Helper.GetBatchQtyByBatchID(x.BatchID)
}).GroupBy(x => x.BatchID).Select(x => x.LastOrDefault()).Where(x => Status.IndexOf(x.TransactionStatus, StringComparison.OrdinalIgnoreCase) >= 0 && TIN.IndexOf(x.Card.TaxPayerTIN, StringComparison.OrdinalIgnoreCase) >= 0).OrderByDescending(x => x.TTransactionID).ToList();
Related
The query below should be selecting a list of information from different tables, and should also bring back a list of VehicleNames that are related to each ID coming back from db.Reservations
The query brings back data, but the list of VehicleNames only has one record, and it should bring back anywhere up to 5 records, depending on how many vehicles were reserved for that specific instance. I have tried adding a foreach to the VehicleName line in the select but I don't think I am using it right. Does anyone have any ideas as to how I can retrieve the list of values I need?
var query = from r in db.Reservations
let e = db.Employees.Where(x => r.RequestorID == x.ColleagueID).FirstOrDefault()
let rtv = db.ReservationToVehicle.Where(x => r.ID == x.ReservationID).FirstOrDefault()
let rs = db.ReservationStatus.Where(x => r.ID == x.ReservationID).FirstOrDefault()
let rst = db.ReservationStatusTypes.Where(x => rs.ReservationStatusTypeID == x.ID).FirstOrDefault()
select new
{
StartDate = r.StartDate,
EndDate = r.EndDate,
Destination = r.Destination,
PurposeOfTrip = r.PurposeOfTrip,
TransportingStudents = r.TransportStudentsFG,
EmployeeName = e.FirstName + " " + e.LastName,
ApprovalStatus = rst.StatusType,
ThemeColor = r.ThemeColor,
VehicleName = (from v in db.Vehicles
where v.ID == rtv.VehicleID
select v.VehicleName).ToList()
};
EDIT: Updated query, still uncertain how to get back list of Vehicles that have been reserved
var query = from r in db.Reservations
let e = db.Employees.Where(x => r.RequestorID == x.ColleagueID).FirstOrDefault()
let rtv = db.ReservationToVehicle.Where(x => r.ID == x.ReservationID).Select(y => y.VehicleID).ToList()
let rs = db.ReservationStatus.Where(x => r.ID == x.ReservationID).FirstOrDefault()
let rst = db.ReservationStatusTypes.Where(x => rs.ReservationStatusTypeID == x.ID).FirstOrDefault()
select new
{
StartDate = r.StartDate,
EndDate = r.EndDate,
Destination = r.Destination,
PurposeOfTrip = r.PurposeOfTrip,
TransportingStudents = r.TransportStudentsFG,
EmployeeName = e.FirstName + " " + e.LastName,
ApprovalStatus = rst.StatusType,
ThemeColor = r.ThemeColor,
VehicleName = (from v in db.Vehicles
where v.ID == rtv.VehicleID
select v.VehicleName).ToList()
};
rtv.VehicleID does not exist anymore, now rtv comes back with a list of IDs....I need to be able to get into that list to find where v.ID is IN the rtv list
Looks like people already told you this in the comments, but here's the code that ought to work:
var query = from r in db.Reservations
let e = db.Employees.Where(x => r.RequestorID == x.ColleagueID).FirstOrDefault()
let rtv = db.ReservationToVehicle.Where(x => r.ID == x.ReservationID).Select(y => y.VehicleID)
let rs = db.ReservationStatus.Where(x => r.ID == x.ReservationID).FirstOrDefault()
let rst = db.ReservationStatusTypes.Where(x => rs.ReservationStatusTypeID == x.ID).FirstOrDefault()
select new
{
StartDate = r.StartDate,
EndDate = r.EndDate,
Destination = r.Destination,
PurposeOfTrip = r.PurposeOfTrip,
TransportingStudents = r.TransportStudentsFG,
EmployeeName = e.FirstName + " " + e.LastName,
ApprovalStatus = rst.StatusType,
ThemeColor = r.ThemeColor,
VehicleName = (from v in db.Vehicles
where rtv.Contains(v.ID)
select v.VehicleName).ToList()
};
I'd also recommend looking at setting up navigation properties between your entities. Your query could be much simpler, something like this:
var query = from r in db.Reservations
let e = r.Requestor
let rs = r.ReservationStatus
let rst = rs.ReservationStatusType
select new
{
StartDate = r.StartDate,
EndDate = r.EndDate,
Destination = r.Destination,
PurposeOfTrip = r.PurposeOfTrip,
TransportingStudents = r.TransportStudentsFG,
EmployeeName = e.FirstName + " " + e.LastName,
ApprovalStatus = rst.StatusType,
ThemeColor = r.ThemeColor,
VehicleName = r.Vehicles.Select(v => v.VehicleName).ToList()
};
My date filter works just fine when I put it into a separate view, but I am having trouble merging it with the other filters and I am not sure where I am going wrong. All other filters are working. Could you please take a look and let me know what I need to change when I join my query to the others to get it working and merged? Thank you!
Here is what it looks like in a separate Controller, and this works in the view:
public ActionResult DateFilter(FormCollection DatePicker)
{
DateTime start = DateTime.Today;
DateTime end = DateTime.Today;
if (DatePicker.Count > 0)
{
start = DateTime.Parse(DatePicker["startDate"].ToString());
end = DateTime.Parse(DatePicker["endDate"].ToString());
}
var Issue = db.Issue.Where(d => d.DateCreated >= start && d.DateCreated <= end).Select(i => new IssueViewModel
{
Name = i.Name,
Description = i.Description,
DateCreated = i.DateCreated,
DateCompleted = i.DateCompleted,
//ect.
}).ToList();
ViewBag.Issue = Issue;
return View();
}
Here is what it looks like merged with the other filters:
private static IQueryable<Issue> FilterDeviceList(List<Issue> issues, FormCollection DatePicker, string EHP, string IssueKey)
{
var query = issue.AsQueryable();
//COPYING STARTS HERE
DateTime start = DateTime.Today;
DateTime end = DateTime.Today;
if (DatePicker.Count > 0)
{
start = DateTime.Parse(DatePicker["startDate"].ToString());
end = DateTime.Parse(DatePicker["endDate"].ToString());
}
query = query.Where(d => d.DateCreated >= start != null && d.DateCreated <= end != null && d.DateCreated == Convert.ToDateTime(DatePicker));
//COPYING ENDS HERE
if (!string.IsNullOrWhiteSpace(EHP))
query = query.Where(i => i.EHPP != null && i.EHPP == (EHP == "1" ? false : true));
if (!string.IsNullOrWhiteSpace(IssueKey))
query = query.Where(i => i.IssueKey != null && i.IssueKey.Contains(IssueKey));
return query;
}
If anyone needs to see the view or the controller that calls IQueryable, please let me know and I can post it, but I think this should be sufficient. Thank you again! :)
Try this:
private static IQueryable<Issue> FilterDeviceList(List<Issue> issues, FormCollection DatePicker, string EHP, string IssueKey)
{
var query = issues.AsQueryable();
DateTime start,end;
if (DatePicker.Count > 0)
{
start = DateTime.ParseExact(DatePicker["startDate"].ToString(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
end = DateTime.ParseExact(DatePicker["endDate"].ToString(), "MM/dd/yyyy", CultureInfo.InvariantCulture);
}
// assuming start and end date will not be null
if(start != null && end !=null)
{
query = query.Where(d => d.DateCreated >= start && d.DateCreated <= end);
}
if (!string.IsNullOrWhiteSpace(EHP))
query = query.Where(i => i.EHPP != null && i.EHPP == (EHP == "1" ? false : true));
if (!string.IsNullOrWhiteSpace(IssueKey))
query = query.Where(i => i.IssueKey != null && i.IssueKey.Contains(IssueKey));
return query;
}
Happens only in IE (Chrome and Firefox, no issues... go figure)
I have a page where customer's can update their details (name, address,password etc.) and everything is working fine, however if the customer submits the form (which also works fine) and then presses the back button all the customer's information will repopulate the form except for the password field.
My boss would like this to repopulate as well, like it does in Chrome and Firefox, but IE won't do it. I'm hoping it's something simple I've missed but I can't see it. I've tried adjusting the lines where the text fields are populated to match the rest of the form, but that just results in empty fields. Code below.
Page_Load
If TypeOf Session("Customer") Is GPCUser Then
c = CType(Session("Customer"), GPCUser)
Else
Response.Redirect("default.aspx")
End If
If Not Page.IsPostBack Then
If c.CustomerID > 0 Then
'populate the table
lblAccountName.Text = c.AccountName
txtFirstName.Text = c.FirstName
txtLastName.Text = c.LastName
txtEmail.Text = c.Email
txtAddress.Text = c.Address
txtSuburb.Text = c.Suburb
txtCityTown.Text = c.City
txtPostcode.Text = c.PostCode
txtPhone.Text = c.Phone
txtMobile.Text = c.Mobile
'chkNewsletter.checked = c.Newsletter
txtPassword.Attributes.Add("value", c.GeneratedPassword)
txtConfirmPassword.Attributes.Add("value", c.GeneratedPassword)
'txtPassword.Text = c.GeneratedPassword
'txtConfirmPassword.Text = c.GeneratedPassword
Dim subscriptions As ContactSubscriptions = New ContactSubscriptions(c.CustomerID)
chkGenernalNewsletters.Checked = subscriptions.IsGenernalNewsletters
End If
Else
End If
Update Button
If TypeOf Session("Customer") Is GPCUser Then
c = CType(Session("Customer"), GPCUser)
Else
Exit Sub
End If
c.AccountName = lblAccountName.Text
c.FirstName = txtFirstName.Text
c.LastName = txtLastName.Text
c.Email = txtEmail.Text
c.Address = txtAddress.Text
c.Suburb = txtSuburb.Text
c.City = txtCityTown.Text
c.PostCode = txtPostcode.Text
c.Phone = txtPhone.Text
c.Mobile = txtMobile.Text
'c.Newsletter = chkNewsletter.Checked
c.GeneratedPassword = txtPassword.Text
c.CustomerUpdatedRequired = false
'Update password field
txtPassword.Attributes.Add("value", c.GeneratedPassword)
txtConfirmPassword.Attributes.Add("value", c.GeneratedPassword)
GPCUser.AddUpdateCustomer(c)
subscriptions.IsGenernalNewsletters = chkGenernalNewsletters.Checked
subscriptions.Save()
Session("Customer") = c
lblMessage.Text = "Your details have been successfully updated."
pnlUpdateAccount.Visible = False
When I filter records in a database by the date they were place, I want to be able to navigate through the filtered records across multiple pages. Right now, when I try to go to page 2 of the filtered records I receive the error:
String reference not set to an instance of a String.
Parameter name: s `
Also, I notice that the parameters that are passed in the url change. For example:
/PurchaseOrder?searchBy=Date&dateSearchBegin=08%2F15%2F2014&dateSearchEnd=09%2F01%2F2014&dateOrderedBegin=&dateOrderedEnd=&search=
becomes when I click page 2:
/PurchaseOrder?page=2&searchBy=Date
As it currently is written in my code I am using the Request.QueryString method to try to maintain the URL but it doesn't work for dates. Is there a method that is similar to this that I can use to fix this error and achieve my desired result?
Here is my code for the controller and the view:
Controller:
else if (searchBy == "Date")
{
if (dateSearchBegin == "" || dateSearchEnd == "")
{
//string message = "Both date fields are required";
}
else
{
var dtFrom = DateTime.Parse(dateSearchBegin);
var dtTo = DateTime.Parse(dateSearchEnd);
return View(db.PurchaseOrders.Where(x => x.Date >= dtFrom && x.Date <= dtTo).OrderBy(i => i.Date).ToPagedList(page ?? 1, 15));
}
}
else if (searchBy == "dateOrder")
{
if (dateOrderedBegin== ""|| dateOrderedEnd == "")
{
//string message = "Both date fields are required";
}
else
{
var dtFrom = DateTime.Parse(dateOrderedBegin);
var dtTo = DateTime.Parse(dateOrderedEnd);
return View(db.PurchaseOrders.Where(x => x.DateOrdered >= dtFrom && x.DateOrdered <= dtTo).OrderBy(i => i.Date).ToPagedList(page ?? 1, 15));
}
}
View:
#Html.PagedListPager(
Model, page => Url.Action("Index",
new { page, searchBy = Request.QueryString["searchBy"],
search = Request.QueryString["search"],
dtFrom = Request.QueryString["dtFrom"],
dtTo = Request.QueryString["dtTo"] }),
new PagedListRenderOptions() { DisplayPageCountAndCurrentLocation = true,
DisplayItemSliceAndTotal = true })
Your query string contains dateSearchBegin and dateSearchEnd and you are using dtFrom = Request.QueryString["dtFrom"], dtTo = Request.QueryString["dtTo"]
Change that to same keys in Url.Action() dateSearchBegin = Request.QueryString["dateSearchBegin "], dateSearchEnd = Request.QueryString["dateSearchEnd"]
Url.Action() will remove the null value query string args. One suggestion to check the string always use string.IsNullOrEmpty(strVar) do not use strVar == ""
"" != null. You're passing null to DateTime.Parse().
Change dateSearchBegin == "" to string.IsNullOrEmpty(dateSearchBegin) in order to prevent that.
I'm trying to have a form usable for both creating a new record or updating another. Currently it is doing it through the value of a textbox (new or edit). The structure works fine, but for some reason, when it is performing the edit function, it is saving changes to the wrong record. For instance, if I am editing record 1027, when i submit it, it'll update record 1073. Its consistent, it'll always update the same, wrong record. Edit 1000, it'll update 1073; if i update 1081, it'll update 1073, and so on. Is there a way to specify which record it should be editing? yes, the record number is the primary key/id. Heres the code:
Private Sub btnSubmit_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strTable As String
Dim strField As String
Dim ID As Long
Dim newID As Long
strTable = "record_holdData"
Set db = CurrentDb
Set rs = db.OpenRecordset(strTable)
'button has 2 modes
If txtMode.Value = "NEW" Then
With rs
.AddNew
.Fields("PO_no") = txtPONum
.Fields("prodSupervisor") = cboProdSup
.Fields("qaSupervisor") = cboQASup
.Fields("labTech") = cboLabTech
.Fields("flavor") = cboFlavor
.Fields("lineNumber") = cboLineNumber
.Fields("container") = cboContainer
.Fields("package") = cboPackage
.Fields("holdQty") = txtQty
.Fields("productionDate") = txtProdDate
.Fields("dateCode") = txtDatecode
.Fields("component") = cboComponent
.Fields("nonconformance") = cboDiscrepancy
.Fields("foundDuring") = cboFoundAt
.Fields("responsibility") = cboRespCode
.Fields("comments") = txtDescription
.Fields("rootCause") = txtRootCause
.Fields("holdStatus") = 1
.Fields("dateOpened") = Now()
.Update
.Bookmark = .LastModified
newID = !ID
End With
MsgBox ("Hold information saved!")
btnPrintTag.Enabled = True
DoCmd.OpenReport "Holdtag", acViewPreview, , "[ID] = " & newID
DoCmd.Close
ElseIf txtMode.Value = "EDIT" Then
'do editing stuff
With rs
.Edit
.Fields("PO_no") = txtPONum
.Fields("prodSupervisor") = cboProdSup
.Fields("qaSupervisor") = cboQASup
.Fields("labTech") = cboLabTech
.Fields("flavor") = cboFlavor
.Fields("lineNumber") = cboLineNumber
.Fields("container") = cboContainer
.Fields("package") = cboPackage
.Fields("holdQty") = txtQty
.Fields("productionDate") = txtProdDate
.Fields("dateCode") = txtDatecode
.Fields("component") = cboComponent
.Fields("nonconformance") = cboDiscrepancy
.Fields("foundDuring") = cboFoundAt
.Fields("responsibility") = cboRespCode
.Fields("comments") = txtDescription
.Fields("rootCause") = txtRootCause
.Fields("lastEditDate") = Now()
.Update
End With
MsgBox ("Information Updated")
End If
End Sub
Sorry i caught it. Problem was I was basically redefining the recordset each time the subroutine was called. I changed the second block to the following:
ElseIf txtMode.Value = "EDIT" Then
'do editing stuff
Set rs = db.OpenRecordset("SELECT * FROM record_holdData WHERE ID=" & txtID)
With rs
.Edit
.Fields("PO_no") = txtPONum
.Fields("prodSupervisor") = cboProdSup
.Fields("qaSupervisor") = cboQASup
.Fields("labTech") = cboLabTech
.Fields("flavor") = cboFlavor
.Fields("lineNumber") = cboLineNumber
.Fields("container") = cboContainer
.Fields("package") = cboPackage
.Fields("holdQty") = txtQty
.Fields("productionDate") = txtProdDate
.Fields("dateCode") = txtDatecode
.Fields("component") = cboComponent
.Fields("nonconformance") = cboDiscrepancy
.Fields("foundDuring") = cboFoundAt
.Fields("responsibility") = cboRespCode
.Fields("comments") = txtDescription
.Fields("rootCause") = txtRootCause
.Fields("lastEditDate") = Now()
.Update
End With