Exemple #1
0
        public ActionResult Add(ContactView contactView)
        {
            //TODO: use auto-mapper
            var contact = new Contact();

            contact.ContactAddress     = contactView.ContactAddress;
            contact.ContactEmail       = contactView.ContactEmail;
            contact.ContactName        = contactView.ContactName;
            contact.ContactMidName     = contactView.ContactMidName;
            contact.ContactSurname     = contactView.ContactSurname;
            contact.ContactPhoneNumber = contactView.ContactPhoneNumber;

            var id = int.Parse(contactView.ContactTypeID);

            contact.ContactType = _contactTypeLogic.GetContactTypeById(id);

            //TODO: fix default login admin
            var authorId = WebSecurity.CurrentUserId;

            contact.User = _userLogic.GetUserById(authorId);

            _contactLogic.AddContact(contact);

            return(RedirectToAction("Index"));
        }
        /// <summary>
        /// Save and update contact details
        /// </summary>
        /// <param name="contact"></param>
        /// <returns></returns>
        public ResponseModel SaveOrUpdateContact(ContactView contact)
        {
            ResponseModel response = new ResponseModel();

            _iAccount.SaveContact(contact);
            return(response);
        }
Exemple #3
0
        /// <summary>
        /// Creates the contact with categories.
        /// </summary>
        /// <param name="exchangeService">The exchange service.</param>
        public static async Task CreateContactWithCategories(ExchangeService exchangeService)
        {
            string  displayName = Guid.NewGuid().ToString();
            Contact contact     = new Contact(exchangeService);

            contact.DisplayName = displayName;
            contact.Department  = "Dept";
            contact.GivenName   = "First Name";
            contact.EmailAddresses.Add(new TypedEmailAddress()
            {
                Address = "*****@*****.**"
            });
            contact.Categories = new List <string>()
            {
                "MyContactCategory"
            };

            await contact.SaveAsync();

            SearchFilter searchFilter = new SearchFilter.IsEqualTo(
                ContactObjectSchema.DisplayName,
                displayName);

            ContactView contactView = new ContactView(10);

            contactView.PropertySet.Add(ContactObjectSchema.Categories);
            FindItemResults <Contact> contacts = await exchangeService.FindItems <Contact>(contactView, searchFilter);

            Assert.AreEqual(
                "MyContactCategory",
                contacts.Items[0].Categories[0]);

            await contacts.Items[0].DeleteAsync();
        }
        public void Test_ContactView()
        {
            ViewBase contactView = new ContactView(10);

            Assert.AreEqual(
                typeof(Contact),
                contactView.ViewType);

            Assert.AreEqual(
                "$top=10&$skip=0",
                contactView.GetUrlQuery());

            contactView.Offset += 8;
            contactView.PropertySet.Expand(ContactObjectSchema.Manager);

            Assert.AreEqual(
                "$top=10&$skip=8&$expand=Manager",
                contactView.GetUrlQuery());

            contactView.ValidateViewTypeSupported(typeof(Contact));

            Assert.ThrowsException <ArgumentException>((() =>
            {
                contactView.ValidateViewTypeSupported(typeof(MailFolder));
            }));
        }
Exemple #5
0
        public ActionResult Edit(ContactView contactView)
        {
            var contact = new Contact();

            //TODO: auto mapping
            contact.ContactId          = contactView.ContactId;
            contact.ContactAddress     = contactView.ContactAddress;
            contact.ContactEmail       = contactView.ContactEmail;
            contact.ContactName        = contactView.ContactName;
            contact.ContactMidName     = contactView.ContactMidName;
            contact.ContactSurname     = contactView.ContactSurname;
            contact.ContactPhoneNumber = contactView.ContactPhoneNumber;

            var id   = int.Parse(contactView.ContactTypeID);
            var type = _contactTypeLogic.GetContactTypeById(id);

            contact.ContactType = type;

            var authorId = WebSecurity.CurrentUserId;
            var user     = _userLogic.GetUserById(authorId);

            contact.User = user;

            _contactLogic.EditContact(contact);

            return(RedirectToAction("Index"));
        }
Exemple #6
0
 public ActionResult WyslijPytanie(ContactView contactView)
 {
     if (ModelState.IsValid)
     {
         EmailService.sendQuestion(contactView.Email, contactView.Content);
         TempData["titleModal"]   = "Powodzenie";
         TempData["contentModal"] = "Wiadomość została wysłana";
         return(RedirectToAction("Kontakt"));
     }
     else
     {
         if (contactView.Email == null)
         {
             TempData["titleModal"]   = "Niepowodzenie";
             TempData["contentModal"] = "Pole e-mail nie może być puste";
             return(RedirectToAction("Kontakt"));
         }
         var email = new System.Net.Mail.MailAddress(contactView.Email);
         if (email.Address != contactView.Email)
         {
             TempData["titleModal"]   = "Niepowodzenie";
             TempData["contentModal"] = "Podano zły adres e-mail";
             return(RedirectToAction("Kontakt"));
         }
         if (contactView.Content == null)
         {
             TempData["titleModal"]   = "Niepowodzenie";
             TempData["contentModal"] = "Treść wiadomości nie może być pusta";
             return(RedirectToAction("Kontakt"));
         }
     }
     return(RedirectToAction("Kontakt"));
 }
Exemple #7
0
        public IActionResult Contact(ContactView model)
        {
            CaptchaResponse response = ValidateCaptcha(Request.Form["g-recaptcha-response"]);

            if (response.Success && ModelState.IsValid)
            {
                try
                {
                    EmailNotification email = new EmailNotification();
                    email.Name    = model.Name;
                    email.Subject = "Message from Resgrid Contact Form";
                    email.From    = model.Email;
                    email.Body    = model.Message;

                    _emailService.Notify(email);

                    model.Result  = "Your message has been sent. We will get back to you within 48 hours M-F.";
                    model.Name    = String.Empty;
                    model.Email   = String.Empty;
                    model.Message = String.Empty;
                }
                catch (Exception ex)
                {
                }


                return(View(model));
            }

            return(View(model));
        }
Exemple #8
0
        public async Task <ContactView> getContactView()
        {
            var contactItems = await _db.Contacts.Where(c => c.isActive).ToListAsync();

            ContactView contactView = new ContactView()
            {
                ContactEmails = new List <string>(),
                ContactPhones = new List <string>()
            };

            foreach (var item in contactItems)
            {
                switch (item.Name)
                {
                case "Address":
                    contactView.Address = item.Value;
                    break;

                case "Email":
                    contactView.ContactEmails.Add(item.Value);
                    break;

                case "Phone":
                    contactView.ContactPhones.Add(item.Value);
                    break;

                case "Vk":
                    contactView.VKHref = item.Value;
                    break;

                case "Facebook":
                    contactView.FacebookHref = item.Value;
                    break;

                case "Instagram":
                    contactView.InstagramHref = item.Value;
                    break;

                case "VkImage":
                    contactView.VKImageHref = item.Value;
                    break;

                case "FacebookImage":
                    contactView.FacebookImageHref = item.Value;
                    break;

                case "InstagramImage":
                    contactView.InstagramImageHref = item.Value;
                    break;

                case "Yandexframe":
                    contactView.YandexFrameSrc = item.Value;
                    break;

                default:
                    break;
                }
            }
            return(contactView);
        }
        public void UpdateContact(ContactModel contact)
        {
            using (ContactDBEntities db = new ContactDBEntities())
            {
                using (var dbContextTransaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        ContactView CT = db.ContactViews.Find(contact.ContactID);
                        CT.FirstName   = contact.FirstName;
                        CT.LastName    = contact.LastName;
                        CT.Phone       = contact.Phone;
                        CT.Email       = contact.Email;
                        CT.Street      = contact.Street;
                        CT.City        = contact.City;
                        CT.State       = contact.State;
                        CT.PostalCode  = contact.PostalCode;
                        CT.DisplayName = contact.DisplayName;

                        db.SaveChanges();

                        dbContextTransaction.Commit();
                    }
                    catch
                    {
                        dbContextTransaction.Rollback();
                    }
                }
            }
        }
Exemple #10
0
        public async Task <bool> SendContactForm(ContactView result)
        {
            var subject = $"[ Wiadomość z formularza ] {result.Subject}";
            var html    = await _renderService.ToHtmlStringAsync("ContactForm", result);

            return(await SendEmail(result.Email, subject, html));
        }
        public ActionResult Edit(ContactView contactView)
        {
            if (ModelState.IsValid)
            {
                var picture = contactView.Image;
                var folder  = "~/Content/Images";

                if (contactView.ImageFile != null)
                {
                    picture = FileHelper.UploadPhoto(contactView.ImageFile, folder);
                    picture = $"{folder}/{picture}";
                }

                var contact = ToContact(contactView);

                contact.Image = picture;

                db.Entry(contact).State = EntityState.Modified;

                db.SaveChanges();

                return(RedirectToAction("Index"));
            }
            return(View(contactView));
        }
        public IActionResult Put(int userId, int contactId, [FromBody] ContactView contactView)
        {
            var user = _apiDbContext.Users.Include(u => u.Contacts).FirstOrDefault(u => u.Id == userId);

            if (user == null)
            {
                return(NotFound($"User[{userId}] not found!"));
            }

            var contact = user.Contacts.FirstOrDefault(c => c.Id == contactId);

            if (contact == null)
            {
                return(NotFound($"Contact[{contactId}] not found!"));
            }

            contact.FirstName   = contactView.FirstName;
            contact.LastName    = contactView.LastName;
            contact.PhoneNumber = contactView.PhoneNumber;

            if (_apiDbContext.SaveChanges() > 0)
            {
                return(StatusCode(StatusCodes.Status200OK));
            }
            else
            {
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
        private void EditContact()
        {
            var v = new ContactView();

            v.DataContext        = ItemSelected;
            ItemSelected.ShowTSL = this.ShowTSL;

            var oldContact = new Contact()
            {
                AreaCode      = ItemSelected.Phone.AreaCode,
                Number        = ItemSelected.Phone.Number,
                NameAbbr      = ItemSelected.Phone.NameAbbr,
                UnitName      = ItemSelected.Phone.UnitName,
                Password      = ItemSelected.Password,
                PhoneNumberId = ItemSelected.Phone.PhoneNumberId,
                TSLAreaCode   = ItemSelected.TSLAreaCode,
                TSLNumber     = ItemSelected.TSLNumber
            };

            this.App.AddLog(string.Format("Thay đổi số điện thoại {0} {1}", oldContact.AreaCode, oldContact.Number), true);

            if (ModalDialog.ShowControl(v, "Sửa danh bạ") == true)
            {
                var service = Proxy.CreateProxy();
                service.SaveContact(ItemSelected.Phone);
                this.App.AddLog(string.Format("Lưu thay đổi số điện thoại {0} {1}", ItemSelected.Phone.AreaCode, ItemSelected.Phone.Number), true);
            }
            else
            {
                ItemSelected.Phone = oldContact;
                this.App.AddLog(string.Format("Hủy thay đổi số điện thoại {0} {1}", oldContact.AreaCode, oldContact.Number), true);
            }

            ItemSelected.Refesh();
        }
        public ContactView GetContactView(int Id)
        {
            ContactView contactView = new ContactView();

             Contact contact = _repository.Get(Id);
             contactView = CreateContactView(contact);

             return contactView;
        }
Exemple #15
0
        public override void OnEnter()
        {
            ContactView contact = gameObject.GameObject.Value.GetComponentInParent <ContactView>();

            demoUtilObj.Value.GetComponent <DemoUtils_Contacts>().DeleteContactAfter(contact);


            Finish();
        }
        public ActionResult Index(ContactView contactData)
        {
            if (ModelState.IsValid)
            {
                this.viewData   = contactData;
                contactProvider = ProviderFactory.GetProvider(contactData.Provider);

                bool       all    = contactData.SelectedAll;
                List <int> indexs = new List <int>();

                if (!string.IsNullOrEmpty(contactData.SelectedIndexes))
                {
                    string[] selected = contactData.SelectedIndexes.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (string index in selected)
                    {
                        indexs.Add(Convert.ToInt32(index));
                    }
                }

                if (!all && indexs.Count == 0)
                {
                    ModelState.AddModelError("Comments", "Please select at least one contact to invite.");
                }
                else
                {
                    IList <IContact> selectedContacts = new List <IContact>();
                    if (Session["Contacts_" + contactData.Provider] != null)
                    {
                        selectedContacts = GetContacts((IList <IContact>)Session["Contacts_" + contactData.Provider], new ContactProvider.Selection(all, indexs));
                    }
                    else
                    {
                        selectedContacts = contactProvider.GetContacts(new ContactProvider.Selection(all, indexs));
                    }

                    FriendProvider fp = friendProviderRepository.GetByName(contactProvider.Name);

                    try
                    {
                        inviteContactsService.InviteUsers(this.ProxyLoggedUser, contactData.Comments, fp, TransformContacts(selectedContacts), Convert.ToBoolean(ConfigurationManager.AppSettings["IsInBeta"]));
                        Session.Remove("Contacts_" + contactData.Provider);
                        Session["NewFriendsAdded"] = true;
                        return(RedirectToAction("Index", "Friend"));
                    }
                    catch (LimitOfFriendsExceededException ex)
                    {
                        ModelState.AddModelError("Comments", ex.Message);
                    }
                }
            }

            LoadViewData(contactData.Provider);

            return(View("Index", viewData));
        }
Exemple #17
0
        private ContactView CreateContactView(Contact contact)
        {
            ContactView contactView = new ContactView();

            contactView.Id        = contact.Id;
            contactView.FirstName = contact.FirstName;
            contactView.LastName  = contact.LastName;
            contactView.Email     = contact.Email;
            return(contactView);
        }
Exemple #18
0
        public ContactView GetContactView(int Id)
        {
            ContactView contactView = new ContactView();

            Contact contact = _repository.Get(Id);

            contactView = CreateContactView(contact);

            return(contactView);
        }
        public async static Task <AbMediaContent> takeContact(Card card, Page parentPage)
        {
            ContentPage editContactPage = new ContentPage();
            ContactView contactCapture  = new ContactView(card, editContactPage);

            editContactPage.Disappearing += (e, v) => { contactCapture.onDisappear(); }; // TODO should move to constructor
            editContactPage.Content       = contactCapture;

            return(await getMediaResult(contactCapture, contactCapture, editContactPage, parentPage));
        }
    public void LoadContent()
    {
        var contacts = _csvContactReader.GetList();

        foreach (ContactModel contact in contacts)
        {
            ContactView contactGameObject = Instantiate(_contact, _contactParent.transform);
            contactGameObject.Contact = contact;
        }
    }
Exemple #21
0
        public IActionResult Contact()
        {
            ContactView result = new ContactView
            {
                EnterpriseName  = _about.Value.Name,
                EnterprisePhone = _about.Value.Phone
            };

            return(View(result));
        }
Exemple #22
0
        public IActionResult Contact()
        {
            if (Config.SystemBehaviorConfig.RedirectHomeToLogin)
            {
                return(RedirectToAction("LogOn", "Account"));
            }

            ContactView model = new ContactView();

            return(View(model));
        }
        public ActionResult Index(int page = 1)
        {
            ContactView         view   = new ContactView();
            List <ContactModel> result = MgtMail.GetInstance().GetAllContact().ToModels(true).ToList();
            Pager pager = new Pager(result.Count(), page, 16);

            view.contact = result.OrderByDescending(x => x.Date).Skip((pager.CurrentPage - 1) * pager.PageSize).Take(pager.PageSize).ToList();
            view.Pager   = pager;

            return(View(view));
        }
 public IActionResult Contact(ContactView model)
 {
     if (ModelState.IsValid)
     {
     }
     else
     {
     }
     ViewBag.UserMessage = "Mail enviado";
     return(View());
 }
Exemple #25
0
 private Contact ToContact(ContactView view)
 {
     return(new Contact
     {
         ContactId = view.ContactId,
         EmailAddress = view.EmailAddress,
         FirstName = view.FirstName,
         Image = view.Image,
         LastName = view.LastName,
         PhoneNumber = view.PhoneNumber,
     });
 }
Exemple #26
0
 private Contact ToContact(ContactView view)
 {
     return(new Contact()
     {
         ContactId = view.ContactId,
         Email = view.Email,
         FirstName = view.FirstName,
         Image = view.Image,
         LastName = view.LastName,
         Phone = view.Phone,
     });
 }
        public async Task <IActionResult> Post([FromBody] ContactView contactView)
        {
            try
            {
                var contact = await ContactService.AddContact(Mapper.Map <Contact>(contactView));

                return(CreatedAtAction(nameof(Get), new { id = contact.Id }, contact));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Exemple #28
0
        private void PopulateGrid()
        {
            mainGrid.ColumnDefinitions.Clear();
            mainGrid.RowDefinitions.Clear();
            mainGrid.Children.Clear();
            TileViewProperties tileCollection = new TileViewProperties();
            int imageWidth  = 302;
            int imageHeight = 180;

            Random random = new Random();

            int columnCount = Convert.ToInt32((rootGrid.ActualWidth - 50) / (imageWidth + 20));
            int rowCount    = Convert.ToInt32((rootGrid.ActualHeight - 120) / (imageHeight + 20));

            for (int i = 0; i < rowCount; i++)
            {
                mainGrid.RowDefinitions.Add(new RowDefinition()
                {
                    Height = new GridLength(imageHeight + 10)
                });
            }

            for (int i = 0; i < columnCount; i++)
            {
                mainGrid.ColumnDefinitions.Add(new ColumnDefinition()
                {
                    Width = new GridLength(imageWidth + 10)
                });
            }

            int index = 0;

            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < columnCount; j++)
                {
                    ContactView contactView = new ContactView();
                    contactView.Margin      = new Thickness(10);
                    contactView.DataContext = tileCollection.Images[index];
                    Grid.SetRow(contactView, i);
                    Grid.SetColumn(contactView, j);
                    mainGrid.Children.Add(contactView);
                    index++;
                    if (index == 9)
                    {
                        index = 0;
                    }
                }
            }
        }
Exemple #29
0
 public IActionResult Contact(ContactView model)
 {
     if (ModelState.IsValid)
     {
         _mailService.SendMessage(model.Email, model.Subject, model.Message);
         ViewBag.UserMessage = "Email Sent";
         ModelState.Clear();
     }
     else
     {
         ViewBag.UserMessage = "Something went wrong!";
     }
     return(View());
 }
        public ContactList GetContact(string Id)
        {
            ContactList contactList = new ContactList();
            ContactView contactView = null;
            Contact     contact     = new Contact();

            contactView       = _contactService.GetContactView(int.Parse(Id));
            contact.Id        = contactView.Id;
            contact.FirstName = contactView.FirstName.Trim();
            contact.LastName  = contactView.LastName.Trim();
            contact.Email     = contactView.Email.Trim();
            contactList.Add(contact);

            return(contactList);
        }
        public ActionResult InsertContact(ContactView cv)
        {
            string path = Path.Combine(Server.MapPath("~/"), "DataContact.hat");

            //Serialize
            using (Stream stream = new FileStream(path, FileMode.OpenOrCreate))
            {
                // đổi tượng BinaryFormatter được sử dụng cho quá trình tuần tự hóa nhị phân.
                BinaryFormatter formatter = new BinaryFormatter();
                //Phương thức Serialize để thực thi tuần tự hóa.
                formatter.Serialize(stream, cv);
                stream.Close();
            }

            return(RedirectToAction("ContactUs"));
        }
        private void Page_Loaded(object sender, RoutedEventArgs e)
        {
            UC_AddressBook.Instance.PageTitle = PageTitles.TITLE_SELECT_CONTACT_FROM_ACCOUNT;
            var emailType = dbController.GetEmailTypePreferredByAccountTypeId(account.AccountType.Id);
            var faxType = dbController.GetFaxTypePreferredByAccountTypeId(account.AccountType.Id);
            var nameOrder = dbController.GetHostNameOrderByAccountTypeId(account.AccountType.Id);
            int index = 0;
            foreach (var item in listContacts)
            {
                var mainEmail = item.Emails.FirstOrDefault(em => em.EmailType.Name.Equals(emailType.Name));
                var mainFax = item.Faxes.FirstOrDefault(fa => fa.FaxType.Name.Equals(faxType.Name));

                var contact = new ContactView
                {
                    Index = index,
                    Id = index,
                    Name = MyUtils.GetContactFullNameFrom(item.FirstName, item.MiddleName, item.LastName, nameOrder.ContactNameOrder.NameOrder),
                    EmailAddress = mainEmail != null ? mainEmail.Value : string.Empty,
                    Fax = mainFax != null ? mainFax.Value : string.Empty,
                    Group = string.Empty,
                    ImportedFrom = account.UserName,
                };

                listContact_EF.Add(contact);
                index++;
            }

            addressBook = UC_AddressBook.Instance;
            ResetListView();
            defaultBackground = Grid_import.Background;
            btnImportContacts.IsEnabled = false;
            btnImportContactsNoFlyout.IsEnabled = false;
            listview_contacts.SelectionChanged -= listview_contacts_SelectionChanged;
            listview_contacts.ItemsSource = listContact_EF;
            listview_contacts.SelectionChanged += listview_contacts_SelectionChanged;
            tblockCurContactLimit.Text = ContactDB.MAX_CONTACT.ToString();
            tblockContactNumber.Text = "0";
            currentContactNumber = dbController.GetTotalContactCount();
            tblockContactNumber.Text = currentContactNumber.ToString();
        }
        private async void btnSave_Click(object sender, RoutedEventArgs e)
            {
            UpdateGUIWhenStartProgressAddorEditContact();
            await Task.Delay(50);
            //var totalContacts = Page_LocalContacts.listContact_EF.Count;
            bool result = false;
            DuplicateContactMode mode;
            string firstName = GroupDB.TrimAll(tbox_firstname.Text);
            string middleName = GroupDB.TrimAll(tbox_middlename.Text);
            string lastName = GroupDB.TrimAll(tbox_lastname.Text);
            string email = GroupDB.TrimAll(tbox_email.Text);
            string fax = GroupDB.TrimAll(tbox_fax.Text);
            string groupsStr = tbox_group.Text.Trim();
            groupsStr = GroupDB.TrimAll(groupsStr);
            groupsStr = GroupDB.Distinct(groupsStr);

            if (radio_btn_allow_duplicate.IsChecked == true)
            {
                mode = DuplicateContactMode.ALLOW_ADD_NEW;
            }
            else if (radio_btn_replace_with_new.IsChecked == true)
            {
                mode = DuplicateContactMode.REPLACE_WITH_NEW_ITEM;
            }
            else
            {
                mode = DuplicateContactMode.DO_NOT_IMPORT;
            }
           
            if (currentMode == MODE_LOCAL)
            {            
                var dispatcher = CoreApplication.MainView.CoreWindow.Dispatcher;
                await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    //var listIdAffectedGroup = dbController.GetAllGroupIdInGroupsContact();
                    var groupsList = GetGroupIdList(groupsStr);

                    if (groupsList == null)
                    {
                        UpdateGUIWhenStopProgressAddOrEditContact();
                        return;
                    }

                    dbController.UpdateDuplicateContactMode(mode);

                    if (currentMode == MODE_LOCAL)
                    {
                        if (contactView == null)
                        {
                            result = dbController.SelfAddContact_EF(firstName, middleName, lastName, email, fax, groupsList);
                        }
                        else
                        {
                            result = dbController.UpdateContact_EF(contactView.Id, firstName, middleName, lastName, email, fax, groupsList);
                        }
                    }

                    //if (result && listIdAffectedGroup != null && listIdAffectedGroup.Count() > 0)
                    //{
                    //    var askDeleteEmptyGroup = await Modals.UIConfirmTask.deleteListEmptyGroup(listIdAffectedGroup);
                    //    listIdAffectedGroup.Clear();
                    //}

                    if (result)
                    {
                        Page_LocalContacts.listContact_EF = dbController.GetAllContactViews();

                        if (mode != DuplicateContactMode.DO_NOT_IMPORT)
                        {
                            var save_success = UC_AddressBook.ResourcesStringLoader.GetString("NOTIFY-Message-SaveSuccess");
                            Page_LocalContacts.SucceededMessage = save_success;
                        }

                        if (addressBook.AppFrame.CanGoBack)
                        {
                            Page_LocalContacts.IsReload = true;
                            Page_LocalContacts.IsResumeSelectContacts = false;
                            UpdateGUIWhenStopProgressAddOrEditContact();
                            UC_AddressBook.Instance.Go_Back();
                            return;
                        }
                    }
                    else
                    {
                        var save_not_success = UC_AddressBook.ResourcesStringLoader.GetString("NOTIFY-Message-SaveNotSuccess");
                        NotifyUser(save_not_success, NotifyType.ErrorMessage);
                    }

                    UpdateGUIWhenStopProgressAddOrEditContact();
                });
            }
            else
            {
                var groups = Page_PrinterContacts.GetTotalGroups;
                var list = GroupDB.DistinctToList(groupsStr);
                list.AddRange(groups);

                if (list.Distinct().ToList().Count > UC_AddressBook.CurrentPrinterContact.GroupLimit)
                {
                    var msg = UC_AddressBook.ResourcesStringLoader.GetString("exceed_max_limit_group");
                    NotifyUser(msg, NotifyType.ErrorMessage);
                    UpdateGUIWhenStopProgressAddOrEditContact();
                    return;
                }

                if (contactView == null)
                {
                    var total = Page_PrinterContacts.GetTotalContactsCount + 1;

                    if (total > UC_AddressBook.CurrentPrinterContact.ContactLimit)
                    {
                        var msg = string.Format(UC_AddressBook.ResourcesStringLoader.GetString("exceed_max_limit_contact"), UC_AddressBook.CurrentPrinterContact.ContactLimit);
                        NotifyUser(msg, NotifyType.ErrorMessage);
                        UpdateGUIWhenStopProgressAddOrEditContact();
                        return;
                    }
                }

                var newc = new ContactView
                {
                    Name = MyUtils.GetContactFullNameFrom(firstName, middleName, lastName, ContactDB.NAME_ORDER_FIRST_LAST_MID),
                    FirstName = firstName,
                    LastName = lastName,
                    MiddleName = middleName,
                    EmailAddress = email,
                    Fax = fax,
                    Group = groupsStr,
                    Id = contactView != null ? contactView.Id : 0,
                    ImportedFrom = contactView != null ? contactView.ImportedFrom : AccountTypeDB.TYPE_SELF_STRING
                };

                dbController.UpdateDuplicateContactMode(mode);
                var rs = ((Page_PrinterContacts)pagePrinter).UpdateListContact(newc, mode, string.Empty);
                Page_PrinterContacts.IsReload = true;
                Page_PrinterContacts.IsResumeSelectContacts = false;
                if (mode != DuplicateContactMode.DO_NOT_IMPORT && !rs)
                {
                    Page_PrinterContacts.SucceededMessage = UC_AddressBook.ResourcesStringLoader.GetString("NOTIFY-Message-SaveSuccess");
                }

                UC_AddressBook.Instance.Go_Back();
            }
        }
 private void AddToJsonList(ContactView c, string mode)
 {
     var found = contactJsons.Where(x => x.Id == c.Id).FirstOrDefault();
     bool isFound = found != null ? true : false;
     if (!isFound)
     {
         ContactJson cj = new ContactJson();
         cj = cj.Clone(c, mode);
         contactJsons.Add(cj);
     }
     else
     {
         if (mode == MyUtils.DELETE)
         {
             ContactJson cj = new ContactJson();
             cj = cj.Clone(c, mode);
             cj.ContactAction = MyUtils.DELETE;
             contactJsons.Remove(found);
             contactJsons.Add(cj);
         }
         if (mode == MyUtils.UPDATE)
         {
             ContactJson cj = new ContactJson();
             cj = cj.Clone(c, mode);
             if (c.Id > oldPrinterMaxID)
             {
                 contactJsons.Remove(found);
                 cj.ContactAction = MyUtils.ADD;
             }
             else
             {
                 contactJsons.Remove(found);
                 cj.ContactAction = MyUtils.UPDATE;
             }
             contactJsons.Add(cj);
         }
     }
 }
        public void RemoveContactsFromGroup(ContactView contact, string gname)
        {
            UpdateFlag();

            foreach (ContactView c in listContact_EF)
            {
                if (c.Id == contact.Id)
                {
                    if (c.Group.ToLower().Contains(gname.ToLower()))
                    {
                        var groups = c.Group;
                        var tmp = groups.Split(';').ToList();
                        if (tmp.Count() > 0)
                        {
                            tmp.Remove(gname);
                        }
                        groups = string.Join(";", tmp);
                        c.Group = groups;
                        AddToJsonList(c, MyUtils.UPDATE);
                    }
                }
            }
        }
        public bool UpdateListContact(ContactView contact, DuplicateContactMode mode, string groupName)
        {
            UpdateFlag();
            var contacts = CheckDuplicateContact(contact, groupName);

            switch (mode)
            {
                case DuplicateContactMode.ALLOW_ADD_NEW:
                    if (groupName == string.Empty)
                    {
                        if (contact.Id == 0)
                        {
                            contact.Id = ++currentPrinterMaxID;
                            listContact_EF.Add(contact);
                            AddToJsonList(contact, MyUtils.ADD);
                        }
                    }

                    break;
                case DuplicateContactMode.DO_NOT_IMPORT:
                    if (groupName != string.Empty && contacts.Count != 0)
                    {
                        return false;
                    }

                    if (groupName == string.Empty && contacts.Count == 0)
                    {
                        if (contact.Id == 0)
                        {
                            contact.Id = ++currentPrinterMaxID;
                            listContact_EF.Add(contact);
                            AddToJsonList(contact, MyUtils.ADD);
                        }
                    }

                    if(contacts.Count != 0)
                    {
                        return false;
                    }

                    break;
                case DuplicateContactMode.REPLACE_WITH_NEW_ITEM:

                    if (groupName != string.Empty)
                    {
                        foreach (var item in contacts)
                        {
                            var groupArr = item.Group.Split(';').ToList();
                            var list = groupArr.Where(l => !l.Equals(groupName));
                            var result = string.Join(";", list.Where(g => !g.Equals(string.Empty)).Select(l => l.ToString()));
                            var contactUpate = listContact_EF.FirstOrDefault(l => l.Id.Equals(item.Id));
                            contactUpate.Group = result;
                            AddToJsonList(contactUpate, MyUtils.UPDATE);
                        }
                    }
                    else
                    {
                        if (contacts.Count != 0)
                        {
                            foreach (var item in contacts)
                            {
                                var data = listContact_EF.FirstOrDefault(l => l.Id.Equals(item.Id));
                                data.Name = contact.Name;
                                data.Group = contact.Group;
                                data.ImportedFrom = contact.ImportedFrom;
                                AddToJsonList(data, MyUtils.UPDATE);
                            }
                        }
                        else
                        {
                            if (contact.Id == 0)
                            {
                                contact.Id = ++currentPrinterMaxID;
                                listContact_EF.Add(contact);
                                AddToJsonList(contact, MyUtils.ADD);
                            }
                        }
                    }

                    break;
                default:
                    break;
            }

            if (contact.Id != 0)
            {
                var data = listContact_EF.FirstOrDefault(l => l.Id.Equals(contact.Id));
                data.Name = contact.Name;
                data.FirstName = contact.FirstName;
                data.LastName = contact.LastName;
                data.MiddleName = contact.MiddleName;
                data.EmailAddress = contact.EmailAddress;
                data.Fax = contact.Fax;
                data.Group = contact.Group;
                AddToJsonList(data, MyUtils.UPDATE);
                UpdateListGroupName();
                UC_AddressBook.Instance.UpdateCountContactPrinter(listContact_EF.Count());
                UC_AddressBook.Instance.UpdateCountContactItemMenu();
                return true;
            }

            if (groupName != string.Empty)
            {
                var data = listContact_EF.FirstOrDefault(l => l.Id.Equals(contact.Id));
                data.Group = contact.Group;
                AddToJsonList(contact, MyUtils.UPDATE);
            }

            UpdateListGroupName();
            UC_AddressBook.Instance.UpdateCountContactPrinter(listContact_EF.Count());
            UC_AddressBook.Instance.UpdateCountContactItemMenu();
            return true;
        }
        public List<ContactView> CheckDuplicateContact(ContactView c, string groupName)
        {
            var contacts = listContact_EF.Where(x => x.FirstName == c.FirstName
                                                    && x.MiddleName == c.MiddleName
                                                    && x.LastName == c.LastName
                                                    && x.Fax == c.Fax 
                                                    && x.EmailAddress == c.EmailAddress 
                                                    && (x.Group.Split(';').Contains(groupName) || groupName == string.Empty)).ToList();

            return contacts;
        }
        public FileImportResult ImportFromCSV(string data, DuplicateContactMode mode)
        {
            FileImportResult result = new FileImportResult();

            //get db
            EmailType emailType = dbManager.GetPreferredEmailTypeByAccountTypeNameEF(AccountTypeDB.TYPE_CSV_STRING);
            FaxType faxType = dbManager.GetPreferredFaxTypeByAccountTypeNameEF(AccountTypeDB.TYPE_CSV_STRING);
            Account account = dbManager.GetCSVAccountEF();
            string accTypeName = AccountTypeDB.TYPE_CSV_STRING;

            //split stream from file
            string[] contactSplits = data.Split(new string[] { "\r", "\r\n", "\n" }, StringSplitOptions.None);
            var CSVHeader = contactSplits[0].Split(new char[] { ',' }).ToList().Select(n => GroupDB.TrimSpace(GroupDB.RemoveControlChars(n)).ToLower()).ToList();

            //define var
            int size = contactSplits.Count();
            List<CMData.Contact> listContact = new List<CMData.Contact>();
            //header index
            int IdFirstName = -1;
            int IdLastName = -1;
            int IdMidName = -1;
            int IdFullName = -1;
            int IdFax = -1;
            int IdEmail = -1;

            //check header
            //step 1: first last mid
            IdFirstName = CSVHeader.FindIndex(n => n.Equals("first name") || n.Equals("first") || n.Equals("first_name"));
            IdLastName = CSVHeader.FindIndex(n => n.Equals("last name") || n.Equals("last") || n.Equals("last_name"));
            IdMidName = CSVHeader.FindIndex(n => n.Equals("middle name") || n.Equals("middle") || n.Equals("middle_name"));

            //step 2: fullname
            if(IdFirstName < 0 && IdLastName < 0 && IdMidName < 0)
            {
                IdFullName = CSVHeader.FindIndex(n => n.Equals("full name") || n.Equals("name") || n.Equals("full_name") || n.Equals("fullname"));
            }

            //step3: Email & Fax
            if(IdFirstName >= 0 || IdLastName >= 0 || IdMidName >= 0 || IdFullName >= 0)
            {
                IdEmail = CSVHeader.FindIndex(n => n.Equals("email address") || n.Equals("email_address") || n.Equals("e-mail_address") || n.Equals("e-mail") || n.Equals("email") || n.Equals("home email") || n.Equals("home_email") || n.Equals("work email") || n.Equals("work_email") || n.Equals("personal email") || n.Equals("personal_email"));
                IdFax = CSVHeader.FindIndex(n => n.Equals("fax number") || n.Equals("fax_number") || n.Equals("business fax") || n.Equals("business_fax") || n.Equals("fax") || n.Equals("home fax") || n.Equals("home_fax") || n.Equals("work fax") || n.Equals("work_fax"));
            }
            else
            {
                result.errorCode = FileImExportController.CODE_FILE_STRUCTURE_NOT_SUITABLE;
                return result;
            }

            //parse data fore each row // i=0 is headers row
            for (int i = 1; i < size; i++)
            {
                string bareData = contactSplits[i];
                var valueSplits = splitCSVLine(bareData);
                var maxColumnIndex = valueSplits.Count() - 1;

                if (valueSplits.Count() < 1)
                    continue;
                var valueFullName = String.Empty;
                var valueLastName = String.Empty;
                var valueFirstName = String.Empty;
                var valueMidName = String.Empty;
                var valueEmail = String.Empty;
                var valueFax = String.Empty;

                //parse

                //get full name or detail FLM name
                if (IdFullName >= 0)
                {
                    if(IdFullName > maxColumnIndex)
                    {
                        continue;
                    }
                    valueFullName = valueSplits.ElementAt(IdFullName);

                    if (string.IsNullOrEmpty(valueFullName)) //specify full name, but it's empty
                        continue;

                    var cv = new ContactView();
                    cv.Name = valueFullName;
                    cv.SplitFirstLastMidFromFullName(ContactDB.NAME_ORDER_FIRST_LAST_MID);
                    valueFirstName = cv.FirstName;
                    valueLastName = cv.LastName;
                    valueMidName = cv.MiddleName;
                }
                else
                {   if(IdFirstName >= 0 && IdFirstName <= maxColumnIndex)
                        valueFirstName = valueSplits.ElementAt(IdFirstName);

                    if (IdLastName >= 0 && IdLastName <= maxColumnIndex)
                        valueLastName = valueSplits.ElementAt(IdLastName);

                    if (IdMidName >= 0 && IdMidName <= maxColumnIndex)
                        valueMidName = valueSplits.ElementAt(IdMidName);
                }

                //get Fax, Email
                if (IdEmail >= 0 && IdEmail <= maxColumnIndex)
                    valueEmail = valueSplits.ElementAt(IdEmail);

                if (IdFax >= 0 && IdFax <= maxColumnIndex)
                    valueFax = valueSplits.ElementAt(IdFax);

                //check to skip row when specify FLM name, but they're empty
                if (String.IsNullOrEmpty(valueFirstName) && String.IsNullOrEmpty(valueLastName) && String.IsNullOrEmpty(valueMidName))
                {
                    continue;
                }

                //Mapping Email / Fax
                List<Email> listEmail = new List<Email>();
                if (!String.IsNullOrEmpty(valueEmail))
                {
                    Email em = new Email();

                    em.Value = valueEmail;
                    em.EmailType = emailType;
                    em.EmailTypeId = emailType.Id;
                    listEmail.Add(em);
                }
                List<Fax> listFax = new List<Fax>();
                if (!String.IsNullOrEmpty(valueFax))
                {
                    Fax faxDB = new Fax();
                    faxDB.Value = valueFax;
                    faxDB.FaxType = faxType;
                    faxDB.FaxTypeId = faxType.Id;
                    listFax.Add(faxDB);
                }

                //Create Contact obj
                CMData.Contact contact;
                contact = new CMData.Contact();
                contact.AccountId = account.Id;
                contact.FirstName = valueFirstName;
                contact.LastName = valueLastName;
                contact.MiddleName = valueMidName;
                contact.Emails = listEmail;
                contact.Faxes = listFax;
                listContact.Add(contact);
            }

            //write to DB
            result = AddOrUpdateContact(listContact, accTypeName, mode);
            return result;
        }
 public void NavigateToAddEditContact(ContactView contact)
 {
     //phtkiet
     //if (this.AppFrame.CanGoBack)
     try
     {
         if (this.AppFrame.BackStack.Count > 1)
             this.AppFrame.BackStack.RemoveAt(this.AppFrame.BackStack.Count - 2);
         GC.Collect();
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.ToString());
     }
     //phtkiet
     var editPage = new Page_AddEditContact(contact, 1, null);
     AppFrame.Navigate(editPage.GetType());
 }
        public void notifyPrinterContactList(PrinterContact c)
        {
            if (!flagSendToPrinter)
            {
                listContact_EF.Clear();
                listGroupName.Clear();
                contactJsons.Clear();
                //listContactPrinter.Clear();
                if (c != null && c.contacts.Count > 0)
                {
                    //listContactPrinter = c.contacts;
                    UC_AddressBook.CurrentPrinterContact = c;

                    foreach (ContactViewPrinter cp in c.contacts)
                    {
                        ContactView cv = new ContactView
                        {
                            Name = cp.Name,
                            EmailAddress = cp.EmailAddress,
                            Fax = cp.Fax,
                            Group = cp.Group,
                            Id = cp.Id,
                            ImportedFrom = cp.ImportedFrom
                        };
                        cv.SplitFirstLastMidFromFullName(ContactDB.NAME_ORDER_FIRST_MID_LAST);
                        listContact_EF.Add(cv);
                        if (!listGroupName.Contains(cp.Group) && !string.IsNullOrEmpty(cp.Group))
                        {
                            listGroupName.Add(cp.Group);
                        }
                    }
                }

                UC_AddressBook.CurrentPrinterContact.contacts = MyUtils.ConvertContactViewToContactViewPrinter(listContact_EF);

                currentPrinterMaxID = oldPrinterMaxID = GetMaxContactIdPrinter();

                printerError = null;
            }
            else
            {
                contactJsons.Clear();
                //listContact_EF.Clear();
                flagSendToPrinter = false;

                if (c != null && c.contacts.Count > 0)
                {
                    //var temp = new List<ContactView>();
                    //foreach (ContactView cw in listContact_EF)
                    //{
                    //    if (cw.Id > oldPrinterMaxID)
                    //    {
                    //        temp.Add(cw);
                    //    }
                    //}

                    //foreach (ContactView cc in temp)
                    //{
                    //    listContact_EF.Remove(cc);
                    //}

                    //foreach (ContactViewPrinter cp in c.contacts)
                    //{
                    //    ContactView cv = new ContactView
                    //    {
                    //        Name = cp.Name,
                    //        EmailAddress = cp.EmailAddress,
                    //        Fax = cp.Fax,
                    //        Group = cp.Group,
                    //        Id = cp.Id,
                    //        ImportedFrom = cp.ImportedFrom
                    //    };

                    //    cv.SplitFirstLastMidFromFullName(ContactDB.NAME_ORDER_FIRST_MID_LAST);

                    //    listContact_EF.Add(cv);

                    //    //if (cp.ContactAction == MyUtils.ADD)
                    //    //{
                    //    //    cv.Id = ++currentPrinterMaxID;
                    //    //    listContact_EF.Add(cv);
                    //    //}
                    //    //if (cp.ContactAction == MyUtils.DELETE)
                    //    //{
                    //    //    var found = listContact_EF.Where(x => x.Id == cp.Id).FirstOrDefault();
                    //    //    if (found != null)
                    //    //    {
                    //    //        listContact_EF.Remove(found);
                    //    //    }
                    //    //}
                    //    //if (cp.ContactAction == MyUtils.UPDATE)
                    //    //{
                    //    //    var found = listContact_EF.Where(x => x.Id == cp.Id).FirstOrDefault();
                    //    //    if (found != null)
                    //    //    {
                    //    //        listContact_EF.Remove(found);
                    //    //    }

                    //    //    listContact_EF.Add(cv);
                    //    //}
                    //    //if (!listGroupName.Contains(cp.Group) && !string.IsNullOrEmpty(cp.Group))
                    //    //{
                    //    //    listGroupName.Add(cp.Group);
                    //    //}
                    //}

                    var contact = c.contacts[0];
                    contact.SplitFirstLastMidFromFullName(ContactDB.NAME_ORDER_FIRST_MID_LAST);
                    contact.Id = ++currentPrinterMaxID;
                    listContact_EF.Add(contact);
                    if (!listGroupName.Contains(contact.Group) && !string.IsNullOrEmpty(contact.Group))
                    {
                        listGroupName.Add(contact.Group);
                    }

                    UC_AddressBook.CurrentPrinterContact.contacts = MyUtils.ConvertContactViewToContactViewPrinter(listContact_EF);

                    currentPrinterMaxID = oldPrinterMaxID = GetMaxContactIdPrinter();
                }
            }

            DoRefreshListView();
        }
 public void PrinterNavigateToAddEditContact(ContactView contact, object o)
 {
     //phtkiet
     //if (this.AppFrame.CanGoBack)
     try
     {
         if (this.AppFrame.BackStack.Count > 1)
             this.AppFrame.BackStack.RemoveAt(this.AppFrame.BackStack.Count - 2);
         GC.Collect();
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine(ex.ToString());
     }
     //phtkiet
     var x = new Page_AddEditContact(contact, 2, o);     // 2: mode printer        
     AppFrame.Navigate(x.GetType());
 }
 public Page_AddEditContact(ContactView c, int mode, object page)
 {
     currentMode = mode;
     contactView = c;
     pagePrinter = page;
     if (c == null)
         UC_AddressBook.Instance.VisibleBackPage(PageTitles.TITLE_ADD_CONTACT);
     else
         UC_AddressBook.Instance.VisibleBackPage(PageTitles.TITLE_EDIT_CONTACT);
 }
 private ContactView CreateContactView(Contact contact)
 {
     ContactView contactView = new ContactView();
      contactView.Id = contact.Id;
      contactView.FirstName = contact.FirstName;
      contactView.LastName = contact.LastName;
      contactView.Email = contact.Email;
      return contactView;
 }