public async Task <IEnumerable <ContactServiceModel> > AllAsync(int page, ContactFilter filter)
        {
            var query = this.db
                        .Contacts
                        .AsQueryable();

            if (filter == ContactFilter.All)
            {
                return(await query
                       .OrderByDescending(c => c.AddedOn)
                       .Skip((page - 1) * ContactsPerPage)
                       .Take(ContactsPerPage)
                       .To <ContactServiceModel>()
                       .ToListAsync());
            }

            return(await this.db
                   .Contacts
                   .Where(c => c.IsAnswered == (filter == ContactFilter.Answered))
                   .OrderByDescending(c => c.AddedOn)
                   .Skip((page - 1) * ContactsPerPage)
                   .Take(ContactsPerPage)
                   .To <ContactServiceModel>()
                   .ToListAsync());
        }
Esempio n. 2
0
        public ResultDataPaged <Contact> SearchContacts(string token, ContactFilter filter, int offset = -1, int limit = -1)
        {
            try
            {
                // Validate
                RequestValidator.ValidateToken(token);

                StringBuilder url = new StringBuilder(apiUrl).Append(ConfigurationReader.GetValue("SearchContact")).Replace("{limit}", limit.ToString()).Replace("{offset}", offset.ToString());;
                if (this.language != null)
                {
                    url.Append("&lang=").Append(this.language);
                }

                RESTResponse   response       = HttpHelper.SendPostRequest(url.ToString(), filter, token, this.appId);
                PaginationInfo paginationInfo = null;

                // create response
                List <Contact> contacts = new List <Contact>();
                contacts = (List <Contact>)HttpHelper.ConvertToSDKResponse(contacts, response, ref paginationInfo);
                ResultDataPaged <Contact> results = new ResultDataPaged <Contact> {
                    Data = contacts, PageInfo = paginationInfo
                };
                return(results);
            }
            catch (WebException webException)
            {
                throw new Exception(HttpHelper.HandleWebException(webException, "Error in Search Record Contacts :"));
            }
            catch (Exception exception)
            {
                throw new Exception(HttpHelper.HandleException(exception, "Error in Search Record Contacts :"));
            }
        }
Esempio n. 3
0
        private GetContactsResult Reuqest(
            Func <long, Pagination, ContactFilter, Tuple <List <Business.DataAccess.Public.Entities.Profile>, int> > reuqest,
            string name, long currentId, int?sexId, int?sexWhoId, int?alcoholId, int?animalId, int?smokeId, int?activityId,
            int?cityId, int page, IEnumerable <int> interests)
        {
            var filter            = new ContactFilter(sexId, sexWhoId, alcoholId, animalId, smokeId, activityId, cityId, interests);
            var getContactsResult = reuqest(
                currentId,
                new Pagination()
            {
                Page     = page,
                PageSize = GetPageSize()
            }, filter);

            var pagingInfo = new PagingInfo
            {
                CurrentPage  = page,
                ItemsPerPage = GetPageSize(),
                TotalItems   = getContactsResult.Item2
            };

            return(new GetContactsResult
            {
                PagingInfo = pagingInfo,
                Profiles = getContactsResult.Item1,
                AvalibleFilters = GetAvalibleFilters(),
                SelectedFilters = filter,
                Action = name
            });
        }
 /// <summary>
 /// Updates the UI element values with the specified Data.com contact filter values.
 /// </summary>
 /// <param name="filter">A Data.com contact filter.</param>
 private void SetFilter(ContactFilter filter)
 {
     FirstNameTextBox.Text = filter.FirstName;
     LastNameTextBox.Text = filter.LastName;
     EmailTextBox.Text = filter.Email;
     CompanyNameTextBox.Text = filter.CompanyName;
 }
        public async Task <ActionResult <List <Contract_ContactDTO> > > SingleListContact([FromBody] Contract_ContactFilterDTO Contract_ContactFilterDTO)
        {
            if (UnAuthorization)
            {
                return(Forbid());
            }
            if (!ModelState.IsValid)
            {
                throw new BindException(ModelState);
            }

            ContactFilter ContactFilter = new ContactFilter();

            ContactFilter.Skip         = 0;
            ContactFilter.Take         = 20;
            ContactFilter.OrderBy      = ContactOrder.Id;
            ContactFilter.OrderType    = OrderType.ASC;
            ContactFilter.Selects      = ContactSelect.ALL;
            ContactFilter.Id           = Contract_ContactFilterDTO.Id;
            ContactFilter.Name         = Contract_ContactFilterDTO.Name;
            ContactFilter.ProfessionId = Contract_ContactFilterDTO.ProfessionId;
            ContactFilter.CompanyId    = Contract_ContactFilterDTO.CompanyId;

            List <Contact> Contacts = await ContactService.List(ContactFilter);

            List <Contract_ContactDTO> Contract_ContactDTOs = Contacts
                                                              .Select(x => new Contract_ContactDTO(x)).ToList();

            return(Contract_ContactDTOs);
        }
Esempio n. 6
0
        public async Task <bool> ValidatePhone(CustomerLead CustomerLead)
        {
            if (string.IsNullOrWhiteSpace(CustomerLead.Contact.Phone))
            {
                CustomerLead.Contact.AddError(nameof(CustomerLeadValidator), nameof(CustomerLead.Contact.Phone), ErrorCode.PhoneEmpty);
            }
            else if (CustomerLead.Contact.Phone.Length > 20)
            {
                CustomerLead.Contact.AddError(nameof(CustomerLeadValidator), nameof(CustomerLead.Contact.Phone), ErrorCode.PhoneOverLength);
            }
            else
            {
                ContactFilter ContactFilter = new ContactFilter
                {
                    Skip = 0,
                    Take = 10,
                    Id   = new IdFilter {
                        NotEqual = CustomerLead.Contact.Id
                    },
                    Phone = new StringFilter {
                        Equal = CustomerLead.Contact.Phone
                    }
                };

                int count = await UOW.ContactRepository.Count(ContactFilter);

                if (count != 0)
                {
                    CustomerLead.Contact.AddError(nameof(CustomerLeadValidator), nameof(CustomerLead.Contact.Phone), ErrorCode.PhoneExisted);
                }
            }
            return(CustomerLead.IsValidated);
        }
 /// <summary>
 /// Updates the UI element values with the specified Data.com contact filter values.
 /// </summary>
 /// <param name="filter">A Data.com contact filter.</param>
 private void SetFilter(ContactFilter filter)
 {
     FirstNameTextBox.Text   = filter.FirstName;
     LastNameTextBox.Text    = filter.LastName;
     EmailTextBox.Text       = filter.Email;
     CompanyNameTextBox.Text = filter.CompanyName;
 }
Esempio n. 8
0
        private ContactFilter ConvertFilterContact(Contract_ContactFilterDTO Contract_ContactFilterDTO)
        {
            ContactFilter ContactFilter = new ContactFilter();

            ContactFilter.Selects   = ContactSelect.ALL;
            ContactFilter.Skip      = Contract_ContactFilterDTO.Skip;
            ContactFilter.Take      = Contract_ContactFilterDTO.Take;
            ContactFilter.OrderBy   = Contract_ContactFilterDTO.OrderBy;
            ContactFilter.OrderType = Contract_ContactFilterDTO.OrderType;

            ContactFilter.Id              = Contract_ContactFilterDTO.Id;
            ContactFilter.Name            = Contract_ContactFilterDTO.Name;
            ContactFilter.ProfessionId    = Contract_ContactFilterDTO.ProfessionId;
            ContactFilter.CompanyId       = Contract_ContactFilterDTO.CompanyId;
            ContactFilter.ProvinceId      = Contract_ContactFilterDTO.ProvinceId;
            ContactFilter.DistrictId      = Contract_ContactFilterDTO.DistrictId;
            ContactFilter.NationId        = Contract_ContactFilterDTO.NationId;
            ContactFilter.CustomerLeadId  = Contract_ContactFilterDTO.CustomerLeadId;
            ContactFilter.ImageId         = Contract_ContactFilterDTO.ImageId;
            ContactFilter.Description     = Contract_ContactFilterDTO.Description;
            ContactFilter.Address         = Contract_ContactFilterDTO.Address;
            ContactFilter.EmailOther      = Contract_ContactFilterDTO.EmailOther;
            ContactFilter.DateOfBirth     = Contract_ContactFilterDTO.DateOfBirth;
            ContactFilter.Phone           = Contract_ContactFilterDTO.Phone;
            ContactFilter.PhoneHome       = Contract_ContactFilterDTO.PhoneHome;
            ContactFilter.FAX             = Contract_ContactFilterDTO.FAX;
            ContactFilter.Email           = Contract_ContactFilterDTO.Email;
            ContactFilter.ZIPCode         = Contract_ContactFilterDTO.ZIPCode;
            ContactFilter.SexId           = Contract_ContactFilterDTO.SexId;
            ContactFilter.AppUserId       = Contract_ContactFilterDTO.AppUserId;
            ContactFilter.PositionId      = Contract_ContactFilterDTO.PositionId;
            ContactFilter.Department      = Contract_ContactFilterDTO.Department;
            ContactFilter.ContactStatusId = Contract_ContactFilterDTO.ContactStatusId;
            return(ContactFilter);
        }
        public void Filter_Supplier_Returns_OwnNHSD()
        {
            var orgId = Guid.NewGuid().ToString();
            var org   = Creator.GetOrganisation(id: orgId, primaryRoleId: PrimaryRole.ApplicationServiceProvider);

            _organisationDatastore.Setup(x => x.ById(orgId)).Returns(org);

            var otherOrgId = Guid.NewGuid().ToString();
            var otherOrg   = Creator.GetOrganisation(id: otherOrgId, primaryRoleId: PrimaryRole.ApplicationServiceProvider);

            _organisationDatastore.Setup(x => x.ById(otherOrgId)).Returns(otherOrg);

            var nhsdOrgId = Guid.NewGuid().ToString();
            var nhsd      = Creator.GetOrganisation(id: nhsdOrgId, primaryRoleId: PrimaryRole.GovernmentDepartment);

            _organisationDatastore.Setup(x => x.ById(nhsdOrgId)).Returns(nhsd);

            var ctx = Creator.GetContext(orgId: orgId, role: Roles.Supplier);

            _context.Setup(c => c.HttpContext).Returns(ctx);

            var filter   = new ContactFilter(_context.Object, _organisationDatastore.Object);
            var cont1    = GetContact(orgId: orgId);
            var cont2    = GetContact(orgId: orgId);
            var cont3    = GetContact(orgId: otherOrgId);
            var cont4    = GetContact(orgId: nhsdOrgId);
            var contacts = new[] { cont1, cont2, cont3, cont4 };


            var res = filter.Filter(contacts.AsQueryable());


            res.Should().BeEquivalentTo(new[] { cont1, cont2, cont4 });
        }
Esempio n. 10
0
    /// <summary>
    /// Restores parameters that were passed on to this dialog.
    /// </summary>
    private void RestoreParameters()
    {
        // Validate parameters
        if (!QueryHelper.ValidateHash("hash"))
        {
            throw new Exception("[DataComSelectContactPage.RestoreParameters]: Invalid query hash.");
        }
        Hashtable parameters = WindowHelper.GetItem(QueryHelper.GetString("pid", null)) as Hashtable;

        if (parameters == null)
        {
            throw new Exception("[DataComSelectContactPage.RestoreParameters]: The dialog page parameters are missing, the session might have been lost.");
        }

        // Restore filter
        string content = parameters["Filter"] as string;

        if (String.IsNullOrEmpty(content))
        {
            FilterParameter = new ContactFilter();
        }
        else
        {
            JsonSerializer serializer = new JsonSerializer();
            FilterParameter = serializer.Unserialize <ContactFilter>(content);
        }

        // Restore site identifier
        SiteIdentifierParameter = ValidationHelper.GetInteger(parameters["SiteID"], 0);
    }
Esempio n. 11
0
        public ActionResult PredictiveFirst(ContactFilter filt)
        {
            List <User> users = new List <User>();
            JsonResult  json  = new JsonResult();

            if (!string.IsNullOrWhiteSpace(filt.First))
            {
                PredictiveFilter filter = new PredictiveFilter
                {
                    First = filt.First
                };
                if (filt.CountryId != null)
                {
                    var couId = Guid.Parse(filt.CountryId);
                    filter.CountryId = couId;
                }
                if (filt.ProvinceId != null)
                {
                    var prId = Guid.Parse(filt.ProvinceId);
                    filter.ProvinceId = prId;
                }
                if (filt.CityId != null)
                {
                    var ciId = Guid.Parse(filt.CityId);
                    filter.CityId = ciId;
                }


                using (var api = new HttpClient())
                {
                    api.BaseAddress = new Uri("https://localhost:44343/api/user/");
                    api.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var get_user = api.PostAsJsonAsync <PredictiveFilter>("search/name", filter);
                    get_user.Wait();
                    var result = get_user.Result;
                    if (result.StatusCode == HttpStatusCode.OK)
                    {
                        var s = result.Content.ReadAsAsync <List <User> >();
                        s.Wait();
                        users = s.Result;
                    }
                    else if (result.StatusCode == HttpStatusCode.NotFound)
                    {
                        var s = result.Content.ReadAsAsync <List <User> >();
                        s.Wait();
                        users = s.Result;
                    }
                }
            }
            json.Data                = users;
            json.MaxJsonLength       = int.MaxValue;
            json.JsonRequestBehavior = JsonRequestBehavior.DenyGet;
            json.ContentType         = "application/json; charset=utf-8";
            json.ContentEncoding     = Encoding.UTF8;
            return(json);
            //json.
            //return Json(users, "application/json; charset=utf-8", Encoding.UTF8, JsonRequestBehavior.DenyGet);
        }
Esempio n. 12
0
 internal ContactManager()
 {
     m_contactList     = null;
     m_contactCount    = 0;
     m_contactFilter   = new ContactFilter();
     m_contactListener = null;
     m_broadPhase      = new BroadPhase();
 }
Esempio n. 13
0
 public ContactManager(World argPool)
 {
     ContactList     = null;
     ContactCount    = 0;
     ContactFilter   = new ContactFilter();
     ContactListener = null;
     BroadPhase      = new BroadPhase();
     pool            = argPool;
 }
Esempio n. 14
0
 public ContactManager(World argPool, BroadPhaseStrategy strategy)
 {
     m_contactList     = null;
     m_contactCount    = 0;
     m_contactFilter   = new ContactFilter();
     m_contactListener = null;
     m_broadPhase      = new BroadPhase(strategy);
     pool = argPool;
 }
        public OutgoingCallDialog(
            BotSettings settings,
            BotServices services,
            ResponseManager responseManager,
            ConversationState conversationState,
            IServiceManager serviceManager,
            IBotTelemetryClient telemetryClient)
            : base(nameof(OutgoingCallDialog), settings, services, responseManager, conversationState, serviceManager, telemetryClient)
        {
            TelemetryClient = telemetryClient;

            var outgoingCall = new List <WaterfallStep>
            {
                GetAuthToken,
                AfterGetAuthToken,
            };

            var outgoingCallNoAuth = new List <WaterfallStep>
            {
                PromptForRecipient,
                AskToSelectContact,
                ConfirmChangeOfPhoneNumberType,
                AskToSelectPhoneNumber,
                ExecuteCall,
            };

            foreach (var step in outgoingCallNoAuth)
            {
                outgoingCall.Add(step);
            }

            AddDialog(new WaterfallDialog(nameof(OutgoingCallDialog), outgoingCall));
            AddDialog(new WaterfallDialog(DialogIds.OutgoingCallNoAuth, outgoingCallNoAuth));

            AddDialog(new TextPrompt(DialogIds.RecipientPrompt, ValidateRecipient));

            AddDialog(new ChoicePrompt(DialogIds.ContactSelection, ValidateContactChoice)
            {
                Style = ListStyle.List,
            });

            AddDialog(new ConfirmPrompt(DialogIds.PhoneNumberTypeConfirmation, ValidatePhoneNumberTypeConfirmation)
            {
                Style = ListStyle.None,
            });

            AddDialog(new ChoicePrompt(DialogIds.PhoneNumberSelection, ValidatePhoneNumberChoice)
            {
                Style = ListStyle.List,
            });

            InitialDialogId = nameof(OutgoingCallDialog);

            contactFilter = new ContactFilter();
        }
Esempio n. 16
0
        static void Main(string[] args)
        {
            //var authCredentials = new AuthorizationCodeAuth("client_id", "client_secret", "code", "http://localhost:3432");
            //var url = AuthorizationCodeAuth.GetClientAuthenticationUrl("client_id", "http://localhost:3432");

            // choose authorization flow
            var clientCred = new ClientCredentialAuth("client_id", "client_secret");

            // initialise context with configuration
            var apiContext = new ApiContext(clientCred)
            {
                AppName = "Application name"
            };

            // initialise api explorer
            var api = new ApiExplorer(apiContext);

            // get template for new contact
            var template = api.Contacts.Default();

            // cast to insert model
            var contact = (ContactCreate)template;

            // fill new contact
            contact.CompanyName = "New Company";

            // insert
            var addedContact = api.Contacts.Create(contact);

            // delete
            bool isDeleted = api.Contacts.Delete(addedContact.Id);

            // get all
            var allContacts = api.Contacts.Contacts(new ApiFilter().WithPaging(1, int.MaxValue));

            // prepare custom filter for querying
            var contactFilter = new ContactFilter();

            contactFilter.DateLastChange.IsEqualOrGreatherThan(new DateTime(2016, 1, 1));

            // query data using custom filter
            var contacts = api.Contacts.ContactsExpand(
                new ApiFilter(contactFilter, FilterType.And).AddOrderDesc("Id").WithPaging(1, 5));

            List <ValidationMessage> errors;
            bool isValid = ApiValidator.ValidateObject(contact, out errors);

            if (isValid)
            {
                var result = api.Contacts.Create(new ContactCreate());
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Get an array of contacts within the specified filters.
        /// Note that the 'contactFilter' will control the 'page' and 'quantity'.
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public IEnumerable <PimsContactMgrVw> Get(ContactFilter filter)
        {
            this.User.ThrowIfNotAuthorized(Permissions.ContactView);
            filter.ThrowIfNull(nameof(filter));
            if (!filter.IsValid())
            {
                throw new ArgumentException("Argument must have a valid filter", nameof(filter));
            }

            IEnumerable <PimsContactMgrVw> contacts = this.Context.GenerateContactQuery(filter).ToArray();

            return(contacts);
        }
Esempio n. 18
0
 public List <Contact> this[string number, ContactFilter filter]
 {
     get
     {
         //TODO: Search by Number
         //TODO: Search by Email
         //Use ContactFilter enum to make a decision
         if (filter == ContactFilter.Number)
         {
             return(this.cList.FindAll(x => x.Number.StartsWith(number)));
         }
         return(new List <Contact>());
     }
 }
        public OutgoingCallDialog(
            IServiceProvider serviceProvider)
            : base(nameof(OutgoingCallDialog), serviceProvider)
        {
            var outgoingCall = new List <WaterfallStep>
            {
                GetAuthTokenAsync,
                AfterGetAuthTokenAsync,
            };

            var outgoingCallNoAuth = new List <WaterfallStep>
            {
                PromptForRecipientAsync,
                AskToSelectContactAsync,
                ConfirmChangeOfPhoneNumberTypeAsync,
                AskToSelectPhoneNumberAsync,
                ExecuteCallAsync,
            };

            foreach (var step in outgoingCallNoAuth)
            {
                outgoingCall.Add(step);
            }

            AddDialog(new WaterfallDialog(nameof(OutgoingCallDialog), outgoingCall));
            AddDialog(new WaterfallDialog(DialogIds.OutgoingCallNoAuth, outgoingCallNoAuth));

            AddDialog(new TextPrompt(DialogIds.RecipientPrompt, ValidateRecipientAsync));

            AddDialog(new ChoicePrompt(DialogIds.ContactSelection, ValidateContactChoiceAsync)
            {
                Style = ListStyle.List,
            });

            AddDialog(new ConfirmPrompt(DialogIds.PhoneNumberTypeConfirmation, ValidatePhoneNumberTypeConfirmationAsync)
            {
                Style = ListStyle.None,
            });

            AddDialog(new ChoicePrompt(DialogIds.PhoneNumberSelection, ValidatePhoneNumberChoiceAsync)
            {
                Style = ListStyle.List,
            });

            InitialDialogId = nameof(OutgoingCallDialog);

            contactFilter = new ContactFilter();
        }
        public ContactFilter Update(int contactListId, ContactFilter filter)
        {
            if (filter.Id == 0)
            {
                throw new ArgumentException("Filter ID is missing.");
            }

            if (filter.GroupId == 0)
            {
                throw new ArgumentException("Filter group ID is missing.");
            }

            int accountId = filter.AccountId > 0 ? filter.AccountId : CurrentAccount;

            return(Update(accountId, contactListId, filter.GroupId, filter.Id, filter));
        }
        public async Task <IActionResult> All(int id = 1, ContactFilter filter = ContactFilter.All)
        {
            var contacts = await this.contacts.AllAsync(id, filter);

            var contactsCount = await this.contacts.CountAsync();

            var model = new ContactsListingViewModel
            {
                Contacts      = contacts,
                CurrentPage   = id,
                ContactsCount = contactsCount,
                PagesCount    = (int)Math.Ceiling(contactsCount / (decimal)WebConstants.ContactsPerPage)
            };

            return(View(model));
        }
        public void Filter_NonSupplier_Returns_All(string role)
        {
            var ctx = Creator.GetContext(role: role);

            _context.Setup(c => c.HttpContext).Returns(ctx);
            var filter   = new ContactFilter(_context.Object, _organisationDatastore.Object);
            var contacts = new[]
            {
                GetContact(),
                GetContact(),
                GetContact()
            };
            var res = filter.Filter(contacts.AsQueryable());

            res.Should().BeEquivalentTo(contacts);
        }
Esempio n. 23
0
        public async Task <ContactFilter> ToFilter(ContactFilter filter)
        {
            if (filter.OrFilter == null)
            {
                filter.OrFilter = new List <ContactFilter>();
            }
            if (CurrentContext.Filters == null || CurrentContext.Filters.Count == 0)
            {
                return(filter);
            }
            List <Organization> Organizations = await OrganizationService.List(new OrganizationFilter
            {
                Skip      = 0,
                Take      = int.MaxValue,
                Selects   = OrganizationSelect.ALL,
                OrderBy   = OrganizationOrder.Id,
                OrderType = OrderType.ASC
            });

            foreach (var currentFilter in CurrentContext.Filters)
            {
                ContactFilter subFilter = new ContactFilter();
                filter.OrFilter.Add(subFilter);
                List <FilterPermissionDefinition> FilterPermissionDefinitions = currentFilter.Value;
                foreach (FilterPermissionDefinition FilterPermissionDefinition in FilterPermissionDefinitions)
                {
                    if (FilterPermissionDefinition.Name == nameof(subFilter.AppUserId))
                    {
                        subFilter.AppUserId = FilterBuilder.Merge(subFilter.AppUserId, FilterPermissionDefinition.IdFilter);
                    }
                    if (FilterPermissionDefinition.Name == nameof(CurrentContext.UserId) && FilterPermissionDefinition.IdFilter != null)
                    {
                        //if (FilterPermissionDefinition.IdFilter.Equal.HasValue && FilterPermissionDefinition.IdFilter.Equal.Value == CurrentUserEnum.IS.Id)
                        //{
                        //    if (subFilter.UserId == null) subFilter.UserId = new IdFilter { };
                        //    subFilter.UserId.Equal = CurrentContext.UserId;
                        //}
                        //if (FilterPermissionDefinition.IdFilter.Equal.HasValue && FilterPermissionDefinition.IdFilter.Equal.Value == CurrentUserEnum.ISNT.Id)
                        //{
                        //    if (subFilter.UserId == null) subFilter.UserId = new IdFilter { };
                        //    subFilter.UserId.NotEqual = CurrentContext.UserId;
                        //}
                    }
                }
            }
            return(filter);
        }
        public async Task <IEnumerable <Contact> > GetList(ContactFilter filter, ContextSession session)
        {
            var context = GetContext(session);
            var query   = context.Contacts.AsQueryable();

            if (filter?.SearchText != null)
            {
                query = query.Where(x => x.FirstName.StartsWith(filter.SearchText) || x.LastName.StartsWith(filter.SearchText));
            }

            return(await query
                   .AsNoTracking()
                   .OrderBy(x => x.FirstName)
                   .Skip(filter.PageSize * (filter.PageNumber - 1))
                   .Take(filter.PageSize)
                   .ToArrayAsync());
        }
Esempio n. 25
0
        public PagedList <Contact> Search(ContactFilter filter, PagingFilter paging)
        {
            // set query criteria
            var query = _dbContext.Contacts.AsQueryable();

            if (!string.IsNullOrWhiteSpace(filter.FirstName))
            {
                query = query.Where(p => p.FirstName.Contains(filter.FirstName));
            }
            if (!string.IsNullOrWhiteSpace(filter.LastName))
            {
                query = query.Where(p => p.LastName.Contains(filter.LastName));
            }
            if (!string.IsNullOrWhiteSpace(filter.PhoneNumber))
            {
                query = query.Where(p => p.PhoneNumber.Contains(filter.PhoneNumber));
            }
            if (!string.IsNullOrWhiteSpace(filter.Address))
            {
                query = query.Where(p => p.Address.Contains(filter.Address));
            }

            // count all records
            var allRecordsCount = query.Count();

            // offset apply
            query = query.Skip(paging.Offset);

            // get records
            var records = query.Take(paging.PageRecords).ToList();

            // return data
            var pagedList = new PagedList <Contact>
            {
                List   = records,
                Paging = new Paging
                {
                    AllRecords  = allRecordsCount,
                    Offset      = paging.Offset,
                    PageRecords = paging.PageRecords
                }
            };

            return(pagedList);
        }
Esempio n. 26
0
        /// <summary>
        /// Get a page with an array of contacts within the specified filters.
        /// Note that the 'contactFilter' will control the 'page' and 'quantity'.
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public Paged <PimsContactMgrVw> GetPage(ContactFilter filter)
        {
            this.User.ThrowIfNotAuthorized(Permissions.ContactView);
            filter.ThrowIfNull(nameof(filter));
            if (!filter.IsValid())
            {
                throw new ArgumentException("Argument must have a valid filter", nameof(filter));
            }

            var skip  = (filter.Page - 1) * filter.Quantity;
            var query = this.Context.GenerateContactQuery(filter);
            var items = query
                        .Skip(skip)
                        .Take(filter.Quantity)
                        .ToArray();

            return(new Paged <PimsContactMgrVw>(items, filter.Page, filter.Quantity, query.Count()));
        }
Esempio n. 27
0
        public async Task <ActionResult <int> > CountContact([FromBody] Company_ContactFilterDTO Company_ContactFilterDTO)
        {
            if (UnAuthorization)
            {
                return(Forbid());
            }
            if (!ModelState.IsValid)
            {
                throw new BindException(ModelState);
            }

            ContactFilter ContactFilter = ConvertFilterContact(Company_ContactFilterDTO);

            ContactFilter = await ContactService.ToFilter(ContactFilter);

            int count = await ContactService.Count(ContactFilter);

            return(count);
        }
Esempio n. 28
0
        public async Task <bool> ValidateId(Contact Contact)
        {
            ContactFilter ContactFilter = new ContactFilter
            {
                Skip = 0,
                Take = 10,
                Id   = new IdFilter {
                    Equal = Contact.Id
                },
                Selects = ContactSelect.Id
            };

            int count = await UOW.ContactRepository.Count(ContactFilter);

            if (count == 0)
            {
                Contact.AddError(nameof(ContactValidator), nameof(Contact.Id), ErrorCode.IdNotExisted);
            }
            return(count == 1);
        }
Esempio n. 29
0
        public async Task <ActionResult <List <Company_ContactDTO> > > ListContact([FromBody] Company_ContactFilterDTO Company_ContactFilterDTO)
        {
            if (UnAuthorization)
            {
                return(Forbid());
            }
            if (!ModelState.IsValid)
            {
                throw new BindException(ModelState);
            }

            ContactFilter ContactFilter = ConvertFilterContact(Company_ContactFilterDTO);

            ContactFilter = await ContactService.ToFilter(ContactFilter);

            List <Contact> Contacts = await ContactService.List(ContactFilter);

            List <Company_ContactDTO> Company_ContactDTOs = Contacts
                                                            .Select(c => new Company_ContactDTO(c)).ToList();

            return(Company_ContactDTOs);
        }
Esempio n. 30
0
        public async Task <List <Contact> > List(ContactFilter ContactFilter)
        {
            try
            {
                List <Contact> Contacts = await UOW.ContactRepository.List(ContactFilter);

                return(Contacts);
            }
            catch (Exception ex)
            {
                if (ex.InnerException == null)
                {
                    await Logging.CreateSystemLog(ex, nameof(ContactService));

                    throw new MessageException(ex);
                }
                else
                {
                    await Logging.CreateSystemLog(ex.InnerException, nameof(ContactService));

                    throw new MessageException(ex.InnerException);
                }
            }
        }
Esempio n. 31
0
        public async Task <bool> ValidateContact(CustomerLead CustomerLead)
        {
            if (CustomerLead.ContactId.HasValue == false)
            {
                CustomerLead.AddError(nameof(CustomerLeadValidator), nameof(CustomerLead.Contact), ErrorCode.ContactEmpty);
            }
            else
            {
                ContactFilter ContactFilter = new ContactFilter
                {
                    Id = new IdFilter {
                        Equal = CustomerLead.ContactId
                    }
                };

                var count = await UOW.ContactRepository.Count(ContactFilter);

                if (count == 0)
                {
                    CustomerLead.AddError(nameof(CustomerLeadValidator), nameof(CustomerLead.Contact), ErrorCode.ContactNotExisted);
                }
            }
            return(CustomerLead.IsValidated);
        }
    /// <summary>
    /// Restores parameters that were passed on to this dialog.
    /// </summary>
    private void RestoreParameters()
    {
        // Validate parameters
        if (!QueryHelper.ValidateHash("hash"))
        {
            throw new Exception("[DataComSelectContactPage.RestoreParameters]: Invalid query hash.");
        }
        Hashtable parameters = WindowHelper.GetItem(QueryHelper.GetString("pid", null)) as Hashtable;
        if (parameters == null)
        {
            throw new Exception("[DataComSelectContactPage.RestoreParameters]: The dialog page parameters are missing, the session might have been lost.");
        }

        // Restore filter
        string content = parameters["Filter"] as string;
        if (String.IsNullOrEmpty(content))
        {
            FilterParameter = new ContactFilter();
        }
        else
        {
            JsonSerializer serializer = new JsonSerializer();
            FilterParameter = serializer.Unserialize<ContactFilter>(content);
        }

        // Restore site identifier
        SiteIdentifierParameter = ValidationHelper.GetInteger(parameters["SiteID"], 0);
    }