I have to check/traverse the table data to delete my user from extra entries using foreach loop.
How can I retrieve my table from controller with foreach loop without accessing to any view.
public ActionResult Accept(int id = 0)
{
Proposal_Requests prop_req = db.Proposal_Request.Find(id);
if (prop_req == null)
{
return HttpNotFound();
}
prop_req.Accept_Date = DateTime.Now;
prop_req.Status = "Proposal Accepted";
db.Entry(prop_req).State = EntityState.Modified;
db.SaveChanges();
foreach( var item in Proposal_Requests)
{
if(item.id!= prop_req.id)
{
if(item.std1 == prop_req.std1 || item.std1 = prop_req.std2 || item.std1 == prop_req.std3)
{
item.std1 = " " ;
}
if(item.std2 == prop_req.std1 || item.std2 == prop_req.std2 || item.std2 == prop_req.std3)
{
item.std2 = " " ;
}
if(item.std3 == prop_req.std1 || item.std3 == prop_req.std2 || item.std3 == prop_req.std3)
{
item.std3 = " " ;
}
}
return RedirectToAction("Index", "Proposal_Requests");
}
i want to delete the user id from all the requests when one of its request get accepted or disable all the requests created by that user.
Proposal_Request is the table from which i wanted to remove
Std_Id (student id)
stored in one of its columns.
Proposal_Requests prop_req = db.Proposal_Request.Find(id);
when this id get accepted by the supervisor.
All the students who are enrolled for this proposal get deleted from
the other proposals.
for this I'm using foreach loop so that every row of the table
Proposal_Request get traversed and data matched to delete the student IDs from the other PROPOSALS with the same STD_ID as the accepted on.
Related
I have a table and company_type is one of its columns. Let's say cells look like this:
I want to filter this table by multiple checkboxes and they have a,b,c... values.
#else if
{
if (checkedBoxes.Length == 1)
{
var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) select new Joincco { Companies = check };
}
else if (checkedBoxes.Length == 2)
{
var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) || check.company_type.Contains(checkedBoxes[1]) select new Joincco { Companies = check };
}
else if (checkedBoxes.Length == 3)
{
var deneme = from check in _context.Companies where check.company_type.Contains(checkedBoxes[0]) || check.company_type.Contains(checkedBoxes[1]) || check.company_type.Contains(checkedBoxes[2]) select new Joincco { Companies = check };
}
This code works but is there an easier way?
I am coding daily counter. Database Counter Table is empty. If someone is my first visitor of current day, then I am adding a record to database and i am setting counter=1; After this, when other visitor visit current day, then i am increasing my counter++ and i am updating the record.
So I my records must be like this:
Date:2018-10-01 counter:23
Date:2018-10-02 counter:65
Date:2018-10-03 counter:20
Date:2018-10-04 counter:89
My problem is this: If the site get visitor same time, linq save 2 record for same day. Like this:
Date:2018-10-01 counter:23
Date:2018-10-02 counter:1 //First record: counter=1
Date:2018-10-02 counter:65 //Second record: counter=65
Date:2018-10-03 counter:20
Date:2018-10-04 counter:1 //First record
Date:2018-10-04 counter:89 //second record
Date must be unique. How can I resolve this problem? My code is below. Thanks a lot.
public static int IncreaseCounter_DailySiteVisitors()
{
int counter = 0;
using (var context = new MyProjectEntities())
{
try
{
string format = "dd.MM.yyyy";
DateTime Today = DateTime.Now;
var obj = (from record in context.CounterDailySiteVisitor
where
record.DateRecord != null
&& record.DateRecord.HasValue
&& record.DateRecord.Value.Year == Today.Year
&& record.DateRecord.Value.Month == Today.Month
&& record.DateRecord.Value.Day == Today.Day
select record).FirstOrDefault();
//var obj = context.CounterDailyVisitor.Where(x => x.DateRecord != null && ((DateTime)x.DateRecord).ToString("yyyy.MM.dd") == DateTime.Now.ToString("yyyy.MM.dd")).FirstOrDefault();
if (obj != null)
{
counter = obj.Count ?? 0;
counter++;
obj.Count = counter;
context.SaveChanges();
}
else
{
var newRecordObj = context.CounterDailySiteVisitor.Create();
newRecordObj.Count = 1;
newRecordObj.DateRecord = Today;
context.CounterDailySiteVisitor.Add(newRecordObj);
context.SaveChanges();
}
}
catch (Exception e)
{
}
}
return counter;
}
the chances of this being hit by two thread at the same time is quite low.
but i guess technically it can so you would need to wrap this in a lock
Something like below...
public static int IncreaseCounter_DailySiteVisitors()
{
private readonly object somethingObject = new object();
var context = new MyProjectEntities()
var today = DateTime.Now;
var todaysRecord = context.CounterDailyVisitor
.SingleOrDefault(x => x.DateRecord.Year == Today.Year
&& x.DateRecord.Month == Today.Month
&& x.DateRecord.Day == Today.Day
);
if (todaysRecord != null)
{
//the existing count + 1
todaysRecord.Count = todaysRecord.Count++;
}
else
{
Lock(somethingObject)
{
//recheck
var todaysRecord = context.CounterDailyVisitor
.SingleOrDefault(x => x.DateRecord.Year == Today.Year
&& x.DateRecord.Month == Today.Month
&& x.DateRecord.Day == Today.Day
);
if (todaysRecord != null)
{
//the existing count + 1
todaysRecord.Count = todaysRecord.Count++;
}
else
{
var newRecordObj = new CounterDailyVisitor();
newRecordObj.Count = 1;
newRecordObj.DateRecord = DateTime.Now; //this shouldnt be nullable
context.CounterDailySiteVisitor.Add(newRecordObj);
}
}
}
context.SaveChanges();
}
This is quite a common concurrency problem i.e. race condition. You will either have to Lock around the code that reads and subsequently updates/inserts the value. Or you should call a stored procedure and have all the logic inside the stored proc.
Lock comes with it's own set of issues if you're planning on using a web farm or running multiple instances of this MVC app.
What I am trying to create is when a user select an item, that item will disappear from the list of items. Some items can be submitted once and once it is submitted, the user not be able to submit the same item again. Submitted items will be logged to the database.
The issue I am having is figuring out what is wrong with my logic here as it is breaking and what can I do to improve this?
using (var db = new myDatabase())
{
var itemLists = db.GetAllItem().ToList();
var userSubmittedItems = db.GetAllUserItem("LoginID").ToList();
if (userSubmittedItems.Count > 0)
{
foreach (var submittedItems in userSubmittedItems)
{
foreach (var item in itemLists)
{
int itemID = item.ItemID;
int userItemID = userSubmittedItems.UserItemID;
if (itemID == userItemID && item.OneTime == true)
{
itemLists.Remove(item);
}
}
}
}
you're only removing the items in your collection itemLists, you are not performing anything in the database it self... for that you should, and imagining that your Entity for the Items is called ItemEntity do this:
using (var db = new myDatabase())
{
var itemLists = db.GetAllItem().ToList();
var userSubmittedItems = db.GetAllUserItem("LoginID").ToList();
if (userSubmittedItems.Count > 0)
{
foreach (var submittedItems in userSubmittedItems)
{
foreach (var item in itemLists)
{
int itemID = item.ItemID;
int userItemID = userSubmittedItems.UserItemID;
if (itemID == userItemID && item.OneTime == true)
{
itemLists.Remove(item);
db.ItemEntity.Remove(item); // mark for delete
}
}
}
db.SaveChanges(); // all marked items, if any, will now
// be committed in a db call
}
more on removing records with EF: Delete a single record from Entity Framework?
I'm having weird behavior with my messagebox
here is the code:
private async void rate_Tap(object sender, System.Windows.Input.GestureEventArgs e) {
string id = (string)((Image)sender).Tag;
ignoreSelectionChanged = true;
MobileServiceCollection<rating, rating> items;
IMobileServiceTable<rating> itemTable = App.MobileService.GetTable<rating>();
items = await itemTable
.Where(Table => Table.userid == userId)
.ToCollectionAsync();
if (id != null) {
for (int i = 0; i < items.Count; i++) {
if (items[i].itemid == id) {
MessageBox.Show("You already giving your rating.");
i = items.Count;
return;
}
else {
RadMessageBox.Show(
new string[] { "very accurate", "not accurate" },
"Acurate?",
"Is this information accurate?", closedHandler: (args) => {
int buttonIndex = args.ButtonIndex;
if (buttonIndex == 0) {
clearListBox();
ratingPlus(id);
saveRating(id);
mvm.LoadDetailData();
}
if (buttonIndex == 1) {
clearListBox();
ratingMinus(id);
saveRating(id);
mvm.LoadDetailData();
}
}
);
}
}
}
}
What my code above dord is I trigger rate_Tap() from my listbox that already contains image, and each time I tap it , it's supposed to check with my windows azure server and check if there is an itemid that equals id. Then I will show messagebox saying I already rated it and if there isn't any itemid that equals id then it will execute radmessagebox.
But it's not working that way: when it checks there is an itemid that's equal to id, it shows the messagebox and after that it show the radmessagebox.
Where did I go wrong?
Your "else" block contains the code that you want to execute after you've checked all items - not on each item.
I think you want:
if (items.Any(item => item.itemid == id))
{
MessageBox.Show("You already giving your rating.");
return;
}
RadMessageBox.Show(...);
// etc
Ideally, don't fetch all the previous ratings - change your query so that it includes the ID of the item you're trying to rate. After all, you only want to know whether or not you've already rated it - the rest of the information is pointless, so why fetch it all?
Im getting angry with this error and cannot solve it.
Please, some Jedi master help me.
I'm trying to save trhee Entities: Region, Content and RegionalContent. Region is OK but Regional Content has to be associated with one Content and each Content may have Many RegionalContents(Translations). But I always get a DbUpdateException that has a UpdateException that has a SqlCeException that says something like:
*Impossible to insert a duplicated value with same index. Table name = XBLContents,Constraint name = PK_XBLContents_000000000000001C *
I'm debugging it for some days and could not find the error. Please, note that I'm still a little Padawan.
This is the code that saves the objects in they proper Tables:
Region region;
if (!db.Regions.Any(x => x.ID == Locale))
{
region = new Region { ID = Locale };
db.Regions.Add(region);
db.SaveChanges();
}
else
region = db.Regions.SingleOrDefault(x => x.ID == Locale);
for (int i = start; i < (start + 2); i++)
{
string guid = itens[i].Groups["guid"].Value;
Content c = new Content(guid);
if (!db.Contents.Any(x => x.GUID == guid))
{
c.Type = Type.ToString();
c.PopularInfo(Locale);
db.Contents.Add(c);
}
else
c = db.Contents.SingleOrDefault(x => x.GUID == c.GUID);
RegionalContent regionalcontent;
if (!db.RegionalInfos.Any(x => x.ContentId == guid && x.RegionId == Locale))
{
if (c.HTML == null)
c.PopularInfo(Locale);
regionalcontent = new RegionalContent(c, Locale);
regionalcontent.Region = region;
regionalcontent.Name = HttpUtility.HtmlDecode(itens[i].Groups["name"].Value);
db.RegionalInfos.Add(regionalcontent);
db.Contents.Add(c);
db.SaveChanges();
}
else
regionalcontent = db.RegionalInfos.SingleOrDefault(x => x.ContentId == guid && x.RegionId == Locale);
c.RegionalInfo.Clear();
regionalcontent.Region = region;
c.RegionalInfo.Add(regionalcontent);
Contents.Add(c);
}
You are calling SingleOrDefault when you know 1 already exists. Just use Single.
I would not call SaveChanges to the very end.
Are you sure the GUIDs are unique every time?