I do have below function which taking more time for execution can someone help to write it properly,its getting while importing data for validation purpose
public void MapReferences(Company company, ISession session, List<Contract> contracts, List<Employee> employees, List<CompanySettingsMap> companies, List<Contact> contacts, IList<ImportEmployeeOrgProfileBatchItem> importedOrgProfileData, int lineNum = 2)
{
var dateConvertor = new DateConverter();
DateTime date;
foreach (var item in importedOrgProfileData)
{
item.CompanyId = company.Id;
item.LineNumber = lineNum;
item.CompanyReference = company?.Reference;
Employee employee = new Employee();
Contact contact = new Contact();
#region " Organisation Validation"
if (string.IsNullOrEmpty(item.Organisation))
{
item.CanContinue = false;
item.ErrorsList.Add("Invalid Organisation");
}
else
{
var allcontact = contacts.Where(x => x.Company.Id == company.Id && x.Reference.ToLower() == item.Organisation.ToLower()).ToList();
if (allcontact.Count > 1)
{
item.ErrorsList.Add("More than one contact found matching with organisation");
}
else
{
contact = allcontact.FirstOrDefault();
}
if (contact != null)
{
item.AgencyId = contact.Id;
item.AgencyReference = contact.Reference;
}
else
{
item.ErrorsList.Add("Contact not found matching with organisation");
item.CanContinue = false;
}
}
#endregion
if(string.IsNullOrEmpty(item.PostCode))
{
item.ErrorsList.Add("Postcode is required");
item.CanContinue = false;
}
#region " Employee Number Validation"
if (string.IsNullOrEmpty(item.EmployeeNumber) || item.EmployeeNumber.Length < 8)
{
item.CanContinue = false;
item.ErrorsList.Add("Invalid Employee Number");
}
else
{
string employeenumber = item.EmployeeNumber.Substring(0, 8);
employee = employees.Where(x => !string.IsNullOrEmpty(x.ExternalReference) && x.ExternalReference.ToLower().StartsWith(employeenumber.ToLower())).FirstOrDefault();
if (employee != null)
{
item.EmployeeId = employee.Id;
item.EmployeeExternalRef = employee.ExternalReference;
if (company.IsPayrollEnabled && employee.PayrollGroup?.Id != null)
{
item.PayrollGroupId = employee.PayrollGroup?.Id;
var payrollGroup = session.Query<PayrollGroup>().Where(x => x.Id == employee.PayrollGroup.Id).FirstOrDefault();
if (payrollGroup != null)
{
item.Payroll = payrollGroup.Description.ToString();
}
}
}
else
{
item.StarterDeclaration = Interfaces.HMRC.StarterDeclaration.OnlyJob;
item.TaxCode = session.Query<PayeSetting>().Single(x => x.Year == GovernmentTaxYearEndDate(DateTime.Today).Year).DefaultTaxCode;
item.EmployeeExternalRef = item.EmployeeNumber;
item.ChangeLogList.Add("Employee " + item.EmployeeNumber + " will be created");
item.CanContinue = true;
}
}
#endregion
#region " Validate Contract(Assignment number) "
if (string.IsNullOrEmpty(item.ContractNumber))
{
item.CanContinue = false;
item.ErrorsList.Add("Invalid Contract Number");
}
else
{
if (dateConvertor.TryConvertFromString(item.ContractStartDateString, out date))
{
item.ContractStartDate = date;
}
if (dateConvertor.TryConvertFromString(item.ContractEndDateString, out date))
{
item.ContractEndDate = date;
}
var contract = contracts.Where(x => !string.IsNullOrEmpty(x.ContractReference) && x.ContractReference.ToLower() == item.ContractNumber.ToLower()).FirstOrDefault();
if (employee == null && contract != null)
{
item.ContractReference = contract.ContractReference;
item.ErrorsList.Add("Contract can not be created because contract with reference " + contract.ContractReference + " is already assigned to other employee");
item.CanContinue = false;
}
else if (contract != null)
{
if (contract.Employee.Id == employee.Id)
{
item.ContractId = contract.Id;
item.ContractReference = contract.ContractReference;
}
else
{
item.ErrorsList.Add("Contract with reference " + contract.ContractReference + " is already assigned to other employee");
item.CanContinue = false;
}
}
else
{
item.ContractReference = item.ContractNumber;
if (contact == null)
{
item.ErrorsList.Add("Contract can not be created automatically because matching contact not found");
item.CanContinue = false;
}
else
{
item.ChangeLogList.Add("Contract " + item.ContractNumber + " will be created");
}
}
}
#endregion
#region " Parse and Assign Dates to date fields "
if (dateConvertor.TryConvertFromString(item.StartDateInPositionString, out date))
{
item.StartDateInPosition = date;
}
if (dateConvertor.TryConvertFromString(item.IncrementalDateString, out date))
{
item.IncrementalDate = date;
}
if (dateConvertor.TryConvertFromString(item.FixedTermEndDateString, out date))
{
item.FixedTermEndDate = date;
}
if (dateConvertor.TryConvertFromString(item.WtrOptOutDateString, out date))
{
item.WtrOptOutDate = date;
}
if (dateConvertor.TryConvertFromString(item.AdjustedServiceDateString, out date))
{
item.AdjustedServiceDate = date;
}
if (dateConvertor.TryConvertFromString(item.NHSEntryDateString, out date))
{
item.NHSEntryDate = date;
}
if (dateConvertor.TryConvertFromString(item.BirthDateString, out date))
{
item.BirthDate = date;
}
if (dateConvertor.TryConvertFromString(item.DateFirstHiredString, out date))
{
item.DateFirstHired = date;
}
else if (!item.EmployeeId.HasValue)
{
item.DateFirstHired = DateTime.Today.Date;
}
#endregion
if (!string.IsNullOrEmpty(item.Title))
{
item.Title = item.Title.Replace(".", "");
}
if (string.IsNullOrEmpty(item.MaritalStatus))
{
item.MaritalStatus = "U";
}
item.Payroll = string.Empty;
lineNum++;
item.Errors = item.ErrorsList.Count > 0 ? String.Join("|", item.ErrorsList.Distinct()) : string.Empty;
item.ChangeLog = item.ChangeLogList.Count > 0 ? String.Join("|", item.ChangeLogList) : string.Empty;
}
}
A good rule of thumb is that if you have copy/pasted code then you should have put it in a function, you could make one function for the date checking then call that, a lot of compilers and translators will then just hold that little bit in memory and repeatedly call it rather than all the lines you have there.
for the sake of readable code, maybe each region should be a separate function?
Shift your temp employee and contact object declarations outside the loop, as it is you have a memory declaration and memory assignation in each loop, moving it outside means you just have the assignation inside the loop (the parser/translator should do this automatically in c# but not always)
Shift everything that is not unique to that particular item to outside of the loop, the taxcode year for example means for every item that hits that else conditional then you are doing a linq query. Incidentally I have noticed great speed and memory gains to be made if you use for loops instead of linq, but they are less readable.
Item.CanContinue isn't used anywhere, maybe each object could handle it's own validation or you could have a static function that checks an object for issues and adds the issues to the list.
one example:
bool chkStringNotNull(string data, ref item, string ErrorMsg)
{
if(String.IsNullOrEmpty(data)) {
item.ErrorsList.Add(ErrorMsg);
return false;
}
return true;
}
Of course you would need to refactor to use item as a ref.
Related
I set a background task on my application using hangfire. But the problem is on the local machine it works fine and the database changes work as well. On the web server, it also executes but can't make any changes to the database.
Here's the initiation code -
public IActionResult CornJobs()
{
CornExpression? corn = _context.Set<CornExpression>().AsNoTracking().FirstOrDefault();
if(corn.PayExpres == null)
{
RecurringJob.RemoveIfExists("Increase Payment");
}
else
{
RecurringJob.AddOrUpdate("Increase Payment", () => _students.IncreasePayment(), corn.PayExpres);
}
if (corn.SMSExpres == null)
{
RecurringJob.RemoveIfExists("Send Alert");
}
else
{
RecurringJob.AddOrUpdate("Send Alert", () => _students.SendDueAlert(), corn.SMSExpres);
}
return View(corn);
}
And here is the interface implementation
public bool IncreasePayment()
{
try
{
var students = _context.Set<Student>().AsNoTracking().Where(x => x.Status == 1 && (x.Batch1 == 1 || x.Batch2 == 1)).ToList();
foreach (var student in students)
{
if(GetMonthDifference(student.DateOfReg, DateTime.Now) == 0)
{
continue;
}
Due due = new()
{
StudentId = student.StudentId,
Recurring = DateTime.Now.ToString("MMMM, yyyy"),
Amount = student.Payment,
PreviousAmount = student.Due,
CurrentAmount = student.Due + student.Payment,
RecurredOn = DateTime.Now
};
student.TotalPayment += due.Amount;
student.Due += due.Amount;
_context.Update(student);
_context.Add(due);
}
_context.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
What mistake have I made here?
Thank you.
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
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 a product ordering page with various product option dropdownlists which are inside a repeater. The "Add To Cart" button is "inactive" until all the options have a selection. Technically, the "Add To Cart" button has two images: a grey one which is used when the user has not selected choices for all options available to a product and an orange one which is used when the user has made a selection from each dropdownlist field.These images are set by the ShowAddToBasket and HideAddToBasket functions.
The dropdownlist fields are connected in that a selection from the first field will determine a selection for the second and sometimes third field. If the second field is NOT pre-set by the first field, then the second field will determine the value for the third field. The first dropdownlist field is never disabled, but the other two can be based on what options have been selected.
There are a few products that have all 3 of their dropdownlists pre-set to certain choices upon entering their page. This means they are all disabled and cannot be changed by the user. Regardless of whether the user enters in a quantity or not, the "Add To Cart" button NEVER activates. I cannot for the life of me figure out how to change it so that, in these rare circumstances, the "Add to Cart" button is automatically set to active once a quantity has been entered. The dropdownlists still have options selected in these pages--it's just that they are fixed and cannot be changed by the user.
Is there anyway I can get the selected value or selected index of these dropdownlist fields upon entering a product page? I want to be able to check to see if they are truly "empty" or if they do have selections made so I can set the "Add to Cart" button accordingly.
Any help would be great because I'm really stuck on this one! :(
Here is the code behind (I removed a lot of the unimportant functions):
protected void Page_Init(object sender, System.EventArgs e)
{
string MyPath = HttpContext.Current.Request.Url.AbsolutePath;
MyPath = MyPath.ToLower();
_Basket = AbleContext.Current.User.Basket;
RedirQryStr = "";
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
if (Request.QueryString["LineID"] != null)
{
int LineID = Convert.ToInt32(Request.QueryString["LineID"].ToString());
int itemIndex = _Basket.Items.IndexOf(LineID);
BasketItem item = _Basket.Items[itemIndex];
OldWeight.Text = item.Weight.ToString();
OldQty.Text = item.Quantity.ToString();
OldPrice.Text = item.Price.ToString();
}
int UnitMeasure = 0;
SetBaidCustoms(ref UnitMeasure);
GetPrefinishNote();
_ProductId = AlwaysConvert.ToInt(Request.QueryString["ProductId"]);
_Product = ProductDataSource.Load(_ProductId);
if (_Product != null)
{
//GetPercentage();
int _PieceCount = 0;
double _SurchargePercent = 0;
CheckoutHelper.GetItemSurcargePercent(_Product, ref _PieceCount, ref _SurchargePercent);
SurchargePieceCount.Text = _PieceCount.ToString();
SurchargePercent.Text = _SurchargePercent.ToString();
//add weight
BaseWeight.Value = _Product.Weight.ToString();
//DISABLE PURCHASE CONTROLS BY DEFAULT
AddToBasketButton.Visible = false;
rowQuantity.Visible = false;
//HANDLE SKU ROW
trSku.Visible = (ShowSku && (_Product.Sku != string.Empty));
if (trSku.Visible)
{
Sku.Text = _Product.Sku;
}
//HANDLE PART/MODEL NUMBER ROW
trPartNumber.Visible = (ShowPartNumber && (_Product.ModelNumber != string.Empty));
if (trPartNumber.Visible)
{
PartNumber.Text = _Product.ModelNumber;
}
//HANDLE REGPRICE ROW
if (ShowMSRP)
{
decimal msrpWithVAT = TaxHelper.GetShopPrice(_Product.MSRP, _Product.TaxCode != null ? _Product.TaxCode.Id : 0);
if (msrpWithVAT > 0)
{
trRegPrice.Visible = true;
RegPrice.Text = msrpWithVAT.LSCurrencyFormat("ulc");
}
else trRegPrice.Visible = false;
}
else trRegPrice.Visible = false;
// HANDLE PRICES VISIBILITY
if (ShowPrice)
{
if (!_Product.UseVariablePrice)
{
trBasePrice.Visible = true;
BasePrice.Text = _Product.Price.ToString("F2") + BairdLookUp.UnitOfMeasure(UnitMeasure);
trOurPrice.Visible = true;
trVariablePrice.Visible = false;
}
else
{
trOurPrice.Visible = false;
trVariablePrice.Visible = true;
VariablePrice.Text = _Product.Price.ToString("F2");
string varPriceText = string.Empty;
Currency userCurrency = AbleContext.Current.User.UserCurrency;
decimal userLocalMinimum = userCurrency.ConvertFromBase(_Product.MinimumPrice.HasValue ? _Product.MinimumPrice.Value : 0);
decimal userLocalMaximum = userCurrency.ConvertFromBase(_Product.MaximumPrice.HasValue ? _Product.MaximumPrice.Value : 0);
if (userLocalMinimum > 0)
{
if (userLocalMaximum > 0)
{
varPriceText = string.Format("(between {0} and {1})", userLocalMinimum.LSCurrencyFormat("ulcf"), userLocalMaximum.LSCurrencyFormat("ulcf"));
}
else
{
varPriceText = string.Format("(at least {0})", userLocalMinimum.LSCurrencyFormat("ulcf"));
}
}
else if (userLocalMaximum > 0)
{
varPriceText = string.Format("({0} maximum)", userLocalMaximum.LSCurrencyFormat("ulcf"));
}
phVariablePrice.Controls.Add(new LiteralControl(varPriceText));
}
}
//UPDATE QUANTITY LIMITS
if ((_Product.MinQuantity > 0) && (_Product.MaxQuantity > 0))
{
string format = " (min {0}, max {1})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity, _Product.MaxQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
QuantityX.MaxValue = _Product.MaxQuantity;
}
else if (_Product.MinQuantity > 0)
{
string format = " (min {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MinQuantity)));
QuantityX.MinValue = _Product.MinQuantity;
}
else if (_Product.MaxQuantity > 0)
{
string format = " (max {0})";
QuantityLimitsPanel.Controls.Add(new LiteralControl(string.Format(format, _Product.MaxQuantity)));
QuantityX.MaxValue = _Product.MaxQuantity;
}
if (QuantityX.MinValue > 0) QuantityX.Text = QuantityX.MinValue.ToString();
AddToWishlistButton.Visible = AbleContext.Current.StoreMode == StoreMode.Standard;
}
else
{
this.Controls.Clear();
}
if (!Page.IsPostBack)
{
if (Request.QueryString["Action"] != null)
{
if (Request.QueryString["Action"].ToString().ToLower() == "edit")
{
SetEdit();
}
}
}
}
protected void Page_Load(object sender, System.EventArgs e)
{
if (_Product != null)
{
if (ViewState["OptionDropDownIds"] != null)
{
_OptionDropDownIds = (Hashtable)ViewState["OptionDropDownIds"];
}
else
{
_OptionDropDownIds = new Hashtable();
}
if (ViewState["OptionPickerIds"] != null)
{
_OptionPickerIds = (Hashtable)ViewState["OptionPickerIds"];
}
else
{
_OptionPickerIds = new Hashtable();
}
_SelectedOptionChoices = GetSelectedOptionChoices();
OptionsList.DataSource = GetProductOptions();
OptionsList.DataBind();
//set all to the first value
foreach (RepeaterItem rptItem in OptionsList.Items)
{
DropDownList OptionChoices = (DropDownList)rptItem.FindControl("OptionChoices");
OptionChoices.SelectedIndex = 1;
}
TemplatesList.DataSource = GetProductTemplateFields();
TemplatesList.DataBind();
KitsList.DataSource = GetProductKitComponents();
KitsList.DataBind();
}
if (!Page.IsPostBack)
{
if (_Product.MSRP != 0)
{
salePrice.Visible = true;
RetailPrice.Text = _Product.MSRP.ToString("$0.00");
}
DataSet ds = new DataSet();
DataTable ResultTable = ds.Tables.Add("CatTable");
ResultTable.Columns.Add("OptionID", Type.GetType("System.String"));
ResultTable.Columns.Add("OptionName", Type.GetType("System.String"));
ResultTable.Columns.Add("LinkHeader", Type.GetType("System.String"));
foreach (ProductOption PhOpt in _Product.ProductOptions)
{
string MasterList = GetProductMaster(_ProductId, PhOpt.OptionId);
string PerFootVal = "";
string LinkHeader = "";
string DefaultOption = "no";
string PrefinishMin = "0";
bool VisPlaceholder = true;
ProductDisplayHelper.TestForVariantDependency(ref SlaveHide, _ProductId, PhOpt, ref PrefinishMin, ref PerFootVal, ref LinkHeader, ref VisPlaceholder, ref HasDefault, ref DefaultOption);
if (PrefinishMin == "")
PrefinishMin = "0";
DataRow dr = ResultTable.NewRow();
dr["OptionID"] = PhOpt.OptionId + ":" + MasterList + ":" + PerFootVal + ":" + DefaultOption + ":" + PrefinishMin;
Option _Option = OptionDataSource.Load(PhOpt.OptionId);
dr["OptionName"] = _Option.Name;
dr["LinkHeader"] = LinkHeader;
ResultTable.Rows.Add(dr);
}
//Bind the data to the Repeater
ItemOptions.DataSource = ds;
ItemOptions.DataMember = "CatTable";
ItemOptions.DataBind();
//determine if buttons show
if (ItemOptions.Items.Count == 0)
{
ShowAddToBasket(1);
resetBtn.Visible = true;
}
else
{
HideAddToBasket(3);
}
if (Request.QueryString["Action"] != null)
{
ShowAddToBasket(1);
SetDllAssociation(false);
}
ShowHideDrops();
}
}
private void HideAddToBasket(int Location)
{
AddToBasketButton.Visible = false;
AddToWishlistButton.Visible = false;
resetBtn.Visible = false;
if (Request.QueryString["Action"] == null)
{
SelectAll.Visible = true;
WishGray.Visible = true;
if (Request.QueryString["OrderItemID"] == null)
BasketGray.Visible = true;
else
UpdateButton.Visible = false;
}
else
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
}
}
private void ShowAddToBasket(int place)
{
resetBtn.Visible = true;
if (Request.QueryString["Action"] != null)
{
UpdateButton.Visible = true;
NewButtons.Visible = false;
}
else
{
UpdateButton.Visible = false;
SelectAll.Visible = false;
WishGray.Visible = false;
BasketGray.Visible = false;
if (Request.QueryString["OrderItemID"] == null)
{
AddToBasketButton.Visible = true;
resetBtn.Visible = true;
AddToWishlistButton.Visible = true;
}
else
{
UpdateButton.Visible = true;
AddToBasketButton.Visible = false;
}
}
if ((_Product.MinQuantity == 1) & (_Product.MaxQuantity == 1))
{
AddToWishlistButton.Visible = false;
BasketGray.Visible = false;
resetBtn.Visible = true;
}
}
protected void OptionChoices_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
if (ddl != null)
{
//bb5.Text = "ddl !=null<br />"; works
List<OptionChoiceItem> ds = (List<OptionChoiceItem>)ddl.DataSource;
if (ds != null && ds.Count > 0)
{
int optionId = ds[0].OptionId;
Option opt = OptionDataSource.Load(optionId);
ShowAddToBasket(4);
OptionChoiceItem oci = ds.FirstOrDefault<OptionChoiceItem>(c => c.Selected);
if (oci != null)
{
ListItem item = ddl.Items.FindByValue(oci.ChoiceId.ToString());
if (item != null)
{
ddl.ClearSelection();
item.Selected = true;
}
}
if (opt != null && !opt.ShowThumbnails)
{
if (!_OptionDropDownIds.Contains(optionId))
{
// bb5.Text = "!_OptionDropDownIds.Contains(optionId)<br />"; works
_OptionDropDownIds.Add(optionId, ddl.UniqueID);
}
if (_SelectedOptionChoices.ContainsKey(optionId))
{
ListItem selectedItem = ddl.Items.FindByValue(_SelectedOptionChoices[optionId].ToString());
if (selectedItem != null)
{
ddl.ClearSelection();
selectedItem.Selected = true;
//bb5.Text = "true: " + selectedItem.Selected.ToString()+"<br />"; doesn't work
}
}
StringBuilder imageScript = new StringBuilder();
imageScript.Append("<script type=\"text/javascript\">\n");
imageScript.Append(" var " + ddl.ClientID + "_Images = {};\n");
foreach (OptionChoice choice in opt.Choices)
{
if (!string.IsNullOrEmpty(choice.ImageUrl))
{
imageScript.Append(" " + ddl.ClientID + "_Images[" + choice.Id.ToString() + "] = '" + this.Page.ResolveUrl(choice.ImageUrl) + "';\n");
}
}
imageScript.Append("</script>\n");
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager != null)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), ddl.ClientID, imageScript.ToString(), false);
}
else
{
Page.ClientScript.RegisterClientScriptBlock(this.GetType(), ddl.ClientID, imageScript.ToString());
}
}
}
ddl.Attributes.Add("onChange", "OptionSelectionChanged('" + ddl.ClientID + "');");
}
}
protected Dictionary<int, int> GetSelectedOptionChoices()
{
HttpRequest request = HttpContext.Current.Request;
Dictionary<int, int> selectedChoices = new Dictionary<int, int>();
if (Page.IsPostBack)
{
foreach (int key in _OptionDropDownIds.Keys)
{
string value = (string)_OptionDropDownIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} DropDownId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
foreach (int key in _OptionPickerIds.Keys)
{
string value = (string)_OptionPickerIds[key];
Trace.Write(string.Format("Checking For - OptionId:{0} PickerId:{1}", key, value));
string selectedChoice = request.Form[value];
if (!string.IsNullOrEmpty(selectedChoice))
{
int choiceId = AlwaysConvert.ToInt(selectedChoice);
if (choiceId != 0)
{
Trace.Write(string.Format("Found Selected Choice : {0} - {1}", key, choiceId));
selectedChoices.Add(key, choiceId);
}
}
}
}
else
{
string optionList = Request.QueryString["Options"];
ShowAddToBasket(2);
if (!string.IsNullOrEmpty(optionList))
{
string[] optionChoices = optionList.Split(',');
if (optionChoices != null)
{
foreach (string optionChoice in optionChoices)
{
OptionChoice choice = OptionChoiceDataSource.Load(AlwaysConvert.ToInt(optionChoice));
if (choice != null)
{
_SelectedOptionChoices.Add(choice.OptionId, choice.Id);
}
}
return _SelectedOptionChoices;
}
}
}
return selectedChoices;
}
protected void SetDDLs(object sender, EventArgs e)
{
bool isRandom = false;
if (LengthDDL.Text != "")
isRandom = true;
SetDllAssociation(isRandom);
}
Try accessing the values in the Page_Load event. I don't believe the values are bound yet in Page_Init
I searched for the solutions in some of the questions that resembles this problem, but couldn solve it, so kindly provide a clear idea about how to solve this.
Order orderDetails= createOrder();
long voucherId = (long)orderDetails.Vouchers.FirstOrDefault().Number; // exception here..
and the createOrder function returns the orderDetails of type Order.
Vouchers is my voucher table,
Number is a column's name in the voucher table.
I have no idea, why how to solve this exception. Any idea about it ?
PART I :
*EDIT:*
private Order createOrder()
{
IList<OfferInfo> offerInformation = new List<OfferInfo>();
OfferInfo offer = new OfferInfo()
{
OfferId = 2,
Message = "test msg",
CreatedDate = System.DateTime.Now,
Gender = "male",
ReceiverName = "john",
ReceiverEmail = "ebenezar#gmail.com"
};
offerInformation.Add(offer);
Order order = new Order();
order.Id = 721;
order.Amount = 1000;
order.CreatedDate = System.DateTime.Now;
order.User = userDetails;
return BLOrder.CreateOrder(order, offerInformation);
}
NOTE:
It inturns call the CreateOrder from the BLOrder which returns the retrieved data in Order type. ( if var is of Order type and is returned, it will have something like, var.xxx="some value" , var.yyy="some value"..)
PART II:
public static Order CreateOrder(Order order, IList<OfferInfo> offerList)
{
order = CreateNewOrder(order, offerList);
Intreat.MSMQ.MSMQHelper.AddOffers(order, offerList);
return order;
}
private static Order CreateNewOrder(Order order, IList<OfferInfo> offerList, bool updateUser = true)
{
try
{
if (updateUser)
{
VerifyUserDetails(order.User);
senderUserId = BLUser.UpdateUser(order.User);
order.User = null;
Logger.WriteLog("Sender user added/updated successfully. UserID:" + senderUserId.ToString());
}
else
senderUserId = order.UserId;
if (order.Company != null)
order.CompanyId = BLCompany.UpdateCompany(order.Company).Id;
VerifyOrderDetails(order, offerList);
using (IntreatEntities intreat = new IntreatEntities())
{
foreach (OfferInfo offer in offerList)
{
orderAmt = (double)((from po in intreat.PartnerOffers
where po.Id == offer.OfferId
select po.Price * offer.Quantity).ToList()).Sum();
order.Amount += orderAmt;
if (offer.IsPos)
tableOrderAmt += orderAmt;
}
if ((tableOrderAmt > 0) && (order.TipPercentage != null) && (order.TipPercentage.Value) > 0)
{
double tipAmt = (tableOrderAmt * (order.TipPercentage.Value * .01));
order.TipAmount = Math.Round(tipAmt);
order.Amount = (double)(order.Amount + order.TipAmount);
}
order.CreatedDate = DateTime.Now;
order.UserId = (Guid)senderUserId;
Logger.WriteLog(string.Format(CultureInfo.InvariantCulture, "order.TableNumber:{0}", order.TableNumber == null ? "(empty)" : order.TableNumber.ToString()));
intreat.Orders.AddObject(order);
intreat.SaveChanges();
Logger.WriteLog("Order added successfully. OrderId:" + order.Id.ToString(CultureInfo.InvariantCulture));
}
return order;
}
catch (Exception ex)
{
Logger.WriteLog(ex);
throw;
}
}
incorporate this line of code order.Vouchers.Load(); as done below and try
private static Order CreateNewOrder(Order order, IList<OfferInfo> offerList, bool updateUser = true)
{
try
{
Guid? senderUserId = null;
/// Process user first so that, the user details are stored even if there is any error in other areas
///
if (updateUser)
{
VerifyUserDetails(order.User);
/// Create/update sending user.
///
senderUserId = BLUser.UpdateUser(order.User);
order.User = null;
Logger.WriteLog("Sender user added/updated successfully. UserID:" + senderUserId.ToString());
}
else
senderUserId = order.UserId;
/// Add company details before processing the order, so that the company details are stored if there is any error in other areas.
///
if (order.Company != null)
order.CompanyId = BLCompany.UpdateCompany(order.Company).Id;
/// Verify and process order
///
VerifyOrderDetails(order, offerList);
using (IntreatEntities intreat = new IntreatEntities())
{
/// Find total amount for the order
double orderAmt = 0;
double tableOrderAmt = 0;
order.Amount = 0;
foreach (OfferInfo offer in offerList)
{
orderAmt = (double)((from po in intreat.PartnerOffers
where po.Id == offer.OfferId
select po.Price * offer.Quantity).ToList()).Sum();
order.Amount += orderAmt;
//If isPos, consider for tip calculation
if (offer.IsPos)
tableOrderAmt += orderAmt;
}
//check if tip amount has to be calculated, by checking for the tableorderAmt
if ((tableOrderAmt > 0) && (order.TipPercentage != null) && (order.TipPercentage.Value) > 0)
{
double tipAmt = (tableOrderAmt * (order.TipPercentage.Value * .01));
order.TipAmount = Math.Round(tipAmt);
order.Amount = (double)(order.Amount + order.TipAmount);
}
order.CreatedDate = DateTime.Now;
order.UserId = (Guid)senderUserId;
Logger.WriteLog(string.Format(CultureInfo.InvariantCulture, "order.TableNumber:{0}", order.TableNumber == null ? "(empty)" : order.TableNumber.ToString()));
/// Create and save order in db
///
intreat.Orders.AddObject(order);
intreat.SaveChanges();
order.Vouchers.Load();
Logger.WriteLog("Order added successfully. OrderId:" + order.Id.ToString(CultureInfo.InvariantCulture));
}
return order;
}
catch (Exception ex)
{
Logger.WriteLog(ex);
throw;
}
}