I tried to get the item on stacklayout into an SQLite Database, but it just won't carry any data with.
private void MainCategory_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var carier = e.SelectedItem as Item;
var cart_Itemsx = new List<cart_Items>();
cart_Itemsx.Add(new Models.cart_Items { cartid = 1, Id = carier.itid, image = carier.image, name = carier.title, price = carier.price1, quantity = "1", type = "Wash and Iron" });
cart_Itemsx.Add(new Models.cart_Items { cartid = 2, Id = carier.itid, image = carier.image, name = carier.title, price = carier.price2, quantity = "1", type = "Iron Only" });
SubCategory.ItemsSource = cart_Itemsx.ToList();
}
private void SubCategory_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
var dbcontet = e.SelectedItem as cart_Items;
_dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData), "WashPro.db3");
var db = new SQLiteConnection(_dbPath);
db.CreateTable<cart_Items>();
var MaximumPrimaryKey = db.Table<cart_Items>().OrderByDescending(zt => zt.cartid).FirstOrDefault();
var waltani = new cart_Items()
{
cartid = (MaximumPrimaryKey == null ? 1 : MaximumPrimaryKey.cartid + 1),
Id = dbcontet.Id,
image = dbcontet.image,
name = dbcontet.name,
price = dbcontet.price,
quantity = dbcontet.quantity,
type = dbcontet.quantity
};
if (MaximumPrimaryKey == null)
{
db.Insert(waltani);
}
else if (MaximumPrimaryKey != null)
{
var MaximumQuantityKey = db.Table<cart_Items>().Where(m => m.cartid.Equals(dbcontet.cartid) && m.type.Equals(dbcontet.type)).FirstOrDefault();
if (MaximumQuantityKey != null)
{
waltani.price = dbcontet.price = 1;
db.Update(waltani);
}
}
SubCategory.SelectedItem = null;
}
image of the null error I got
I cannot even begin to understand the problem. The way I found around the problem will make my already dirty code way dirtier.
I have the damaging method I tried was using the selected context of the main stack panel to influence the second stack pannel.
I have even made the primary key of the cart_item model null.
Your selected element is null or database table does not contain any elements you are looking for in query, which is more likely because you are trying to initialize your database on SubCategory_ItemSelected. This is wrong approach.
Try to check if database item exist first.
var exist = db.Table<cart_Items>().OrderByDescending(zt => zt.cartid).Any();
if (exist)
{
var MaximumPrimaryKey = db.Table<cart_Items>().OrderByDescending(zt => zt.cartid).FirstOrDefault();
var waltani = new cart_Items()
{
cartid = (MaximumPrimaryKey == null ? 1 : MaximumPrimaryKey.cartid + 1),
Id = dbcontet.Id,
image = dbcontet.image,
name = dbcontet.name,
price = dbcontet.price,
quantity = dbcontet.quantity,
type = dbcontet.quantity
};
}
The problem lies at the last line of code.
SubListview.SelectedItem = null;
This somehow makes the casting not see the e.selected items.
Related
I'm new to CS. I have a ListBox control that I populate from an SQL table called Category. I have a class called Category to match the fields from the DB. I want all my fields available to edit and save. The ListBox has a single field, CategoryDesc. When I select an item in the ListBox I want two textboxes and a check box to update with the CategoryID (string), CategoryDesc (string), and IsActive (bool). I have it working but it seems cumbersome and like I'm taking a lot of steps. I want to learn efficient coding so I'm submitting the following for suggestions on how to clean it up and make it more efficient. Any positive comments will be greatly appreciated.
id ListControl()
{
this.LstCategory.SelectedIndexChanged -= new System.EventHandler(this.LstCategory_SelectedIndexChanged);
DataTable categoryDt = new DataTable();
categoryDt = GetDataTable("GetListCategory");
for (int i = 0; i < categoryDt.Rows.Count; i++)
{
category.Add(new Category()
{
CategoryID = (int)(categoryDt.Rows[i]["CategoryId"]),
CategoryDesc = (string)(categoryDt.Rows[i]["CategoryDesc"]),
ShortCode = (string)(categoryDt.Rows[i]["ShortCode"]),
IsActive = (bool)(categoryDt.Rows[i]["IsActive"]),
CanDelete = (bool)(categoryDt.Rows[i]["CanDelete"])
});
LstCategory.Items.Add((string)(categoryDt.Rows[i]["CategoryDesc"]));
}
this.LstCategory.SelectedIndexChanged += new System.EventHandler(this.LstCategory_SelectedIndexChanged);
}
private void LstCategory_SelectedIndexChanged(object sender, EventArgs e)
{
if (LstCategory.SelectedIndex >= 0)
{
string desc = LstCategory.SelectedItem.ToString();
foreach (var c in category)
{
if (c.CategoryDesc == desc)
{
TxtDescription.Text = c.CategoryDesc;
TxtShortCode.Text = c.ShortCode;
ChkIsActive.Checked = c.IsActive;
}
}
}
else
{
TxtDescription.Text = string.Empty;
TxtShortCode.Text = string.Empty;
ChkIsActive.Checked = false;
}
}
Thanks.
Learn to use Linq
This
categoryDt = GetDataTable("GetListCategory");
for (int i = 0; i < categoryDt.Rows.Count; i++)
{
category.Add(new Category()
{
CategoryID = (int)(categoryDt.Rows[i]["CategoryId"]),
CategoryDesc = (string)(categoryDt.Rows[i]["CategoryDesc"]),
ShortCode = (string)(categoryDt.Rows[i]["ShortCode"]),
IsActive = (bool)(categoryDt.Rows[i]["IsActive"]),
CanDelete = (bool)(categoryDt.Rows[i]["CanDelete"])
});
LstCategory.Items.Add((string)(categoryDt.Rows[i]["CategoryDesc"]));
}
can be replaced by
category = categoryDt.Select(cd => new Category{
CategoryID = (int)(cd["CategoryId"]),
CategoryDesc = (string)(cd[i]["CategoryDesc"]),
ShortCode = (string)(cd["ShortCode"]),
IsActive = (bool)(cd[i]["IsActive"]),
CanDelete = (bool)(cd[i]["CanDelete"])}).ToList();
LstCategory.Items.AddRange(category.Select(c=>c.Desc));
and
string desc = LstCategory.SelectedItem.ToString();
foreach (var c in category)
{
if (c.CategoryDesc == desc)
{
TxtDescription.Text = c.CategoryDesc;
TxtShortCode.Text = c.ShortCode;
ChkIsActive.Checked = c.IsActive;
}
}
can be replaced by
var c = category.FirstOrDefault(c=>c ==desc);
TxtDescription.Text = c.CategoryDesc;
TxtShortCode.Text = c.ShortCode;
ChkIsActive.Checked = c.IsActive;
There might be a few typos here and there becuase I dont have yur data structures to try it out on.
But LINQ is incredibly useful for performing operations on collections.
'select' is used to transform 'project' (its not a filter)
'where' is used to filter
'FindFirstOrDefault' will retunr the first match (or null)
'Count' counts
'ToList' converts to list
The nice thing is you can chain then together
mylist.Where(...).Select(..) etc
I have section in my class that looks like this:
public Details GetTicketById(string #ref)
{
var query = "SELECT * FROM support WHERE ref = #ref";
var args = new Dictionary<string, object>
{
{"#ref", #ref}
};
DataTable dt = ExecuteRead(query, args);
if (dt == null || dt.Rows.Count == 0)
{
return null;
}
var details = new Details
{
#ref = Convert.ToString(dt.Rows[0]["ref"]),
subject = Convert.ToString(dt.Rows[0]["subject"]),
contact_name = Convert.ToString(dt.Rows[0]["contact_name"]),
company_name = Convert.ToString(dt.Rows[0]["company_name"]),
description = Convert.ToString(dt.Rows[0]["description"]),
business_impact = Convert.ToString(dt.Rows[0]["business_impact"]),
severity = Convert.ToString(dt.Rows[0]["severity"])
};
return details;
}
I know that there is a return value when I debug.
My button in my main form looks like this:
private void Button3_Click(object sender, EventArgs e)
{
var getTicket = new ticket();
getTicket.GetTicketById("1235");
ticket.Details td = new ticket.Details();
td.#ref = txtRef.Text;
td.subject = txtSubject.Text;
td.contact_name = txtContact_Name.Text;
td.company_name = txtCompany_Name.Text;
td.description = rtDescription.Text;
td.business_impact = rtBusiness_Impact.Text;
td.severity = txtSeverity.Text;
}
Unfortunately my text boxes do not show the values from my returned data table.
Can you see why?
Your method GetTicketById() return value like you and see with debug. But you don't take this value into variable. Do this:
var details = getTicket.GetTicketById("1235");
In order to set Text property to new value do this:
txtSubject.Text = details.subject
txtContact_Name.Text = details.contact_name
txtCompany_Name.Text = details.company_name
// and so on
This line need to delete
ticket.Details td = new ticket.Details();
I am trying to add Tax Code for SalesItemLineDetail inside Invoice of Quickbooks online api, but it is not setting tax code correctly when checking it in Online Quickbooks.
Here is my C# Code, which I am using to create Line Item
Line = new Intuit.Ipp.Data.Line();
InvoiceLine = new Intuit.Ipp.Data.SalesItemLineDetail();
InvoiceLine.ItemRef = new Intuit.Ipp.Data.ReferenceType
{
Value = GetItem.Id, // this is inventory Item Id
name = GetItem.Name // inventory item name
};
Line.DetailTypeSpecified = true;
Line.DetailType = Intuit.Ipp.Data.LineDetailTypeEnum.SalesItemLineDetail;
Line.Description = inv.Description;
Line.Amount = (inv.Price == null || inv.Price == 0.0) ? (decimal)0.00 : (decimal)inv.Price;
Line.AmountSpecified = true;
InvoiceLine.Qty = decimal.Parse(inv.Quantity.Value.ToString());
InvoiceLine.QtySpecified = true;
InvoiceLine.AnyIntuitObject = (inv.Price == null || inv.Price == 0.0) ? (decimal)0.00 : (decimal)(Math.Round(inv.Price.Value, 2) / inv.Quantity.Value);
InvoiceLine.ItemElementName = Intuit.Ipp.Data.ItemChoiceType.UnitPrice;
// this line is not settings tax code properly
InvoiceLine.TaxCodeRef = new Intuit.Ipp.Data.ReferenceType
{
name = taxName,
Value = TaxId
};
//Line Sales Item Line Detail - ServiceDate
InvoiceLine.ServiceDate = DateTime.Now.Date;
InvoiceLine.ServiceDateSpecified = true;
//Assign Sales Item Line Detail to Line Item
Line.AnyIntuitObject = InvoiceLine;
lines.Add(Line);
Intuit.Ipp.Data.Invoice invoice = new Intuit.Ipp.Data.Invoice();
// SalesOrder is a database table object, and OrderNumber is auto generated number
invoice.DocNumber = SalesOrder.OrderNumber.ToString();
//TxnDate
invoice.TxnDate = DateTime.Now.Date;
invoice.TxnDateSpecified = true;
invoice.CustomerRef = new Intuit.Ipp.Data.ReferenceType
{
Value = CompanyId
};
//convert list to array for Intuit Line
invoice.Line = lines.ToArray();
//TxnTaxDetail
Intuit.Ipp.Data.Line taxLine = new Intuit.Ipp.Data.Line();
Intuit.Ipp.Data.TxnTaxDetail txnTaxDetail = new Intuit.Ipp.Data.TxnTaxDetail();
Intuit.Ipp.Data.TaxLineDetail taxLineDetail = new Intuit.Ipp.Data.TaxLineDetail(); ;
//txnTaxDetail.TotalTaxSpecified = true;
//txnTaxDetail.TotalTax = decimal.Parse("2");
var MainTaxValue = "";
txnTaxDetail.TxnTaxCodeRef = new Intuit.Ipp.Data.ReferenceType()
{
Value = TaxId,
name = SalesOrder.TaxCode.TaxCodeName
};
foreach (var TAXName in TaxObject.TaxRateDetail)
{
if(TAXName.TaxRateRef.name.Contains(SalesOrder.TaxCode.TaxCodeName))
{
MainTaxValue = TAXName.TaxRateRef.value;
}
}
taxLineDetail.TaxRateRef = new Intuit.Ipp.Data.ReferenceType
{
Value = MainTaxValue
};
taxLine.AnyIntuitObject = taxLineDetail;
txnTaxDetail.TaxLine = new Intuit.Ipp.Data.Line[] { taxLine };
//DueDate
invoice.DueDate = SalesOrder.InvoiceDueDate != null ? SalesOrder.InvoiceDueDate.Value : DateTime.Now.AddDays(30).Date;
invoice.DueDateSpecified = true;
invoice.TxnTaxDetail = txnTaxDetail;
I have tried these reference links, but it is not working for me
https://gist.github.com/IntuitDeveloperRelations/6500373
How to export Line items with Tax Code and Value in QBO Canada
https://developer.intuit.com/app/developer/qbo/docs/develop/tutorials/manage-sales-tax-for-non-us-locales
Using above links, I can see we can create Tax Code ref using this line of code, for Each Invoice Line item, but it is not setting value correctly.
InvoiceLine.TaxCodeRef = new Intuit.Ipp.Data.ReferenceType
{
name = taxName,
Value = TaxId
};
But it is not working.
Note: this is non-US company, so I have to specify tax code ref for each Invoice Line.
Edit 1:
Attaching Image of Postman API request, which I sent to Quickbooks for creating invoice.
try by removing the name field I think it might not be required
InvoiceLine.TaxCodeRef = new Intuit.Ipp.Data.ReferenceType()
{
Value = TaxId
};
The main difference between our versions is that I let QB calculate the tax.
I commented out the Tax detail line, and told QB that tax amount wasn't included.
// //TxnTaxDetail
// TxnTaxDetail txnTaxDetail = new TxnTaxDetail();
// Line taxLine = new Line();
// taxLine.DetailType = LineDetailTypeEnum.TaxLineDetail;
// TaxLineDetail taxLineDetail = new TaxLineDetail();
// taxLineDetail.TaxRateRef = stateTaxCode.SalesTaxRateList.TaxRateDetail[0].TaxRateRef;
// txnTaxDetail.TxnTaxCodeRef = new ReferenceType
// {
// name = stateTaxCode.Name,
// Value = stateTaxCode.Id
// };
// if (customer.DefaultTaxCodeRef != null)
// {
// txnTaxDetail.TxnTaxCodeRef = customer.DefaultTaxCodeRef;
// taxLineDetail.TaxRateRef = customer.DefaultTaxCodeRef;
// }
// //Assigning the first Tax Rate in this Tax Code
// taxLine.AnyIntuitObject = taxLineDetail;
// txnTaxDetail.TaxLine = new[] { taxLine };
// invoice.TxnTaxDetail = txnTaxDetail;
invoice.GlobalTaxCalculationSpecified = true;
invoice.GlobalTaxCalculation = GlobalTaxCalculationEnum.TaxExcluded;
Here is my code for doing this, and it definitely works. I can't see a difference between the two though.This calculates VAT in Europe and puts in the Tax Code.
Hope this helps.
var invlines = new List<Line>();
foreach (var lineitem in inv.Lines)
{
//Line
Line invoiceLine = new Line();
//Line Description
invoiceLine.Description = (((lineitem.PublicationName == "N/A" || lineitem.PublicationName == "-") ? "" : lineitem.PublicationName) + " " + lineitem.Description).Trim();
//Line Detail Type
invoiceLine.DetailType = LineDetailTypeEnum.SalesItemLineDetail;
invoiceLine.DetailTypeSpecified = true;
//Line Sales Item Line Detail
SalesItemLineDetail lineSalesItemLineDetail = new SalesItemLineDetail();
//Line Sales Item Line Detail - ItemRef
if (!string.IsNullOrEmpty(lineitem.ItemCode))
{
lineSalesItemLineDetail.ItemRef = new ReferenceType()
{
Value = lineitem.ItemCode
};
}
else if (item != null)
{
lineSalesItemLineDetail.ItemRef = new ReferenceType
{
name = item.Name,
Value = item.Id
};
}
//Line Sales Item Line Detail - UnitPrice
//Line Sales Item Line Detail - Qty
lineSalesItemLineDetail.Qty = 1;
lineSalesItemLineDetail.QtySpecified = true;
if (inv.DiscountPercent > 0)
{
invoiceLine.Amount = (decimal)lineitem.PriceBeforeDiscount;
invoiceLine.AmountSpecified = true;
lineSalesItemLineDetail.ItemElementName = ItemChoiceType.UnitPrice;
}
else
{
invoiceLine.Amount = (decimal)lineitem.Price;
invoiceLine.AmountSpecified = true;
lineSalesItemLineDetail.AnyIntuitObject = lineitem.Price;
lineSalesItemLineDetail.ItemElementName = ItemChoiceType.UnitPrice;
}
//Line Sales Item Line Detail - TaxCodeRef
//For US companies, this can be 'TAX' or 'NON'
var taxref = lineitem.TaxAmount == null || lineitem.TaxAmount == 0 ? nonvatid.ToString() : vatid.ToString();
if (country == "US")
{
taxref = lineitem.TaxAmount == null || lineitem.TaxAmount == 0 ? "NON" : "TAX";
}
lineSalesItemLineDetail.TaxCodeRef = new ReferenceType
{
Value = taxref
};
//Line Sales Item Line Detail - ServiceDate
lineSalesItemLineDetail.ServiceDate = DateTimeService.Now.Date;
lineSalesItemLineDetail.ServiceDateSpecified = true;
//Assign Sales Item Line Detail to Line Item
invoiceLine.AnyIntuitObject = lineSalesItemLineDetail;
//Assign Line Item to Invoice
invlines.Add(invoiceLine);
}
if (inv.DiscountPercent > 0)
{
Line invoiceLine = new Line();
DiscountLineDetail discLine = new DiscountLineDetail();
discLine.PercentBased = true;
discLine.DiscountPercent = (decimal)inv.DiscountPercent;
discLine.DiscountPercentSpecified = true;
discLine.PercentBased = true;
discLine.PercentBasedSpecified = true;
invoiceLine.DetailType = LineDetailTypeEnum.DiscountLineDetail;
invoiceLine.DetailTypeSpecified = true;
invoiceLine.AnyIntuitObject = discLine;
invlines.Add(invoiceLine);
invoice.DiscountRate = (decimal) (inv.DiscountPercent);
invoice.DiscountRateSpecified = true;
}
invoice.Line = invlines.ToArray();
Finally was able to find the correct solution.
My Above code is right, there is no issue in it and #sheavens code is also right.
Actual problem was, I was assigning "default Tax code" to a selected company, which we cannot override while passing tax code reference in Invoice Line item.
To Check if there is any default code for company, navigate to Companies list in quickbooks online website , Select your desired Company from the list, click "Edit", then in the "Tax Info" tab, uncheck "Assign Default tax code" to pass tax code using Invoice Line item.
Hope this helps other developers, with same problem.
public async virtual Task<ActionResult> Store(int? id, int? mainRoadID, int? segmentID, int? cityid, string serverMessage = "")
{
UserTrafficReport_Create model = await Task.WhenAll(GetNewModel, InitialCameras, GetMonitoredWaysListAndPushViewData(mainRoadID, segmentID, cityid));
return View(model);
}
The previous function has an error line ... I can't find the exact error
Error 1358 The best overloaded method match for 'System.Threading.Tasks.Task.WhenAll(params System.Threading.Tasks.Task[])' has some invalid arguments
And those are the three functions used in When All
public async virtual Task<UserTrafficReport_Create> GetNewModel(int? id, int? mainRoadID, int? segmentID, int? cityid)
{
var model = new UserTrafficReport_Create();
var serializer = new JavaScriptSerializer();
if (id != null && id > 0)
{
var report = _repository.FindOne<UserTrafficReport>((int)id);
model.InjectFrom(report);
model.Comments = report.Comments;
if (report.PictureSize.HasValue && report.PictureSize > 0)
model.photo_name = report.ID.ToString(CultureInfo.InvariantCulture);
if (report.RoadID != null)
{
model.RoadID = (int)report.RoadID;
_repository.FindOne<MonitoredWay>((int)report.RoadID);
}
FakeUsers(report.UserID);
model.RoadStatus = report.RoadStatus ?? 99;
if (report.traffic_rating >= 0)
model.traffic_rating = report.traffic_rating;
else
model.traffic_rating = null;
}
else
{
var fakeGroup = _repository.First<UserGroup>(g => g.Name.Contains("Fake"));
var fakeGroupId = 3;
if (fakeGroup != null)
fakeGroupId = fakeGroup.ID;
var dbNamesList = (from userAD in _context.UserAdditionalDatas
join groups in _context.UserMultiGroups on userAD.ID equals groups.UserDataId
join aspUser in _context.AspnetUsers on userAD.ID equals aspUser.ID
where (groups.UserGroupId == fakeGroupId)
select new
{
name = userAD.FirstName,
UserName = aspUser.Username,
userId = aspUser.ID
}).Distinct().ToList();
if (dbNamesList.Any())
{
var randomedList = dbNamesList.Randomize();
var fakeUser = randomedList.FirstOrDefault();
if (fakeUser != null)
{
model.GuestName = fakeUser.name;
model.UserID = fakeUser.userId;
}
}
model.RoadID = segmentID.GetValueOrDefault(-1);
model.traffic_rating = -1;
if (cityid != null)
model.CityId = (int)cityid;
}
return model;
}
.
public async virtual Task InitialCameras(int? cityid,string serverMessage = "")
{
var serializer = new JavaScriptSerializer();
var conditionslist = CreateListFromSingle(
new
{
value = "99",
text = "Not Specified"
}
);
conditionslist.Add(new { value = "4", text = "Accident" });
conditionslist.Add(new { value = "2", text = "Danger" });
conditionslist.Add(new { value = "3", text = "Road Work" });
string outputOfConditions = serializer.Serialize(conditionslist);
ViewData["ConditionsListSerialized"] = outputOfConditions;
var conditionslistitems =
(from condition in conditionslist
select new SelectListItem
{
Value = condition.value,
Text = condition.text
}).ToList();
ViewBag.ConditionsList = conditionslistitems;
ViewData["serverMsg"] = serverMessage;
if (cityid == null || cityid == -1)
{
var cameras = _context.Cameras.Select(c => new
{
value = c.Id,
text = c.Name
}).ToList();
cameras.Insert(0, new { value = (long)0, text = "--Select a Camera --" });
ViewData["Cameras"] = serializer.Serialize(cameras);
}
else
ViewData["Cameras"] = GetCityCameras((int)cityid);
}
..
private async Task GetMonitoredWaysListAndPushViewData(int? roadID = null, int? segmentID = null, int? cityID = null, Guid? reporterId = null)
{
int? id = cityID;
var dbWaysList =
_context.MonitoredWays.Where(
m =>
!m.IsTest &&
(m.RoadID != null && m.Road.AppOrder >= 0 && (id <= 0 || id == null)
? m.Road.AreaID > 0
: m.Road.AreaID == id));
var xWayseSelectList = (from s in dbWaysList
select new
{
OppId = s.OppositeSegment ?? 0,
Value = s.ID,
Title = s.EnglishName,
RoadTitle = s.Road.EnglishName
}).ToList().Distinct();
var repsList = (from s in xWayseSelectList//context.MonitoredWays
select new SelectListItem
{
Value = s.Value.ToString(CultureInfo.InvariantCulture),
Text = string.IsNullOrEmpty(s.RoadTitle) ? s.Title : s.RoadTitle + " (" + s.Title + ")",
Selected = segmentID != null && (segmentID.Value == s.Value)
}).Distinct().ToList();
var serializer = new JavaScriptSerializer();
string wayseSelectListOppId = serializer.Serialize(xWayseSelectList);
string outputOfAreas = serializer.Serialize(repsList);
ViewData["MonitoredWaysListSerialized"] = outputOfAreas;
ViewData["OppositeMonitoredWays"] = wayseSelectListOppId;
ViewBag.MonitoredWaysList = repsList;
var conditionslist = CreateListFromSingle(
new
{
value = "99",
text = "Not Specified"
}
);
conditionslist.Add(new { value = "4", text = "Accident" });
conditionslist.Add(new { value = "2", text = "Danger" });
conditionslist.Add(new { value = "3", text = "Road Work" });
string outputOfConditions = serializer.Serialize(conditionslist);
ViewData["ConditionsListSerialized"] = outputOfConditions;
var conditionslistitems =
(from condition in conditionslist
select new SelectListItem
{
Value = condition.value,
Text = condition.text
}).ToList();
ViewBag.ConditionsList = conditionslistitems;
var ratingslist = CreateListFromSingle(
new
{
value = "0",
text = "V. Bad"
}
);
ratingslist.Add(new { value = "1", text = "Bad" });
ratingslist.Add(new { value = "2", text = "Average" });
ratingslist.Add(new { value = "3", text = "Good" });
ratingslist.Add(new { value = "3", text = "V. Good" });
ViewBag.Ratingslist = ratingslist;
string outputOfRatings = serializer.Serialize(ratingslist);
ViewData["RatingsListSerialized"] = outputOfRatings;
if (roadID != null)
{
var rod = _context.Roads.FirstOrDefault(r => r.ID == roadID);
if (rod != null)
{
cityID = rod.AreaID;
}
}
var dbAreassList = _context.Cities.ToList();
var areas =
(from area in dbAreassList
select new SelectListItem
{
Value = area.ID.ToString(CultureInfo.InvariantCulture),
Text = area.EnglishName,
Selected = cityID != null && (cityID.Value == area.ID)
}).ToList();
ViewBag.AreasList = areas;
var areasList = (from s in _context.Cities
select
new
{
id = s.ID,
text = s.EnglishName
}).ToList();
serializer = new JavaScriptSerializer();
string outputOfAreas1 = serializer.Serialize(areasList);
ViewData["AreasListSerialized"] = outputOfAreas1;
var fakeGroup = _repository.First<UserGroup>(g => g.Name.Contains("Fake"));
var fakeGroupId = 3;
if (fakeGroup != null)
fakeGroupId = fakeGroup.ID;
var dbNamesList = (from userAD in _context.UserAdditionalDatas
join groups in _context.UserMultiGroups on userAD.ID equals groups.UserDataId
join aspUser in _context.AspnetUsers on userAD.ID equals aspUser.ID
where (groups.UserGroupId == fakeGroupId)
select new
{
Text = userAD.FirstName,
Value = userAD.ID,
Selected = false
//Email = aspUser.Username
}).Distinct().ToList();
var namess = dbNamesList.Select(s => new SelectListItem
{
Text = s.Text,
Value = s.Value.ToString(),
Selected = s.Selected
}).ToList();
if (reporterId != null)
{
var member = _repository.FindOne<UserAdditionalData>((Guid)reporterId);
if (member != null)
{
namess.Add(new SelectListItem
{
Text = member.FirstName,
Value = member.ID.ToString(),
Selected = true
});
}
}
var random = new Random();
if (!namess.Any(n => n.Selected))
{
int rand = random.Next(0, namess.Count - 1);
namess[rand].Selected = true;
}
ViewBag.FakeUsersList = namess;
}
A few things wrong with this line:
UserTrafficReport_Create model =
await Task.WhenAll(
GetNewModel,
InitialCameras,
GetMonitoredWaysListAndPushViewData(mainRoadID, segmentID, cityid));
Task.WhenAll takes a collection of Task instances as an argument.
You're passing 2 delegates and a task. You probably meant to actually call the first two methods, so that they'll return a task?
Task.WhenAll returns a Task. Awaiting that task won't return anything, so you won't be able to assign anything to model.
Task<UserTrafficReport_Create> modelFactoryTask = GetNewModel(...);
await Task.WhenAll(
modelFactoryTask ,
InitialCameras(...),
GetMonitoredWaysListAndPushViewData(mainRoadID, segmentID, cityid));
UserTrafficReport_Create model = modelFactoryTask.Result;
I've got the following code and I wish to set the AssignmentID and the ToDoAssignmentID to the same value. Setting AssignmentID to workOrder.AssignmentID works just fine, but setting ToDoAssignmentID to workOrder.AssignmentID results in ToDoAssignmentID being set to 0. Why is that?
workOrder.ClientID = this.Client.ClientID;
workOrder.AssignmentID = this.WorkOrderID;
workOrder.AssignmentNumber = this.GetNextWorkOrderNumber(this.Client);
workOrder.CustomerID = this._CustomerID;
workOrder.DateCreated = this.Created;
workOrder.DatoAvtaltStart = this.AgreedStart == DateTime.MinValue ? new DateTime().MinSDTValue() : this.AgreedStart;
workOrder.DatoAvtaltSlutt = this.AgreedEnd == DateTime.MinValue ? new DateTime().MinSDTValue() : this.AgreedEnd;
workOrder.DateStopped = this.Ended == DateTime.MinValue ? new DateTime().MinSDTValue() : this.Ended;
workOrder.CreatedByEmployeeID = this._CreatedByEmployeeID;
workOrder.ResponsibleEmployeeID = this._ResponsibleEmployeeID;
workOrder.KoordinatorAnsattId = this._CoordinatorEmployeeID;
workOrder.Description = this.Description;
workOrder.Notes = this.Notes;
workOrder.EstimertTimerFra = this.EstimatedHoursFrom;
workOrder.EstimertTimerTil = this.EstimatedHoursTo;
workOrder.EstimatedBillingDate = this.EstimatedBillingDate;
workOrder.Priority = (byte)this.Priority;
workOrder.OBS = this.OBS;
workOrder.CustomerReference = this.CustomersReference;
workOrder.InterntOrdrenr = this.InternalOrderNumber;
workOrder.EksterntOrdrenr = this.ExternalOrderNumber;
workOrder.AssignmentStatusID = this.WorkOrderStatusID;
foreach (var activity in this.Activities)
{
var ProductID = 0;
try
{
ProductID = activity.Product.ProductID;
}
catch (Exception ex)
{
}
workOrder.Activities.Add(new Activity()
{
ActivityID = activity.ActivityID,
ClientID = activity.Client.ClientID,
AssignmentID = workOrder.AssignmentID,
Description = activity.Description,
Notes = activity.Notes,
IsBillable = activity.Billable,
Priority = (byte)activity.Priority,
ActivityTypeID = activity.ActivityType.TypeID,
PerformedByEmployeeID = activity.PerformedByEmployee.EmployeeID,
ProductID = ProductID,
ToDo = activity.IsPlanned,
ToDoAssignmentID = workOrder.AssignmentID,
ToDoCustomerID = workOrder.CustomerID
});
}
workOrderContext.SubmitChanges();
The key is not to think database style, but ORM style.
So instead of setting keys, you assign entities.
so change
ToDoAssignmentID = workOrder.AssignmentID
to (most probable guess of tablenames, check the definition of your entity) the following assignment of entities
ToDoAssignment = workOrder
This will be handled during SubmitChanges as well.