public async Task <IActionResult> Index(PostModel postModel) { //Set status to search posts. int statusId = 1; if (postModel != null && !string.IsNullOrEmpty(postModel.SelectedStatus)) { statusId = Convert.ToInt32(postModel.SelectedStatus); } PostModel model = new PostModel(); //Setting url of the api. var url = new Uri(apiRoutes.BaseUrl + string.Format(apiRoutes.GetPostByStatusUrl, statusId)); List <Post> publishedPost = new List <Post>(); using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync(url)) { //Call api method. string apiResponse = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { //Get object from the result publishedPost = JsonConvert.DeserializeObject <List <Post> >(apiResponse); if (publishedPost.IsAny()) { //Add related user to the post, to show in the UI foreach (Post post in publishedPost) { var user = await userManager.FindByIdAsync(post.AuthorId.ToString()); if (user != null) { post.UserName = user.UserName; post.EmailUser = user.Email; } } } } else { ViewBag.Result = MessageValues.ServerError; ModelState.AddModelError(string.Empty, apiResponse); } } } if (publishedPost.IsAny()) { model.Posts = publishedPost; } return(View(model)); }
void updateLastTouchedInformation(List <LastTouchedDetails> details) { if (details.IsAny()) { contactRepository.UpdateLastTouchedInformation(details, AppModules.ContactNotes, null); } }
private static string GetEmailContent(AccountBasicInfo accountInfo, List <WebVisitReport> relatedVisits, GetDropdownValueResponse lifeCycleStages, string ownerName) { string emailContent = string.Empty; if (relatedVisits.IsAny()) { emailContent = "<div style='font-family:verdana;font-size:12px'> Account Executive: <strong>" + ownerName + "</strong><br>" + emailContent + "</div><br>"; relatedVisits.ForEach(c => { TimeZoneInfo tzInfo = TimeZoneInfo.FindSystemTimeZoneById(accountInfo.TimeZone); c.VisitedOn = TimeZoneInfo.ConvertTimeFromUtc(c.VisitedOn, tzInfo); c.LifecycleStage = lifeCycleStages.DropdownValues.DropdownValuesList.Where(d => d.DropdownValueID == c.LifecycleStageId).Select(d => d.DropdownValue).FirstOrDefault() ?? ""; c.Phone = FormatPhoneNumber(c.Phone); }); emailContent += relatedVisits.GetTable(p => p.FirstName , p => p.LastName , p => p.Email , p => p.Phone , p => p.Zip , p => p.LifecycleStage , p => p.VisitedOn , p => p.PageViews , p => p.Duration , p => p.Page1 , p => p.Page2 , p => p.Page3 , p => p.Source , p => p.LeadScore , p => p.Location); } return(emailContent); }
/// <summary> /// sql跟踪 /// </summary> /// <param name="profiler"></param> private void WriteLog(MiniProfiler profiler) { if (profiler?.Root != null) { var root = profiler.Root; if (root.HasChildren) { root.Children.ForEach(chil => { if (chil.CustomTimings?.Count > 0) { foreach (var customTiming in chil.CustomTimings) { var all_sql = new List <string>(); var err_sql = new List <string>(); var all_log = new List <string>(); int i = 1; customTiming.Value?.ForEach(value => { if (value.ExecuteType != "OpenAsync") { all_sql.Add(value.CommandString.Replace("\r", "").Replace("\n", "").Replace("\t", "") .Replace(" ", " ").Replace(" ", " ") .Replace(" ", " ").Replace(" ", " ") .Replace(" ", " ")); } if (value.Errored) { err_sql.Add(value.CommandString.Replace("\r", "").Replace("\n", "").Replace("\t", "") .Replace(" ", " ").Replace(" ", " ") .Replace(" ", " ").Replace(" ", " ") .Replace(" ", " ")); } var log = $@"【{customTiming.Key}{i++}】{value.CommandString.Replace("\r", "").Replace("\n", "").Replace("\t", "") .Replace(" ", " ").Replace(" ", " ") .Replace(" ", " ").Replace(" ", " ") .Replace(" ", " ")} Execute time :{value.DurationMilliseconds} ms,Start offset :{value.StartMilliseconds} ms,Errored :{value.Errored}"; all_log.Add(log); }); if (err_sql.IsAny()) { Logger.Error(new Exception("sql异常"), "异常sql:\r\n" + err_sql.StringJoin("\r\n"), sql: err_sql.StringJoin("\r\n\r\n")); } Logger.Debug(all_log.StringJoin("\r\n"), sql: all_sql.StringJoin("\r\n\r\n")); } } }); } } }
private void SearchPath(Dweller target) { if (target && pursuit) { movePath = Map.AStar(Coords, target.Coords); } else { if (!movePath.IsAny()) { movePath = PatrolPath; } } }
public Banner GetBanner(int?menuId = null, int status = 1, List <int> position = null, bool isCache = true) { var sbKey = new StringBuilder(); sbKey.AppendFormat(CacheKey, "GetBanner"); var expression = PredicateBuilder.True <Banner>(); expression = expression.And(x => x.Status == status); sbKey.AppendFormat("-{0}", status); if (menuId != null) { sbKey.AppendFormat("-{0}", menuId); expression = expression.And(x => x.MenuId == menuId); } if (position.IsAny()) { var i = 0; foreach (var pos in position) { sbKey.AppendFormat("-{0}", pos); expression = i == 0 ? expression.And(x => x.PageBanner.Position == pos) : expression.Or(x => x.PageBanner.Position == pos); i++; } } //Where from date and to date expression = expression.And(x => (!x.FromDate.HasValue || DbFunctions.DiffHours(x.ToDate.Value, DateTimeOffset.UtcNow.Offset) >= 0) && (!x.ToDate.HasValue || DbFunctions.DiffHours(x.ToDate.Value, DateTimeOffset.UtcNow.Offset) <= 0)); if (!isCache) { return(_bannerRepository.Get(expression)); } var key = sbKey.ToString(); var banner = _cacheManager.Get <Banner>(key); if (banner == null) { banner = _bannerRepository.Get(expression); _cacheManager.Put(key, banner); } return(banner); }
private void SearchTxtBox_TextChanged(object sender, TextChangedEventArgs e) { TextBox searchTxtBox = sender as TextBox; if (searchTxtBox.Text != "" || searchTxtBox.Text != null) { if (_grFilteredContacts == null) { contactsDataGrid.ItemsSource = _contacts.Where(c => c.LastName.ToLower().Contains(searchTxtBox.Text.ToLower())); } else if (_grFilteredContacts != null && _grFilteredContacts.IsAny()) { contactsDataGrid.ItemsSource = _grFilteredContacts.Where(c => c.LastName.ToLower().Contains(searchTxtBox.Text.ToLower())); } } }
private static void CreateSectionFourExample001(PdfBuilder pdfBuilder, MarginInfo parentPadding) { const string columnWidths = "350 100"; var descriptions = new List <string[]> { new [] { "[ex code 01]", "ex foo", "cm" }, new [] { "[ex code 02]", "ex foo", "mm" } }; if (descriptions.IsAny()) { // Create an inner table var sectionFourExampleTable = pdfBuilder.CreateInnerTable( columnWidths, keepContentTogether: true); // Create inner table row var projectFundedServicesRow = pdfBuilder.CreateInnerTableRow(sectionFourExampleTable, parentPadding); // Create Header Cell Titles pdfBuilder.CreateInnerTableItemCells( projectFundedServicesRow, cellContent: new[] { new DisplayCell { Content = "Example Code", IsHeader = true }, new DisplayCell { Content = "Example Measure", IsHeader = true } }); // create a row for each description foreach (var item in descriptions) { pdfBuilder.CreateInnerTableItemCells( sectionFourExampleTable.Rows.Add(), cellContent: new[] { new DisplayCell { Content = item[0] + " - " + item[1] }, new DisplayCell { Content = item[2] } }); } } pdfBuilder.BlankRow(); }
private List <string> getDomains(List <string> emails) { List <string> domains = new List <string>(); if (emails != null && emails.IsAny()) { emails.Each(e => { string[] strArray = e.Split('@'); if (strArray != null && strArray.Any() && strArray.Length > 1) { domains.Add(strArray[1]); } }); domains = domains.Distinct().ToList(); } return(domains); }
private string GetEmailContent(Account accountInfo, List <WebVisitReport> relatedVisits, GetDropdownValueResponse lifeCycleStages, string ownerName) { var emailContent = string.Empty; if (!relatedVisits.IsAny()) { return(emailContent); } emailContent = "<div style='font-family:verdana;font-size:12px'> " + "Account Executive: <strong>" + ownerName + "</strong>" + "<br>" + emailContent + "</div><br>"; relatedVisits.ForEach(x => { x.VisitedOn = x.VisitedOn.ToTimezone(accountInfo.TimeZone); x.LifecycleStage = lifeCycleStages .DropdownValues .DropdownValuesList .Where(d => d.DropdownValueID == x.LifecycleStageId) .Select(d => d.DropdownValue) .FirstOrDefault() ?? ""; }); emailContent += relatedVisits.GetTable( p => p.FirstName, p => p.LastName, p => p.Email, p => p.Phone, p => p.Zip, p => p.LifecycleStage, p => p.VisitedOn, p => p.PageViews, p => p.Duration, p => p.Page1, p => p.Page2, p => p.Page3, p => p.Source, p => p.LeadScore, p => p.Location); return(emailContent); }
/// <summary> /// Finds the by contact. /// </summary> /// <param name="ContactID">The contact identifier.</param> /// <param name="userId">The user identifier.</param> /// <returns></returns> public IEnumerable <Opportunity> FindByContact(int ContactID, int userId) { var db = ObjectContextFactory.Create(); var ownerSql = userId != 0 ? "AND O.Owner = @UserId" : ""; var opportunitySql = @"SELECT O.* FROM Opportunities(NOLOCK) O INNER JOIN OpportunityContactMap(NOLOCK) OCM ON OCM.OpportunityID = O.OpportunityID WHERE OCM.ContactID = @ContactId " + ownerSql; List <OpportunitiesDb> oppDb = db.Get <OpportunitiesDb>(opportunitySql, new { contactId = ContactID, UserId = userId }).ToList(); if (oppDb.IsAny()) { foreach (var item in oppDb) { Opportunity opportunity = new Opportunity(); Mapper.Map <OpportunitiesDb, Opportunity>(item, opportunity); yield return(opportunity); } } }
public static void ListToExcel <T>(List <T> query) { using (ExcelPackage excelPackage = new ExcelPackage()) { string dataFormat = DateTime.Now.ToString("dd-MM-yyyy"); ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add(dataFormat); PropertyInfo[] properties = typeof(T).GetProperties(); for (int i = 0; i < properties.Length; i++) { object[] customAttributes = properties[i].GetCustomAttributes(typeof(DisplayAttribute), true); if (customAttributes.Length == 0) { worksheet.Cells[1, i + 1].Value = properties[i].Name; } else { string name = ((DisplayAttribute)customAttributes[0]).Name; worksheet.Cells[1, i + 1].Value = name; } } if (query.IsAny()) { worksheet.Cells["A2"].LoadFromCollection(query); } using (ExcelRange item = worksheet.Cells["A1:BZ1"]) { item.Style.Font.Bold = true; item.Style.Fill.PatternType = ExcelFillStyle.Solid; item.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); item.Style.Font.Color.SetColor(Color.White); } HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; HttpContext.Current.Response.AddHeader("content-disposition", string.Concat("attachment; filename=", dataFormat, ".xlsx")); HttpContext.Current.Response.BinaryWrite(excelPackage.GetAsByteArray()); HttpContext.Current.Response.End(); } }
private string GetEmailContent(UserBasicInfo ownerInfo, List <WebVisitReport> relatedVisits, GetDropdownValueResponse lifeCycleStages) { var emailContent = string.Empty; if (!relatedVisits.IsAny()) { return(emailContent); } relatedVisits.ForEach(c => { c.VisitedOn = c.VisitedOn.ToTimezone(ownerInfo.TimeZone); c.LifecycleStage = lifeCycleStages .DropdownValues .DropdownValuesList .Where(d => d.DropdownValueID == c.LifecycleStageId) .Select(d => d.DropdownValue) .FirstOrDefault() ?? ""; }); emailContent += relatedVisits.GetTable( p => p.FirstName, p => p.LastName, p => p.Email, p => p.Phone, p => p.Zip, p => p.LifecycleStage, p => p.VisitedOn, p => p.PageViews, p => p.Duration, p => p.Page1, p => p.Page2, p => p.Page3, p => p.Source, p => p.LeadScore, p => p.Location); return(emailContent); }
/// <summary> /// Production Jobs /// </summary> protected IQueryable<ProductionJob> JobsForRun(decimal? runID, List<string> statusList) { if ((runID == null) || (runID < 1)) { return null; } else { var jobs = from j in PrdnDBContext.ProductionJobs .Include("Customer") .Include("Product.LeatherCharVW") .Include("Product.LeatherCompVW") .Include("Worksheet.WorksheetCharVW") .Include("Worksheet.WorksheetCompVW") .Include("Priority") .Include("PrdnInvItem") where j.RunID == runID //orderby j.RunSeqNo select j; if (statusList.IsAny()) { jobs = from j in jobs where statusList.Contains(j.StatusStr) select j; } jobs = from j in jobs orderby j.RunSeqNo select j; return jobs; } }
public ActionResult Edit([Bind] RepairViewModel repairView, string returnUrl) { ActionResult action; try { if (!ModelState.IsValid) { ModelState.AddModelError("", MessageUI.ErrorMessage); return(View(repairView)); } var repair = _repairService.Get(x => x.Id == repairView.Id); var files = Request.Files; var lstRepairGalleries = new List <RepairGallery>(); if (files.Count > 0) { var count = files.Count - 1; var num = 0; var allKeys = files.AllKeys; for (var i = 0; i < allKeys.Length; i++) { var str = allKeys[i]; if (num <= count) { if (!str.Equals("ImageBigSize")) { var item = files[num]; if (item.ContentLength > 0) { var repairGalleryViewModel = new RepairGalleryViewModel { RepairId = repairView.Id }; var str1 = $"{repairView.RepairCode}-{Guid.NewGuid()}.jpg"; _imagePlugin.CropAndResizeImage(item, $"{Contains.MenuFolder}{repairView.RepairCode}/", str1, ImageSize.WithBigSize, ImageSize.WithBigSize); repairGalleryViewModel.ImagePath = $"{Contains.MenuFolder}{repairView.RepairCode}/{str1}"; lstRepairGalleries.Add(Mapper.Map <RepairGallery>(repairGalleryViewModel)); } num++; } else { num++; } } } } if (lstRepairGalleries.IsAny()) { repair.RepairGalleries = lstRepairGalleries; } var repairItems = new List <RepairItem>(); if (repairView.RepairItems.IsAny()) { foreach (var repairItem in repairView.RepairItems) { var repairItemViewModel = new RepairItemViewModel(); if (repairItem.Id > 0) { repairItemViewModel.Id = repairItem.Id; } repairItemViewModel.RepairId = repairView.Id; repairItemViewModel.FixedFee = repairItem.FixedFee; repairItemViewModel.Category = repairItem.Category; repairItemViewModel.WarrantyFrom = repairItem.WarrantyFrom; repairItemViewModel.WarrantyTo = repairItem.WarrantyTo; repairItems.Add(Mapper.Map <RepairItem>(repairItemViewModel)); } } if (repairItems.IsAny()) { repair.RepairItems = repairItems; } var repairItems1 = _repairItemService.FindBy(x => x.RepairId == repairView.Id); _repairItemService.BatchDelete(repairItems1); repair = Mapper.Map(repairView, repair); _repairService.Update(repair); Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.UpdateSuccess, FormUI.Repair))); if (!Url.IsLocalUrl(returnUrl) || returnUrl.Length <= 1 || !returnUrl.StartsWith("/") || returnUrl.StartsWith("//") || returnUrl.StartsWith("/\\")) { action = RedirectToAction("Index"); } else { action = Redirect(returnUrl); } } catch (Exception exception1) { var exception = exception1; ModelState.AddModelError("", exception.Message); ExtentionUtils.Log(string.Concat("Repair.Edit: ", exception.Message)); return(View(repairView)); } return(action); }
public ActionResult Create([Bind] RepairViewModel repair, string returnUrl) { ActionResult action; try { if (!ModelState.IsValid) { ModelState.AddModelError("", MessageUI.ErrorMessage); return(View(repair)); } var files = Request.Files; var repairGalleries = new List <RepairGallery>(); if (files.Count > 0) { var count = files.Count - 1; var num = 0; var allKeys = files.AllKeys; for (var i = 0; i < allKeys.Length; i++) { var str = allKeys[i]; if (num <= count) { if (!str.Equals("ImageBigSize")) { var httpPostedFileBase = files[num]; if (httpPostedFileBase.ContentLength > 0) { var repairGalleryViewModel = new RepairGalleryViewModel { RepairId = repair.Id }; var str1 = $"{repair.RepairCode}-{Guid.NewGuid()}.jpg"; _imagePlugin.CropAndResizeImage(httpPostedFileBase, $"{Contains.MenuFolder}{repair.RepairCode}/", str1, ImageSize.WithBigSize, ImageSize.WithBigSize); repairGalleryViewModel.ImagePath = $"{Contains.MenuFolder}{repair.RepairCode}/{str1}"; repairGalleries.Add(Mapper.Map <RepairGallery>(repairGalleryViewModel)); } num++; } else { num++; } } } } var repair1 = Mapper.Map <RepairViewModel, Repair>(repair); if (repairGalleries.IsAny()) { repair1.RepairGalleries = repairGalleries; } var repairItems = new List <RepairItem>(); if (repair.RepairItems.IsAny()) { repairItems.AddRange( from item in repair.RepairItems select Mapper.Map <RepairItem>(item)); } if (repairItems.IsAny()) { repair1.RepairItems = repairItems; } _repairService.Create(repair1); Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.CreateSuccess, FormUI.Repair))); if (!Url.IsLocalUrl(returnUrl) || returnUrl.Length <= 1 || !returnUrl.StartsWith("/") || returnUrl.StartsWith("//") || returnUrl.StartsWith("/\\")) { action = RedirectToAction("Index"); } else { action = Redirect(returnUrl); } } catch (Exception exception1) { var exception = exception1; ExtentionUtils.Log(string.Concat("Repair.Create: ", exception.Message)); ModelState.AddModelError("", exception.Message); return(View(repair)); } return(action); }
private PersonViewModel GetUpdatedPersonData(PersonViewModel existingModel, PersonViewModel newModel) { Person person = new Person(); var dropdownValues = _cachingService.GetDropdownValues(newModel.AccountID); existingModel.FirstName = !string.IsNullOrEmpty(newModel.FirstName) ? newModel.FirstName : existingModel.FirstName; existingModel.LastName = !string.IsNullOrEmpty(newModel.LastName) ? newModel.LastName : existingModel.LastName; existingModel.CompanyName = !string.IsNullOrEmpty(newModel.CompanyName) ? newModel.CompanyName : existingModel.CompanyName; existingModel.Title = !string.IsNullOrEmpty(newModel.Title) ? newModel.Title : existingModel.Title; List <short> phoneTypeIds = newModel.Phones.IsAny() ? newModel.Phones.Select(p => p.PhoneType).ToList() : new List <short>(); List <short> dropdownValueTyeIds = new List <short>(); if (phoneTypeIds.IsAny()) { dropdownValueTyeIds = _formRepository.GetDropdownValueTypeIdsByPhoneTypes(phoneTypeIds, newModel.AccountID); } var mobilePhoneNumber = dropdownValueTyeIds.Contains((short)DropdownValueTypes.MobilePhone) ? newModel.Phones.Select(m => m.Number).FirstOrDefault() : null; var homePhoneNumber = dropdownValueTyeIds.Contains((short)DropdownValueTypes.Homephone) ? newModel.Phones.Select(m => m.Number).FirstOrDefault() : null; var workPhoneNumber = dropdownValueTyeIds.Contains((short)DropdownValueTypes.WorkPhone) ? newModel.Phones.Select(m => m.Number).FirstOrDefault() : null; var phoneTypes = dropdownValues.Where(s => s.DropdownID == (byte)DropdownFieldTypes.PhoneNumberType) .Select(s => s.DropdownValuesList).FirstOrDefault().Where(d => d.IsActive == true); existingModel.Phones = new List <Phone>(); Log.Informational("While Updating phones."); IEnumerable <Phone> existingPhones = _formRepository.GetPhoneFields(existingModel.ContactID); Phone mobilePhone = existingPhones.Where(w => w.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).FirstOrDefault(); if (!string.IsNullOrEmpty(mobilePhoneNumber) && !(mobilePhoneNumber.Length < 10 || mobilePhoneNumber.Length > 15)) { string number = mobilePhoneNumber.TrimStart(new char[] { '0', '1' }); Phone phone = new Phone(); phone.Number = number; phone.AccountID = existingModel.AccountID; phone.IsPrimary = mobilePhone != null ? mobilePhone.IsPrimary : (homePhoneNumber == null && workPhoneNumber == null && !existingPhones.IsAny()) || phoneTypes.Where(c => c.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).Select(c => c.IsDefault).FirstOrDefault(); phone.PhoneType = phoneTypes.Where(c => c.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).Select(c => c.DropdownValueID).FirstOrDefault(); phone.PhoneTypeName = phoneTypes.Where(c => c.DropdownValueTypeID == (short)DropdownValueTypes.MobilePhone).Select(c => c.DropdownValue).FirstOrDefault(); if (person.IsValidPhoneNumberLength(number)) { existingModel.Phones.Add(phone); } } else if (mobilePhone != null) { existingModel.Phones.Add(mobilePhone); } Phone homePhone = existingPhones.Where(w => w.DropdownValueTypeID == (short)DropdownValueTypes.Homephone).FirstOrDefault(); if (!string.IsNullOrEmpty(homePhoneNumber) && !(homePhoneNumber.Length < 10 || homePhoneNumber.Length > 15)) { string number = homePhoneNumber.TrimStart(new char[] { '0', '1' }); Phone phone = new Phone(); phone.Number = number; phone.AccountID = existingModel.AccountID; phone.IsPrimary = homePhone != null ? homePhone.IsPrimary : (mobilePhoneNumber == null && workPhoneNumber == null && !existingPhones.IsAny()) || phoneTypes.Where(c => c.DropdownValueTypeID == (short)DropdownValueTypes.Homephone).Select(c => c.IsDefault).FirstOrDefault(); phone.PhoneType = phoneTypes.Where(c => c.DropdownValueTypeID == (short)DropdownValueTypes.Homephone).Select(c => c.DropdownValueID).FirstOrDefault(); phone.PhoneTypeName = phoneTypes.Where(c => c.DropdownValueTypeID == (short)DropdownValueTypes.Homephone).Select(c => c.DropdownValue).FirstOrDefault(); if (person.IsValidPhoneNumberLength(number)) { existingModel.Phones.Add(phone); } } else if (homePhone != null) { existingModel.Phones.Add(homePhone); } Phone workPhone = existingPhones.Where(w => w.DropdownValueTypeID == (short)DropdownValueTypes.WorkPhone).FirstOrDefault(); if (!string.IsNullOrEmpty(workPhoneNumber) && !(workPhoneNumber.Length < 10 || workPhoneNumber.Length > 15)) { string number = workPhoneNumber.TrimStart(new char[] { '0', '1' }); Phone phone = new Phone(); phone.Number = number; phone.AccountID = existingModel.AccountID; phone.IsPrimary = workPhone != null ? workPhone.IsPrimary : (mobilePhoneNumber == null && homePhoneNumber == null && !existingPhones.IsAny()) || phoneTypes.Where(c => c.DropdownValueTypeID == (short)DropdownValueTypes.WorkPhone).Select(c => c.IsDefault).FirstOrDefault(); phone.PhoneType = phoneTypes.Where(c => c.DropdownValueTypeID == (short)DropdownValueTypes.WorkPhone).Select(c => c.DropdownValueID).FirstOrDefault(); phone.PhoneTypeName = phoneTypes.Where(c => c.DropdownValueTypeID == (short)DropdownValueTypes.WorkPhone).Select(c => c.DropdownValue).FirstOrDefault(); if (person.IsValidPhoneNumberLength(number)) { existingModel.Phones.Add(phone); } } else if (workPhone != null) { existingModel.Phones.Add(workPhone); } IEnumerable <Phone> existingNonDefaultPhones = existingPhones.Where(w => w.DropdownValueTypeID != 9 && w.DropdownValueTypeID != 10 && w.DropdownValueTypeID != 11 && !w.IsDeleted); if (existingNonDefaultPhones.IsAny()) { existingNonDefaultPhones.Each(e => { if (phoneTypeIds.IsAny()) { if (phoneTypeIds.Contains(e.PhoneType)) { var nonDefaultPhone = newModel.Phones.Where(p => p.PhoneType == e.PhoneType).FirstOrDefault();//workPhoneNumber.TrimStart(new char[] { '0', '1' }); string number = nonDefaultPhone.Number.TrimStart(new char[] { '0', '1' }); if (e.Number != number) { e.IsPrimary = false; Phone phone = new Phone(); phone.Number = number; phone.AccountID = existingModel.AccountID; phone.IsPrimary = true; phone.PhoneType = nonDefaultPhone.PhoneType; phone.PhoneTypeName = nonDefaultPhone.PhoneTypeName; if (person.IsValidPhoneNumberLength(number.TrimStart(new char[] { '0', '1' }))) { existingModel.Phones.Add(phone); } } } } existingModel.Phones.Add(e); }); } Log.Informational("While Updating Addresses."); existingModel.Addresses = new List <AddressViewModel>(); var addressLine1 = newModel.Addresses.IsAny() ? newModel.Addresses.Select(a => a.AddressLine1).FirstOrDefault() : null; var addressLine2 = newModel.Addresses.IsAny() ? newModel.Addresses.Select(a => a.AddressLine2).FirstOrDefault() : null; var city = newModel.Addresses.IsAny() ? newModel.Addresses.Select(a => a.City).FirstOrDefault() : null; var state = newModel.Addresses.IsAny() ? newModel.Addresses.Select(a => a.State).FirstOrDefault() : null; var zip = newModel.Addresses.IsAny() ? newModel.Addresses.Select(a => a.ZipCode).FirstOrDefault() : null; var country = newModel.Addresses.IsAny() ? newModel.Addresses.Select(a => a.Country).FirstOrDefault() : null; if (addressLine1 != null || addressLine2 != null || city != null || zip != null || country != null || state != null) { existingModel.AddressTypes = dropdownValues.Where(s => s.DropdownID == (byte)DropdownFieldTypes.AddressType) .Select(s => s.DropdownValuesList).ToList().FirstOrDefault().Where(d => d.IsActive == true); AddressViewModel newAddress = new AddressViewModel(); newAddress.AddressTypeID = existingModel.AddressTypes.SingleOrDefault(a => a.IsDefault).DropdownValueID; newAddress.AddressLine1 = addressLine1 != null && !string.IsNullOrEmpty(addressLine1) ? addressLine1 : ""; newAddress.AddressLine2 = addressLine2 != null && !string.IsNullOrEmpty(addressLine2) ? addressLine2 : ""; newAddress.City = city != null && !string.IsNullOrEmpty(city) ? city : ""; if (state != null) { newAddress.State = new State() { Code = state.Code } } ; else { newAddress.State = new State(); } if (country != null) { newAddress.Country = new Country() { Code = country.Code } } ; else { newAddress.Country = new Country(); } var zipCode = zip != null && !string.IsNullOrEmpty(zip) ? zip : ""; newAddress.ZipCode = zipCode; newAddress.IsDefault = true; if ((newAddress.State != null && !string.IsNullOrEmpty(newAddress.State.Code)) && (newAddress.Country == null || string.IsNullOrEmpty(newAddress.Country.Code))) { newAddress.Country = new Country(); newAddress.Country.Code = newAddress.State.Code.Substring(0, 2); } existingModel.Addresses.Add(newAddress); } existingModel.ContactType = Entities.ContactType.Person.ToString(); existingModel.SecondaryEmails = new List <dynamic>(); Log.Informational("While Updating Life Cycle Stage."); existingModel.LifecycleStages = dropdownValues.Where(s => s.DropdownID == (byte)DropdownFieldTypes.LifeCycle) .Select(s => s.DropdownValuesList).ToList().FirstOrDefault().Where(d => d.IsActive == true); var defaultLifeCycleType = existingModel.LifecycleStages.SingleOrDefault(a => a.IsDefault); if (newModel.LifecycleStage > 0) { if (!existingModel.LifecycleStages.Where(l => l.DropdownValueID == newModel.LifecycleStage).IsAny()) { newModel.LifecycleStage = existingModel.LifecycleStages.Where(l => l.IsDefault).Select(s => s.DropdownValueID).FirstOrDefault(); } } existingModel.LifecycleStage = newModel.LifecycleStage > 0 ? newModel.LifecycleStage : defaultLifeCycleType.DropdownValueID; existingModel.AccountID = newModel.AccountID; existingModel.LastUpdatedOn = DateTime.Now.ToUniversalTime(); GetAllCustomFieldsResponse accountCustomFields = new GetAllCustomFieldsResponse(); GetAllCustomFieldsRequest request = new GetAllCustomFieldsRequest(newModel.AccountID); accountCustomFields.CustomFields = _customFieldService.GetAllCustomFields(request).CustomFields; if (newModel.CustomFields.IsAny()) { Log.Informational("While Updating Custom fields."); foreach (ContactCustomFieldMapViewModel submittedField in newModel.CustomFields) { try { var isCustomField = accountCustomFields.CustomFields.Where(c => c.FieldId == submittedField.CustomFieldId).FirstOrDefault(); if (isCustomField != null) { ContactCustomFieldMapViewModel contactCustomField = new ContactCustomFieldMapViewModel(); contactCustomField.CustomFieldId = submittedField.CustomFieldId; contactCustomField.Value = submittedField.Value; contactCustomField.FieldInputTypeId = (int)isCustomField.FieldInputTypeId; contactCustomField.ContactId = existingModel.ContactID; var existingCustomField = existingModel.CustomFields.Where(c => c.CustomFieldId == isCustomField.FieldId).FirstOrDefault(); if (existingCustomField == null) { existingModel.CustomFields.Add(contactCustomField); } else { existingCustomField.Value = submittedField.Value; } } } catch { Log.Informational("While Update: Submitted customfieldId: " + submittedField.CustomFieldId + " cannot be Updated. Value: " + submittedField.Value); } } } return(existingModel); }
public ActionResult Edit(PostViewModel model, string ReturnUrl) { ActionResult action; try { if (!base.ModelState.IsValid) { String messages = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors) .Select(v => v.ErrorMessage + " " + v.Exception)); base.ModelState.AddModelError("", messages); return(base.View(model)); } else if (!_postService.FindBy((Post x) => x.ProductCode.Equals(model.ProductCode) && x.Id != model.Id, true).IsAny <Post>()) { Post byId = this._postService.GetById(model.Id, isCache: false); string titleNonAccent = model.Title.NonAccent(); IEnumerable <MenuLink> bySeoUrl = this._menuLinkService.GetListSeoUrl(titleNonAccent, isCache: false); model.SeoUrl = model.Title.NonAccent(); if (bySeoUrl.Any <MenuLink>((MenuLink x) => x.Id != model.Id)) { PostViewModel postViewModel = model; postViewModel.SeoUrl = string.Concat(postViewModel.SeoUrl, "-", bySeoUrl.Count <MenuLink>()); } //string str1 = titleNonAccent; //if (str1.Length > 250) //{ // str1 = Utils.Utils.SplitWords(250, str1); //} string folderName = string.Format("{0:ddMMyyyy}", DateTime.UtcNow); if (model.Image != null && model.Image.ContentLength > 0) { string fileExtension = Path.GetExtension(model.Image.FileName); string fileName1 = titleNonAccent.FileNameFormat(fileExtension); string fileName2 = titleNonAccent.FileNameFormat(fileExtension); string fileName3 = titleNonAccent.FileNameFormat(fileExtension); this._imagePlugin.CropAndResizeImage(model.Image, string.Format("{0}{1}/", Contains.PostFolder, folderName), fileName1, ImageSize.WithBigSize, ImageSize.HeightBigSize, false); this._imagePlugin.CropAndResizeImage(model.Image, string.Format("{0}{1}/", Contains.PostFolder, folderName), fileName2, ImageSize.WithMediumSize, ImageSize.HeightMediumSize, false); this._imagePlugin.CropAndResizeImage(model.Image, string.Format("{0}{1}/", Contains.PostFolder, folderName), fileName3, ImageSize.WithSmallSize, ImageSize.HeightSmallSize, false); model.ImageBigSize = string.Format("{0}{1}/{2}", Contains.PostFolder, folderName, fileName1); model.ImageMediumSize = string.Format("{0}{1}/{2}", Contains.PostFolder, folderName, fileName2); model.ImageSmallSize = string.Format("{0}{1}/{2}", Contains.PostFolder, folderName, fileName3); } int?menuId = model.MenuId; int i = 0; if ((menuId.GetValueOrDefault() > i ? menuId.HasValue : false)) { IMenuLinkService menuLinkService = this._menuLinkService; menuId = model.MenuId; MenuLink menuLink = menuLinkService.GetById(menuId.Value, isCache: false); model.VirtualCatUrl = menuLink.VirtualSeoUrl; model.VirtualCategoryId = menuLink.VirtualId; } //GalleryImage HttpFileCollectionBase files = base.Request.Files; List <GalleryImage> lstGalleryImages = new List <GalleryImage>(); if (files.Count > 0) { int count = files.Count - 1; int num = 0; string[] allKeys = files.AllKeys; for (i = 0; i < (int)allKeys.Length; i++) { string str7 = allKeys[i]; if (num <= count) { if (!str7.Equals("Image")) { string str8 = str7.Replace("[]", ""); HttpPostedFileBase item = files[num]; if (item.ContentLength > 0) { string item1 = base.Request[str8]; GalleryImageViewModel galleryImageViewModel = new GalleryImageViewModel() { PostId = model.Id, AttributeValueId = int.Parse(str8) }; string fileName1 = string.Format("{0}-{1}.jpg", titleNonAccent, Guid.NewGuid()); string fileName2 = string.Format("{0}-{1}.jpg", titleNonAccent, Guid.NewGuid()); this._imagePlugin.CropAndResizeImage(item, string.Format("{0}{1}/", Contains.PostFolder, folderName), fileName1, ImageSize.WithBigSize, ImageSize.WithBigSize, false); this._imagePlugin.CropAndResizeImage(item, string.Format("{0}{1}/", Contains.PostFolder, folderName), fileName2, ImageSize.WithThumbnailSize, ImageSize.HeightThumbnailSize, false); galleryImageViewModel.ImageThumbnail = string.Format("{0}{1}/{2}", Contains.PostFolder, folderName, fileName2); galleryImageViewModel.ImagePath = string.Format("{0}{1}/{2}", Contains.PostFolder, folderName, fileName1); galleryImageViewModel.OrderDisplay = num; galleryImageViewModel.Status = 1; galleryImageViewModel.Title = model.Title; galleryImageViewModel.Price = new double?(double.Parse(item1)); lstGalleryImages.Add(Mapper.Map <GalleryImage>(galleryImageViewModel)); } num++; } else { num++; } } } } if (lstGalleryImages.IsAny <GalleryImage>()) { byId.GalleryImages = lstGalleryImages; } //AttributeValue List <AttributeValue> lstAttributeValues = new List <AttributeValue>(); List <int> nums = new List <int>(); string item2 = base.Request["Values"]; if (!string.IsNullOrEmpty(item2)) { foreach (string list in item2.Split(new char[] { ',' }).ToList <string>()) { int num1 = int.Parse(list); nums.Add(num1); lstAttributeValues.Add(this._attributeValueService.GetById(num1, isCache: false)); } if (nums.IsAny <int>()) { ( from x in byId.AttributeValues where !nums.Contains(x.Id) select x).ToList <AttributeValue>().ForEach((AttributeValue att) => byId.AttributeValues.Remove(att)); } } byId.AttributeValues = lstAttributeValues; Post modelMap = Mapper.Map(model, byId); this._postService.Update(byId); //Update GalleryImage if (lstAttributeValues.IsAny <AttributeValue>()) { foreach (AttributeValue attributeValue in lstAttributeValues) { GalleryImage nullable = this._galleryService.Get((GalleryImage x) => x.AttributeValueId == attributeValue.Id && x.PostId == model.Id, false); if (nullable == null) { continue; } HttpRequestBase request = base.Request; i = attributeValue.Id; double num2 = double.Parse(request[i.ToString()]); nullable.Price = new double?(num2); this._galleryService.Update(nullable); } } //Update Localized foreach (var localized in model.Locales) { _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.Title, localized.Title, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.ProductCode, localized.ProductCode, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.ShortDesc, localized.ShortDesc, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.Description, localized.Description, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.TechInfo, localized.TechInfo, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.SeoUrl, localized.SeoUrl, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaTitle, localized.MetaTitle, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaKeywords, localized.MetaKeywords, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaDescription, localized.MetaDescription, localized.LanguageId); } base.Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.UpdateSuccess, FormUI.Post))); if (!base.Url.IsLocalUrl(ReturnUrl) || ReturnUrl.Length <= 1 || !ReturnUrl.StartsWith("/") || ReturnUrl.StartsWith("//") || ReturnUrl.StartsWith("/\\")) { action = base.RedirectToAction("Index"); } else { action = this.Redirect(ReturnUrl); } } else { base.ModelState.AddModelError("", "Mã sản phẩm đã tồn tại."); action = base.View(model); } } catch (Exception ex) { base.ModelState.AddModelError("", ex.Message); ExtentionUtils.Log(string.Concat("Post.Edit: ", ex.Message)); return(base.View(model)); } return(action); }
public IEnumerable <MenuLink> GetByOptions(List <int> positions = null , List <int> template = null , string virtualId = null , string seoUrl = null , List <int> parentId = null , bool?isDisplayHomePage = null , bool?isDisplaySearch = null , int status = 1 , int?id = null , bool isCache = true) { var sbKey = new StringBuilder(); sbKey.AppendFormat(CacheMenuKey, "GetByOption"); var expression = PredicateBuilder.True <MenuLink>(); sbKey.AppendFormat("-{0}", status); expression = expression.And(x => x.Status == status); if (positions.IsAny()) { var i = 0; foreach (var pos in positions) { sbKey.AppendFormat("-{0}", pos); expression = i == 0 ? expression.And(x => x.PositionMenuLinks.Any(p => p.Id == pos)) : expression.Or(x => x.PositionMenuLinks.Any(p => p.Id == pos)); //expression = i == 0 ? expression.And(x => x.Position == pos) : expression.Or(x => x.Position == pos); i++; } } if (template != null && !template.IsNullOrEmpty()) { foreach (var temp in template) { sbKey.AppendFormat("-{0}", temp); var i = 0; expression = i == 0 ? expression.And(x => x.TemplateType == temp) : expression.Or(x => x.TemplateType == temp); i++; } } if (parentId != null && !parentId.IsNullOrEmpty()) { var i = 0; foreach (var par in parentId) { sbKey.AppendFormat("-{0}", parentId); expression = i == 0 ? expression.And(x => x.ParentId == par) : expression.Or(x => x.ParentId == par); i++; } } if (virtualId != null && virtualId.HasValue()) { sbKey.AppendFormat("-{0}", virtualId); expression = expression.And(x => x.VirtualId.Contains(virtualId)); } if (seoUrl != null && seoUrl.HasValue()) { sbKey.AppendFormat("-{0}", seoUrl); expression = expression.And(x => x.SeoUrl.Equals(seoUrl)); } if (isDisplayHomePage != null) { //isDisplayHomePage sbKey.AppendFormat("-{0}", isDisplayHomePage); expression = expression.And(x => x.DisplayOnHomePage == isDisplayHomePage); } if (isDisplaySearch != null) { //isDisplaySearch sbKey.AppendFormat("-{0}", isDisplaySearch); expression = expression.And(x => x.DisplayOnSearch == isDisplaySearch); } if (id != null) { sbKey.AppendFormat("-{0}", id); expression = expression.And(x => x.Id == id); } IEnumerable <MenuLink> menuLinks; if (isCache) { var key = sbKey.ToString(); menuLinks = _cacheManager.GetCollection <MenuLink>(key); if (menuLinks == null) { menuLinks = FindBy(expression); _cacheManager.Put(key, menuLinks); } } else { menuLinks = FindBy(expression); } return(menuLinks); }
public ActionResult EditPost(PostViewModel postView) { try { if (!ModelState.IsValid) { ModelState.AddModelError("", MessageUI.ErrorMessage); } else { var byId = _postService.GetById(postView.Id); var str = postView.Title.NonAccent(); var bySeoUrl = _menuLinkService.GetListSeoUrl(str); postView.SeoUrl = postView.Title.NonAccent(); if (bySeoUrl.Any(x => x.Id != postView.Id)) { var postViewModel = postView; postViewModel.SeoUrl = string.Concat(postViewModel.SeoUrl, "-", bySeoUrl.Count()); } var files = Request.Files; if (postView.Image != null && postView.Image.ContentLength > 0) { var str1 = $"{str}-{Utils.GetTime()}"; var str2 = $"{str}-{Utils.GetTime()}"; var str3 = $"{str}-{Utils.GetTime()}"; _imagePlugin.CropAndResizeImage(postView.Image, $"{Contains.PostFolder}/{str}/", str1, ImageSize.WithBigSize, ImageSize.HeightBigSize); _imagePlugin.CropAndResizeImage(postView.Image, $"{Contains.PostFolder}/{str}/", str2, ImageSize.WithMediumSize, ImageSize.HeightMediumSize); _imagePlugin.CropAndResizeImage(postView.Image, $"{Contains.PostFolder}/{str}/", str3, ImageSize.WithSmallSize, ImageSize.HeightSmallSize); postView.ImageBigSize = $"{Contains.PostFolder}/{str}/{str1}"; postView.ImageMediumSize = $"{Contains.PostFolder}/{str}/{str2}"; postView.ImageSmallSize = $"{Contains.PostFolder}/{str}/{str3}"; } var menuId = postView.MenuId; var i = 0; if (menuId.GetValueOrDefault() > i && menuId.HasValue) { var menuLinkService = _menuLinkService; menuId = postView.MenuId; var menuLink = menuLinkService.GetById(menuId.Value); postView.VirtualCatUrl = menuLink.VirtualSeoUrl; postView.VirtualCategoryId = menuLink.VirtualId; } var galleryImages = new List <GalleryImage>(); if (files.Count > 0) { var count = files.Count - 1; var num = 0; var allKeys = files.AllKeys; for (i = 0; i < allKeys.Length; i++) { var str4 = allKeys[i]; if (num <= count) { if (!str4.Equals("ImageBigSize")) { var item = files[num]; if (item.ContentLength > 0) { var galleryImageViewModel = new GalleryImageViewModel { PostId = postView.Id }; var str5 = $"{str}-{Utils.GetTime()}"; var str6 = $"{str}-{Utils.GetTime()}"; _imagePlugin.CropAndResizeImage(item, $"{Contains.PostFolder}/{str}/", str5, ImageSize.WithOrignalSize, ImageSize.HeighthOrignalSize); _imagePlugin.CropAndResizeImage(item, $"{Contains.PostFolder}/{str}/", str6, ImageSize.WithThumbnailSize, ImageSize.HeightThumbnailSize); galleryImageViewModel.ImageThumbnail = $"{Contains.PostFolder}/{str}/{str6}"; galleryImageViewModel.ImageBig = $"{Contains.PostFolder}/{str}/{str5}"; galleryImageViewModel.OrderDisplay = num; galleryImageViewModel.Status = 1; galleryImageViewModel.Title = postView.Title; galleryImages.Add(Mapper.Map <GalleryImage>(galleryImageViewModel)); } num++; } else { num++; } } } } if (galleryImages.IsAny()) { byId.GalleryImages = galleryImages; } byId = Mapper.Map(postView, byId); _postService.Update(byId); ViewBag.Message = "Cập nhật tin rao thành công"; return(View(postView)); } } catch (Exception exception1) { var exception = exception1; ModelState.AddModelError("", exception.Message); ExtentionUtils.Log(string.Concat("Post.Edit: ", exception.Message)); } ViewBag.Message = "Cập nhật tin rao KHÔNG thành công"; return(View(postView)); }
public ActionResult Edit(GenericControlViewModel model, string returnUrl) { ActionResult action; try { if (!ModelState.IsValid) { var messages = string.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors) .Select(v => v.ErrorMessage + " " + v.Exception)); ModelState.AddModelError("", messages); return(View(model)); } var objGenericControl = _gCService.GetById(model.Id); var menuLinks = new List <MenuLink>(); var menuIds = new List <int>(); var menuLink = Request["MenuLink"]; if (!string.IsNullOrEmpty(menuLink)) { foreach (var item in menuLink.Split(',').ToList()) { var menuId = int.Parse(item); menuIds.Add(menuId); menuLinks.Add(_menuLinkService.GetMenu(menuId, false)); } if (menuIds.IsAny()) { (from x in objGenericControl.MenuLinks where !menuIds.Contains(x.Id) select x).ToList() .ForEach(m => objGenericControl.MenuLinks.Remove(m) ); } } objGenericControl.MenuLinks = menuLinks; var modelMap = Mapper.Map <GenericControlViewModel, GenericControl>(model); _gCService.Update(objGenericControl); //Update Localized foreach (var localized in model.Locales) { _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.Name, localized.Name, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.Description, localized.Description, localized.LanguageId); } Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.UpdateSuccess, FormUI.GenericControl))); if (!Url.IsLocalUrl(returnUrl) || returnUrl.Length <= 1 || !returnUrl.StartsWith("/") || returnUrl.StartsWith("//") || returnUrl.StartsWith("/\\")) { action = RedirectToAction("Index"); } else { action = Redirect(returnUrl); } } catch (Exception ex) { LogText.Log(string.Concat("GenericControl.Create: ", ex.Message)); return(View(model)); } return(action); }
public ActionResult Edit(MenuLinkViewModel model, string returnUrl) { ActionResult action; try { if (!ModelState.IsValid) { var messages = string.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors) .Select(v => v.ErrorMessage + " " + v.Exception)); ModelState.AddModelError("", messages); return(View(model)); } var menuExsist = _menuLinkService.GetMenu(model.Id); var menuName = model.MenuName.NonAccent(); var bySeoUrl = _menuLinkService.GetListSeoUrl(menuName); model.SeoUrl = model.MenuName.NonAccent(); if (bySeoUrl.Any(x => x.Id != model.Id)) { var menuLinkViewModel = model; var seoUrl = menuLinkViewModel.SeoUrl; var num = bySeoUrl.Count(); menuLinkViewModel.SeoUrl = string.Concat(seoUrl, "-", num.ToString()); } ImageHandler(model); var parentId = model.ParentId; if (!parentId.HasValue) { model.ParentId = null; model.VirtualId = menuExsist.CurrentVirtualId; model.VirtualSeoUrl = null; } else { var byId1 = _menuLinkService.GetMenu(parentId.Value); model.VirtualId = $"{byId1.VirtualId}/{menuExsist.CurrentVirtualId}"; model.VirtualSeoUrl = $"{byId1.SeoUrl}/{model.SeoUrl}"; } //Get PositionMenuLink selected var positionMenuLinks = new List <Domain.Menus.PositionMenuLink>(); var positionIds = new List <int>(); var position = Request["Position"]; if (!string.IsNullOrEmpty(position)) { foreach (var item in position.Split(',').ToList()) { var positionId = int.Parse(item); positionIds.Add(positionId); positionMenuLinks.Add(_positionMenuLink.GetById(positionId, false)); } if (positionIds.IsAny()) { (from x in menuExsist.PositionMenuLinks where !positionIds.Contains(x.Id) select x).ToList() .ForEach(m => menuExsist.PositionMenuLinks.Remove(m) ); } } menuExsist.PositionMenuLinks = positionMenuLinks; var modelMap = Mapper.Map(model, menuExsist); _menuLinkService.Update(menuExsist); //Update Localized foreach (var localized in model.Locales) { _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MenuName, localized.MenuName, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.SeoUrl, localized.MenuName.NonAccent(), localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaTitle, localized.MetaTitle, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaKeywords, localized.MetaKeywords, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaDescription, localized.MetaDescription, localized.LanguageId); } Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.UpdateSuccess, FormUI.MenuLink))); if (!Url.IsLocalUrl(returnUrl) || returnUrl.Length <= 1 || !returnUrl.StartsWith("/") || returnUrl.StartsWith("//") || returnUrl.StartsWith("/\\")) { action = RedirectToAction("Index"); } else { action = Redirect(returnUrl); } } catch (Exception ex) { ModelState.AddModelError("", ex.Message); LogText.Log(string.Concat("MenuLink.Create: ", ex.Message)); return(View(model)); } return(action); }
private static void CreateSectionTwoExample001(PdfBuilder pdfBuilder, MarginInfo parentPadding) { const VerticalAlignmentType parentVerticalAlignment = VerticalAlignmentType.Center; const bool keepContentTogether = false; const bool isKeptTogether = false; const bool isKeptWithNext = false; const string exampleDocWidths = "100 250 100"; var exampleDocPadding = new MarginInfo { Left = 2, Bottom = 2, Top = 2 }; var exampleDocs = new List <string[]> { new[] { "item 1 type", "item 1 desc", "item 1 filename" }, new[] { "item 2 type", "item 2 desc", "item 2 filename" }, new[] { "item 3 type", "item 3 desc", "item 3 filename" }, new[] { "item 4 type", "item 4 desc", "item 4 filename" }, }; if (exampleDocs.IsAny()) { // Create an inner table var exampleDocumentTable = pdfBuilder.CreateInnerTable( exampleDocWidths, isKeptTogether: isKeptTogether, isKeptWithNext: isKeptWithNext, keepContentTogether: keepContentTogether); // Create inner table row var docRow = pdfBuilder.CreateInnerTableRow(exampleDocumentTable, exampleDocPadding); // Create inner table cells pdfBuilder.CreateInnerTableHeaderCells(docRow, new[] { new HeaderCell { Content = "Example 001 doc type" }, new HeaderCell { Content = "Example 001 doc desc" }, new HeaderCell { Content = "Example 001 doc filename" } }); // format rows for each document foreach (var document in exampleDocs) { var itemRow = exampleDocumentTable.Rows.Add(); pdfBuilder.CreateInnerTableItemCells( itemRow, exampleDocPadding, verticalAlignment: parentVerticalAlignment, cellContent: new[] { new DisplayCell { Content = document[0].Trim() }, new DisplayCell { Content = document[1].Trim() }, new DisplayCell { Content = document[2].Trim() } }); } } pdfBuilder.BlankRow(); }
// save list of halls to xml private static void SaveHalls(List<Hall> halls) { if (!halls.IsAny()) return; Console.WriteLine($"\nGet {halls.Count} halls."); var path = $@"{HallsPath}Halls_{DateTime.Now.ToString("dd-MM-yyyy")}.xml"; if (File.Exists(path)) { Console.WriteLine($"File \"{Path.GetFileName(path)}\" [{new FileInfo(path).Length.ToReadableFileSize()}] loaded successfuly"); return; } File.WriteAllText(path, halls.Serialize()); Console.WriteLine($"File \"{Path.GetFileName(path)}\" [{new FileInfo(path).Length.ToReadableFileSize()}] saved successfuly to:\n{path}"); }
public ActionResult Create(PostViewModel model, string ReturnUrl) { ActionResult action; try { if (!base.ModelState.IsValid) { String messages = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors) .Select(v => v.ErrorMessage + " " + v.Exception)); base.ModelState.AddModelError("", messages); return(base.View(model)); } else //if (!this._postService.FindBy((Post x) => x.ProductCode.Equals(model.ProductCode), true).IsAny<Post>()) { string str = model.Title.NonAccent(); IEnumerable <Post> bySeoUrl = this._postService.GetBySeoUrl(str); model.SeoUrl = model.Title.NonAccent(); if (bySeoUrl.Any <Post>((Post x) => x.Id != model.Id)) { PostViewModel postViewModel = model; postViewModel.SeoUrl = string.Concat(postViewModel.SeoUrl, "-", bySeoUrl.Count <Post>()); } string str1 = str; if (str1.Length > 250) { str1 = AdminHelper.SplitWords(250, str1); } string str2 = string.Format("{0:ddMMyyyy}", DateTime.UtcNow); if (model.Image != null && model.Image.ContentLength > 0) { string str3 = string.Concat(str1, ".jpg"); string str4 = string.Format("{0}-{1}.jpg", str1, Guid.NewGuid()); string str5 = string.Format("{0}-{1}.jpg", str1, Guid.NewGuid()); this._imagePlugin.CropAndResizeImage(model.Image, string.Format("{0}{1}/", Contains.PostFolder, str2), str3, new int?(ImageSize.WithBigSize), new int?(ImageSize.HeightBigSize), false); this._imagePlugin.CropAndResizeImage(model.Image, string.Format("{0}{1}/", Contains.PostFolder, str2), str4, new int?(ImageSize.WithMediumSize), new int?(ImageSize.HeightMediumSize), false); this._imagePlugin.CropAndResizeImage(model.Image, string.Format("{0}{1}/", Contains.PostFolder, str2), str5, new int?(ImageSize.WithSmallSize), new int?(ImageSize.HeightSmallSize), false); model.ImageBigSize = string.Format("{0}{1}/{2}", Contains.PostFolder, str2, str3); model.ImageMediumSize = string.Format("{0}{1}/{2}", Contains.PostFolder, str2, str4); model.ImageSmallSize = string.Format("{0}{1}/{2}", Contains.PostFolder, str2, str5); } int?menuId = model.MenuId; int i = 0; if ((menuId.GetValueOrDefault() > i ? menuId.HasValue : false)) { IMenuLinkService menuLinkService = this._menuLinkService; menuId = model.MenuId; MenuLink byId = menuLinkService.GetById(menuId.Value); model.VirtualCatUrl = byId.VirtualSeoUrl; model.VirtualCategoryId = byId.VirtualId; } HttpFileCollectionBase files = base.Request.Files; List <GalleryImage> galleryImages = new List <GalleryImage>(); if (files.Count > 0) { int count = files.Count - 1; int num = 0; string str6 = str; string[] allKeys = files.AllKeys; for (i = 0; i < (int)allKeys.Length; i++) { string str7 = allKeys[i]; if (num <= count) { if (!str7.Equals("Image")) { string str8 = str7.Replace("[]", ""); HttpPostedFileBase item = files[num]; if (item.ContentLength > 0) { string item1 = base.Request[str8]; GalleryImageViewModel galleryImageViewModel = new GalleryImageViewModel() { PostId = model.Id, AttributeValueId = int.Parse(str8) }; string str9 = string.Format("{0}-{1}.jpg", str6, Guid.NewGuid()); string str10 = string.Format("{0}-{1}.jpg", str6, Guid.NewGuid()); this._imagePlugin.CropAndResizeImage(item, string.Format("{0}{1}/", Contains.PostFolder, str2), str9, new int?(ImageSize.WithBigSize), new int?(ImageSize.HeightBigSize), false); this._imagePlugin.CropAndResizeImage(item, string.Format("{0}{1}/", Contains.PostFolder, str2), str10, new int?(ImageSize.WithThumbnailSize), new int?(ImageSize.HeightThumbnailSize), false); galleryImageViewModel.ImageThumbnail = string.Format("{0}{1}/{2}", Contains.PostFolder, str2, str10); galleryImageViewModel.ImagePath = string.Format("{0}{1}/{2}", Contains.PostFolder, str2, str9); galleryImageViewModel.OrderDisplay = num; galleryImageViewModel.Status = 1; galleryImageViewModel.Title = model.Title; galleryImageViewModel.Price = new double?(double.Parse(item1)); galleryImages.Add(Mapper.Map <GalleryImage>(galleryImageViewModel)); } num++; } else { num++; } } } } List <AttributeValue> attributeValues = new List <AttributeValue>(); string item2 = base.Request["Values"]; if (!string.IsNullOrEmpty(item2)) { foreach (string list in item2.Split(new char[] { ',' }).ToList <string>()) { int num1 = int.Parse(list); attributeValues.Add(this._attributeValueService.GetById(num1)); } } Post modelMap = Mapper.Map <PostViewModel, Post>(model); if (galleryImages.IsAny <GalleryImage>()) { modelMap.GalleryImages = galleryImages; } if (attributeValues.IsAny <AttributeValue>()) { modelMap.AttributeValues = attributeValues; } this._postService.Create(modelMap); //Update Localized foreach (var localized in model.Locales) { _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.Title, localized.Title, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.ProductCode, localized.ProductCode, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.ShortDesc, localized.ShortDesc, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.Description, localized.Description, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.TechInfo, localized.TechInfo, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.SeoUrl, localized.SeoUrl, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaTitle, localized.MetaTitle, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaKeywords, localized.MetaKeywords, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.MetaDescription, localized.MetaDescription, localized.LanguageId); } base.Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.CreateSuccess, FormUI.Post))); if (!base.Url.IsLocalUrl(ReturnUrl) || ReturnUrl.Length <= 1 || !ReturnUrl.StartsWith("/") || ReturnUrl.StartsWith("//") || ReturnUrl.StartsWith("/\\")) { action = base.RedirectToAction("Index"); } else { action = this.Redirect(ReturnUrl); } } //else //{ // base.ModelState.AddModelError("", "Mã sản phẩm đã tồn tại."); // action = base.View(model); //} } catch (Exception exception1) { Exception exception = exception1; ExtentionUtils.Log(string.Concat("Post.Create: ", exception.Message)); base.ModelState.AddModelError("", exception.Message); return(base.View(model)); } return(action); }
public void LoadFromRequest(string requestID) { WorksheetOpts = WorksheetEditOpt.ReqWorksheet<WorksheetEditOpt>(requestID); //WorksheetOpts = WorksheetEditOpt.ReqWorksheetWith300Groups(requestID); DefineForProdType(); if (WorksheetOpts.IsAny()) { WorksheetOpts.ForEach(o => o.WorksheetID = WorksheetID); } }
protected override void ExecuteInternal(IJobExecutionContext context) { var response = _accountService.GetBulkOperationData(new GetBulkOperationDataRequest()); try { Log.Informational("Entering into BulkOperation processor"); List <int> ids = null; while (response.BulkOperations != null) { var notification = new Notification { Time = DateTime.Now.ToUniversalTime(), Status = NotificationStatus.New, EntityId = response.BulkOperations.OperationID, UserID = response.BulkOperations.UserID, ModuleID = (byte)AppModules.Contacts }; try { if (response.BulkOperations.SearchDefinitionID != null) { Log.Informational("Bulk SearchDefinitionID" + response.BulkOperations.SearchDefinitionID); GetSavedSearchContactIdsRequest advRequest = new GetSavedSearchContactIdsRequest() { SearchDefinitionId = (int)response.BulkOperations.SearchDefinitionID, AccountId = response.BulkOperations.AccountID }; Log.Informational("For Getting SavedSearch Contacts By SearchdefinitionID In BulkOperation"); ids = _advancedSearchService.GetSavedSearchContactIds(advRequest).Result; } else if (response.BulkContactIDs.Length > 0) { Log.Informational("Bulk contacts Length" + response.BulkContactIDs.ToList()); ids = response.BulkContactIDs.ToList(); } if (ids.IsAny() || !string.IsNullOrEmpty(response.BulkOperations.SearchCriteria)) { GetBulkContactsResponse contactsResponse = _contactService.GetBulkContacts(new GetBulkContactsRequest() { BulkOperations = response.BulkOperations, ContactIds = ids }); _accountService.InsertBulkData(contactsResponse.ContactIds, response.BulkOperations.BulkOperationID); #region Actions if (response.BulkOperations.OperationType == (int)BulkOperationTypes.Action) { Log.Informational("Performing bulk add action with operationId : " + response.BulkOperations.OperationID); IEnumerable <int> contactIds = null; IDictionary <int, Guid> emailGuids = new Dictionary <int, Guid>(); IDictionary <int, Guid> textGuids = new Dictionary <int, Guid>(); var action = _actionService.UpdateActionBulkData(response.BulkOperations.OperationID, response.BulkOperations.AccountID, response.BulkOperations.UserID, response.BulkOperations.AccountPrimaryEmail, response.BulkOperations.AccountDomain, false, false, "", response.BulkOperations.ActionCompleted, contactIds, false, 0, emailGuids, textGuids); notification.Subject = action.Details; notification.Details = "Bulk Operation for adding action completed successfully"; notification.ModuleID = (byte)AppModules.ContactActions; } #endregion #region Note else if (response.BulkOperations.OperationType == (int)BulkOperationTypes.Note) { Log.Verbose("Updating Note Bulk Data for operationid: " + response.BulkOperations.OperationID); if (ids.IsAny()) { var note = _noteService.UpdateNoteBulkData(response.BulkOperations.OperationID, response.BulkOperations.AccountID, contactsResponse.ContactIds); notification.Subject = note.Details; notification.Details = "Bulk Operation for adding note completed successfully"; } else { notification.Subject = "Could not perform operation"; notification.Details = "Opeartion could not be performed as there were no contacts found"; } notification.ModuleID = (byte)AppModules.Contacts; } #endregion #region Tour else if (response.BulkOperations.OperationType == (int)BulkOperationTypes.Tour) { Log.Informational("Performing bulk add tour with operationId : " + response.BulkOperations.OperationID); IDictionary <int, Guid> emailGuids = new Dictionary <int, Guid>(); IDictionary <int, Guid> textGuids = new Dictionary <int, Guid>(); var tour = _tourService.UpdateTourBulkData(response.BulkOperations.OperationID, response.BulkOperations.AccountID, response.BulkOperations.UserID, response.BulkOperations.AccountPrimaryEmail, response.BulkOperations.AccountDomain, false, "", null, false, 0, emailGuids, textGuids); notification.Subject = tour.TourDetails; notification.Details = "Bulk Operation for adding tour completed successfully"; notification.ModuleID = (byte)AppModules.ContactTours; } #endregion #region Tag else if (response.BulkOperations.OperationType == (int)BulkOperationTypes.Tag) { Log.Informational("Performing bulk add tag with operationId : " + response.BulkOperations.OperationID); var tag = _tagService.UpdateTagBulkData(response.BulkOperations.OperationID, response.BulkOperations.AccountID, response.BulkOperations.UserID); notification.Subject = tag.TagName; notification.Details = "Bulk Operation for adding tag completed successfully"; notification.ModuleID = (byte)AppModules.Contacts; _accountService.ScheduleAnalyticsRefresh(response.BulkOperations.OperationID, (byte)IndexType.Tags); } #endregion #region ChangeOwner else if (response.BulkOperations.OperationType == (int)BulkOperationTypes.ChangeOwner) { Log.Informational("Performing bulk change owner with operationId : " + response.BulkOperations.OperationID); if (ids.IsAny()) { var owner = _contactService.UpdateOwnerBulkData(response.BulkOperations.OperationID, response.BulkOperations.UserID, response.BulkOperations.AccountID, contactsResponse.ContactIds); notification.Subject = "New owner: " + owner.FirstName + " " + owner.LastName; notification.Details = "Bulk Operation for changing owner completed successfully"; } else { notification.Subject = "Could not perform operation"; notification.Details = "Opeartion could not be performed as there were no contacts found"; } notification.ModuleID = (byte)AppModules.Contacts; } #endregion #region Export else if (response.BulkOperations.OperationType == (int)BulkOperationTypes.Export) { Log.Informational("Performing bulk export with operationId : " + response.BulkOperations.OperationID); IEnumerable <FieldViewModel> searchFields = null; GetAdvanceSearchFieldsResponse filedsresponse = _advancedSearchService.GetSearchFields(new GetAdvanceSearchFieldsRequest() { accountId = response.BulkOperations.AccountID, RoleId = response.BulkOperations.RoleID }); if (filedsresponse.FieldsViewModel != null) { searchFields = ExcludeNonViewableFields(filedsresponse.FieldsViewModel); } Task.Run(() => _contactService.UpdateBulkExcelExport(response.BulkOperations, contactsResponse.Contacts, searchFields)); } #endregion #region Delete else if (response.BulkOperations.OperationType == (int)BulkOperationTypes.Delete) { Log.Informational("Performing bulk delete with operationId : " + response.BulkOperations.OperationID); if (ids.IsAny()) { _contactService.UpdateDeleteBulkData(response.BulkOperations.OperationID, response.BulkOperations.UserID, response.BulkOperations.AccountID, contactsResponse.ContactIds); notification.Subject = "Bulk Operation for deleting contacts completed successfully"; notification.Details = "Bulk Operation for deleting contacts completed successfully"; } else { notification.Subject = "Could not perform operation"; notification.Details = "Opeartion could not be performed as there were no contacts found"; } notification.ModuleID = (byte)AppModules.Contacts; } #endregion _accountService.UpdateBulkOperationStatus(new UpdateBulkOperationStatusRequest() { BulkOperationId = response.BulkOperations.BulkOperationID, Status = BulkOperationStatus.Completed }); if (response.BulkOperations.OperationType != (int)BulkOperationTypes.Export) { _userService.AddNotification(new AddNotificationRequest() { Notification = notification }); } } else { _accountService.UpdateBulkOperationStatus(new UpdateBulkOperationStatusRequest() { BulkOperationId = response.BulkOperations.BulkOperationID, Status = BulkOperationStatus.Failed }); } //TODO: Remove this, will cause job run too much time response = _accountService.GetBulkOperationData(new GetBulkOperationDataRequest() { }); } catch (Exception exe) { Log.Error("Error while BulkOperation", exe); _accountService.UpdateBulkOperationStatus(new UpdateBulkOperationStatusRequest() { BulkOperationId = response.BulkOperations.BulkOperationID, Status = BulkOperationStatus.Failed }); //TODO: Remove this, will cause job run too much time response = _accountService.GetBulkOperationData(new GetBulkOperationDataRequest() { }); } } } catch (Exception ex) { Log.Error("Error while BulkOperation", ex); _accountService.UpdateBulkOperationStatus(new UpdateBulkOperationStatusRequest() { BulkOperationId = response.BulkOperations.BulkOperationID, Status = BulkOperationStatus.Failed }); } }
public ActionResult Edit(GenericControlViewModel model, string ReturnUrl) { ActionResult action; try { if (!base.ModelState.IsValid) { String messages = String.Join(Environment.NewLine, ModelState.Values.SelectMany(v => v.Errors) .Select(v => v.ErrorMessage + " " + v.Exception)); base.ModelState.AddModelError("", messages); return(base.View(model)); } else { GenericControl objGenericControl = _genericControlService.GetById(model.Id); List <MenuLink> lstMenuLink = new List <MenuLink>(); List <int> lstMenuId = new List <int>(); string menuLink = this.Request["MenuLink"]; if (!string.IsNullOrEmpty(menuLink)) { foreach (var item in menuLink.Split(new char[] { ',' }).ToList <string>()) { int menuId = int.Parse(item); lstMenuId.Add(menuId); lstMenuLink.Add(_menuLinkService.GetById(menuId, isCache: false)); } if (lstMenuId.IsAny()) { (from x in objGenericControl.MenuLinks where !lstMenuId.Contains(x.Id) select x).ToList <MenuLink>() .ForEach((MenuLink m) => objGenericControl.MenuLinks.Remove(m) ); } } objGenericControl.MenuLinks = lstMenuLink; GenericControl modelMap = Mapper.Map <GenericControlViewModel, GenericControl>(model); this._genericControlService.Update(objGenericControl); //Update Localized foreach (var localized in model.Locales) { _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.Name, localized.Name, localized.LanguageId); _localizedPropertyService.SaveLocalizedValue(modelMap, x => x.Description, localized.Description, localized.LanguageId); } base.Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.UpdateSuccess, FormUI.GenericControl))); if (!base.Url.IsLocalUrl(ReturnUrl) || ReturnUrl.Length <= 1 || !ReturnUrl.StartsWith("/") || ReturnUrl.StartsWith("//") || ReturnUrl.StartsWith("/\\")) { action = base.RedirectToAction("Index"); } else { action = this.Redirect(ReturnUrl); } } } catch (Exception exception1) { Exception exception = exception1; ExtentionUtils.Log(string.Concat("GenericControl.Create: ", exception.Message)); return(base.View(model)); } return(action); }
public ActionResult BuyProduct(OrderViewModel order) { int id = 1; Order order1 = this._orderService.GetTop <int>(1, (Order x) => x.Id > 0, (Order x) => x.Id).FirstOrDefault <Order>(); if (order1 != null) { id = order1.Id; } order.OrderCode = string.Concat("DH", id.ToString()); order.CustomerCode = string.Concat("KH", id.ToString()); order.Category = "Định giá và thu mua sản phẩm"; if (!base.Request.IsAjaxRequest()) { return(base.Json(new { success = false, errors = string.Join(", ", base.ModelState.Values.SelectMany <System.Web.Mvc.ModelState, string>((System.Web.Mvc.ModelState v) => from x in v.Errors select x.ErrorMessage).ToArray <string>()) })); } HttpFileCollectionBase files = base.Request.Files; List <OrderGallery> orderGalleries = new List <OrderGallery>(); if (files.Count > 0) { int count = files.Count - 1; int num = 0; string[] allKeys = files.AllKeys; for (int i = 0; i < (int)allKeys.Length; i++) { string str = allKeys[i]; if (num <= count) { if (!str.Equals("Image")) { HttpPostedFileBase item = files[num]; if (item.ContentLength > 0) { OrderGalleryViewModel orderGalleryViewModel = new OrderGalleryViewModel() { OrderId = order.Id }; string str1 = string.Format("{0}-{1}.jpg", order.OrderCode, Guid.NewGuid()); this._imagePlugin.CropAndResizeImage(item, string.Format("{0}{1}/", Contains.ImageFolder, order.OrderCode), str1, new int?(ImageSize.WithBigSize), new int?(ImageSize.WithBigSize), false); orderGalleryViewModel.ImagePath = string.Format("{0}{1}/{2}", Contains.ImageFolder, order.OrderCode, str1); orderGalleries.Add(Mapper.Map <OrderGallery>(orderGalleryViewModel)); } num++; } else { num++; } } } } Order order2 = Mapper.Map <OrderViewModel, Order>(order); if (orderGalleries.IsAny <OrderGallery>()) { order2.OrderGalleries = orderGalleries; } this._orderService.Create(order2); return(base.Json(new { success = true })); }
public ActionResult Edit([Bind] OrderViewModel orderView, string ReturnUrl) { ActionResult action; try { if (!base.ModelState.IsValid) { base.ModelState.AddModelError("", MessageUI.ErrorMessage); return(base.View(orderView)); } else { Order order = this._orderService.Get((Order x) => x.Id == orderView.Id, false); HttpFileCollectionBase files = base.Request.Files; List <OrderGallery> orderGalleries = new List <OrderGallery>(); if (files.Count > 0) { int count = files.Count - 1; int num = 0; string[] allKeys = files.AllKeys; for (int i = 0; i < (int)allKeys.Length; i++) { string str = allKeys[i]; if (num <= count) { if (!str.Equals("Image")) { HttpPostedFileBase item = files[num]; if (item.ContentLength > 0) { OrderGalleryViewModel orderGalleryViewModel = new OrderGalleryViewModel() { OrderId = orderView.Id }; string str1 = string.Format("{0}-{1}.jpg", orderView.OrderCode, Guid.NewGuid()); this._imagePlugin.CropAndResizeImage(item, string.Format("{0}{1}/", Contains.ImageFolder, orderView.OrderCode), str1, new int?(ImageSize.WithBigSize), new int?(ImageSize.WithBigSize), false); orderGalleryViewModel.ImagePath = string.Format("{0}{1}/{2}", Contains.ImageFolder, orderView.OrderCode, str1); orderGalleries.Add(Mapper.Map <OrderGallery>(orderGalleryViewModel)); } num++; } else { num++; } } } } if (orderGalleries.IsAny <OrderGallery>()) { order.OrderGalleries = orderGalleries; } List <OrderItem> orderItems = new List <OrderItem>(); if (orderView.OrderItems.IsAny <OrderItemViewModel>()) { foreach (OrderItemViewModel orderItem in orderView.OrderItems) { OrderItemViewModel orderItemViewModel = new OrderItemViewModel(); if (orderItem.Id > 0) { orderItemViewModel.Id = orderItem.Id; } orderItemViewModel.OrderId = orderView.Id; orderItemViewModel.FixedFee = orderItem.FixedFee; orderItemViewModel.Category = orderItem.Category; orderItemViewModel.WarrantyFrom = orderItem.WarrantyFrom; orderItemViewModel.WarrantyTo = orderItem.WarrantyTo; orderItems.Add(Mapper.Map <OrderItem>(orderItemViewModel)); } } if (orderItems.IsAny <OrderItem>()) { order.OrderItems = orderItems; } IEnumerable <OrderItem> orderItems1 = this._orderItemService.FindBy((OrderItem x) => x.OrderId == orderView.Id, false); this._orderItemService.BatchDelete(orderItems1); order = Mapper.Map <OrderViewModel, Order>(orderView, order); this._orderService.Update(order); base.Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.UpdateSuccess, FormUI.Order))); if (!base.Url.IsLocalUrl(ReturnUrl) || ReturnUrl.Length <= 1 || !ReturnUrl.StartsWith("/") || ReturnUrl.StartsWith("//") || ReturnUrl.StartsWith("/\\")) { action = base.RedirectToAction("Index"); } else { action = this.Redirect(ReturnUrl); } } } catch (Exception exception1) { Exception exception = exception1; base.ModelState.AddModelError("", exception.Message); ExtentionUtils.Log(string.Concat("Order.Edit: ", exception.Message)); return(base.View(orderView)); } return(action); }
protected override void Execute() { GetBulkOperationDataResponse response = accountService.GetQueuedBulkOperationData(new GetBulkOperationDataRequest() { }); try { Logger.Current.Informational("Entering into BulkOperation Ready processor"); List <int> ids = null; while (response.BulkOperations != null) { try { if (response.BulkOperations.SearchDefinitionID != null) { Logger.Current.Informational("BulkOperation Ready processor SearchDefinitionID" + response.BulkOperations.SearchDefinitionID); GetSavedSearchContactIdsRequest advRequest = new GetSavedSearchContactIdsRequest() { SearchDefinitionId = (int)response.BulkOperations.SearchDefinitionID, AccountId = response.BulkOperations.AccountID, SearchCriteria = response.BulkOperations.SearchCriteria, RoleId = response.BulkOperations.RoleID, RequestedBy = response.BulkOperations.UserID }; Logger.Current.Informational("For Getting SavedSearch Contacts By SearchdefinitionID In BulkOperation Ready processor"); ids = advancedSearchService.GetSavedSearchContactIds(advRequest).Result; } else if (!response.BulkContactIDs.IsAny() && (response.BulkOperations.SearchDefinitionID == null || response.BulkOperations.SearchDefinitionID == 0)) { GetBulkContactsResponse contactsResponse = contactService.GetBulkContacts(new GetBulkContactsRequest() { BulkOperations = response.BulkOperations, ContactIds = new List <int>() { }, RoleId = response.BulkOperations.RoleID, RequestedBy = response.BulkOperations.UserID }); ids = contactsResponse.ContactIds.ToList(); } if (ids.IsAny() && ids.Count > 0) { var bulkConactsData = ids.Select(i => new BulkContact() { BulkOperationID = response.BulkOperations.BulkOperationID, ContactID = i }).ToList(); contactService.InsertBulkOperationConacts(new BulkoperationConactsInsertionRequest() { ConactsData = bulkConactsData }); Logger.Current.Informational("BulkOperation Ready processor Conacts Inserted Successfully,BulkoperationId: " + response.BulkOperations.BulkOperationID); } else { if (!response.BulkContactIDs.IsAny()) { accountService.UpdateBulkOperationStatus(new UpdateBulkOperationStatusRequest() { BulkOperationId = response.BulkOperations.BulkOperationID, Status = BulkOperationStatus.Failed }); } } accountService.UpdateBulkOperationStatus(new UpdateBulkOperationStatusRequest() { BulkOperationId = response.BulkOperations.BulkOperationID, Status = BulkOperationStatus.Created }); response = accountService.GetQueuedBulkOperationData(new GetBulkOperationDataRequest() { }); } catch (Exception exe) { Logger.Current.Error("Error while BulkOperation Ready Processor Processing", exe); accountService.UpdateBulkOperationStatus(new UpdateBulkOperationStatusRequest() { BulkOperationId = response.BulkOperations.BulkOperationID, Status = BulkOperationStatus.Failed }); response = accountService.GetQueuedBulkOperationData(new GetBulkOperationDataRequest() { }); } } } catch (Exception ex) { Logger.Current.Error("Error while BulkOperation Ready Processor", ex); accountService.UpdateBulkOperationStatus(new UpdateBulkOperationStatusRequest() { BulkOperationId = response.BulkOperations.BulkOperationID, Status = BulkOperationStatus.Failed }); } }
public ActionResult EditPost(PostViewModel postView) { try { if (!base.ModelState.IsValid) { base.ModelState.AddModelError("", MessageUI.ErrorMessage); } else { Post byId = this._postService.GetById(postView.Id); string str = postView.Title.NonAccent(); IEnumerable <MenuLink> bySeoUrl = this._menuLinkService.GetBySeoUrl(str); postView.SeoUrl = postView.Title.NonAccent(); if (bySeoUrl.Any <MenuLink>((MenuLink x) => x.Id != postView.Id)) { PostViewModel postViewModel = postView; postViewModel.SeoUrl = string.Concat(postViewModel.SeoUrl, "-", bySeoUrl.Count <MenuLink>()); } HttpFileCollectionBase files = base.Request.Files; if (postView.Image != null && postView.Image.ContentLength > 0) { string str1 = string.Format("{0}-{1}", str, App.Utils.Utils.GetTime()); string str2 = string.Format("{0}-{1}", str, App.Utils.Utils.GetTime()); string str3 = string.Format("{0}-{1}", str, App.Utils.Utils.GetTime()); this._imagePlugin.CropAndResizeImage(postView.Image, string.Format("{0}/{1}/", Contains.PostFolder, str), str1, new int?(ImageSize.WithBigSize), new int?(ImageSize.HeightBigSize), false); this._imagePlugin.CropAndResizeImage(postView.Image, string.Format("{0}/{1}/", Contains.PostFolder, str), str2, new int?(ImageSize.WithMediumSize), new int?(ImageSize.HeightMediumSize), false); this._imagePlugin.CropAndResizeImage(postView.Image, string.Format("{0}/{1}/", Contains.PostFolder, str), str3, new int?(ImageSize.WithSmallSize), new int?(ImageSize.HeightSmallSize), false); postView.ImageBigSize = string.Format("{0}/{1}/{2}", Contains.PostFolder, str, str1); postView.ImageMediumSize = string.Format("{0}/{1}/{2}", Contains.PostFolder, str, str2); postView.ImageSmallSize = string.Format("{0}/{1}/{2}", Contains.PostFolder, str, str3); } int?menuId = postView.MenuId; int i = 0; if ((menuId.GetValueOrDefault() > i ? menuId.HasValue : false)) { IMenuLinkService menuLinkService = this._menuLinkService; menuId = postView.MenuId; MenuLink menuLink = menuLinkService.GetById(menuId.Value); postView.VirtualCatUrl = menuLink.VirtualSeoUrl; postView.VirtualCategoryId = menuLink.VirtualId; } List <GalleryImage> galleryImages = new List <GalleryImage>(); if (files.Count > 0) { int count = files.Count - 1; int num = 0; string[] allKeys = files.AllKeys; for (i = 0; i < (int)allKeys.Length; i++) { string str4 = allKeys[i]; if (num <= count) { if (!str4.Equals("Image")) { HttpPostedFileBase item = files[num]; if (item.ContentLength > 0) { GalleryImageViewModel galleryImageViewModel = new GalleryImageViewModel() { PostId = postView.Id }; string str5 = string.Format("{0}-{1}", str, App.Utils.Utils.GetTime()); string str6 = string.Format("{0}-{1}", str, App.Utils.Utils.GetTime()); this._imagePlugin.CropAndResizeImage(item, string.Format("{0}/{1}/", Contains.PostFolder, str), str5, new int?(ImageSize.WithOrignalSize), new int?(ImageSize.HeighthOrignalSize), false); this._imagePlugin.CropAndResizeImage(item, string.Format("{0}/{1}/", Contains.PostFolder, str), str6, new int?(ImageSize.WithThumbnailSize), new int?(ImageSize.HeightThumbnailSize), false); galleryImageViewModel.ImageThumbnail = string.Format("{0}/{1}/{2}", Contains.PostFolder, str, str6); galleryImageViewModel.ImagePath = string.Format("{0}/{1}/{2}", Contains.PostFolder, str, str5); galleryImageViewModel.OrderDisplay = num; galleryImageViewModel.Status = 1; galleryImageViewModel.Title = postView.Title; galleryImages.Add(Mapper.Map <GalleryImage>(galleryImageViewModel)); } num++; } else { num++; } } } } if (galleryImages.IsAny <GalleryImage>()) { byId.GalleryImages = galleryImages; } byId = Mapper.Map <PostViewModel, Post>(postView, byId); this._postService.Update(byId); ((dynamic)base.ViewBag).Message = "Cập nhật tin rao thành công"; return(base.View(postView)); } } catch (Exception exception1) { Exception exception = exception1; base.ModelState.AddModelError("", exception.Message); ExtentionUtils.Log(string.Concat("Post.Edit: ", exception.Message)); } ((dynamic)base.ViewBag).Message = "Cập nhật tin rao KHÔNG thành công"; return(base.View(postView)); }
public ActionResult Create([Bind] OrderViewModel order, string ReturnUrl) { ActionResult action; try { if (!base.ModelState.IsValid) { base.ModelState.AddModelError("", MessageUI.ErrorMessage); return(base.View(order)); } else { HttpFileCollectionBase files = base.Request.Files; List <OrderGallery> orderGalleries = new List <OrderGallery>(); if (files.Count > 0) { int count = files.Count - 1; int num = 0; string[] allKeys = files.AllKeys; for (int i = 0; i < (int)allKeys.Length; i++) { string str = allKeys[i]; if (num <= count) { if (!str.Equals("Image")) { HttpPostedFileBase httpPostedFileBase = files[num]; if (httpPostedFileBase.ContentLength > 0) { OrderGalleryViewModel orderGalleryViewModel = new OrderGalleryViewModel() { OrderId = order.Id }; string str1 = string.Format("{0}-{1}.jpg", order.OrderCode, Guid.NewGuid()); this._imagePlugin.CropAndResizeImage(httpPostedFileBase, string.Format("{0}{1}/", Contains.ImageFolder, order.OrderCode), str1, new int?(ImageSize.WithBigSize), new int?(ImageSize.WithBigSize), false); orderGalleryViewModel.ImagePath = string.Format("{0}{1}/{2}", Contains.ImageFolder, order.OrderCode, str1); orderGalleries.Add(Mapper.Map <OrderGallery>(orderGalleryViewModel)); } num++; } else { num++; } } } } Order order1 = Mapper.Map <OrderViewModel, Order>(order); if (orderGalleries.IsAny <OrderGallery>()) { order1.OrderGalleries = orderGalleries; } List <OrderItem> orderItems = new List <OrderItem>(); if (order.OrderItems.IsAny <OrderItemViewModel>()) { orderItems.AddRange( from item in order.OrderItems select Mapper.Map <OrderItem>(item)); } if (orderItems.IsAny <OrderItem>()) { order1.OrderItems = orderItems; } this._orderService.Create(order1); base.Response.Cookies.Add(new HttpCookie("system_message", string.Format(MessageUI.CreateSuccess, FormUI.Order))); if (!base.Url.IsLocalUrl(ReturnUrl) || ReturnUrl.Length <= 1 || !ReturnUrl.StartsWith("/") || ReturnUrl.StartsWith("//") || ReturnUrl.StartsWith("/\\")) { action = base.RedirectToAction("Index"); } else { action = this.Redirect(ReturnUrl); } } } catch (Exception exception1) { Exception exception = exception1; ExtentionUtils.Log(string.Concat("Order.Create: ", exception.Message)); base.ModelState.AddModelError("", exception.Message); return(base.View(order)); } return(action); }