public ActionResult Edit(CustomerNote customernote, string Id, HttpPostedFileBase file) { CustomerNote noteToEdit = customernoteContext.Find(Id); if (noteToEdit == null) { return(HttpNotFound()); } else { if (!ModelState.IsValid) { return(View(customernote)); } noteToEdit.CustomerId = customernote.CustomerId; noteToEdit.UserName = customernote.UserName; noteToEdit.Category = customernote.Category; noteToEdit.NoteBody = customernote.NoteBody; noteToEdit.CustomerId = customernote.CustomerId; noteToEdit.CreatedAt = customernote.CreatedAt; customernoteContext.Commit(); return(RedirectToAction("Index")); } }
public CustomerNote DetailCustomerNote(int?NoteId) { var results = (from brd in context.CustomerNotes join urs in context.UserProfiles on brd.CreateId equals urs.UserId into bru from uid in bru.DefaultIfEmpty() where brd.NoteId == NoteId select new { brd.NoteId, brd.CustomerId, brd.NoteContents, brd.NoteStatus, brd.CreateId, brd.CreateDt, FullName = uid.FirstName + " " + uid.LastName }).FirstOrDefault(); var viweModel = new CustomerNote { NoteId = results.NoteId, CustomerId = results.CustomerId, NoteContents = results.NoteContents, NoteStatus = results.NoteStatus, CreateId = results.CreateId, CreateDt = results.CreateDt, FullName = results.FullName }; return(viweModel); }
public async Task <IActionResult> Edit(Guid id, [Bind("ID,CreatedDateUtc,IsActive,Name,Description")] CustomerNote customerNote) { if (id != customerNote.ID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(customerNote); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CustomerNoteExists(customerNote.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(customerNote)); }
public override bool Equals(object obj) { if (obj == null) { return(false); } if (obj == this) { return(true); } return(obj is Booking other && ((Id == null && other.Id == null) || (Id?.Equals(other.Id) == true)) && ((Version == null && other.Version == null) || (Version?.Equals(other.Version) == true)) && ((Status == null && other.Status == null) || (Status?.Equals(other.Status) == true)) && ((CreatedAt == null && other.CreatedAt == null) || (CreatedAt?.Equals(other.CreatedAt) == true)) && ((UpdatedAt == null && other.UpdatedAt == null) || (UpdatedAt?.Equals(other.UpdatedAt) == true)) && ((StartAt == null && other.StartAt == null) || (StartAt?.Equals(other.StartAt) == true)) && ((LocationId == null && other.LocationId == null) || (LocationId?.Equals(other.LocationId) == true)) && ((CustomerId == null && other.CustomerId == null) || (CustomerId?.Equals(other.CustomerId) == true)) && ((CustomerNote == null && other.CustomerNote == null) || (CustomerNote?.Equals(other.CustomerNote) == true)) && ((SellerNote == null && other.SellerNote == null) || (SellerNote?.Equals(other.SellerNote) == true)) && ((AppointmentSegments == null && other.AppointmentSegments == null) || (AppointmentSegments?.Equals(other.AppointmentSegments) == true))); }
private IList <CustomerNote> ExecuteLoadCustomerNotes(SqlParameter[] sqlParameters) { IList <CustomerNote> customerNotes = new List <CustomerNote>(); using (SqlConnection connection = CreateConnection()) { using (SqlDataReader dataReader = SqlHelper.ExecuteReader(connection, CommandType.StoredProcedure, "NotesCurrent_GetCustomerNotes", sqlParameters)) { CleverReader cleverReader = new CleverReader(dataReader); while (!cleverReader.IsNull && cleverReader.Read()) { string parsedNotes = CustomerNotesParser.Parse(cleverReader.ToString("notes")); CustomerNote customerNote = new CustomerNote(cleverReader.FromBigInteger("NotesID"), cleverReader.ToDate("Created"), ActivityType.Parse(cleverReader.ToInteger("ActivityTypeId")), NoteType.Parse(cleverReader.ToInteger("NoteTypeId")), parsedNotes, cleverReader.ToInteger("CreatedBy"), cleverReader.ToString("EmployeeName"), cleverReader.ToInteger("ModifiedBy"), cleverReader.ToString("ModifiedByEmployeeName"), cleverReader.ToDate("Modified") ); customerNotes.Add(customerNote); } } } return(customerNotes); }
public override int GetHashCode() { unchecked { var hashCode = Billing != null?Billing.GetHashCode() : 0; hashCode = (hashCode * 397) ^ (CartHash != null ? CartHash.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (CartTax != null ? CartTax.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (CreatedVia != null ? CreatedVia.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Currency != null ? Currency.GetHashCode() : 0); hashCode = (hashCode * 397) ^ CustomerId; hashCode = (hashCode * 397) ^ (CustomerIpAddress != null ? CustomerIpAddress.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (CustomerNote != null ? CustomerNote.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (CustomerUserAgent != null ? CustomerUserAgent.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (DiscountTax != null ? DiscountTax.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (DiscountTotal != null ? DiscountTotal.GetHashCode() : 0); hashCode = (hashCode * 397) ^ Id; hashCode = (hashCode * 397) ^ (Number != null ? Number.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (OrderKey != null ? OrderKey.GetHashCode() : 0); hashCode = (hashCode * 397) ^ ParentId; hashCode = (hashCode * 397) ^ (PaymentMethod != null ? PaymentMethod.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (PaymentMethodTitle != null ? PaymentMethodTitle.GetHashCode() : 0); hashCode = (hashCode * 397) ^ PricesIncludeTax.GetHashCode(); hashCode = (hashCode * 397) ^ (Shipping != null ? Shipping.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (ShippingTax != null ? ShippingTax.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (ShippingTotal != null ? ShippingTotal.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Status != null ? Status.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Total != null ? Total.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (TotalTax != null ? TotalTax.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (TransactionId != null ? TransactionId.GetHashCode() : 0); hashCode = (hashCode * 397) ^ (Version != null ? Version.GetHashCode() : 0); return(hashCode); } }
protected void SaveButton_Click(object sender, ImageClickEventArgs e) { int employeeId = CurrentPrincipal.CffUser.EmployeeId; ICffCustomer xCustomer = (SessionWrapper.Instance.Get != null) ? SessionWrapper.Instance.Get.CustomerFromQueryString : (!string.IsNullOrWhiteSpace(QueryString.ViewIDValue)) ? SessionWrapper.Instance.GetSession(QueryString.ViewIDValue).CustomerFromQueryString : null; if (PermanentNoteCheckBox.Checked) { var permanentNote = new PermanentCustomerNote(CommentTextBox.EncodedText, ((xCustomer == null)?0:xCustomer.Id), employeeId); presenter.SavePermanentNote(permanentNote); } else { if (!string.IsNullOrEmpty(NextCallDueTextBox.EncodedText)) { var calendar = new Calendar(); var nextCallDueDate = new Date(DateTime.Parse(NextCallDueTextBox.EncodedText)); presenter.UpdateCustomerNextCallDue(nextCallDueDate, ((xCustomer == null) ? 0 : xCustomer.Id), calendar.Now, employeeId); if (NextCallDueUpdated != null) { NextCallDueUpdated(nextCallDueDate, new EventArgs()); } } ActivityType activityType = ActivityType.Parse(int.Parse(ActivityTypeDropDownList.SelectedValue)); NoteType noteType = NoteType.Parse(int.Parse(NoteTypeDropDownList.SelectedValue)); var customerNote = new CustomerNote(activityType, noteType, CommentTextBox.EncodedText, ((xCustomer == null) ? 0 : xCustomer.Id), employeeId); presenter.SaveCustomerNote(customerNote); } }
public int SaveNote(CustomerNote noteInfo) { if (string.IsNullOrEmpty(noteInfo.NoteId.ToString()) || noteInfo.NoteId == 0) { noteInfo.UpdateDt = DateTime.Now; noteInfo.CreateDt = DateTime.Now; noteInfo.CreateId = System.Web.HttpContext.Current.User.Identity.GetUserId(); noteInfo.UpdateId = System.Web.HttpContext.Current.User.Identity.GetUserId(); context.CustomerNotes.Add(noteInfo); context.SaveChanges(); } else { var updateRow = (from note in context.CustomerNotes where note.NoteId == noteInfo.NoteId select note).Single(); updateRow.NoteContents = noteInfo.NoteContents; updateRow.UpdateDt = DateTime.Now; updateRow.UpdateId = System.Web.HttpContext.Current.User.Identity.GetUserId(); } return(noteInfo.NoteId);; }
public LiquidCustomer(Customer customer, Store store, CustomerNote customerNote = null) { _customer = customer; _customerNote = customerNote; _store = store; AdditionalTokens = new Dictionary <string, string>(); }
public IList <CustomerNote> LoadAllCustomerNotesForClientOnRange(int clientId, DateRange dateRange) { //we make use of CFF's DataEntry DLL as the stored procedure for this method is already defined, so we just reuse it. //where clientid=-1 : Load All Client's Customer Notes within a given date range //where clientid>0 : Load All Customer notes within a given date range for this client DataEntry.Clients mClient = new DataEntry.Clients(); ArrayList arrPar = new ArrayList(); int yrmth = Convert.ToInt32(DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString()); if (dateRange != null) { yrmth = Convert.ToInt32(dateRange.EndDate.Year.ToString() + dateRange.EndDate.Month.ToString().PadLeft(2, '0')); } arrPar.Add(1); //whichnotes arrPar.Add(clientId); arrPar.Add(yrmth); if (dateRange == null) { arrPar.Add(DateTime.Now.ToShortDateString() + " 11:59:59 pm"); } else { arrPar.Add(String.Format("{0:MM/dd/yyyy}", dateRange.StartDate) + " 23:59:59 pm"); //arrPar.Add(System.Convert.ToDateTime(dateRange.StartDate.ToShortDateString() + " 23:59:59 pm")); } if (dateRange == null) { arrPar.Add(DateTime.Now.ToShortDateString() + " 11:59:59 pm"); } else { arrPar.Add(String.Format("{0:MM/dd/yyyy}", dateRange.EndDate) + " 23:59:59 pm"); //arrPar.Add(System.Convert.ToDateTime(dateRange.EndDate.ToShortDateString() + " 23:59:59 pm")); } System.Data.DataSet theDS = mClient.getClientNotes(arrPar); IList <CustomerNote> custNoteList = new List <CustomerNote>(); if (theDS != null) { for (int ix = 0; ix < theDS.Tables[0].Rows.Count; ix++) { DataRow DR = theDS.Tables[0].Rows[ix]; CustomerNote custNoteDetail = new CustomerNote(Convert.ToInt64(DR["NotesId"]), new Date(Convert.ToDateTime(DR["Created"])), ActivityType.Parse(Convert.ToInt32(DR["ActivityTypeId"])), NoteType.Parse(Convert.ToInt32(DR["NoteTypeId"])), DR["notes"].ToString(), Convert.ToInt32(DR["CreatedBy"]), DR["CreatedByEmpName"].ToString(), Convert.ToInt32(DR["ModifiedBy"]), DR["LastModifiedBy"].ToString(), new Date(Convert.ToDateTime(DR["Modified"])), DR["Customer"].ToString(), Convert.ToInt32(DR["custid"]), DR["authorRole"].ToString(), ((clientId > 0)?clientId:Convert.ToInt32(DR["ClientID"].ToString())) ); custNoteList.Add(custNoteDetail); } } return(custNoteList); }
internal static void AssertEqual(this CustomerNote expected, ICustomerCompanyNoteReturn result) { Assert.AreEqual(expected.ToCustomerNoteKey().KeyValue, result.NoteKey); Assert.AreEqual(expected.Bold, result.DisplayBold); Assert.AreEqual(expected.Type, result.NoteType); Assert.AreEqual(expected.Text, result.Text); Assert.AreEqual(expected.TimeStamp, result.TimeStamp); expected.Employee.AssertEqual(result.CreatedByUser); }
public void PopulateCustomerNotesControls(CustomerNote selectedCustomerNote) { PopulateNoteTypes(NoteType.KnownTypesForNewNotes); PopulateActivityTypes(ActivityType.KnownTypesForNewNotes); CommentEditTextBox.Text = EncodedText(CustomerNotesParser.RemoveBr(selectedCustomerNote.Comment)); ActivityTypeDropDownList.SelectedValue = selectedCustomerNote.ActivityType.Id.ToString(); NoteTypeDropDownList.SelectedValue = selectedCustomerNote.NoteType.Id.ToString(); }
public void UpdateCustomerNote(long noteId, ActivityType activityType, NoteType noteType, string comment, int modifiedBy) { ArgumentChecker.ThrowIfNullOrEmpty(comment, "comment"); CustomerNote customerNote = new CustomerNote(noteId, activityType, noteType, comment, modifiedBy); repository.UpdateCustomerNote(customerNote); view.DisplayFeedback(); }
/// <summary> /// Formats the customer note text /// </summary> /// <param name="customerNote">Customer note</param> /// <returns>Formatted text</returns> public static string FormatCustomerNoteText(this CustomerNote customerNote) { if (customerNote == null) { throw new ArgumentNullException("customerNote"); } return(FormatText.ConvertText(customerNote.Note)); }
public LiquidCustomer(Customer customer, Store store, Language language, CustomerNote customerNote = null) { this._customer = customer; this._customerNote = customerNote; this._store = store; this._language = language; AdditionalTokens = new Dictionary <string, string>(); }
public void AddCustomerTokens(LiquidObject liquidObject, Customer customer, CustomerNote customerNote = null) { var liquidCustomer = new LiquidCustomer(customer, customerNote); liquidObject.Customer = liquidCustomer; _eventPublisher.EntityTokensAdded(customer, liquidCustomer, liquidObject); _eventPublisher.EntityTokensAdded(customerNote, liquidCustomer, liquidObject); }
public void Show(CustomerNote selectedCustomerNote) { PopulateCustomerNotesControls(selectedCustomerNote); ViewState.Add(SelectedNote, selectedCustomerNote); CustomerNoteDescriptors.Visible = true; Visible = true; BlockScreen(); }
public void InsertCustomerNote(CustomerNote customerNote) { ArgumentChecker.ThrowIfNull(customerNote, "customerNote"); using (SqlConnection connection = CreateConnection()) { SqlHelper.ExecuteNonQuery(connection, CommandType.StoredProcedure, "NotesCurrent_InsertNewNotes", CreateSaveCustomerNoteParameters(customerNote)); } }
/// <summary> /// Deletes an customer note /// </summary> /// <param name="customerNote">The customer note</param> public virtual async Task DeleteCustomerNote(CustomerNote customerNote) { if (customerNote == null) { throw new ArgumentNullException(nameof(customerNote)); } await _customerNoteRepository.DeleteAsync(customerNote); //event notification await _mediator.EntityDeleted(customerNote); }
public async Task <IActionResult> Create([Bind("ID,CreatedDateUtc,IsActive,Name,Description")] CustomerNote customerNote) { if (ModelState.IsValid) { customerNote.ID = Guid.NewGuid(); _context.Add(customerNote); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(customerNote)); }
// GET: /CustomerNoteManager/Edit Page public ActionResult Edit(string Id) { CustomerNote customernote = customernoteContext.Find(Id); if (customernote == null) { return(HttpNotFound()); } else { return(View(customernote)); } }
public ActionResult DeleteCustomerNote(int CustomerNoteID) { CustomerNote objF = new CustomerNote(); if (objF.Delete(CustomerNoteID)) { return(Json("0")); } else { return(Json("There was an error deleting the customer.")); } }
public ActionResult SaveCustomerNote(CustomerNote noteInfo) { if (ModelState.IsValid) { int notetId = dbCust.SaveNote(noteInfo); return(Json(dbCust.DetailCustomerNote(notetId), JsonRequestBehavior.AllowGet)); } else { return(Json(new { success = false, SaveError = "Not Saved" }, JsonRequestBehavior.AllowGet)); } }
public ActionResult Create(CustomerNote customernote, HttpPostedFileBase file) { if (!ModelState.IsValid) { return(View(customernote)); } else { customernoteContext.Insert(customernote); customernoteContext.Commit(); return(RedirectToAction("Index")); } }
private void SaveCustomerNote(int employeeId, string comment, int customerId, ActivityType activityType, NoteType noteType) { if (!string.IsNullOrEmpty(comment)) { //comment = comment.Replace("\n", ";"); //dbb comment = comment.Replace("\n", " "); } var customerNote = new CustomerNote(activityType, noteType, comment, customerId, employeeId); presenter.SaveCustomerNote(customerNote); }
private void UpdateCustomerNote(object orginalNote, int modifiedBy, string newComment) { newComment = newComment.Replace("&", "&"); NoteType noteType = NoteType.Parse(int.Parse(NoteTypeDropDownList.SelectedValue)); ActivityType activityType = ActivityType.Parse(int.Parse(ActivityTypeDropDownList.SelectedValue)); CustomerNote originalCustomerNote = orginalNote as CustomerNote; if (originalCustomerNote != null) { presenter.UpdateCustomerNote(originalCustomerNote.NoteId, activityType, noteType, newComment, modifiedBy); } }
// GET: /CustomerNoteManager/Delete Page public ActionResult Delete(string Id) { CustomerNote noteToDelete = customernoteContext.Find(Id); if (noteToDelete == null) { return(HttpNotFound()); } else { return(View(noteToDelete)); } }
public CustomerNote Save(CustomerNote customerNote) { var url = string.Format("CustomerNote/Save?apikey={0}&companyid={1}", _apiKey, _companyId); var request = new RestRequest(url, Method.POST) { JsonSerializer = new JsonSerializer() }; request.RequestFormat = DataFormat.Json; request.AddBody(customerNote); var response = _client.Execute <CustomerNote>(request); return(response.Data); }
public ActionResult AddCustomerNote(CustomerNote CustomerNote) { CustomerNote.DateAdded = DateTime.Now; CustomerNote.AddedBy = base.Associate.AssociateID; if (CustomerNote.Update()) { return(Json("1")); } else { return(Json("0")); } }
public ActionResult ConfirmDelete(string Id) { CustomerNote noteToDelete = customernoteContext.Find(Id); if (noteToDelete == null) { return(HttpNotFound()); } else { customernoteContext.Delete(Id); customernoteContext.Commit(); return(RedirectToAction("Index")); } }
protected Customer GetCustomer(Guid consultantKey, DateTime utcNow, bool toAdd = false) { var customer = new Customer { ConsultantKey = consultantKey, CustomerId = toAdd ? Guid.NewGuid() : CustomerId, Addresses = Addresses.Values.ToDictionary<Address, Guid>(address => address.AddressKey), ContactInformation = ContactInformation, EmailAddress = EmailAddress }; if (!string.IsNullOrWhiteSpace(ExternalPictureUrl)) { //This is where to add the facebook picture url if there is one } if (!string.IsNullOrWhiteSpace(Notes)) { var noteKey = Guid.NewGuid(); var note = new CustomerNote { ConsultantKey = consultantKey, CustomerId = CustomerId, CustomerNoteKey = Guid.NewGuid(), NoteType = CustomerNoteType.RegularNote, DateCreatedUtc = utcNow, Content = Notes }; customer.Notes = new Dictionary<Guid, CustomerNote>(1); customer.Notes.Add(note.CustomerNoteKey, note); } customer.PhoneNumbers = PhoneNumbers.Values.ToDictionary<PhoneNumber, Guid>(phoneNumber => phoneNumber.PhoneNumberKey); customer.SpecialOccasions = SpecialOccasions.Values.ToDictionary<SpecialOccasion, Guid>(specialOccasion => specialOccasion.SpecialOccasionKey); customer.HyperLinks = Hyperlinks.Values.ToDictionary<HyperLink, Guid>(hyperLinks => hyperLinks.HyperLinkKey); foreach (KeyValuePair<Guid, HyperLink> link in customer.HyperLinks) { link.Value.CustomerId = customer.CustomerId; } // this was put in because quarted complained about it not being there even though we don't have this information to import if (customer.PersonalInformation == null) customer.PersonalInformation = new PersonalInformation(); return customer; }
public ActionResult Add(CustomerAccountWithEmployeeModel m, string command, FormCollection fc ) { if (command.ToLower() == "cancel") return RedirectToAction("Index"); SemplestModel.Semplest dbcontext = new SemplestModel.Semplest(); //check if userid has been taken by other users var userIDSs = from c in dbcontext.Credentials where c.Username.Equals(m.CustomerAccount.UserID) select c; if (userIDSs.Count() > 0) ModelState.AddModelError("CustomerAccount.UserID", "This UserID is already taken!!"); if (!ModelState.IsValid) { //repopulate #region needs to repopulate lists to get the same view again var roles = (from r in dbcontext.Roles select r).ToList().OrderBy(r => r.RoleName); m.Roles = roles.Select(r => new SelectListItem { Value = r.RolePK.ToString(), Text = r.RoleName.ToString() }); //repopualte var allreps = from e in dbcontext.Employees //join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID join u in dbcontext.Users on e.UsersFK equals u.UserPK where (et.EmployeeType1 == "Rep" && u.IsActive.Equals(true)) select new EmployeeCustomerAssociaitionModel { //AccountNumber = eca.CustomerFK, employeePK = e.EmployeePK, EmployeeType = et.EmployeeType1, EmployeeUserPK = u.UserPK, FirstName = u.FirstName, MiddleInitial = u.MiddleInitial, LastName = u.LastName }; ///////////////////////////////////////////////////////////////////////////////// //for sales dropdown ///////////////////////////////////////////////////////////////////////////////// var allsalespersons = from e in dbcontext.Employees //join eca in dbcontext.EmployeeCustomerAssociations on e.EmployeePK equals eca.EmployeeFK join et in dbcontext.EmployeeTypes on e.EmployeeTypeFK equals et.EmployeeTypeID join u in dbcontext.Users on e.UsersFK equals u.UserPK where (et.EmployeeType1 == "Sales" && u.IsActive.Equals(true)) select new EmployeeCustomerAssociaitionModel { //AccountNumber = eca.CustomerFK, employeePK = e.EmployeePK, EmployeeType = et.EmployeeType1, EmployeeUserPK = u.UserPK, FirstName = u.FirstName, MiddleInitial = u.MiddleInitial, LastName = u.LastName }; var allparents = from c in dbcontext.Customers join chi in dbcontext.CustomerHierarchies.Where(p => p.CustomerParentFK == null) on c.CustomerPK equals chi.CustomerFK select c; List<SelectListItem> sli = new List<SelectListItem>(); sli.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Parent »»" }); sli.Add(new SelectListItem { Value = (0).ToString(), Text = "«« Single User »»" }); //x.SelectedParentID = -1; m.Parents = allparents.ToList().Select(r => new SelectListItem { Value = r.CustomerPK.ToString(), Text = r.Name.ToString() }).Union(sli); ///////////////////////////////////////////////////////////////////////////////// //for billtype dropdown ///////////////////////////////////////////////////////////////////////////////// var allbilltypes = (from a in dbcontext.BillTypes select a).ToList(); m.BillTypes = allbilltypes.Select(r => new SelectListItem { Value = r.BillTypePK.ToString(), Text = r.BillType1.ToString() }); //for state dropdown ///////////////////////////////////////////////////////////////////////////////// var allstates = (from sc in dbcontext.StateCodes select sc).ToList(); m.States = allstates.Select(r => new SelectListItem { Value = r.StateAbbrPK.ToString(), Text = r.StateAbbr.ToString() }); List<SelectListItem> slina = new List<SelectListItem>(); slina.Add(new SelectListItem { Value = (-1).ToString(), Text = "«« Not Assigned »»" }); List<EmployeeCustomerAssociaitionModel> ll1 = allreps.OrderBy(r => r.LastName).ThenBy(r => r.FirstName).ToList(); ; List<SelectListItem> sl1 = new List<SelectListItem>(); foreach (EmployeeCustomerAssociaitionModel s in ll1) { SelectListItem mylistitem = new SelectListItem(); mylistitem.Text = s.FirstName + " " + s.LastName; mylistitem.Value = s.employeePK.ToString(); sl1.Add(mylistitem); } m.Reps = sl1.Union(slina); List<EmployeeCustomerAssociaitionModel> ll2 = allsalespersons.OrderBy(r => r.LastName).ThenBy(r => r.FirstName).ToList(); List<SelectListItem> sl2 = new List<SelectListItem>(); foreach (EmployeeCustomerAssociaitionModel s in ll2) { SelectListItem mylistitem = new SelectListItem(); mylistitem.Text = s.FirstName + " " + s.LastName; mylistitem.Value = s.employeePK.ToString(); sl2.Add(mylistitem); } m.SalesPersons = sl2.Union(slina); return View(m); #endregion } try { //BillType bt = dbcontext.BillTypes.First(p => p.BillType1 == "Flat Fee"); // --- feees --- !!! //revisit ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30"); var c = new Customer { Name = m.CustomerAccount.Customer, BillTypeFK = m.SelectedBillTypeID, ProductGroupCycleType = pgct, PercentOfMedia=m.CustomerAccount.PercentMedia, ServiceFee= m.CustomerAccount.ServiceFee, InternalCustomerId= m.CustomerAccount.internalID, PromotionFeeAmount = m.CustomerAccount.PromotionFeeAmount, CreditLimit=m.CustomerAccount.CreditLimit, PromotionFeeOverride=m.CustomerAccount.PromotionFeeOverride }; dbcontext.Customers.Add(c); var u = new User { Customer = c, Email = m.CustomerAccount.Email, FirstName = m.CustomerAccount.FirstName, LastName = m.CustomerAccount.LastName, MiddleInitial = m.CustomerAccount.MiddleInitial, IsActive = m.CustomerAccount.isActive }; dbcontext.Users.Add(u); var r = dbcontext.Roles.First(p => p.RolePK == m.SelectedRoleID); var ura = new UserRolesAssociation { Role = r, User = u }; dbcontext.UserRolesAssociations.Add(ura); // var cr = new Credential { User = u, UsersFK = u.UserPK, Username = m.CustomerAccount.UserID, Password = m.CustomerAccount.UserPassword }; dbcontext.Credentials.Add(cr); PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!! var ph = new Phone {Phone1 = m.CustomerAccount.Phone, PhoneType = pt}; dbcontext.Phones.Add(ph); var cpa = new CustomerPhoneAssociation {Customer = c, Phone = ph}; dbcontext.CustomerPhoneAssociations.Add(cpa); var sc = dbcontext.StateCodes.First(p => p.StateAbbrPK == m.SelectedStateID); var at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!! var a = new Address { Address1 = m.CustomerAccount.Address1, Address2 = m.CustomerAccount.Address2, City = m.CustomerAccount.City, ZipCode = m.CustomerAccount.Zip, StateCode = sc }; dbcontext.Addresses.Add(a); var caa = new CustomerAddressAssociation {Address = a, Customer = c, AddressType = at}; dbcontext.CustomerAddressAssociations.Add(caa); var cn = new CustomerNote {Customer = c, Note = m.CustomerAccount.CustomerNote}; dbcontext.CustomerNotes.Add(cn); //don't add if not assigned if (m.SelectedRepID != -1) { var addrep = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedRepID }; dbcontext.EmployeeCustomerAssociations.Add(addrep); } //don't add if not assigned if (m.SelectedSalesPersonID != -1) { var addsales = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = m.SelectedSalesPersonID }; dbcontext.EmployeeCustomerAssociations.Add(addsales); } CustomerHierarchy ch = null; if (m.SelectedParentID == -1) //set parent { ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = null}; dbcontext.CustomerHierarchies.Add(ch); } else if (m.SelectedParentID == 0) //set self -- single user { ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = c.CustomerPK}; dbcontext.CustomerHierarchies.Add(ch); } else //assign a parent { ch = new CustomerHierarchy {CustomerFK = c.CustomerPK, CustomerParentFK = m.SelectedParentID}; dbcontext.CustomerHierarchies.Add(ch); } dbcontext.SaveChanges(); ///////////////////////////////////////////////////////////////////////////// ///// sending of emails AesEncyrption ae = AesEncyrption.getInstance(); string encryptedToken = ae.GenerateToken(ch.CustomerParentFK.Value.ToString(), DateTime.Now.ToString(), cr.Username, cr.Password); string emailUrl = System.Configuration.ConfigurationManager.AppSettings["VerificationUrl"].ToString() + encryptedToken; if (fc["sendcustomeremail"] != null) { string from, to, body, subject; //send email to child customers //if child customer if (m.SelectedParentID >0) { var emailtemplate = ( from et in dbcontext.EmailTemplates join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK where ey.EmailType1.Equals("WelcomeEmailChild") select et).FirstOrDefault(); var parentdetails = from usr in dbcontext.Users join cus in dbcontext.Customers on usr.CustomerFK equals cus.CustomerPK where usr.CustomerFK == m.SelectedParentID select new { usr.CustomerFK, usr.Email, cus.Name }; //send mail //revisit from = "*****@*****.**"; to = u.Email; body = emailtemplate.EmailBody; //parent name in subject line subject = parentdetails.FirstOrDefault().Name + " " +emailtemplate.EmailSubject; body = body.Replace("[ChildCustomerFirstLast]", u.FirstName.ToString() + " " + u.LastName.ToString()); body = body.Replace("[ParentCustomerName]", parentdetails.FirstOrDefault().Name.ToString()); body = body.Replace("[FAQs]", "http://faq"); body = body.Replace("[ChildCustomerUserID]", cr.Username.ToString()); body = body.Replace("[ChildCustomerPassword]", cr.Password.ToString()); body = body.Replace("[INSERT LINK]", emailUrl); bool sent = false; ServiceClientWrapper scw = new ServiceClientWrapper(); sent = scw.SendEmail(subject, from, to, body); } if (m.SelectedParentID == -1) ///set parent { var emailtemplate = ( from et in dbcontext.EmailTemplates join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK where ey.EmailType1.Equals("WelcomeEmailParent") select et).FirstOrDefault(); //send mail //revisit from = "*****@*****.**"; to = u.Email; body = emailtemplate.EmailBody; subject = emailtemplate.EmailSubject; body = body.Replace("[ParentCustomerName]", c.Name.FirstOrDefault().ToString()); body = body.Replace("[ParentCustomerUserID]", cr.Username.ToString()); body = body.Replace("[ParentCustomerPassword]", cr.Password.ToString()); body = body.Replace("[INSERT LINK]", emailUrl); body = body.Replace("[DefaultEmailContactUS]", dbcontext.Configurations.First().DefaultEmailContactUs.ToString()); bool sent = false; ServiceClientWrapper scw = new ServiceClientWrapper(); sent = scw.SendEmail(subject, from, to, body); } if (m.SelectedParentID ==0) // non child parent customer - self { var emailtemplate = ( from et in dbcontext.EmailTemplates join ey in dbcontext.EmailTypes on et.EmailTypeFK equals ey.EmailTypePK where ey.EmailType1.Equals("WelcomeEmailNonParentUser") select et).FirstOrDefault(); //send mail //revisit from = "*****@*****.**"; to = u.Email; body = emailtemplate.EmailBody; subject = emailtemplate.EmailSubject; body = body.Replace("[NonParentCustomer]", u.FirstName.ToString() + " " + u.LastName.ToString()); body = body.Replace("[NonParentCustomerUserID]", cr.Username.ToString()); body = body.Replace("[NonParentCustomerPassword]", cr.Password.ToString()); body = body.Replace("[INSERT LINK]", emailUrl); bool sent = false; ServiceClientWrapper scw = new ServiceClientWrapper(); sent = scw.SendEmail(subject, from, to, body); } //SendEmail } } catch (Exception ex) { Semplest.SharedResources.Helpers.ExceptionHelper.LogException(ex); } return RedirectToAction("Index"); }
public ActionResult Upload(HttpPostedFileBase uploadFile, CustomerImport imp, FormCollection fc) { string importstatus; importstatus = "The import was the successful.."; SemplestModel.Semplest dbcontext = new SemplestModel.Semplest(); { StringBuilder strValidations = new StringBuilder(string.Empty); try { if (uploadFile.ContentLength > 0) { string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), Path.GetFileName(uploadFile.FileName)); uploadFile.SaveAs(filePath); FileHelperEngine engine = new FileHelperEngine(typeof(CustomerImportData)); engine.ErrorManager.ErrorMode = ErrorMode.SaveAndContinue; CustomerImportData[] customersimported = (CustomerImportData[])engine.ReadFile(filePath); if (engine.ErrorManager.HasErrors) foreach (ErrorInfo err in engine.ErrorManager.Errors) { string s; s = err.LineNumber + " / " + err.RecordString + " / " + err.ExceptionInfo.ToString(); //Console.WriteLine(err.LineNumber); //Console.WriteLine(err.RecordString); //Console.WriteLine(err.ExceptionInfo.ToString()); } if (customersimported.Count() < 1) throw new Exception("No customers could be imported from csv file"); /////////// /////////// foreach (CustomerImportData cust in customersimported) { CustomerAccount m = new CustomerAccount(); #region //cust.ContactCompanyName; //cust.ContactEmail; //cust.ContactFirstName; //cust.ContactLastName; //cust.ContactMiddleInitial; //cust.ContactPhoneNumber; //cust.ContactAddressLine1; //cust.ContactAddressLine2; //cust.ContactCity; //cust.ContactState; //cust.ContactStatus; //cust.ContactZip; //cust.FixedMonthlybudget; //cust.InternalCustomerID; /////// //cust.LocalTargetAddress1; //cust.LocalTargetAddress2; //cust.LocalTargetAddress3; //cust.LocalTargetProximity1; //cust.LocalTargetProximity1; //cust.LocalTargetProximity2; //cust.LocalTargetProximity3; //cust.ParentCompanyName; //ca.Address1; //ca.Address2; //ca.City; //ca.Customer; //ca.Email; //ca.FirstName; //ca.MiddleInitial; //ca.Phone; //ca.State; //ca.UserID; //ca.UserPassword; //ca.Zip; //ca.isActive; #endregion /* //cust.ContactStatus; cust.FixedMonthlybudget; //cust.InternalCustomerID; ///// cust.LocalTargetAddress1; cust.LocalTargetAddress2; cust.LocalTargetAddress3; cust.LocalTargetProximity1; cust.LocalTargetProximity2; cust.LocalTargetProximity3; cust.ParentCompanyName; ///// */ m.internalID = cust.InternalCustomerID; m.Address1 = cust.ContactAddressLine1; m.Address2 = cust.ContactAddressLine2; m.City = cust.ContactCity; m.Customer = cust.ContactCompanyName; m.Email = cust.ContactEmail; m.FirstName = cust.ContactFirstName; m.MiddleInitial = cust.ContactMiddleInitial; m.LastName = cust.ContactLastName; m.Phone = cust.ContactPhoneNumber; m.State = cust.ContactState; m.UserID = cust.ContactEmail; m.UserPassword = Semplest.SharedResources.Helpers.RandomPassword.Generate(8, 10); m.Zip = cust.ContactZip; m.isActive = true; var emailtemplate = (from et in dbcontext.EmailTemplates where et.EmailTemplatePK.Equals(13) select et).FirstOrDefault(); try { var existing = (from ex in dbcontext.Customers where ex.InternalCustomerId.Equals(cust.InternalCustomerID) && ex.Name.Equals(m.Customer) select ex).ToList(); if (existing.Count() > 0) throw new Exception(); ProductGroupCycleType pgct = dbcontext.ProductGroupCycleTypes.First(p => p.ProductGroupCycleType1 == "Product Group Cycle 30"); //Customer c = dbcontext.Customers.Add(new Customer { Name = m.Customer, BillTypeFK = imp.SelectedBillTypeID, ProductGroupCycleType = pgct, InternalCustomerId = cust.InternalCustomerID }); var c = new Customer { Name = m.Customer, BillTypeFK = imp.SelectedBillTypeID, ProductGroupCycleType = pgct, InternalCustomerId = cust.InternalCustomerID }; dbcontext.Customers.Add(c); var u = new User { Customer = c, Email = m.Email, FirstName = m.FirstName, LastName = m.LastName, MiddleInitial = m.MiddleInitial, IsActive = m.isActive }; dbcontext.Users.Add(u); var cr = new Credential { User = u, UsersFK = u.UserPK, Username = m.UserID, Password = m.UserPassword }; dbcontext.Credentials.Add(cr); PhoneType pt = dbcontext.PhoneTypes.First(p => p.PhoneType1 == "Business"); // --- phone types --- !!!! Phone ph = new Phone { Phone1 = m.Phone, PhoneType = pt }; dbcontext.Phones.Add(ph); var cpa = new CustomerPhoneAssociation { Customer = c, Phone = ph }; dbcontext.CustomerPhoneAssociations.Add(cpa); StateCode sc = dbcontext.StateCodes.First(p => p.StateAbbr == m.State); AddressType at = dbcontext.AddressTypes.First(p => p.AddressType1 == "H"); // --- address types --- !!! var a = new Address { Address1 = m.Address1, Address2 = m.Address2, City = m.City, ZipCode = m.Zip, StateCode = sc }; dbcontext.Addresses.Add(a); var caa = new CustomerAddressAssociation { Address = a, Customer = c, AddressType = at }; dbcontext.CustomerAddressAssociations.Add(caa); var cn = new CustomerNote { Customer = c, Note = m.CustomerNote }; dbcontext.CustomerNotes.Add(cn); var r = dbcontext.Roles.First(p => p.RolePK == imp.SelectedRoleID); var ura = new UserRolesAssociation { Role = r, User = u }; dbcontext.UserRolesAssociations.Add(ura); //default to the parent's rep and salesperson var parentrepandsales = (from prs in dbcontext.EmployeeCustomerAssociations where prs.CustomerFK.Equals(imp.ParentID) select prs).ToList(); foreach (EmployeeCustomerAssociation eca in parentrepandsales) { var addrepandsales = new EmployeeCustomerAssociation { Customer = c, EmployeeFK = eca.EmployeeFK }; dbcontext.EmployeeCustomerAssociations.Add(addrepandsales); } //add child to parent in customerhierarchy var ch = new CustomerHierarchy { CustomerFK = c.CustomerPK, CustomerParentFK = imp.ParentID }; dbcontext.CustomerHierarchies.Add(ch); dbcontext.SaveChanges(); if (fc["sendcustomeremail"] != null) { /////////////////////////////////////////////////////////////// //FOR SENDING OUT EMAILS to child customers /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// /// var parentdetails = from usr in dbcontext.Users join cus in dbcontext.Customers on usr.CustomerFK equals cus.CustomerPK where usr.CustomerFK == imp.ParentID select new { usr.CustomerFK, usr.Email, cus.Name }; //send mail //revisit string from = "*****@*****.**"; string to = u.Email; string body = emailtemplate.EmailBody; string subject = emailtemplate.EmailSubject; body = body.Replace("[ChildCustomerFirstLast]", u.FirstName.ToString() + " " + u.LastName.ToString()); body = body.Replace("[ParentCustomerName]", parentdetails.FirstOrDefault().Name.ToString()); body = body.Replace("[FAQs]", "http://faq"); body = body.Replace("[ChildCustomerUserID]", cr.Username.ToString()); body = body.Replace("[ChildCustomerPassword]", cr.Password.ToString()); body = body.Replace("[INSERT LINK]", "http://encrypto"); //SendEmail bool sent = false; ServiceClientWrapper scw = new ServiceClientWrapper(); sent = scw.SendEmail(subject, from, to, body); } } catch (Exception ex) { //Console.WriteLine(ex.TargetSite); SemplestModel.Semplest _dbContext = new SemplestModel.Semplest(); SemplestModel.Error er = new SemplestModel.Error(); er.ErrorMessage = ex.Message+" \r\n "+ex.InnerException +" \r\n "+ex.StackTrace +" \r\n "+ex.Source+" \r\n "+ex.TargetSite; //filterContext.RequestContext.HttpContext.Session //if (HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] == null) // er.UsersFK = 1; //else // er.UsersFK = ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]) == null ? 1 : ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).UsersFK; er.CreatedDate = DateTime.Now; _dbContext.Errors.Add(er); _dbContext.SaveChanges(); var scw = new ServiceClientWrapper(); scw.SendEmail("WebSite Error Message", "*****@*****.**", _dbContext.Configurations.First().OnErrorEmail, er.ErrorMessage); } }//endforeach } else throw new Exception(); } catch (Exception ex) { importstatus = "An error has occured. Please check the file for errors and try again.."; //Console.WriteLine(ex.TargetSite); SemplestModel.Semplest _dbContext = new SemplestModel.Semplest(); SemplestModel.Error er = new SemplestModel.Error(); er.ErrorMessage = ex.Message + " \r\n " + ex.InnerException + " \r\n " + ex.StackTrace + " \r\n " + ex.Source + " \r\n " + ex.TargetSite; //filterContext.RequestContext.HttpContext.Session //if (HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID] == null) // er.UsersFK = 1; //else // er.UsersFK = ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]) == null ? 1 : ((Credential)HttpContext.Current.Session[Semplest.SharedResources.SEMplestConstants.SESSION_USERID]).UsersFK; er.CreatedDate = DateTime.Now; _dbContext.Errors.Add(er); _dbContext.SaveChanges(); var scw = new ServiceClientWrapper(); scw.SendEmail("WebSite Error Message", "*****@*****.**", _dbContext.Configurations.First().OnErrorEmail, er.ErrorMessage); } /* * public Boolean SendEmail(String subject, String from, String recipient, String msgTxt) { var jsonHash = new Dictionary<string, string>(); jsonHash.Add("subject", subject); jsonHash.Add("from", from); jsonHash.Add("recipient", recipient); jsonHash.Add("msgTxt", msgTxt); string jsonstr = JsonConvert.SerializeObject(jsonHash); string returnData = runMethod(_baseURLTest, MAILSERVICEOFFERED, "SendEmail", jsonstr, timeoutMS); var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(returnData); string boolResult = dict.Values.First(); return Convert.ToBoolean(boolResult); } */ //scope.Complete(); } //return View(m); ImportResultModel res = new ImportResultModel(); res.Importresult = importstatus; return RedirectToAction("CustomerImportResult", "AccountService", res ); }