how can i add collection to another collection? I am returnging one collection _lastOpenedArticles and if that collection has less than 3 articles i need to add articles from allUsersArticles. However i keep getting article from collection _lastOpenedArticles 3 times. Can you help please.
async Task ShowLastListenedAsync(List<Article> allUserArticles)
{
var downloadedArticles = LangUpDataSaverLoader.DeserializeAllOptimizationData();
if (_lastOpenedArticles != null && _lastOpenedArticles.Count > 0)
{
foreach (var article in _lastOpenedArticles.Take(3))
{
var filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var newCell = new ArticleDetailData()
{
Author = article.Author,
Id = article.Id,
};
if (downloadedArticles.DownloadedArticles.Any(m => m.Id == article.Id))
{
newCell.BackgroundImage = article.Id.ArticleImageFile();
}
else
{
newCell.BackgroundImage = filename;
}
var sec = article.Category;
if (sec == null)
{
newCell.Section = " ";
}
else
{
newCell.Section = article.Category;
}
LastThreeArticles.Add(newCell);
if (_lastOpenedArticles.Count < 3)
{
foreach (var art in allUserArticles.Take(3))
{
filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var cell = new ArticleDetailData()
{
Author = article.Author,
BackgroundImage = filename,
Id = article.Id,
};
sec = article.Category;
if (sec == null)
{
cell.Section = " ";
}
else
{
cell.Section = article.Category;
}
LastThreeArticles.Add(cell);
}
await FillAnonymousArticles(allUserArticles);
}
}
}
else
{
await FillAnonymousArticles(allUserArticles);
}
}
Instead of checking the count in the for loop, I'd propose to move the check whether you already have 3 articles after the loop. So you avoid to get the articles 3 times (once for each run of the loop):
async Task ShowLastListenedAsync(List<Article> allUserArticles)
{
var downloadedArticles = LangUpDataSaverLoader.DeserializeAllOptimizationData();
if (_lastOpenedArticles != null && _lastOpenedArticles.Count > 0)
{
foreach (var article in _lastOpenedArticles.Take(3))
{
var filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var newCell = new ArticleDetailData()
{
Author = article.Author,
Id = article.Id,
};
if (downloadedArticles.DownloadedArticles.Any(m => m.Id == article.Id))
{
newCell.BackgroundImage = article.Id.ArticleImageFile();
}
else
{
newCell.BackgroundImage = filename;
}
var sec = article.Category;
if (sec == null)
{
newCell.Section = " ";
}
else
{
newCell.Section = article.Category;
}
LastThreeArticles.Add(newCell);
}
// Move this check out of the for loop
if (_lastOpenedArticles.Count < 3)
{
foreach (var art in allUserArticles.Take(3))
{
filename = string.Format(SharedConstants.ArticleImageUrl, SharedConstants.ApiBaseUri, article.Id);
var cell = new ArticleDetailData()
{
Author = article.Author,
BackgroundImage = filename,
Id = article.Id,
};
sec = article.Category;
if (sec == null)
{
cell.Section = " ";
}
else
{
cell.Section = article.Category;
}
LastThreeArticles.Add(cell);
}
await FillAnonymousArticles(allUserArticles);
}
}
else
{
await FillAnonymousArticles(allUserArticles);
}
}
In addition, you could use Linq to create a union of the lists. This will result in much shorter code, for example:
_lastOpenedArticles
.Union(allUserArticles)
.Take(3)
.Select(x => ConvertToCell(x)) // You need this method that converts the articles to a cell
.ToArray(); // If you need a list, you can also use ToList()
_lastOpenedArticles.AddRange(allUserArticles)
_lastOpenedArticles.Concat(allUserArticles)
the last one returns IEnumerable<T> and first one is void. Take one that suits you better
Related
I am trying to add a listing group tree in google ads api V10 but it is returning internal error. Here is my code:
public GoogleAwApi.AdGroupCriterionReturnValue MutateProductPartitionsForAdGroupGA(GoogleAwApi.AdGroupCriterionOperation[] operations, long clientId)
{
var result = new GoogleAwApi.AdGroupCriterionReturnValue();
AdGroupCriterionServiceClient service = this.AdGroupCriterionServiceGA;
List<AdGroupCriterionOperation> operationsGA = new List<AdGroupCriterionOperation>();
List<GoogleAwApi.AdGroupCriterion> results = new List<GoogleAwApi.AdGroupCriterion>();
List<GoogleAwApi.ApiError> partialFailures = new List<GoogleAwApi.ApiError>();
foreach (var item in operations)
{
try
{
var operand = (GoogleAwApi.BiddableAdGroupCriterion)item.operand;
// Start creating the criteron...
GoogleAdsResources.AdGroupCriterion adGroupCriterion = new GoogleAdsResources.AdGroupCriterion()
{
// The resource name the criterion will be created with. This will define the ID
// for the ad group criterion.
AdGroup = ResourceNames.AdGroup(clientId, item.operand.adGroupId),
//ResourceName = ResourceNames.AdGroupCriterion(clientId, item.operand.adGroupId, item.operand.criterion.id),
Status = Google.Ads.GoogleAds.V10.Enums.AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Enabled
};
switch (operand.userStatus)
{
case GoogleAwApi.UserStatus.ENABLED:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Enabled;
break;
case GoogleAwApi.UserStatus.REMOVED:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Removed;
break;
case GoogleAwApi.UserStatus.PAUSED:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Paused;
break;
default:
adGroupCriterion.Status = AdGroupCriterionStatusEnum.Types.AdGroupCriterionStatus.Enabled;
break;
}
string cType = item.operand.criterion.GetType().Name;
if (operand.biddingStrategyConfiguration != null)
{
var bids = operand.biddingStrategyConfiguration.bids;
var thidBid = (GoogleAwApi.CpcBid)bids[0];
adGroupCriterion.CpcBidMicros = thidBid.bid.microAmount;
adGroupCriterion.EffectiveCpcBidSource = Google.Ads.GoogleAds.V10.Enums.BiddingSourceEnum.Types.BiddingSource.AdGroup;
}
adGroupCriterion.ApprovalStatus = APIHelper.MapApprovalStatus(operand.approvalStatus);
adGroupCriterion.BidModifier = operand.bidModifier;
var criterion = (GoogleAwApi.ProductPartition)item.operand.criterion;
adGroupCriterion.CriterionId = criterion.id;
ListingGroupTypeEnum.Types.ListingGroupType lType = ListingGroupTypeEnum.Types.ListingGroupType.Unknown;
if (criterion.partitionType == GoogleAwApi.ProductPartitionType.SUBDIVISION)
{
lType = ListingGroupTypeEnum.Types.ListingGroupType.Subdivision;
adGroupCriterion.ResourceName = ResourceNames.AdGroupCriterion(clientId, item.operand.adGroupId, item.operand.criterion.id);
}
if (criterion.partitionType == GoogleAwApi.ProductPartitionType.UNIT)
{
lType = ListingGroupTypeEnum.Types.ListingGroupType.Unit;
}
var casevalue = (GoogleAwApi.ProductDimension)criterion.caseValue;
var lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Unknown;
var cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Unknown;
var lValue = "";
Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo listingDimensionInfo = null;
if (casevalue != null)
{
//Get listing Group Info
switch (casevalue.ProductDimensionType)
{
case "ProductType":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
if (caseValueItems[0].Contains("PRODUCT_TYPE_L1"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level1;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L2"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level2;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L3"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level3;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L4"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level4;
if (caseValueItems[0].Contains("PRODUCT_TYPE_L5"))
lLevel = Google.Ads.GoogleAds.V10.Enums.ProductTypeLevelEnum.Types.ProductTypeLevel.Level5;
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
if (String.IsNullOrEmpty(lValue))
{
//isEverythingElse
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductType = new Google.Ads.GoogleAds.V10.Common.ProductTypeInfo
{ Level = lLevel }
};
}
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductType = new Google.Ads.GoogleAds.V10.Common.ProductTypeInfo
{ Level = lLevel, Value = lValue }
};
}
}
break;
case "Brand":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
if (caseValueItems.Length == 1)
{
string[] lValueItems = caseValueItems[0].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
//isEverythingElse
if (String.IsNullOrEmpty(lValue))
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductBrand = new Google.Ads.GoogleAds.V10.Common.ProductBrandInfo()
};
}
else
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductBrand = new Google.Ads.GoogleAds.V10.Common.ProductBrandInfo
{ Value = lValue }
};
}
}
break;
case "Custom":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_0"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index0;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_1"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index1;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_2"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index2;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_3"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index3;
if (caseValueItems[0].Contains("CUSTOM_ATTRIBUTE_4"))
cIndex = Google.Ads.GoogleAds.V10.Enums.ProductCustomAttributeIndexEnum.Types.ProductCustomAttributeIndex.Index4;
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
if (String.IsNullOrEmpty(lValue))
{
//isEverythingElse
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductCustomAttribute = new Google.Ads.GoogleAds.V10.Common.ProductCustomAttributeInfo
{ Index = cIndex }
};
}
else
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductCustomAttribute = new Google.Ads.GoogleAds.V10.Common.ProductCustomAttributeInfo
{ Index = cIndex, Value = lValue }
};
}
}
}
break;
case "OfferId":
if (casevalue != null)
{
string[] caseValueItems = casevalue.ToString().Split(',');
if (caseValueItems.Length == 2)
{
string[] lValueItems = caseValueItems[1].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
if (caseValueItems.Length == 1)
{
string[] lValueItems = caseValueItems[0].Split(':');
if (lValueItems.Length == 2)
lValue = lValueItems[1].Trim();
}
if (String.IsNullOrEmpty(lValue))
{
//isEverythingElse
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductItemId = new Google.Ads.GoogleAds.V10.Common.ProductItemIdInfo()
};
}
else
{
listingDimensionInfo = new Google.Ads.GoogleAds.V10.Common.ListingDimensionInfo()
{
ProductItemId = new Google.Ads.GoogleAds.V10.Common.ProductItemIdInfo
{ Value = lValue }
};
}
}
break;
default:
break;
}
}
Google.Ads.GoogleAds.V10.Common.ListingGroupInfo ListingGroup = new Google.Ads.GoogleAds.V10.Common.ListingGroupInfo()
{
Type = lType, // SubDivision OR Unit
CaseValue = listingDimensionInfo
};
if (criterion.id != -1)
ListingGroup.ParentAdGroupCriterion = ResourceNames.AdGroupCriterion(clientId, item.operand.adGroupId, criterion.parentCriterionId);
adGroupCriterion.ListingGroup = ListingGroup;
adGroupCriterion.CriterionId = criterion.id;
if (item.#operator == GoogleAwApi.Operator.ADD) { operationsGA.Add(new AdGroupCriterionOperation() { Create = adGroupCriterion }); }
if (item.#operator == GoogleAwApi.Operator.REMOVE) { operationsGA.Add(new AdGroupCriterionOperation() { Remove = adGroupCriterion.ResourceName }); }
if (item.#operator == GoogleAwApi.Operator.SET) { operationsGA.Add(new AdGroupCriterionOperation() { Update = adGroupCriterion }); }
}
catch (Exception ex)
{
string except = ex.Message;
}
}
try
{
// Issues a mutate request to process Ads.
MutateAdGroupCriteriaResponse retVal = service.MutateAdGroupCriteria(
new MutateAdGroupCriteriaRequest()
{
CustomerId = clientId.ToString(),
Operations = { operationsGA },
PartialFailure = true,
ValidateOnly = false,
ResponseContentType = ResponseContentTypeEnum.Types.ResponseContentType.MutableResource // required to bring back a complete mutated object to report on.
});
if (retVal.Results[0].AdGroupCriterion != null)
results.Add(APIHelper.MapAdGroupCriterion(retVal.Results[0].AdGroupCriterion));
if (retVal.PartialFailureError != null)
{
var ApiError = new ApiErrorGA();
ApiError.errorString = retVal.PartialFailureError.Message;
ApiError.ApiErrorType = retVal.PartialFailureError.GetType().ToString();
partialFailures.Add(ApiError);
}
}
catch (GoogleAdsException ex)
{
string except = ex.Message;
}
result.ListReturnValueType = "AdGroupAdService";
result.value = results.ToArray();
result.partialFailureErrors = partialFailures.ToArray();
return result;
}
I need the code to be able to create new trees and also replace existing one.
I have tried a lot of different possibilities of trying to get it to work but all return internal error which really doesn't give me any pointers on what the issue is. Any help will be appreciated.
I have an excel file with about 21000 rows . I imported it into a temp Table in my database.
Now I want to do some conversions on my data and then put them into my main table.
When I do SaveChanges() inside a foreach I got the following error:
Microsoft.Data.SqlClient.SqlException: 'New transaction is not allowed because there are other threads running in the session
When I use it after the foreach no error occurs and the table has just 4 records inserted instead of all 21000 records that I expected.
public ActionResult FeedTempdataToMainDB()
{
var L = new Leave();
// var leaves = new List<Leave>();
foreach (var item in db.TempLeaves)
{
L.Pcode = Int32.Parse(item.Cod);
var z = int.Parse(item.LT) - 1;
if (z == 0) L.LT = Leave.LeaveType.Saati;
else L.LT = Leave.LeaveType.Roozane;
var o = int.Parse(item.DLT) - 1;
if (o == 0) L.DLT = Leave.DLType.Estehghaghi;
if (o == 1) L.DLT = Leave.DLType.Estelaji;
else L.DLT = Leave.DLType.Bihoghoogh;
L.LeaveDayStart = item.LeaveDayStart.Old6digToMiladi();
L.LeaveDayEnd = item.LeaveDayEnd.Old6digToMiladi();
L.LeaveTimeStart = StringToHour(item.LeaveTimeStart);
L.LeaveTimeEnd = StringToHour(item.LeaveTimeEnd);
L.LeaveDays = int.Parse(item.LeaveDays);
L.LeaveMinuts = SaatiLengh(item.LeaveMinuts);
L.RegDate = StringToHour(item.RegTime);
L.RegDate = item.RegDate.Old6digToMiladi().Date;
L.RegistrarCode = Int32.Parse(item.RegistrarCode);
L.HijriYear = L.LeaveDayStart.GetHijriYear();
var t = IsOk(item.RegTime);
if (L.DLT == 0 && t == false || L.LT == 0)
{
L.Calculate = false;
L.IsActive = false;
}
else { L.Calculate = true; L.IsActive = true; }
db.Leaves.Add(L);
db.SaveChangesAsync();
}
//db.SaveChanges();
return RedirectToAction("index");
You have a bug in your code. You declared and created L outside of the loop. Each time you add the same L , only with different data. In the end you have list of the same data that was created during the last foreach loop cicle.
try this:
foreach (var item in db.TempLeaves)
{
var z = int.Parse(item.LT) - 1;
var L = new Leave{
Pcode = Int32.Parse(item.Cod),
LeaveTimeStart = StringToHour(item.LeaveTimeStart),
LeaveTimeEnd = StringToHour(item.LeaveTimeEnd),
LeaveDays = int.Parse(item.LeaveDays),
LT = z == 0? Leave.LeaveType.Saati : Leave.LeaveType.Roozane
};
db.Leaves.Add(L);
}
or this
var leaves= new List<Leave>();
foreach (var item in db.TempLeaves)
{
var z = int.Parse(item.LT) - 1;
var L = new Leave{
Pcode = Int32.Parse(item.Cod),
LeaveTimeStart = StringToHour(item.LeaveTimeStart),
LeaveTimeEnd = StringToHour(item.LeaveTimeEnd),
LeaveDays = int.Parse(item.LeaveDays),
LT = z == 0? Leave.LeaveType.Saati : Leave.LeaveType.Roozane
};
leaves.Add(L);
}
if(leaves.Count>0)
{
db.Leaves.AddRange(leaves);
db.SaveChanges();
}
if you want to use async save you have to make async action at first.
The raison every time that foreach execute the savechnages there is a thread that your not note controlling. Since entity framework is managing the savechanges function. You have to execute your savechnages after the foreach or use async function.
here an example for the async:
private static async Task<Student> GetStudent()
{
Student student = null;
using (var context = new SchoolDBEntities())
{
Console.WriteLine("Start GetStudent...");
student = await (context.Students.Where(s => s.StudentID == 1).FirstOrDefaultAsync<Student>());
Console.WriteLine("Finished GetStudent...");
}
return student;
}
*This Code finally worked:
public ActionResult FeedTempdataToMainDB()
{
var leaves = new List<Leave>();
foreach (var item in db.TempLeaves)
{
var L = new Leave();
L.Pcode = Int32.Parse(item.Cod);
var z = int.Parse(item.LT) - 1;
if (z == 0) L.LT = Leave.LeaveType.Saati;
else L.LT = Leave.LeaveType.Roozane;
var o = int.Parse(item.DLT);
if (o == 0) L.DLT = Leave.DLType.Estehghaghi;
if (o == 1) L.DLT = Leave.DLType.Estelaji;
else L.DLT = Leave.DLType.Bihoghoogh;
L.LeaveDayStart = item.LeaveDayStart.Old6digToMiladi();
L.LeaveDayEnd = item.LeaveDayEnd.Old6digToMiladi();
L.LeaveTimeStart = StringToHour(item.LeaveTimeStart);
L.LeaveTimeEnd = StringToHour(item.LeaveTimeEnd);
L.LeaveDays = int.Parse(item.LeaveDays);
L.LeaveMinuts = SaatiLengh(item.LeaveMinuts);
L.RegDate = StringToHour(item.RegTime);
L.RegDate = item.RegDate.Old6digToMiladi().Date;
L.RegistrarCode = Int32.Parse(item.RegistrarCode);
L.HijriYear = L.LeaveDayStart.GetHijriYear();
var t = IsOk(item.RegTime);
if (L.DLT == 0 && t == false || L.LT == 0 && t == false)
{
L.Calculate = false;
L.IsActive = false;
}
else { L.Calculate = true; L.IsActive = true; }
leaves.Add(L);
}
if (leaves.Count > 0)
{
db.Leaves.AddRange(leaves);
db.SaveChanges();
}
return RedirectToAction("index");
}
I am getting error for this line me.Id = int.Parse(cols[0]); to do entry in my text file.
I am parsing my string but it is giving blank string "" when I am debugging the file.
Can anyone help me regarding solving the file
public static List<MatchupEntryModel> ConvertToMatchupEntryModels(this List<string> lines)
{
//id = 0, TeamCompeting = 1, Score = 2, ParentCompeting = 3
List<MatchupEntryModel> output = new List<MatchupEntryModel>();
foreach(string line in lines)
{
string[] cols = line.Split(',');
MatchupEntryModel me = new MatchupEntryModel();
me.Id = int.Parse(cols[0]);
if(cols[1].Length == 0)
{
me.TeamCompeting = null;
}
else
{
me.TeamCompeting = LookupTeamById(int.Parse(cols[1]));
}
me.Score = double.Parse(cols[2]);
int parentId = 0;
if(int.TryParse(cols[3], out parentId))
{
me.ParentMatchup = LookupMatchupById(parentId);
}
else
{
me.ParentMatchup = null;
}
output.Add(me);
}
return output;
//List<PersonModel> output = new List<PersonModel>();
//foreach (string line in lines)
//{
// string[] cols = line.Split(',');
// PersonModel p = new PersonModel();
// p.Id = int.Parse(cols[0]);
// p.FirstName = cols[1];
// p.LastName = cols[2];
// p.EmailAddress = cols[3];
// p.CellphoneNumber = cols[4];
// output.Add(p);
//}
//return output;
}
I am also sending the my save entry to file function which is used for saving the file.
public static void SaveEntryToFile(this MatchupEntryModel entry, string matchupEntryFile)
{
List<MatchupEntryModel> entries =
GlobalConfig.MatchupEntryFile.FullFilePath().LoadFile().ConvertToMatchupEntryModels();
int currentId = 1;
if(entries.Count > 0)
{
currentId = entries.OrderByDescending(x => x.Id).First().Id + 1;
}
entry.Id = currentId;
entries.Add(entry);
List<string> lines = new List<string>();
//id = 0, TeamCompeting = 1, Score = 2, ParentCompeting = 3
foreach (MatchupEntryModel e in entries)
{
string parent = "";
if(e.ParentMatchup != null)
{
parent = e.ParentMatchup.Id.ToString();
}
string teamCompeting = "";
if(e.TeamCompeting != null)
{
teamCompeting = e.TeamCompeting.Id.ToString();
}
lines.Add($"{ e.Id }, { teamCompeting }, { e.Score }, { parent }");
}
File.WriteAllLines(GlobalConfig.MatchupEntryFile.FullFilePath(), lines);
//foreach (TeamModel t in models)
//{
// lines.Add($"{ t.Id }, { t.TeamName }, { ConvertPeopleListToString(t.TeamMembers)}");
//}
//File.WriteAllLines(fileName.FullFilePath(), lines);
}
Use TryParse instead of Parse. It will return 0 instead of throwing exception.
I want to update table but its not working
Here is the code:
public Boolean setSectionTickSign(decimal Trans_ID, decimal Job_ID, string SectioName)
{
string sectionames = "";
Transcription_Master Trans_Mastr = new Transcription_Master();
try
{
var Trans_Master = (from Trans_Mast in r2ge.Transcription_Master where Trans_Mast.Transcription_Id == Trans_ID && Trans_Mast.Entity_Id == Job_ID select new
{
Trans_Mast.Completed_Trans_Sections
}).Distinct().ToList();
var complt_trans = Trans_Master.AsEnumerable().Where(dr = > dr.Completed_Trans_Sections != null).ToList();
if (complt_trans.Count == 0)
{
if (sectionames == "")
{
Trans_Mastr.Completed_Trans_Sections = SectioName;
}
}
else
{
Trans_Mastr.Completed_Trans_Sections = "," + SectioName;
}
int sc = r2ge.SaveChanges();
}
}
It does not update database..what is wrong in it??
You should change this piece of code to such a thing:
var Trans_Master = (from Trans_Mast in r2ge.Transcription_Master
where Trans_Mast.Transcription_Id == Trans_ID
&& Trans_Mast.Entity_Id == Job_ID
select Trans_Mast).Distinct().ToList();
In this case Your variable Trans_Maser will be refference to object from collection, so changes will be done on object taken from EF context, and SaveChanges will give correct result.
Solved my own problem Transcription_Master Trans_Mastr = new Transcription_Master(); no need to create new object
public Boolean setSectionTickSign(decimal Trans_ID, decimal Job_ID, string SectioName)
{
string sectionames = "";
try
{
var empQuery = r2ge.Transcription_Master.Where(l => l.Transcription_Id == Trans_ID && l.Entity_Id == Job_ID).ToList();
foreach (Transcription_Master Trans_Mastrr in empQuery)
{
if (empQuery.Count == 0)
{
if (sectionames == "")
{
Trans_Mastrr.Completed_Trans_Sections = SectioName;
}
}
else
{
Trans_Mastrr.Completed_Trans_Sections = Trans_Mastrr.Completed_Trans_Sections + "," + SectioName;
}
}
int sc = r2ge.SaveChanges();
}
I have the following method it creates a generic list recursively. I'm getting some interesting results. The property CurrentAllocation is always overwritten with the last value.
Here is the line in question.
courierTypeRegion.CurrentAllocation = remaining;
courierTypeRegionOutput.Add(courierTypeRegion);
Here is the whole method
public static List<CourierTypeRegion> FindClosest2(decimal quantity, decimal remaining, ICollection<CourierTypeRegion> courierTypeRegions, List<CourierTypeRegion> courierTypeRegionOutput)
{
var processed = false;
var courierOrderByDesc = courierTypeRegions.OrderByDescending(x => x.CourierType.PalletsPerTrailer).ToList();
var courierCount = courierOrderByDesc.Count();
var courierCurrent = 0;
foreach (var courierTypeRegion in courierOrderByDesc)
{
if (remaining >= courierTypeRegion.CourierType.PalletsPerTrailer && !processed)
{
courierTypeRegion.CurrentAllocation = courierTypeRegion.CourierType.PalletsPerTrailer;
courierTypeRegionOutput.Add(courierTypeRegion);
processed = true;
}
if (!processed)
{
if (courierOrderByDesc[courierCurrent + 1] != null)
{
if (remaining > courierOrderByDesc[courierCurrent + 1].CourierType.PalletsPerTrailer)
{
courierTypeRegion.CurrentAllocation = remaining;
courierTypeRegionOutput.Add(courierTypeRegion);
processed = true;
}
}
}
courierCurrent++;
}
if (!processed)
{
if (courierTypeRegions.Count > 0)
{
var courierTypeRegionRemaining =
courierTypeRegions.Where(x => x.CourierType.PalletsPerTrailer >= remaining).OrderByDescending(
x => x.CourierType.PalletsPerTrailer).SingleOrDefault();
if (courierTypeRegionRemaining != null) courierTypeRegionOutput.Add(courierTypeRegionRemaining);
processed = true;
}
}
var currentRemaining = quantity - courierTypeRegionOutput.Sum(x => x.CourierType.PalletsPerTrailer);
if (currentRemaining > 0)
{
FindClosest(quantity, currentRemaining, courierTypeRegions, courierTypeRegionOutput);
}
return courierTypeRegionOutput;
}
'CourierTypeRegion' is one instance that lives for the entire foreach loop, it is not instantiated and destroyed every loop iteration. You are repeatedly adding the same instance to your list. You end up with a list where all items reference the the last value in the loop.
You need to change your foreach loop as follows:
foreach (var courierTypeRegion in courierOrderByDesc)
{
var courierRegionCopy = courierTypeRegion;
if (remaining >= courierTypeRegion.CourierType.PalletsPerTrailer && !processed)
{
courierRegionCopy.CurrentAllocation = courierTypeRegion.CourierType.PalletsPerTrailer;
courierTypeRegionOutput.Add(courierRegionCopy);
processed = true;
}
if (!processed)
{
if (courierOrderByDesc[courierCurrent + 1] != null)
{
if (remaining > courierOrderByDesc[courierCurrent + 1].CourierType.PalletsPerTrailer)
{
courierRegionCopy.CurrentAllocation = remaining;
courierTypeRegionOutput.Add(courierRegionCopy);
processed = true;
}
}
}
courierCurrent++;
}