示例#1
0
 public Task <PagedResult <Category> > GetChildren(long channelId, long categoryId, QueryResultSettings queryResultSettings)
 {
     return(Task.Run(() => ChannelManager.Create(CommerceRuntimeManager.Runtime).GetDirectChildCategories(channelId, categoryId, queryResultSettings)));
 }
示例#2
0
            /// <summary>
            /// Loads the specified listing page, and returns true if a full page was loaded.
            /// </summary>
            /// <param name="productsSearchCriteria">The search criteria.</param>
            /// <param name="querySettings">The query settings.</param>
            /// <returns>Returns changed products.</returns>
            private ChangedProductsSearchResult LoadChangedProducts(ChangedProductsSearchCriteria productsSearchCriteria, QueryResultSettings querySettings)
            {
                Stopwatch watch = Stopwatch.StartNew();

                ChangedProductsSearchResult results;

                results = this.productManager.GetChangedProducts(productsSearchCriteria, querySettings);

                watch.Stop();
                int numberOfReadProducts = results.Results.Count;

                this.LogTimingMessage(Resources.NumberOfReadProductsInPage, numberOfReadProducts, watch.Elapsed);

                return(results);
            }
示例#3
0
            /// <summary>
            /// Gets terminal entity by identifier.
            /// </summary>
            /// <param name="context">The request context.</param>
            /// <param name="terminalId">The terminal identifier.</param>
            /// <param name="settings">The query result settings to retrieve the terminal.</param>
            /// <returns>The terminal object.</returns>
            private Terminal GetTerminalById(RequestContext context, string terminalId, QueryResultSettings settings)
            {
                ThrowIf.NullOrWhiteSpace(terminalId, "terminalId");
                ThrowIf.Null(settings, "settings");

                Terminal terminal;
                var      query = new SqlPagedQuery(settings)
                {
                    From  = TerminalDatabaseAccessor.TerminalsViewName,
                    Where = "TERMINALID = @id"
                };

                query.Parameters["@id"] = terminalId;

                using (var databaseContext = new DatabaseContext(context))
                {
                    terminal = databaseContext.ReadEntity <Terminal>(query).Results.SingleOrDefault();
                }

                return(terminal);
            }
示例#4
0
 public Task <PagedResult <PurchaseOrder> > ReadAll(QueryResultSettings queryResultSettings)
 {
     return(Task.Run(() => InventoryManager.Create(CommerceRuntimeManager.Runtime).GetPurchaseOrder(null)));
 }
示例#5
0
            private PagedResult <GlobalCustomer> SearchCustomersSproc(string keyword, bool onlyCurrentCompany, QueryResultSettings settings)
            {
                using (SqliteDatabaseContext databaseContext = new SqliteDatabaseContext(this.Context))
                {
                    // Use the "LIKE" to search for customer related table fields
                    // Based on the pre-populated materialized view crt_CUSTOMERSEARCHABLEFIELDSVIEW
                    string queryText = @"WITH UNIQUEPARTYIDS AS
                                    (
                                        SELECT DISTINCT csfv.PARTY
                                        FROM crt_CUSTOMERSEARCHABLEFIELDSVIEW csfv
                                            INNER JOIN (
                                                SELECT PARTY, ADDRESSBOOK
                                                FROM AX_DIRADDRESSBOOKPARTY
                                                WHERE PARTY NOT IN (SELECT RECID FROM AX_OMINTERNALORGANIZATION)) dap ON csfv.PARTY = dap.PARTY
                                            INNER JOIN AX_RETAILSTOREADDRESSBOOK rsab ON dap.ADDRESSBOOK = rsab.ADDRESSBOOK
                                        WHERE rsab.STORERECID = @bi_ChannelId AND csfv.FIELD LIKE @nvc_SearchCondition
                                    )
                                    SELECT PARTYNUMBER,
                                            CASE
                                                WHEN gcv.DATAAREAID <> '' THEN gcv.ACCOUNTNUMBER
                                                ELSE ''
                                            END AS ACCOUNTNUMBER,
                                            NAME,
                                            FULLADDRESS,
                                            PHONE,
                                            EMAIL,
                                            INSTANCERELATIONTYPE as CUSTOMERTYPE,
                                            ORGID,
                                            RECORDID
                                    FROM CRT_GLOBALCUSTOMERSVIEW gcv
                                        INNER JOIN UNIQUEPARTYIDS pid ON gcv.RECORDID = pid.PARTY
                                    WHERE (@b_SearchCrossCompany <> 1 AND ACCOUNTNUMBER != '' AND gcv.DATAAREAID = @nvc_DataAreaId)
                                        OR (@b_SearchCrossCompany = 1)
                                    LIMIT @i_Top, @i_Skip;";

                    var parameters = new ParameterSet();
                    parameters["@bi_ChannelId"]         = databaseContext.ChannelId;
                    parameters["@nvc_DataAreaId"]       = databaseContext.DataAreaId;
                    parameters["@nvc_SearchCondition"]  = string.Format("%{0}%", keyword);
                    parameters["@b_SearchCrossCompany"] = Convert.ToInt32(onlyCurrentCompany);
                    parameters["@i_Top"]  = settings.Paging.Top;
                    parameters["@i_Skip"] = settings.Paging.Skip;
                    var query = new SqlQuery(queryText, parameters);
                    PagedResult <GlobalCustomer> customers = databaseContext.ReadEntity <GlobalCustomer>(query);

                    return(customers);
                }
            }
示例#6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlServerDatabaseContext"/> class.
 /// </summary>
 /// <param name="request">The data request.</param>
 public SqlServerDatabaseContext(Request request)
     : base(request.RequestContext)
 {
     this.settings = request.QueryResultSettings;
 }
示例#7
0
            /// <summary>
            /// Gets the order delivery options for shipping.
            /// </summary>
            /// <param name="shipToAddress">The ship to address.</param>
            /// <param name="queryResultSettings">The query result settings.</param>
            /// <returns>The service response containing the available delivery options.</returns>
            public async Task <ActionResult> GetOrderDeliveryOptionsForShipping(Address shipToAddress, QueryResultSettings queryResultSettings)
            {
                EcommerceContext      ecommerceContext      = ServiceUtilities.GetEcommerceContext(this.HttpContext);
                CartOperationsHandler cartOperationsHandler = new CartOperationsHandler(ecommerceContext);

                SessionType sessionType = ServiceUtilities.GetSessionType(this.HttpContext, isCheckoutSession: true);
                string      cartId      = ServiceUtilities.GetCartIdFromRequestCookie(this.HttpContext, sessionType);

                PagedResult <DeliveryOption> deliveryOptions = await cartOperationsHandler.GetOrderDeliveryOptionsForShipping(cartId, shipToAddress, queryResultSettings);

                return(this.Json(deliveryOptions));
            }
            public async Task <PagedResult <ProductSearchResult> > SearchByText(string searchText, long catalogId, QueryResultSettings queryResultSettings)
            {
                if (string.IsNullOrEmpty(searchText))
                {
                    throw new ArgumentNullException(nameof(searchText));
                }

                ManagerFactory  managerFactory = Utilities.GetManagerFactory(this.EcommerceContext);
                IProductManager productManager = managerFactory.GetManager <IProductManager>();
                long            channelId      = await Utilities.GetChannelId(this.EcommerceContext);

                PagedResult <ProductSearchResult> productSearchResults = await productManager.SearchByText(channelId, catalogId, searchText, queryResultSettings);

                return(productSearchResults);
            }
            public virtual async Task <PagedResult <ProductAvailableQuantity> > GetProductAvailability(IEnumerable <long> productIds, long channelId, QueryResultSettings queryResultSettings)
            {
                if (productIds == null)
                {
                    throw new ArgumentNullException(nameof(productIds));
                }

                ManagerFactory  managerFactory = Utilities.GetManagerFactory(this.EcommerceContext);
                IProductManager productManager = managerFactory.GetManager <IProductManager>();

                PagedResult <ProductAvailableQuantity> productAvailableQuantities =
                    await productManager.GetProductAvailabilities(productIds, 0, queryResultSettings);

                return(productAvailableQuantities);
            }
示例#10
0
 public Task <PagedResult <ProductCatalog> > GetCatalogs(long channelId, bool activeOnly, QueryResultSettings queryResultSettings)
 {
     return(Task.Run(() => Runtime.Client.ProductManager.Create(CommerceRuntimeManager.Runtime).GetProductCatalogs(channelId, activeOnly, queryResultSettings)));
 }
            public async Task <PagedResult <ProductPrice> > GetActivePrices(IEnumerable <long> productIds, long?catalogId, IEnumerable <long> affiliationLoyaltyTierIds, QueryResultSettings queryResultSettings)
            {
                IProductManager manager   = Utilities.GetManagerFactory(this.EcommerceContext).GetManager <IProductManager>();
                long            channelId = await Utilities.GetChannelId(this.EcommerceContext);

                ProjectionDomain projectionDomain = new ProjectionDomain {
                    ChannelId = channelId, CatalogId = catalogId
                };
                IList <AffiliationLoyaltyTier> tiers = null;

                if (affiliationLoyaltyTierIds != null)
                {
                    tiers = new List <AffiliationLoyaltyTier>();
                    foreach (long affiliationLoyaltyTierId in affiliationLoyaltyTierIds)
                    {
                        tiers.Add(new AffiliationLoyaltyTier {
                            AffiliationId = affiliationLoyaltyTierId
                        });
                    }
                }

                PagedResult <ProductPrice> productPrices = await manager.GetActivePrices(projectionDomain, productIds, DateTimeOffset.UtcNow, null, tiers, queryResultSettings);

                return(productPrices);
            }
示例#12
0
 public Task <PagedResult <ProductCatalog> > ReadAll(QueryResultSettings queryResultSettings)
 {
     throw new NotSupportedException();
 }
示例#13
0
            /// <summary>
            /// Gets the sales order.
            /// </summary>
            /// <param name="salesOrderSearchCriteria">The sales order search criteria.</param>
            /// <param name="queryResultSettings">The query result settings.</param>
            /// <returns>A response containing the sales orders inquired for.</returns>
            public async Task <ActionResult> GetSalesOrder(SalesOrderSearchCriteria salesOrderSearchCriteria, QueryResultSettings queryResultSettings)
            {
                EcommerceContext            ecommerceContext           = ServiceUtilities.GetEcommerceContext(this.HttpContext);
                SalesOrderOperationsHandler salesOrderOperationHandler = new SalesOrderOperationsHandler(ecommerceContext);
                PagedResult <SalesOrder>    salesOrders = await salesOrderOperationHandler.GetSalesOrder(salesOrderSearchCriteria, queryResultSettings);

                return(this.Json(salesOrders.Results));
            }
示例#14
0
            public EntityDataServiceResponse <Shift> Execute(QueryResultSettings queryResultSettings)
            {
                SqlPagedQuery query = new SqlPagedQuery(queryResultSettings)
                {
                    From    = ShiftsView,
                    OrderBy = "SHIFTID",
                };

                IList <string> whereClauses = new List <string>();

                // Builds where clauses for query.
                if (this.request.Criteria.ChannelId != null)
                {
                    whereClauses.Add("CHANNEL = @ChannelId");
                }

                if (this.request.Criteria.Status != null)
                {
                    whereClauses.Add("STATUS = @Status");
                }

                if (!string.IsNullOrEmpty(this.request.Criteria.StaffId))
                {
                    if (this.request.Criteria.SearchByStaffId && this.request.Criteria.SearchByCurrentStaffId)
                    {
                        whereClauses.Add("(STAFFID = @StaffId OR CURRENTSTAFFID = @StaffId)");
                    }

                    if (this.request.Criteria.SearchByStaffId && !this.request.Criteria.SearchByCurrentStaffId)
                    {
                        whereClauses.Add("STAFFID = @StaffId");
                    }

                    if (!this.request.Criteria.SearchByStaffId && this.request.Criteria.SearchByCurrentStaffId)
                    {
                        whereClauses.Add("CURRENTSTAFFID = @StaffId");
                    }
                }

                if (!string.IsNullOrEmpty(this.request.Criteria.TerminalId))
                {
                    if (this.request.Criteria.SearchByTerminalId && this.request.Criteria.SearchByCurrentTerminalId)
                    {
                        whereClauses.Add("(TERMINALID = @TerminalId OR CURRENTTERMINALID = @TerminalId)");
                    }

                    if (this.request.Criteria.SearchByTerminalId && !this.request.Criteria.SearchByCurrentTerminalId)
                    {
                        whereClauses.Add("TERMINALID = @TerminalId");
                    }

                    if (!this.request.Criteria.SearchByTerminalId && this.request.Criteria.SearchByCurrentTerminalId)
                    {
                        whereClauses.Add("CURRENTTERMINALID = @TerminalId");
                    }
                }

                if (this.request.Criteria.ShiftId != null)
                {
                    whereClauses.Add("SHIFTID = @ShiftId");
                }

                query.Where = string.Join(" AND ", whereClauses);

                // Build query for shared shifts.
                if (!this.request.Criteria.IncludeSharedShifts)
                {
                    query.Where += " AND (ISSHARED IS NULL OR ISSHARED <> 1)";
                }

                // Sets query parameters.
                if (this.request.Criteria.ChannelId != null)
                {
                    query.Parameters.Add("@ChannelId", this.request.Criteria.ChannelId);
                }

                if (this.request.Criteria.Status != null)
                {
                    query.Parameters.Add("@Status", this.request.Criteria.Status);
                }

                if (!string.IsNullOrEmpty(this.request.Criteria.StaffId))
                {
                    query.Parameters.Add("@StaffId", this.request.Criteria.StaffId);
                }

                if (!string.IsNullOrEmpty(this.request.Criteria.TerminalId))
                {
                    query.Parameters.Add("@TerminalId", this.request.Criteria.TerminalId);
                }

                if (this.request.Criteria.ShiftId != null)
                {
                    query.Parameters.Add("@ShiftId", this.request.Criteria.ShiftId);
                }

                PagedResult <Shift> shifts = this.databaseContext.ReadEntity <Shift>(query);

                return(new EntityDataServiceResponse <Shift>(shifts));
            }
示例#15
0
            /// <summary>
            /// Executes the operation asynchronous with paged results.
            /// </summary>
            /// <typeparam name="T">The type of of entity.</typeparam>
            /// <param name="entitySet">The entity set.</param>
            /// <param name="entitySetTypeName">Type name of the entity set.</param>
            /// <param name="operation">The operation name.</param>
            /// <param name="isAction">True, if the operation is an action; false, if the operation is a function.</param>
            /// <param name="queryResultSettings">The query result settings.</param>
            /// <param name="expandProperties">The navigation properties to be expanded.</param>
            /// <param name="operationParameters">The operation parameters.</param>
            /// <returns>The paged results of objects.</returns>
            public async Task <PagedResult <T> > ExecuteOperationAsync <T>(string entitySet, string entitySetTypeName, string operation, bool isAction, QueryResultSettings queryResultSettings, ICollection <string> expandProperties, params OperationParameter[] operationParameters)
            {
                if (BatchHelper.IsInBatchMode(this.batchId))
                {
                    if (isAction)
                    {
                        throw new NotSupportedException("Action is not supported in batch mode, only Read, ReadAll, and Functions are supported.");
                    }
                    else
                    {
                        Guid localBatchId = this.batchId.Value;

                        TaskCompletionSource <object> taskCompletionSource = this.parametersCache.PutParameters <T>(localBatchId, entitySet, entitySetTypeName, operation, queryResultSettings, expandProperties, operationParameters);

                        return(await taskCompletionSource.Task.ContinueWith <PagedResult <T> >(this.GetPagedResult <T>));
                    }
                }
                else
                {
                    string result = await Task.Run(async() => await AdaptorCaller.ExecuteAsync(GetRequestUri(entitySetTypeName, operation, queryResultSettings, operationParameters)));

                    result = AdaptorCaller.RemoveCommerceRuntimePrefix(result);

                    TryThrowAsCommerceException(result);
                    PagedResult <T> pagedResult = result.DeserializeJsonObject <PagedResult <T> >();

                    return(pagedResult);
                }
            }
            public virtual async Task <PagedResult <Product> > SearchProducts(ProductSearchCriteria productSearchCriteria, IEnumerable <long> catalogIds, QueryResultSettings queryResultSettings)
            {
                if (productSearchCriteria == null)
                {
                    throw new ArgumentNullException(nameof(productSearchCriteria));
                }

                if (catalogIds == null || !catalogIds.Any())
                {
                    throw new ArgumentNullException(nameof(catalogIds));
                }

                if (Utilities.AreNonCataloguedProductsIncludedByDefault() || catalogIds.Contains(0))
                {
                    // Override the list of catalog Ids to zero, because query for zero will automatically included products from all catalogs.
                    catalogIds = new long[] { 0 };
                }

                ManagerFactory  managerFactory = Utilities.GetManagerFactory(this.EcommerceContext);
                IOrgUnitManager orgUnitManager = managerFactory.GetManager <IOrgUnitManager>();
                long            channelId      = await Utilities.GetChannelId(this.EcommerceContext);

                List <Product> productsFromAllCatalogs = new List <Product>();

                IProductManager productManager = managerFactory.GetManager <IProductManager>();

                foreach (long catalogId in catalogIds.Distinct())
                {
                    productSearchCriteria.Context = new ProjectionDomain()
                    {
                        ChannelId = channelId,
                        CatalogId = catalogId
                    };

                    PagedResult <Product> products = await productManager.Search(productSearchCriteria, queryResultSettings);

                    productsFromAllCatalogs.AddRange(products.Results);
                }

                PagedResult <Product> allProducts = new PagedResult <Product>(productsFromAllCatalogs);

                return(allProducts);
            }
示例#17
0
 /// <summary>
 /// Reads all entities of type T.
 /// </summary>
 /// <typeparam name="T">The type of of entity.</typeparam>
 /// <param name="entitySet">The entity set.</param>
 /// <param name="expandProperties">The navigation properties to be expanded.</param>
 /// <param name="queryResultSettings">The query result settings.</param>
 /// <returns>
 /// Collection of objects.
 /// </returns>
 public async Task <RetailProxy.PagedResult <T> > ReadAll <T>(string entitySet, ICollection <string> expandProperties, QueryResultSettings queryResultSettings)
     where T : ICommerceEntity
 {
     return(await this.ExecuteOperationAsync <T>(entitySet, typeof(T).Name, ActionNames.ReadAll, false, queryResultSettings, expandProperties));
 }
            public virtual async Task <PagedResult <StateProvinceInfo> > GetStateProvinces(string countryCode, QueryResultSettings queryResultSettings)
            {
                ManagerFactory          managerFactory         = Utilities.GetManagerFactory(this.EcommerceContext);
                IStoreOperationsManager storeOperationsManager = managerFactory.GetManager <IStoreOperationsManager>();

                PagedResult <StateProvinceInfo> stateProvinceInfoCollection = await storeOperationsManager.GetStateProvinces(countryCode, queryResultSettings);

                return(stateProvinceInfoCollection);
            }
示例#19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SqlServerDatabaseContext"/> class.
 /// </summary>
 /// <param name="context">The data request context.</param>
 /// <param name="requestSettings">The request settings.</param>
 public SqlServerDatabaseContext(RequestContext context, QueryResultSettings requestSettings)
     : base(context)
 {
     this.settings = requestSettings;
 }
            public virtual async Task <PagedResult <LoyaltyCardTransaction> > GetLoyaltyCardTransactions(string loyaltyCardNumber, string rewardPointId, QueryResultSettings queryResultSettings)
            {
                ManagerFactory          managerFactory         = Utilities.GetManagerFactory(this.EcommerceContext);
                IStoreOperationsManager storeOperationsManager = managerFactory.GetManager <IStoreOperationsManager>();

                PagedResult <LoyaltyCardTransaction> loyaltyCardTransactions = await storeOperationsManager.GetLoyaltyCardTransactions(loyaltyCardNumber, rewardPointId, queryResultSettings);

                return(loyaltyCardTransactions);
            }
示例#21
0
            /// <summary>
            /// Gets the line delivery options for shipping.
            /// </summary>
            /// <param name="lineShippingAddresses">The line shipping addresses.</param>
            /// <param name="queryResultSettings">The query result settings.</param>
            /// <returns>
            /// The service response containing the available delivery options for the specified lines.
            /// </returns>
            public async Task <ActionResult> GetLineDeliveryOptionsForShipping(IEnumerable <LineShippingAddress> lineShippingAddresses, QueryResultSettings queryResultSettings)
            {
                EcommerceContext      ecommerceContext      = ServiceUtilities.GetEcommerceContext(this.HttpContext);
                CartOperationsHandler cartOperationsHandler = new CartOperationsHandler(ecommerceContext);

                SessionType sessionType = ServiceUtilities.GetSessionType(this.HttpContext, isCheckoutSession: true);
                string      cartId      = ServiceUtilities.GetCartIdFromRequestCookie(this.HttpContext, sessionType);

                PagedResult <SalesLineDeliveryOption> lineDeliveryOptions = await cartOperationsHandler.GetLineDeliveryOptionsForShipping(cartId, lineShippingAddresses, queryResultSettings);

                return(this.Json(lineDeliveryOptions.Results));
            }
            public virtual async Task <PagedResult <CountryRegionInfo> > GetCountryRegionInfo(string languageId, QueryResultSettings queryResultSettings)
            {
                ManagerFactory          managerFactory         = Utilities.GetManagerFactory(this.EcommerceContext);
                IStoreOperationsManager storeOperationsManager = managerFactory.GetManager <IStoreOperationsManager>();

                PagedResult <CountryRegionInfo> countryRegionInfoCollection =
                    await storeOperationsManager.GetCountryRegionsByLanguageId(languageId, queryResultSettings);

                return(countryRegionInfoCollection);
            }
示例#23
0
            /// <summary>
            /// Gets the customers.
            /// </summary>
            /// <param name="keyword">Optional record identifier of the customer to retrieve.</param>
            /// <param name="onlyCurrentCompany">If set to <c>true</c> [only current company].</param>
            /// <param name="settings">The query result settings.</param>
            /// <returns>
            /// A collection of customers.
            /// </returns>
            public PagedResult <GlobalCustomer> SearchCustomers(string keyword, bool onlyCurrentCompany, QueryResultSettings settings)
            {
                ThrowIf.Null(settings, "settings");
                ThrowIf.Null(keyword, "keyword");

                PagedResult <GlobalCustomer> customers = this.SearchCustomersSproc(keyword, onlyCurrentCompany, settings);

                return(customers);
            }
            /// <summary>
            /// Retrieves terminal and device association information data from headquarters.
            /// </summary>
            /// <param name="orgUnitNumber">The store number.</param>
            /// <param name="deviceType">The device type value.</param>
            /// <param name="settings">The query result settings.</param>
            /// <returns>The paged results of terminal info of the given store.</returns>
            internal PagedResult <Microsoft.Dynamics.Commerce.Runtime.DataModel.TerminalInfo> GetTerminalInfo(string orgUnitNumber, int deviceType, QueryResultSettings settings)
            {
                ThrowIf.NullOrWhiteSpace(orgUnitNumber, "orgUnitNumber");
                ThrowIf.Null(settings, "settings");
                ThrowIf.Null(settings.Paging, "settings.Paging");

                var terminalInfoList = new List <Microsoft.Dynamics.Commerce.Runtime.DataModel.TerminalInfo>();
                var data             = this.InvokeMethodAllowNullResponse(
                    GetAvailableTerminalsMethodName,
                    new object[] { orgUnitNumber, deviceType, settings.Paging.NumberOfRecordsToFetch, settings.Paging.Skip });

                if (data != null)
                {
                    var xmlTerminalInfoList   = (string)data[0];
                    var availableTerminalInfo = SerializationHelper.DeserializeObjectDataContractFromXml <Serialization.TerminalInfo[]>(xmlTerminalInfoList);

                    if (availableTerminalInfo != null)
                    {
                        terminalInfoList = availableTerminalInfo.Select(terminalInfo => new Microsoft.Dynamics.Commerce.Runtime.DataModel.TerminalInfo()
                        {
                            TerminalId            = terminalInfo.TerminalId,
                            DeviceNumber          = terminalInfo.DeviceNumber,
                            Name                  = terminalInfo.Name,
                            DeviceType            = terminalInfo.DeviceType,
                            ActivationStatusValue = terminalInfo.ActivationStatusValue
                        }).ToList();
                    }
                }

                return(new PagedResult <Microsoft.Dynamics.Commerce.Runtime.DataModel.TerminalInfo>(terminalInfoList.AsReadOnly(), settings.Paging));
            }
示例#25
0
            /// <summary>
            /// Initiates a catalog publishing.
            /// </summary>
            /// <param name="catalogPublisher">Instance of the object which implements ICatalogPublisher.</param>
            /// <returns>True if changed products were found in CRT, False otherwise.</returns>
            /// <remarks>Retrieves the channel's catalogs from CRT and then checks whether CRT contains changed products for each of the catalogs. If changed products are found then
            /// ICatalogPublisher's callbacks are executed to let the caller's code process changed products.</remarks>
            public bool PublishCatalog(ICatalogPublisher catalogPublisher)
            {
                if (catalogPublisher == null)
                {
                    throw new ArgumentNullException(nameof(catalogPublisher));
                }

                List <long> productCatalogIds = new List <long>(1);

                // If catalogs were published to this channel, a given product will be published into SP for each catalog
                // in which it appears, so catalogless publishing would not yield different results for those products.
                // If, however, a product was published directly from the assortment, that product will only be detected
                // and published to SP if the ForceCataloglessPublishing flag is set to 'true' (1) in the job configuration file.
                // The semantics of forcing catalogless publishing as strict, in that catalog-less products will be published
                // if and only if the flag is set. That means, for instance, that if the flag is not set and there are no
                // catalogs published to this channel, the SP job will not detect/publish any products to SP.
                if (this.publishingConfig.ForceNoCatalogPublishing)
                {
                    NetTracer.Information(Resources.ProductCatalogToPublish, 0, "unspecified", "(not a proper catalog)");
                    productCatalogIds.Add(0);
                }

                IReadOnlyCollection <ProductCatalog> productCatalogs = this.GetCatalogs();

                bool deletesFound = this.DeleteProducts(productCatalogs, catalogPublisher);

                foreach (ProductCatalog productCatalog in productCatalogs)
                {
                    productCatalogIds.Add(productCatalog.RecordId);
                }

                ChangedProductsSearchCriteria searchCriteria = new ChangedProductsSearchCriteria
                {
                    DataLevel = CommerceEntityDataLevel.Complete
                };

                searchCriteria.Context.ChannelId = this.onlineChannel.RecordId;

                bool isInitialSync;

                QueryResultSettings productsQuerySettings = this.CreateGetListingsCriteria(
                    this.onlineChannel.ChannelProperties,
                    searchCriteria,
                    out isInitialSync);

                bool changesFound = false;

                try
                {
                    Stopwatch readChangedProductsWatch = Stopwatch.StartNew();
                    searchCriteria.Session = this.productManager.BeginReadChangedProducts(searchCriteria);
                    readChangedProductsWatch.Stop();
                    this.LogTimingMessage(Resources.Duration_ReadChangedProducts, readChangedProductsWatch.Elapsed, searchCriteria.Session.TotalNumberOfProducts);

                    if (searchCriteria.Session.TotalNumberOfProducts > 0)
                    {
                        changesFound = true;
                        int totalProductsCount = 0;

                        Stopwatch timerCummulativeListingRetrieval = new Stopwatch();

                        // loop through the product catalogs, retrieving products.
                        foreach (long productCatalogId in productCatalogIds)
                        {
                            NetTracer.Information(Resources.StartReadProductsFromCatalog, productCatalogId);

                            // set the catalog id on the search criteria
                            searchCriteria.Context.CatalogId = productCatalogId;
                            searchCriteria.Session.ResetNumberOfProductsRead();

                            int pageNumberForCatalog = 0;
                            int catalogProductsCount = 0;

                            // inner loop: load changes, page by page, up to catalog max size
                            do
                            {
                                timerCummulativeListingRetrieval.Start();
                                ChangedProductsSearchResult getProductsResults = this.LoadChangedProducts(searchCriteria, productsQuerySettings);
                                timerCummulativeListingRetrieval.Stop();

                                int numberOfReadProducts = getProductsResults.Results.Count;
                                totalProductsCount   += numberOfReadProducts;
                                catalogProductsCount += numberOfReadProducts;
                                this.LogTimingMessage(Resources.NumberOfReadProductsInPageSummary, productCatalogId, catalogProductsCount, totalProductsCount, timerCummulativeListingRetrieval.Elapsed);

                                catalogPublisher.OnChangedProductsFound(getProductsResults, pageNumberForCatalog, productCatalogId);
                                pageNumberForCatalog++;
                            }while (searchCriteria.Session.NumberOfProductsRead < searchCriteria.Session.TotalNumberOfProducts);

                            this.LogTimingMessage(Resources.CatalogReadCompleted, productCatalogId, catalogProductsCount, totalProductsCount, timerCummulativeListingRetrieval.Elapsed);

                            catalogPublisher.OnCatalogReadCompleted(productCatalogId, this);
                        }   // for each product catalog

                        this.LogTimingMessage(Resources.AllCatalogsReadCompleted, totalProductsCount, timerCummulativeListingRetrieval.Elapsed);
                    } // if changed products were found
                }
                finally
                {
                    this.productManager.EndReadChangedProducts(searchCriteria.Session);
                }

                ChannelProperty channelProperty = new ChannelProperty
                {
                    Name  = KeySyncAnchor,
                    Value = new string(searchCriteria.Session.NextSynchronizationToken)
                };

                this.channelManager.UpdateChannelProperties(new ChannelProperty[] { channelProperty });

                return(changesFound || deletesFound);
            }
            /// <summary>
            /// Retrieves devices available for activation from headquarters.
            /// </summary>
            /// <param name="deviceType">The device type value.</param>
            /// <param name="settings">The query result settings.</param>
            /// <returns>The paged results of devices matches the given device type.</returns>
            internal PagedResult <Microsoft.Dynamics.Commerce.Runtime.DataModel.Device> GetAvailableDevices(int deviceType, QueryResultSettings settings)
            {
                ThrowIf.Null(settings, "settings");
                ThrowIf.Null(settings.Paging, "settings.Paging");

                var devices = new List <Microsoft.Dynamics.Commerce.Runtime.DataModel.Device>();
                var data    = this.InvokeMethodAllowNullResponse(
                    GetAvailableDevicesMethodName,
                    new object[] { deviceType, settings.Paging.NumberOfRecordsToFetch, settings.Paging.Skip });

                if (data != null)
                {
                    var xmlDevices       = (string)data[0];
                    var availableDevices = SerializationHelper.DeserializeObjectDataContractFromXml <Serialization.Device[]>(xmlDevices);

                    if (availableDevices != null)
                    {
                        devices = availableDevices.Select(device => new Microsoft.Dynamics.Commerce.Runtime.DataModel.Device()
                        {
                            DeviceNumber          = device.DeviceNumber,
                            DeviceType            = device.DeviceType,
                            ActivationStatusValue = device.ActivationStatusValue
                        }).ToList();
                    }
                }

                return(new PagedResult <Microsoft.Dynamics.Commerce.Runtime.DataModel.Device>(devices.AsReadOnly(), settings.Paging));
            }
            /// <summary>
            /// Gets the product search results using the specified category identifier.
            /// </summary>
            /// <param name="currentChannelId">The identifier of the channel that the request is originating from.</param>
            /// <param name="searchText">The search text that the result should be relevant to.</param>
            /// <param name="targetChannelId">The identifier of the channel to which the resultant product representatives must belong to.</param>
            /// <param name="targetCatalogId">The identifier of the catalog to which the resultant product representatives must belong to.</param>
            /// <param name="attributeIdCollectionString">The attribute values to retrieve along with the result set.</param>
            /// <param name="settings">The settings to use while processing this request.</param>
            /// <returns>A collection of product search results representing products in the requested category or its sub-categories.</returns>
            internal ReadOnlyCollection <ProductSearchResult> SearchProductsByText(long currentChannelId, string searchText, long targetChannelId, long targetCatalogId, string attributeIdCollectionString, QueryResultSettings settings)
            {
                CP.RetailTransactionServiceResponse transactionServiceResponse = this.GetResponseFromMethod(
                    GetProductsByKeywordMethodName,
                    currentChannelId,
                    searchText,
                    settings.Paging.Skip + 1,                                                                                                // 1-based in AX
                    settings.Paging.NumberOfRecordsToFetch,
                    settings.Sorting == null ? RecordIdAttributeName : settings.Sorting.ToString(),                                          // order by
                    settings.Sorting == null || !settings.Sorting.IsSpecified ? (settings.Sorting.Columns.First().IsDescending ? 1 : 0) : 0, // sort order: Ascending by default
                    false,                                                                                                                   // return total count
                    string.Empty,                                                                                                            // language
                    targetChannelId,
                    targetCatalogId,
                    attributeIdCollectionString);

                // Check result
                if (!transactionServiceResponse.Success)
                {
                    throw new CommunicationException(
                              CommunicationErrors.Microsoft_Dynamics_Commerce_Runtime_HeadquarterCommunicationFailure,
                              string.Format("Invoke method {0} failed: {1}", GetProductsByCategoryMethodName, transactionServiceResponse.Message));
                }

                // Throw if service response does not contain any data.
                if (transactionServiceResponse.Data == null || transactionServiceResponse.Data.Length == 0)
                {
                    throw new CommunicationException(CommunicationErrors.Microsoft_Dynamics_Commerce_Runtime_HeadquarterResponseParsingError, "Service response does not contain any data.");
                }

                string searchResultsXml = (string)transactionServiceResponse.Data[0];
                var    results          = this.GetResultsFromXml(searchResultsXml);

                return(results);
            }
示例#28
0
            public TaskCompletionSource <object> PutParameters <T>(Guid batchId, string entitySet, string entitySetType, string functionName, QueryResultSettings settings, ICollection <string> expandProperties, params OperationParameter[] operationParameters)
            {
                if (!this.IsThreadRegistered(batchId))
                {
                    throw new InvalidOperationException("The calling thread is trying to cache tasks for batch operation, but the thread has not been registered on this cache.");
                }
                else
                {
                    ParametersGroup prametersGroup = new ParametersGroup(entitySet, entitySetType, functionName, typeof(T), settings, expandProperties, operationParameters);
                    this.requestsCache[batchId.ToString()].Add(prametersGroup);

                    TaskCompletionSource <object> taskCompletionSource = new TaskCompletionSource <object>();
                    this.tasksCache[batchId.ToString()].Add(taskCompletionSource);
                    return(taskCompletionSource);
                }
            }
示例#29
0
            public void OnExecuting(Request request)
            {
                SaveCartRequest           saveCartRequest  = request as SaveCartRequest;
                SalesTransaction          salesTransaction = saveCartRequest.SalesTransaction;
                Dictionary <string, bool> checkDict        = new Dictionary <string, bool>();

                if (saveCartRequest.Cart.CartType == CartType.CustomerOrder && saveCartRequest.Cart.CustomerOrderMode == CustomerOrderMode.CustomerOrderCreateOrEdit)
                {
                    if (salesTransaction == null)
                    {
                        salesTransaction = CartWorkflowHelper.LoadSalesTransaction(saveCartRequest.RequestContext, saveCartRequest.Cart.Id, saveCartRequest.Cart.Version);
                    }

                    if (salesTransaction != null &&
                        salesTransaction.CartType == CartType.CustomerOrder && salesTransaction.CustomerOrderMode == CustomerOrderMode.CustomerOrderCreateOrEdit &&
                        (!String.IsNullOrEmpty(saveCartRequest.Cart.DeliveryMode)))
                    {
                        bool DeliveryOnhandCheck = saveCartRequest.Cart.DeliveryMode == "99" ? true : false;

                        if (DeliveryOnhandCheck == true)
                        {
                            InventoryManager inventoryManager = InventoryManager.Create(request.RequestContext.Runtime);
                            foreach (SalesLine salesLine in salesTransaction.InventorySalesLines)
                            {
                                PagingInfo  pagingInfo  = new PagingInfo(30, 0);
                                SortingInfo sortingInfo = new SortingInfo();
                                var         settings    = new QueryResultSettings(pagingInfo, sortingInfo);

                                PagedResult <OrgUnitAvailability> orgUnitAvailabilities = inventoryManager.SearchAvailableInventory(salesLine.ProductId, null, settings);
                                foreach (OrgUnitAvailability orgUnitAvailability in orgUnitAvailabilities)
                                {
                                    if (checkDict.ContainsKey(salesLine.LineId))
                                    {
                                        break;
                                    }

                                    foreach (ItemAvailability itemAvailability in orgUnitAvailability.ItemAvailabilities)
                                    {
                                        if (itemAvailability.ProductId == salesLine.ProductId &&
                                            (itemAvailability.InventoryLocationId == salesLine.InventoryLocationId || string.IsNullOrEmpty(salesLine.InventoryLocationId))
                                            //  && itemAvailability.VariantInventoryDimensionId == salesLine.InventoryDimensionId
                                            && itemAvailability.AvailableQuantity >= salesLine.Quantity)
                                        {
                                            checkDict.Add(salesLine.LineId, true);
                                            break;
                                        }
                                    }
                                }

                                if (!checkDict.ContainsKey(salesLine.LineId))
                                {
                                    checkDict.Add(salesLine.LineId, false);
                                }
                            }

                            if (checkDict.ContainsValue(false))
                            {
                                throw new CartValidationException(DataValidationErrors.Microsoft_Dynamics_Commerce_Runtime_InvalidDeliveryMode, String.Format("Delivery mode {0} is not applicable since some product are out stock", salesTransaction.DeliveryMode));
                            }
                        }
                    }
                }
            }
示例#30
0
 public Task <PagedResult <Category> > GetCategories(long channelId, QueryResultSettings queryResultSettings)
 {
     return(Task.Run(() => ChannelManager.Create(CommerceRuntimeManager.Runtime).GetChannelCategoryHierarchy(channelId, queryResultSettings)));
 }