コード例 #1
0
        public List <PurchaseOrder> ReadPurchaseOrderHeadersInDateRange(Guid customerId, string customerNumber, DateTime startDate, DateTime endDate)
        {
            var queryBaskets = new CommerceQuery <CommerceEntity, CommerceModelSearch <CommerceEntity>, CommerceBasketQueryOptionsBuilder>("Basket");

            queryBaskets.SearchCriteria.Model.Properties["UserId"]           = customerId.ToCommerceServerFormat();
            queryBaskets.SearchCriteria.Model.Properties["BasketType"]       = 1;
            queryBaskets.SearchCriteria.Model.Properties["CustomerId"]       = customerNumber;
            queryBaskets.SearchCriteria.Model.Properties["CreatedDateStart"] = startDate;
            queryBaskets.SearchCriteria.Model.Properties["CreatedDateEnd"]   = endDate;


            queryBaskets.QueryOptions.RefreshBasket = false;

            var response = FoundationService.ExecuteRequest(queryBaskets.ToRequest());

            if (response.OperationResponses.Count == 0)
            {
                return(null);
            }

            CommerceQueryOperationResponse basketResponse = response.OperationResponses[0] as CommerceQueryOperationResponse;

            return(basketResponse.CommerceEntities.Cast <CommerceEntity>().Where(c => c.Properties["CustomerId"] != null &&
                                                                                 c.Properties["CustomerId"].ToString().Equals(customerNumber) &&
                                                                                 c.Properties["RequestedShipDate"].ToString().ToDateTime().Value >= startDate && c.Properties["RequestedShipDate"].ToString().ToDateTime().Value <= endDate
                                                                                 ).Select(p => (PurchaseOrder)p).ToList());
            //return basketResponse.CommerceEntities.Cast<CommerceEntity>().Select(p => (PurchaseOrder)p).ToList();
        }
コード例 #2
0
        public PurchaseOrder ReadPurchaseOrderByTrackingNumber(string confirmationNumber)
        {
            Guid?userId = GetSoldToIdForPurchaseOrderByInvoice(confirmationNumber);

            if (userId.HasValue)
            {
                var queryBaskets = new CommerceQuery <CommerceEntity, CommerceModelSearch <CommerceEntity>, CommerceBasketQueryOptionsBuilder>("Basket");

                queryBaskets.SearchCriteria.Model.Properties["UserId"]      = userId.Value.ToString("B");
                queryBaskets.SearchCriteria.Model.Properties["BasketType"]  = 1;
                queryBaskets.SearchCriteria.Model.Properties["OrderNumber"] = confirmationNumber;

                queryBaskets.QueryOptions.RefreshBasket = false;

                var queryLineItems = new CommerceQueryRelatedItem <CommerceEntity>("LineItems", "LineItem");
                queryBaskets.RelatedOperations.Add(queryLineItems);

                var response = FoundationService.ExecuteRequest(queryBaskets.ToRequest());

                if (response.OperationResponses.Count == 0)
                {
                    return(null);
                }

                CommerceQueryOperationResponse basketResponse = response.OperationResponses[0] as CommerceQueryOperationResponse;

                return(basketResponse.CommerceEntities.Cast <CommerceEntity>().Select(p => (PurchaseOrder)p).First());
            }
            else
            {
                return(null);
            }
        }
コード例 #3
0
        public Basket ReadBasket(Guid userId, Guid cartId, bool runPipelines = false)
        {
            var queryBaskets = new CommerceQuery <CommerceEntity, CommerceModelSearch <CommerceEntity>, CommerceBasketQueryOptionsBuilder>("Basket");

            queryBaskets.SearchCriteria.Model.Properties["UserId"]     = userId.ToCommerceServerFormat();
            queryBaskets.SearchCriteria.Model.Properties["BasketType"] = 0;
            queryBaskets.SearchCriteria.Model.Id    = cartId.ToCommerceServerFormat();
            queryBaskets.QueryOptions.RefreshBasket = runPipelines;

            var queryLineItems = new CommerceQueryRelatedItem <CommerceEntity>("LineItems", "LineItem");

            queryBaskets.RelatedOperations.Add(queryLineItems);

            var response = FoundationService.ExecuteRequest(queryBaskets.ToRequest());

            if (response.OperationResponses.Count == 0)
            {
                return(null);
            }

            CommerceQueryOperationResponse basketResponse = response.OperationResponses[0] as CommerceQueryOperationResponse;

            if (basketResponse.CommerceEntities.Count == 0)
            {
                return(null);
            }

            return((Basket)basketResponse.CommerceEntities[0]);
        }
コード例 #4
0
        /// <summary>
        ///     retrieve the user's profile from commerce server
        /// </summary>
        /// <param name="emailAddress">the user's email address</param>
        /// <returns>a commerce server user profile object</returns>
        /// <remarks>
        ///     jwames - 10/14/14 - original code
        /// </remarks>
        public Core.Models.Generated.UserProfile GetCSProfile(Guid userId)
        {
            CommerceQuery <CommerceEntity> profileQuery = new CommerceQuery <CommerceEntity>("UserProfile");

            profileQuery.SearchCriteria.Model.Properties["Id"] = userId.ToCommerceServerFormat();

            profileQuery.Model.Properties.Add("Id");
            profileQuery.Model.Properties.Add("Email");
            profileQuery.Model.Properties.Add("LastLoginDate");
            profileQuery.Model.Properties.Add("LastActivityDate");
            profileQuery.Model.Properties.Add("FirstName");
            profileQuery.Model.Properties.Add("LastName");
            profileQuery.Model.Properties.Add("DefaultBranch");
            profileQuery.Model.Properties.Add("DefaultCustomer");
            profileQuery.Model.Properties.Add("Telephone");

            // Execute the operation and get the results back
            CommerceResponse response = Helpers.FoundationService.ExecuteRequest(profileQuery.ToRequest());
            CommerceQueryOperationResponse profileResponse = response.OperationResponses[0] as CommerceQueryOperationResponse;

            if (profileResponse.Count == 0)
            {
                return(null);
            }
            return((Core.Models.Generated.UserProfile)profileResponse.CommerceEntities[0]);
        }
コード例 #5
0
        /// <summary>
        ///     retrieve the user's profile from commerce server
        /// </summary>
        /// <param name="emailAddress">the user's email address</param>
        /// <returns>a commerce server user profile object</returns>
        /// <remarks>
        ///     jwames - 10/3/2014 - documented
        /// </remarks>
        public Core.Models.Generated.UserProfile GetCSProfile(string emailAddress)
        {
            CommerceQuery <CommerceEntity> profileQuery = new CommerceQuery <CommerceEntity>("UserProfile");

            profileQuery.SearchCriteria.Model.Properties["Email"] = emailAddress;
            profileQuery.SearchCriteria.Model.DateModified        = DateTime.Now;

            profileQuery.Model.Properties.Add("Id");
            profileQuery.Model.Properties.Add("Email");
            profileQuery.Model.Properties.Add("LastLoginDate");
            profileQuery.Model.Properties.Add("LastActivityDate");
            profileQuery.Model.Properties.Add("FirstName");
            profileQuery.Model.Properties.Add("LastName");
            profileQuery.Model.Properties.Add("DefaultBranch");
            profileQuery.Model.Properties.Add("DefaultCustomer");
            profileQuery.Model.Properties.Add("Telephone");

            CommerceResponse response = Helpers.FoundationService.ExecuteRequest(profileQuery.ToRequest());
            CommerceQueryOperationResponse profileResponse = response.OperationResponses[0] as CommerceQueryOperationResponse;

            if (profileResponse.Count == 0)
            {
                return(null);
            }
            return((Core.Models.Generated.UserProfile)profileResponse.CommerceEntities[0]);
        }
コード例 #6
0
        public Customer GetCustomerByCustomerNumber(string customerNumber, string branchId)
        {
            var customerFromCache = _customerCacheRepository.GetItem <Customer>(CACHE_GROUPNAME, CACHE_PREFIX, CACHE_NAME, GetCacheKey(string.Format("{0}-{1}", customerNumber, branchId)));

            if (customerFromCache == null)
            {
                var queryOrg = new CommerceServer.Foundation.CommerceQuery <KeithLink.Svc.Core.Models.Generated.Organization>("Organization");
                queryOrg.SearchCriteria.WhereClause = "u_organization_type = '0' AND u_customer_number = '" + customerNumber + "' AND u_branch_number = '" + branchId + "'"; // org type of customer

                CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;

                if (res.CommerceEntities.Count > 0)
                {
                    List <Customer> results = BuildCustomerList(res.CommerceEntities);

                    _customerCacheRepository.AddItem <Customer>(CACHE_GROUPNAME, CACHE_PREFIX, CACHE_NAME, GetCacheKey(string.Format("{0}-{1}", customerNumber, branchId)), TimeSpan.FromHours(4), results[0]);

                    return(results[0]);
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(customerFromCache);
            }
        }
コード例 #7
0
        public List <Customer> GetCustomersForParentAccountOrganization(string accountId)
        {
            var customerFromCache = _customerCacheRepository.GetItem <List <Customer> >(CACHE_GROUPNAME, CACHE_PREFIX, CACHE_NAME, GetCacheKey(string.Format("acct-{0}", accountId)));

            if (customerFromCache == null)
            {
            }
            else
            {
                return(customerFromCache);
            }

            var queryOrg = new CommerceServer.Foundation.CommerceQuery <KeithLink.Svc.Core.Models.Generated.Organization>("Organization");

            queryOrg.SearchCriteria.WhereClause = "u_parent_organization = '" + accountId + "'";             // org type of customer

            CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;
            List <Customer> results            = BuildCustomerList(res.CommerceEntities);

            if (results.Count > 0)
            {
                _customerCacheRepository.AddItem <List <Customer> >(CACHE_GROUPNAME, CACHE_PREFIX, CACHE_NAME, GetCacheKey(string.Format("acct-{0}", accountId)), TimeSpan.FromHours(4), results);
            }

            return(results);
        }
コード例 #8
0
        public List <UserProfile> GetExternalUsers()
        {
            CommerceQuery <CommerceEntity> queryOrg = new CommerceQuery <CommerceEntity>("ProfileCustomSearch");

            queryOrg.SearchCriteria.WhereClause = "u_email_address not like '%benekeith.com'"; // org type of customer

            CommerceQueryOperationResponse res = Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())
                                                 .OperationResponses[0] as CommerceQueryOperationResponse;
            List <UserProfile> users = new List <UserProfile>();

            if (res.CommerceEntities.Count > 0)
            {
                foreach (CommerceEntity ent in res.CommerceEntities)
                {
                    users.Add(new UserProfile {
                        UserId       = Guid.Parse(ent.Id),
                        FirstName    = (string)ent.Properties["FirstName"],
                        LastName     = (string)ent.Properties["LastName"],
                        EmailAddress = (string)ent.Properties["Email"]
                    });
                }
            }

            return(users);
        }
コード例 #9
0
        public PurchaseOrder ReadPurchaseOrder(Guid customerId, string orderNumber)
        {
            var queryBaskets = new CommerceQuery <CommerceEntity, CommerceModelSearch <CommerceEntity>, CommerceBasketQueryOptionsBuilder>("Basket");

            queryBaskets.SearchCriteria.Model.Properties["UserId"]      = customerId.ToCommerceServerFormat();
            queryBaskets.SearchCriteria.Model.Properties["BasketType"]  = 1;
            queryBaskets.SearchCriteria.Model.Properties["OrderNumber"] = orderNumber;

            queryBaskets.QueryOptions.RefreshBasket = false;

            var queryLineItems = new CommerceQueryRelatedItem <CommerceEntity>("LineItems", "LineItem");

            queryBaskets.RelatedOperations.Add(queryLineItems);

            var response = FoundationService.ExecuteRequest(queryBaskets.ToRequest());

            if (response.OperationResponses.Count == 0)
            {
                return(null);
            }

            CommerceQueryOperationResponse basketResponse = response.OperationResponses[0] as CommerceQueryOperationResponse;

            return((PurchaseOrder)basketResponse.CommerceEntities[0]);
        }
コード例 #10
0
        List <Catalog> IDivisionRepository.GetDivisions()
        {
            var queryCatalog = new CommerceQuery <CommerceEntity, CommerceModelSearch <CommerceEntity> >("Catalog");
            var response     = FoundationService.ExecuteRequest(queryCatalog.ToRequest());


            CommerceQueryOperationResponse basketResponse = response.OperationResponses[0] as CommerceQueryOperationResponse;

            return(basketResponse.CommerceEntities.Cast <CommerceEntity>().Select(i => (Catalog)i).ToList());
        }
コード例 #11
0
        public List <Customer> GetCustomersByNameOrNumber(string search)
        {
            var queryOrg = new CommerceServer.Foundation.CommerceQuery <KeithLink.Svc.Core.Models.Generated.Organization>("Organization");

            queryOrg.SearchCriteria.WhereClause = "u_name LIKE '%" + search + "%' OR u_customer_number LIKE '%" + search + "%'";

            CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;
            List <Customer> results            = BuildCustomerList(res.CommerceEntities);

            return(results);
        }
コード例 #12
0
        protected KeithLink.Svc.Core.Models.Generated.SiteTerm GetOrganizationTypes()
        {
            var siteTermQuery = new CommerceServer.Foundation.CommerceQuery <KeithLink.Svc.Core.Models.Generated.SiteTerm>("SiteTerm");

            siteTermQuery.SearchCriteria.Model.Properties["Id"] = "OrganizationType";
            siteTermQuery.RelatedOperations.Add(
                new CommerceQueryRelatedItem <KeithLink.Svc.Core.Models.Generated.SiteTermElement>
                    (KeithLink.Svc.Core.Models.Generated.SiteTerm.RelationshipName.Elements));
            CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(siteTermQuery.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;

            return(new KeithLink.Svc.Core.Models.Generated.SiteTerm(res.CommerceEntities[0]));
        }
コード例 #13
0
        /// <summary>
        /// perform the seach for all of the paged customer methods
        /// </summary>
        /// <param name="paging">paging model</param>
        /// <param name="searchTerm">the terms to use during the search</param>
        /// <param name="whereClause">the where clause that was built in each of the GetPageCustomer methods</param>
        /// <param name="searchType">search on customer name/number, NA, or RA info</param>
        /// <returns>paged list of customers</returns>
        private PagedResults <Customer> RetrievePagedResults(PagingModel paging, string searchTerm, string whereClause, CustomerSearchType searchType)
        {
            var queryOrg = new CommerceServer.Foundation.CommerceQuery <KeithLink.Svc.Core.Models.Generated.Organization>("Organization");

            queryOrg.SearchCriteria.WhereClause           = BuildWhereClauseForCustomerSearch(whereClause, searchTerm, searchType);
            queryOrg.SearchCriteria.FirstItemIndex        = paging.From.HasValue ? paging.From.Value : 0;
            queryOrg.SearchCriteria.NumberOfItemsToReturn = paging.Size.HasValue ? paging.Size.Value : int.MaxValue;
            queryOrg.SearchCriteria.ReturnTotalItemCount  = true;

            if (paging.Sort != null && paging.Sort.Count > 0)
            {
                queryOrg.SearchCriteria.SortProperties = new List <CommerceSortProperty>();
                foreach (var sortOption in paging.Sort)
                {
                    switch (sortOption.Field.ToLower())
                    {
                    case "customername":
                        CommerceSortProperty sortName = new CommerceSortProperty()
                        {
                            CommerceEntityModelName = "u_name",
                            SortDirection           = sortOption.SortOrder == SortOrder.Ascending ? SortDirection.Ascending : SortDirection.Descending
                        };
                        queryOrg.SearchCriteria.SortProperties.Add(sortName);
                        break;

                    case "customernumber":
                        CommerceSortProperty sortNumber = new CommerceSortProperty()
                        {
                            CommerceEntityModelName = "u_customer_number",
                            SortDirection           = sortOption.SortOrder == SortOrder.Ascending ? SortDirection.Ascending : SortDirection.Descending
                        };
                        queryOrg.SearchCriteria.SortProperties.Add(sortNumber);
                        break;
                    }
                }
            }

            CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;
            List <Customer> results            = BuildCustomerList(res.CommerceEntities);


            return(new PagedResults <Customer>()
            {
                Results = results.ToList(), TotalResults = res.TotalItemCount ?? 0
            });
        }
コード例 #14
0
        public Customer GetCustomerById(Guid customerId)
        {
            var queryOrg = new CommerceQuery <Organization>("Organization");

            queryOrg.SearchCriteria.WhereClause = "u_org_id = '" + customerId.ToCommerceServerFormat() + "'";

            CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;

            if (res.CommerceEntities.Count > 0)
            {
                List <Customer> results = BuildCustomerList(res.CommerceEntities);

                return(results[0]);
            }
            else
            {
                return(null);
            }
        }
コード例 #15
0
        public Customer GetCustomerForUser(string customerNumber, string branchId, Guid userId)
        {
            var queryOrg = new CommerceServer.Foundation.CommerceQuery <KeithLink.Svc.Core.Models.Generated.Organization>("Organization");

            queryOrg.SearchCriteria.WhereClause = string.Format("inner join [BEK_Commerce_profiles].[dbo].[UserOrganizationObject] uoo on oo.u_org_id = uoo.u_org_id WHERE uoo.u_user_id = '{0}' AND u_customer_number = '{1}' AND u_branch_number = '{2}'", userId.ToCommerceServerFormat(), customerNumber, branchId);


            CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;

            if (res.CommerceEntities.Count > 0)
            {
                List <Customer> results = BuildCustomerList(res.CommerceEntities);

                return(results[0]);
            }
            else
            {
                return(null);
            }
        }
コード例 #16
0
        public List <Customer> GetCustomersForDSR(List <Dsr> dsrList)
        {
            var queryOrg = new CommerceServer.Foundation.CommerceQuery <KeithLink.Svc.Core.Models.Generated.Organization>("Organization");

            System.Text.StringBuilder whereText = new System.Text.StringBuilder();
            for (int i = 0; i < dsrList.Count; i++)
            {
                if (i > 0)
                {
                    whereText.Append(" OR ");
                }
                whereText.AppendFormat("(u_branch_number = '{0}' AND u_dsr_number = '{1}')", dsrList[i].Branch, dsrList[i].DsrNumber);
            }
            queryOrg.SearchCriteria.WhereClause = whereText.ToString();

            CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;
            List <Customer> results            = BuildCustomerList(res.CommerceEntities);

            return(results);
        }
コード例 #17
0
        public List <Core.Models.Generated.UserProfile> GetCSProfileForInternalUsers()
        {
            CommerceQuery <CommerceEntity> queryOrg = new CommerceQuery <CommerceEntity>("ProfileCustomSearch");

            queryOrg.SearchCriteria.WhereClause = "u_email_address like '%benekeith.com'"; // org type of customer

            CommerceQueryOperationResponse res = Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())
                                                 .OperationResponses[0] as CommerceQueryOperationResponse;
            List <Core.Models.Generated.UserProfile> users = new List <Core.Models.Generated.UserProfile>();

            if (res.CommerceEntities.Count > 0)
            {
                foreach (CommerceEntity ent in res.CommerceEntities)
                {
                    users.Add((Core.Models.Generated.UserProfile)ent);
                }
            }

            return(users);
        }
コード例 #18
0
        public List <Basket> ReadAllBaskets(Guid userId, BasketType type, bool runPipelines = false)
        {
            var queryBaskets = new CommerceQuery <CommerceEntity, CommerceModelSearch <CommerceEntity>, CommerceBasketQueryOptionsBuilder>("Basket");

            queryBaskets.SearchCriteria.Model.Properties["UserId"]     = userId.ToCommerceServerFormat();
            queryBaskets.SearchCriteria.Model.Properties["BasketType"] = 0;
            queryBaskets.SearchCriteria.Model.Properties["ListType"]   = (int)type;

            queryBaskets.QueryOptions.RefreshBasket = runPipelines;

            var queryLineItems = new CommerceQueryRelatedItem <CommerceEntity>("LineItems", "LineItem");

            queryBaskets.RelatedOperations.Add(queryLineItems);


            var response = FoundationService.ExecuteRequest(queryBaskets.ToRequest());

            CommerceQueryOperationResponse basketResponse = response.OperationResponses[0] as CommerceQueryOperationResponse;

            return(basketResponse.CommerceEntities.Cast <CommerceEntity>().Where(b => b.Properties["ListType"].Equals((int)type)).Select(i => (Basket)i).ToList());
        }
コード例 #19
0
        /// <summary>
        /// create a profile for the user in commerce server
        /// </summary>
        /// <param name="emailAddress">the user's email address</param>
        /// <param name="firstName">user's given name</param>
        /// <param name="lastName">user's surname</param>
        /// <param name="phoneNumber">user's telephone number</param>
        /// <remarks>
        /// jwames - 10/3/2014 - documented
        /// </remarks>
        public List <Customer> GetCustomers()
        {
            var allCustomersFromCache = _customerCacheRepository.GetItem <List <Customer> >(CACHE_GROUPNAME, CACHE_PREFIX, CACHE_NAME, GetCacheKey("allCustomers"));

            if (allCustomersFromCache == null)
            {
                var queryOrg = new CommerceServer.Foundation.CommerceQuery <KeithLink.Svc.Core.Models.Generated.Organization>("Organization");
                queryOrg.SearchCriteria.WhereClause = "u_organization_type = '0'"; // org type of customer

                CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;
                List <Customer> results            = BuildCustomerList(res.CommerceEntities);

                _customerCacheRepository.AddItem <List <Customer> >(CACHE_GROUPNAME, CACHE_PREFIX, CACHE_NAME, GetCacheKey("allCustomers"), TimeSpan.FromHours(4), results);

                return(results);
            }
            else
            {
                return(allCustomersFromCache);
            }
        }
コード例 #20
0
        public List <Customer> GetCustomersByNameSearch(string searchText)
        {
            var customerFromCache = _customerCacheRepository.GetItem <List <Customer> >(CACHE_GROUPNAME, CACHE_PREFIX, CACHE_NAME, GetCacheKey(searchText));

            if (customerFromCache == null)
            {
                var queryOrg = new CommerceServer.Foundation.CommerceQuery <KeithLink.Svc.Core.Models.Generated.Organization>("Organization");
                queryOrg.SearchCriteria.WhereClause = "u_name LIKE '%" + searchText.Replace("'", "''") + "%'"; // org type of customer

                CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;
                List <Customer> results            = BuildCustomerList(res.CommerceEntities);

                _customerCacheRepository.AddItem <List <Customer> >(CACHE_GROUPNAME, CACHE_PREFIX, CACHE_NAME, GetCacheKey(searchText), TimeSpan.FromMinutes(2), results);

                return(results);
            }
            else
            {
                return(customerFromCache);
            }
        }
コード例 #21
0
        public List <Customer> GetCustomersForUser(Guid userId)
        {
            var customerFromCache = _customerCacheRepository.GetItem <List <Customer> >(CACHE_GROUPNAME, CACHE_PREFIX, CACHE_NAME, GetCacheKey(string.Format("user_{0}", userId.ToString())));

            if (customerFromCache != null && customerFromCache.Count > 0)
            {
                //} else {
                return(customerFromCache);
            }

            // get user organization info
            var profileQuery = new CommerceServer.Foundation.CommerceQuery <CommerceServer.Foundation.CommerceEntity>("UserOrganizations");

            profileQuery.SearchCriteria.Model.Properties["UserId"] = userId.ToCommerceServerFormat();

            CommerceQueryOperationResponse res = (FoundationService.ExecuteRequest(profileQuery.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;
            List <Customer> results            = BuildCustomerList(res.CommerceEntities);

            _customerCacheRepository.AddItem <List <Customer> >(CACHE_GROUPNAME, CACHE_PREFIX, CACHE_NAME, GetCacheKey(string.Format("user_{0}", userId.ToString())), TimeSpan.FromHours(4), results);

            return(results);
        }
コード例 #22
0
        public List <Account> GetAccounts()
        {
            var queryOrg = new CommerceServer.Foundation.CommerceQuery <KeithLink.Svc.Core.Models.Generated.Organization>("Organization");

            queryOrg.SearchCriteria.WhereClause = "u_organization_type = '1'"; // org type of account

            CommerceQueryOperationResponse res = (Svc.Impl.Helpers.FoundationService.ExecuteRequest(queryOrg.ToRequest())).OperationResponses[0] as CommerceQueryOperationResponse;

            var accounts = new System.Collections.Concurrent.BlockingCollection <Account>();

            System.Threading.Tasks.Parallel.ForEach(res.CommerceEntities, e =>
            {
                KeithLink.Svc.Core.Models.Generated.Organization org = new KeithLink.Svc.Core.Models.Generated.Organization(e);
                accounts.Add(new Account()
                {
                    Id   = Guid.Parse(org.Id),
                    Name = org.Name,
                });
            });

            return(accounts.ToList());
        }
コード例 #23
0
ファイル: BeginLogging.cs プロジェクト: xorcrud/csutilities
        public override void ExecuteQuery(CommerceQueryOperation queryOperation, OperationCacheDictionary operationCache, CommerceQueryOperationResponse response)
        {
            if (LoggingShared.SkipLogging(queryOperation))
            {
                return;
            }

            operationCache[LoggingShared.WatchCacheKey] = Stopwatch.StartNew();
        }
コード例 #24
0
        public override void ExecuteQuery(CommerceQueryOperation queryOperation, OperationCacheDictionary operationCache, CommerceQueryOperationResponse response)
        {
            CommerceModelSearch searchCriteria = queryOperation.GetSearchCriteria <CommerceModelSearch>();

            ParameterChecker.CheckForNull(searchCriteria, "searchCriteria");

            if (searchCriteria.Model.Properties.Count == 1)
            {
                string sproc = string.Empty;

                if (searchCriteria.Model.Properties[0].Key == "OrganizationId")   // looking for users associated to org
                {
                    sproc = "[dbo].[sp_BEK_ReadUsersForOrg]";
                }
                else if (searchCriteria.Model.Properties[0].Key == "UserId")    // looking for orgs associated to user
                {
                    sproc = "[dbo].[sp_BEK_ReadOrgsForUser]";
                }

                CommerceResourceCollection csResources = SiteHelper.GetCsConfig();
                String connStr = csResources["Biz Data Service"]["s_BizDataStoreConnectionString"].ToString();
                //ProfileContext pContext = CommerceSiteContexts.Profile[GetSiteName()];

                using (OleDbConnection conn = new OleDbConnection(connStr)) {
                    conn.Open();

                    CommercePropertyItem item = searchCriteria.Model.Properties[0];

                    OleDbCommand cmd = new OleDbCommand(sproc, conn);

                    cmd.Parameters.Add(new OleDbParameter("@id", OleDbType.VarChar, 50));
                    cmd.Parameters[0].Value     = item.Value;
                    cmd.Parameters[0].Direction = ParameterDirection.Input;
                    cmd.CommandType             = CommandType.StoredProcedure;

                    using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd)) {
                        DataTable dt = new DataTable();
                        adapter.Fill(dt);

                        foreach (DataRow r in dt.Rows)
                        {
                            if (searchCriteria.Model.Properties[0].Key == "UserId")   // todo: use profile entity mapping to fill this in
                            //this.Metadata.ProfileMapping;
                            {
                                CommerceEntity org = new CommerceEntity("Organization");

                                org.Id = r.GetString("u_org_id");
                                org.SetPropertyValue("Name", r.GetString("u_name"));
                                org.SetPropertyValue("CustomerNumber", r.GetString("u_customer_number"));
                                org.SetPropertyValue("BranchNumber", r.GetString("u_branch_number"));
                                org.SetPropertyValue("DsrNumber", r.GetString("u_dsr_number"));
                                org.SetPropertyValue("ContractNumber", r.GetString("u_contract_number"));
                                org.SetPropertyValue("IsPoRequired", r.GetNullableBool("u_is_po_required"));
                                org.SetPropertyValue("IsPowerMenu", r.GetNullableBool("u_is_power_menu"));
                                org.SetPropertyValue("OrganizationType", r.GetString("u_organization_type"));
                                org.SetPropertyValue("NationalOrRegionalAccountNumber", r.GetString("u_national_or_regional_account_number"));
                                org.SetPropertyValue("ParentOrganizationId", r.GetString("u_parent_organization"));
                                org.SetPropertyValue("TermCode", r.GetString("u_term_code"));
                                org.SetPropertyValue("CurrentBalance", r.GetNullableDecimal("u_current_balance"));
                                org.SetPropertyValue("BalanceAge1", r.GetNullableDecimal("u_balance_age_1"));
                                org.SetPropertyValue("BalanceAge2", r.GetNullableDecimal("u_balance_age_2"));
                                org.SetPropertyValue("BalanceAge3", r.GetNullableDecimal("u_balance_age_3"));
                                org.SetPropertyValue("BalanceAge4", r.GetNullableDecimal("u_balance_age_4"));
                                org.SetPropertyValue("AmountDue", r.GetNullableDecimal("u_amount_due"));
                                org.SetPropertyValue("AchType", r.GetString("u_customer_ach_type"));
                                org.SetPropertyValue("GeneralInfo.preferred_address", r.GetString("u_preferred_address"));

                                response.CommerceEntities.Add(org);
                            }
                            else if (searchCriteria.Model.Properties[0].Key == "OrganizationId")
                            {
                                CommerceEntity org = new CommerceEntity("UserProfile");

                                org.Id = r.GetString("u_user_id");
                                org.SetPropertyValue("FirstName", r.GetString("u_first_name"));
                                org.SetPropertyValue("LastName", r.GetString("u_last_name"));
                                org.SetPropertyValue("Email", r.GetString("u_email_address"));

                                response.CommerceEntities.Add(org);
                            }
                        }
                    }

                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                }
            }
            else
            {
                base.ExecuteQuery(queryOperation, operationCache, response);
            }
        }
コード例 #25
0
        public override void ExecuteQuery(CommerceQueryOperation queryOperation, OperationCacheDictionary operationCache, CommerceQueryOperationResponse response)
        {
            if ((int)((CommerceServer.Foundation.CommerceModelSearch)(queryOperation.SearchCriteria)).Model.Properties["BasketType"] == 1) // when retrieving purchase order, supplement data that isn't auto mapped
            {
                foreach (CommerceEntity e in response.CommerceEntities)
                {
                    CommerceServer.Core.Runtime.Orders.PurchaseOrder po =
                        (operationCache.FirstOrDefault().Value as Dictionary <string, CommerceServer.Core.Runtime.Orders.OrderGroup>)[e.Id] as CommerceServer.Core.Runtime.Orders.PurchaseOrder;
                    CommerceServer.Core.Runtime.Orders.LineItem[] lineItems = new CommerceServer.Core.Runtime.Orders.LineItem[po.OrderForms[0].LineItems.Count];

                    if (po.OrderForms[0].LineItems.Count > 0)
                    {
                        po.OrderForms[0].LineItems.CopyTo(lineItems, 0);
                    }

                    bool skip = true;
                    foreach (var prop in e.Properties)
                    {
                        if (skip)
                        {
                            if (prop.Key == "BranchId") // only start setting custom properties
                            {
                                skip = false;
                            }
                            if (skip)
                            {
                                continue;
                            }
                        }
                        if (po[prop.Key] != null)
                        {
                            prop.Value = po[prop.Key];
                        }
                    }
                    // next do line items
                    if (e.Properties["LineItems"] != null)
                    {
                        foreach (var l in (e.Properties["LineItems"] as CommerceRelationshipList))
                        {
                            List <CommercePropertyItem> items = l.Target.Properties.Where(x => x.Value == null).ToList();
                            CommerceServer.Core.Runtime.Orders.LineItem poLineItem = lineItems.Where(x => x.LineItemId.ToCommerceServerFormat() == l.Target.Id).FirstOrDefault();
                            skip = true;
                            foreach (var prop in l.Target.Properties)
                            {
                                if (skip)
                                {
                                    if (prop.Key == "LinePosition") // only lookup BEK custom properties
                                    {
                                        skip = false;
                                    }
                                    if (skip)
                                    {
                                        continue;
                                    }
                                }
                                if (poLineItem[prop.Key] != null)
                                {
                                    prop.Value = poLineItem[prop.Key];
                                }
                            }
                        }
                    }
                }
            }
        }
コード例 #26
0
        // by default, CS Profile Sequence Components only load profiles by ID; so we have to override that functionality to get a list back
        public override void ExecuteQuery(CommerceQueryOperation queryOperation, OperationCacheDictionary operationCache, CommerceQueryOperationResponse response)
        {
            CommerceModelSearch search = ((CommerceModelSearch)(queryOperation.SearchCriteria));

            if (!String.IsNullOrEmpty(search.WhereClause))   // no search criteria, so override CS behavior to load all orgs
            {
                CommerceResourceCollection csResources = SiteHelper.GetCsConfig();

                String connStr = csResources["Biz Data Service"]["s_BizDataStoreConnectionString"].ToString();
                //ProfileContext pContext = CommerceSiteContexts.Profile[GetSiteName()];
                string         fields = string.Join(", ", Array.ConvertAll(this.ProfileEntityMappings.PropertyMappings.ToArray(), i => i.Value));
                ProfileContext ctxt   = CommerceSiteContexts.Profile[SiteHelper.GetSiteName()];

                var sqlFormat = " SELECT * FROM [BEK_Commerce_profiles].[dbo].[OrganizationObject] oo {0} Order By oo.u_name OFFSET {1} ROWS FETCH NEXT {2} ROWS ONLY;";

                var pageSize = queryOperation.SearchCriteria.NumberOfItemsToReturn.HasValue ? queryOperation.SearchCriteria.NumberOfItemsToReturn.Value : int.MaxValue;
                var from     = queryOperation.SearchCriteria.FirstItemIndex.HasValue ? queryOperation.SearchCriteria.FirstItemIndex.Value : 0;

                string dataSQLText = string.Format(sqlFormat, search.WhereClause.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) >= 0
                                                    ? search.WhereClause : "WHERE " + search.WhereClause, from, pageSize);
                string countSQLText = string.Format("SELECT count(*) FROM [BEK_Commerce_profiles].[dbo].[OrganizationObject] oo {0}",
                                                    search.WhereClause.IndexOf("where", StringComparison.CurrentCultureIgnoreCase) >= 0 ? search.WhereClause : "WHERE " + search.WhereClause);


                var entities = new List <CommerceEntity>();

                using (OleDbConnection conn = new OleDbConnection(connStr)) {
                    conn.Open();

                    //Get total count
                    using (OleDbCommand cmdTotal = new OleDbCommand(countSQLText, conn)) {
                        response.TotalItemCount = (int)cmdTotal.ExecuteScalar();
                    }

                    //Read paged results
                    using (OleDbCommand cmdRead = new OleDbCommand(dataSQLText, conn)) {
                        using (OleDbDataReader dataReader = cmdRead.ExecuteReader()) {
                            while (dataReader.Read())
                            {
                                CommerceEntity org = new CommerceEntity("Organization");

                                org.Id = dataReader.GetString("u_org_id");
                                org.SetPropertyValue("Name", dataReader.GetString("u_name"));
                                org.SetPropertyValue("CustomerNumber", dataReader.GetString("u_customer_number"));
                                org.SetPropertyValue("BranchNumber", dataReader.GetString("u_branch_number"));
                                org.SetPropertyValue("DsrNumber", dataReader.GetString("u_dsr_number"));
                                org.SetPropertyValue("ContractNumber", dataReader.GetString("u_contract_number"));
                                org.SetPropertyValue("IsPoRequired", dataReader.GetNullableBool("u_is_po_required"));
                                org.SetPropertyValue("IsPowerMenu", dataReader.GetNullableBool("u_is_power_menu"));
                                org.SetPropertyValue("OrganizationType", dataReader.GetString("u_organization_type"));
                                org.SetPropertyValue("NationalOrRegionalAccountNumber", dataReader.GetString("u_national_or_regional_account_number"));
                                org.SetPropertyValue("ParentOrganizationId", dataReader.GetString("u_parent_organization"));
                                org.SetPropertyValue("TermCode", dataReader.GetString("u_term_code"));
                                org.SetPropertyValue("CurrentBalance", dataReader.GetNullableDecimal("u_current_balance"));
                                org.SetPropertyValue("BalanceAge1", dataReader.GetNullableDecimal("u_balance_age_1"));
                                org.SetPropertyValue("BalanceAge2", dataReader.GetNullableDecimal("u_balance_age_2"));
                                org.SetPropertyValue("BalanceAge3", dataReader.GetNullableDecimal("u_balance_age_3"));
                                org.SetPropertyValue("BalanceAge4", dataReader.GetNullableDecimal("u_balance_age_4"));
                                org.SetPropertyValue("AmountDue", dataReader.GetNullableDecimal("u_amount_due"));
                                org.SetPropertyValue("AchType", dataReader.GetString("u_customer_ach_type"));
                                org.SetPropertyValue("DsmNumber", dataReader.GetString("u_dsm_number"));
                                org.SetPropertyValue("NationalId", dataReader.GetString("u_national_id"));
                                org.SetPropertyValue("NationalNumber", dataReader.GetString("u_national_number"));
                                org.SetPropertyValue("NationalSubNumber", dataReader.GetString("u_national_sub_number"));
                                org.SetPropertyValue("RegionalId", dataReader.GetString("u_regional_id"));
                                org.SetPropertyValue("RegionalNumber", dataReader.GetString("u_regional_number"));
                                org.SetPropertyValue("IsKeithnetCustomer", dataReader.GetString("u_is_keithnet_customer"));
                                org.SetPropertyValue("NationalIdDesc", dataReader.GetString("u_national_id_desc"));
                                org.SetPropertyValue("NationalNumberSubDesc", dataReader.GetString("u_national_numbersub_desc"));
                                org.SetPropertyValue("RegionalIdDesc", dataReader.GetString("u_regional_id_desc"));
                                org.SetPropertyValue("RegionalNumberDesc", dataReader.GetString("u_regional_number_desc"));
                                org.SetPropertyValue("GeneralInfo.preferred_address", dataReader.GetString("u_preferred_address"));
                                org.SetPropertyValue("CanViewPricing", dataReader.GetNullableBool("u_can_view_pricing"));

                                response.CommerceEntities.Add(org);
                            }
                        }
                    }

                    if (conn.State == System.Data.ConnectionState.Open)
                    {
                        conn.Close();
                    }
                }
            }
            else
            {
                base.ExecuteQuery(queryOperation, operationCache, response);
            }
        }
コード例 #27
0
 public override void ExecuteQuery(CommerceQueryOperation queryOperation, OperationCacheDictionary operationCache, CommerceQueryOperationResponse response)
 {
     // don't need to do anything; the profile loading process loads Commerce Entities directly...
 }
コード例 #28
0
        public override void ExecuteQuery(CommerceQueryOperation queryOperation, OperationCacheDictionary operationCache, CommerceQueryOperationResponse response)
        {
            int numToTake = 2000;

            lock (_addressLoaderLock) {
                for (int i = 0; i < response.CommerceEntities.Count && response.CommerceEntities.Count < numToTake; i += numToTake)   // only load addresses if we have less than 2000; any more than that will require a incoming filter
                {
                    List <string> preferredAddressIds = new List <string>();
                    Dictionary <string, string> addressToParentIdMap = new Dictionary <string, string>();
                    List <CommerceEntity>       currentBatch         = response.CommerceEntities.Skip(i).Take(numToTake).ToList();

                    foreach (var entity in currentBatch)
                    {
                        string preferredAddressId = entity.GetPropertyValue("GeneralInfo.preferred_address") as string;
                        if (!String.IsNullOrEmpty(preferredAddressId) && !addressToParentIdMap.ContainsKey(preferredAddressId))
                        {
                            preferredAddressIds.Add("'" + preferredAddressId + "'");
                            addressToParentIdMap.Add(preferredAddressId, entity.Id);
                        }
                    }
                    // query them out
                    if (preferredAddressIds.Count == 0)
                    {
                        continue;
                    }

                    CommerceResourceCollection csResources = SiteHelper.GetCsConfig();

                    String connStr = csResources["Biz Data Service"]["s_BizDataStoreConnectionString"].ToString();
                    //ProfileContext pContext = CommerceSiteContexts.Profile[GetSiteName()];
                    string         fields = string.Join(", ", Array.ConvertAll(this.ProfileEntityMappings.PropertyMappings.ToArray(), p => p.Value));
                    string         keys   = string.Join(", ", Array.ConvertAll(this.ProfileEntityMappings.PropertyMappings.ToArray(), p => p.Key));
                    ProfileContext ctxt   = CommerceSiteContexts.Profile[SiteHelper.GetSiteName()];

                    string dataSQLText = "SELECT *  FROM [BEK_Commerce_profiles].[dbo].[Addresses] WHERE u_address_id in (" + String.Join(",", preferredAddressIds.ToArray()) + ")";

                    try {
                        using (OleDbConnection conn = new OleDbConnection(connStr)) {
                            conn.Open();

                            using (OleDbCommand cmdRead = new OleDbCommand(dataSQLText, conn)) {
                                using (OleDbDataReader dataReader = cmdRead.ExecuteReader()) {
                                    while (dataReader.Read())
                                    {
                                        CommerceEntity entity = new CommerceEntity("Address");

                                        entity.Id = dataReader.GetString("u_address_id");
                                        entity.SetPropertyValue("LastName", dataReader.GetString("u_last_name"));
                                        entity.SetPropertyValue("FirstName", dataReader.GetString("u_first_name"));
                                        entity.SetPropertyValue("AddressName", dataReader.GetString("u_address_name"));
                                        entity.SetPropertyValue("AddressType", dataReader.GetNullableInt("i_address_type"));
                                        entity.SetPropertyValue("Description", dataReader.GetString("u_description"));
                                        entity.SetPropertyValue("Line1", dataReader.GetString("u_address_line1"));
                                        entity.SetPropertyValue("Line2", dataReader.GetString("u_address_line2"));
                                        entity.SetPropertyValue("City", dataReader.GetString("u_city"));
                                        entity.SetPropertyValue("StateProvinceCode", dataReader.GetString("u_region_code"));
                                        entity.SetPropertyValue("StateProvinceName", dataReader.GetString("u_region_name"));
                                        entity.SetPropertyValue("ZipPostalCode", dataReader.GetString("u_postal_code"));
                                        entity.SetPropertyValue("CountryRegionCode", dataReader.GetString("u_country_code"));
                                        entity.SetPropertyValue("CountryRegionName", dataReader.GetString("u_country_name"));
                                        entity.SetPropertyValue("Telephone", dataReader.GetString("u_tel_number"));
                                        entity.SetPropertyValue("TelephoneExtension", dataReader.GetString("u_tel_extension"));
                                        entity.SetPropertyValue("LocaleId", dataReader.GetString("i_locale"));
                                        entity.SetPropertyValue("DateModified", dataReader.GetNullableDateTime("dt_date_last_changed"));
                                        entity.SetPropertyValue("DateCreated", dataReader.GetNullableDateTime("dt_date_created"));

                                        currentBatch.Where(x => x.Id == (addressToParentIdMap[entity.Id])).FirstOrDefault()
                                        .Properties.Add("PreferredAddress", new CommerceRelationship(entity));
                                    }
                                    dataReader.Close();
                                }
                            }
                        }
                    } catch (Exception ex) {
                        throw new ApplicationException("Error loading organization addresses", ex);
                    }
                }
            }
        }
コード例 #29
0
        public override void ExecuteQuery(CommerceQueryOperation queryOperation, OperationCacheDictionary operationCache, CommerceQueryOperationResponse response)
        {
            CommerceModelSearch search = ((CommerceModelSearch)(queryOperation.SearchCriteria));

            if (!String.IsNullOrEmpty(search.WhereClause))
            {
                // do nothing
            }
            else
            {
                base.ExecuteQuery(queryOperation, operationCache, response);
            }
        }
コード例 #30
0
ファイル: EndLogging.cs プロジェクト: xorcrud/csutilities
        public override void ExecuteQuery(CommerceQueryOperation queryOperation, OperationCacheDictionary operationCache, CommerceQueryOperationResponse response)
        {
            if (queryOperation == null)
            {
                throw new ArgumentNullException("queryOperation");
            }
            if (operationCache == null)
            {
                throw new ArgumentNullException("operationCache");
            }
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            if (LoggingShared.SkipLogging(queryOperation))
            {
                return;
            }

            if (!EnsureStorageProvider())
            {
                return;
            }

            TimeSpan?elapsedTime = GetExecutionTime(operationCache);
            CommerceCatalogFullTextSearch searchCriteria = GetSearchCriteria(queryOperation);

            if (searchCriteria == null)
            {
                return;
            }

            var provider = _container.GetService <ILoggingStorageProvider>();

            provider.Log(new LoggingResult());
        }