### Install Episerver CLI Tool
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/setting-up-your-development-environment.md
Installs the global Episerver CLI tool, which provides command-line utilities for Optimizely development. It specifies the package source for NuGet.
```bash
dotnet tool install EPiServer.Net.Cli --global --add-source https://nuget.optimizely.com/feed/packages.svc/
```
--------------------------------
### Install Optimizely Templates
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/setting-up-your-development-environment.md
Installs the necessary Optimizely templates for creating new projects. This command uses the .NET CLI to add the template package globally.
```bash
dotnet new -i EPiServer.Templates
```
--------------------------------
### Integrated Tracking and Recommendation Setup in CSHTML
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/client-side-api-integration.md
A complete example within a CSHTML file demonstrating the integration of creating tracking data, adding custom attributes, and sending a tracking request with section mappings for recommendations.
```cshtml
@section Tracking
{
}
```
--------------------------------
### Get Discounted Prices using Promotion Engine
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/multi-market-examples.md
Retrieves the current market and uses the IPromotionEngine to fetch discounted prices for a specified content link. It then selects the first discount, orders the prices by price, and returns the lowest price. This snippet requires access to the ServiceLocator and IMarketService.
```csharp
var promotionEngine = ServiceLocator.Current.GetInstance();
var market = currentMarketService.GetCurrentMarket();
return promotionEngine.GetDiscountPrices(contentLink, market, currency).First().DiscountPrices.OrderBy(p=>p.Price).First().Price;
```
--------------------------------
### Front-end Site Deployment and Configuration
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/authorizetokenex-installation-and-configuration.md
Instructions for deploying necessary DLLs and the JavaScript file to the front-end site, and updating the web.config.
```APIDOC
Front-end Site Deployment:
1. Deploy DLLs: AuthorizeNet.dll, EPiServer.Commerce.Payment.Authorize.dll, EPiServer.Commerce.Payment.AuthorizeTokenEx.CSR.dll to the bin folder.
2. Add references to the deployed DLLs in your front-end site project and rebuild.
3. Create folder: CSRExtensibility\react-app\dist in the root of your front-end site project.
4. Copy tokenExPayment.min.js to the created folder. Update TokenExConfiguration.cs if the location is changed.
5. Update appSettings in web.config.
Note: The front-end site must run on HTTPS.
```
--------------------------------
### Install EPiServer.Commerce.Core NuGet Package
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/authorizetokenex-installation-and-configuration.md
Installs the EPiServer.Commerce.Core NuGet package using the Package Manager Console. This package is required for the AuthorizeTokenEx payment provider.
```powershell
Install-Package EPiServer.Commerce.Core
```
--------------------------------
### Get All Available Markets
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/multi-market-examples.md
Retrieves all markets available in the Optimizely Commerce system. This function depends on the IMarketService.
```csharp
public IEnumerable GetAvailableMarkets()
{
var marketService = ServiceLocator.Current.GetInstance();
// Get all available markets.
return marketService.GetAllMarkets();
}
```
--------------------------------
### Example ICouponUsage Implementation
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/coupons.md
Provides a C# example implementation of the ICouponUsage interface. This class demonstrates how to implement the Report method to store information about used coupon codes when a purchase is made.
```csharp
public class CustomCouponUsage : ICouponUsage
{
public void Report(IEnumerable appliedPromotions)
{
// Store any information needed about the coupon codes that were used.
}
}
```
--------------------------------
### PriceType Examples
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/pricing.md
Illustrates different price types and their usage within the Optimizely Commerce Connect pricing system.
```csharp
// Example usage of PriceType (specific enum values not provided in source text)
// var priceType = PriceType.Retail;
// var price = priceService.GetCatalogEntryPrices(catalogEntryId, new PriceFilter { PriceType = priceType });
```
--------------------------------
### Get Discount Price by Content Link
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/multi-market-examples.md
Retrieves the discounted price for a given content link and currency. It utilizes the current market and promotion engine to find the best applicable discount. Dependencies include ICurrentMarket and IPromotionEngine.
```csharp
public Price GetDiscountPrice(ContentReference contentLink, Curreny currency)
{
var currentMarketService = ServiceLocator.Current.GetInstance();
var promotionEngine = ServiceLocator.Current.GetInstance();
var market = currentMarketService.GetCurrentMarket();
return promotionEngine.GetDiscountPrices(contentLink, market, currency).First().DiscountPrices.OrderBy(p=>p.Price).First().Price;
}
```
--------------------------------
### Customer Configuration Options
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/feature-specific-commerce-configurations.md
Settings related to customer management, including auto-installation and demo installation flags.
```json
{
"CustomerOptions": {
"AutoInstall": true,
"DemoInstall": true
}
}
```
--------------------------------
### Example ICouponFilter Implementation
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/coupons.md
Provides a C# example implementation of the ICouponFilter interface. This implementation iterates through included promotions, checks for valid coupon codes, and excludes promotions that require a coupon but are not provided.
```csharp
public virtual PromotionFilterContext Filter(PromotionFilterContext filterContext, IEnumerable couponCodes)
{
foreach (var promotion in filterContext.IncludedPromotions)
{
var couponCode = promotion.Coupon.Code;
if (String.IsNullOrEmpty(couponCode))
{
continue;
}
if (couponCodes.Contains(couponCode, StringComparer.OrdinalIgnoreCase))
{
filterContext.AddCouponCode(promotion.ContentGuid, couponCode);
}
else
{
filterContext.ExcludePromotion(
promotion,
FulfillmentStatus.CouponCodeRequired,
filterContext.RequestedStatuses.HasFlag(RequestFulfillmentStatus.NotFulfilled));
}
}
return filterContext;
}
```
--------------------------------
### Get Sale Price for Customer
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/multi-market-examples.md
Retrieves the sale price for a given entry and quantity, considering customer-specific pricing rules. It fetches the current market, currency, and applies pricing based on user identity, price groups, and general customer pricing. Dependencies include ICurrentMarket, IPriceService, and PrincipalInfo.
```csharp
public Price GetSalePrice(Entry entry, decimal quantity)
{
var currentMarketService = ServiceLocator.Current.GetInstance();
var currentMarket = currentMarketService.GetCurrentMarket();
var currency = currentMarket.DefaultCurrency;
List customerPricing = new List();
customerPricing.Add(CustomerPricing.AllCustomers);
var principal = PrincipalInfo.CurrentPrincipal;
if (principal != null)
{
if (!string.IsNullOrEmpty(principal.Identity.Name))
{
customerPricing.Add(new CustomerPricing(CustomerPricing.PriceType.UserName, principal.Identity.Name));
}
CustomerContact currentUserContact = principal.GetCustomerContact();
if (currentUserContact != null && !string.IsNullOrEmpty(currentUserContact.EffectiveCustomerGroup))
{
customerPricing.Add(new CustomerPricing(CustomerPricing.PriceType.PriceGroup, currentUserContact.EffectiveCustomerGroup));
}
}
IPriceService priceService = ServiceLocator.Current.GetInstance();
PriceFilter filter = new PriceFilter()
{
Quantity = quantity,
Currencies = new Currency[] { currency },
CustomerPricing = customerPricing
};
// return less price value
IPriceValue priceValue = priceService.GetPrices(currentMarket.MarketId, FrameworkContext.Current.CurrentDateTime, new CatalogKey(entry.ID), filter)
.OrderBy(pv => pv.UnitPrice)
.FirstOrDefault();
if (priceValue != null)
{
return new Mediachase.Commerce.Catalog.Objects.Price(priceValue.UnitPrice);
}
return null;
}
```
--------------------------------
### Install Optimizely Commerce Connect
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/find-integration.md
Installs the Optimizely Commerce Connect integration using the specified NuGet package for enabling catalog content indexing with Optimizely Customized Commerce search.
```csharp
Install-Package EPiServer.Find.Commerce
```
--------------------------------
### Inventory Request Item Examples
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/inventory-requests.md
Examples of `InventoryRequestItem` objects for different operations within the inventory system. These demonstrate the structure and required fields for operations like 'Purchase'.
```JSON
{
"ItemIndex": 2,
"RequestType": "Purchase",
"CatalogEntryCode": "item",
"WarehouseCode": "warehouse",
"Quantity": 1
},
{
"ItemIndex": 3,
"RequestType": "Purchase",
"CatalogEntryCode": "item",
"WarehouseCode": "warehouse",
"Quantity": 1
},
{
"ItemIndex": 4,
"RequestType": "Purchase",
"CatalogEntryCode": "item",
"WarehouseCode": "warehouse",
"Quantity": 1
}
```
--------------------------------
### List All Inventories
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/warehouses-and-inventories-examples.md
Retrieves a list of all inventory records available in the system. This is a comprehensive fetch of all inventory data.
```csharp
// List all inventory records.
public IEnumerable ListAllInventories()
{
var inventoryService = ServiceLocator.Current.GetInstance();
return inventoryService.List();
}
```
--------------------------------
### Custom ICurrentMarket Implementation Example (Commerce 14+)
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/markets.md
An example of a custom implementation of the ICurrentMarket interface for Optimizely Commerce Connect version 14 and higher. This implementation is registered in the ConfigureServices method of the Startup class.
```csharp
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.Framework.ServiceLocation;
using Mediachase.Commerce;
// The custom implementation of ICurrentMarket
public class MyCurrentMarketImplementation : ICurrentMarket
{
public IMarket GetCurrentMarket()
{
... implementation ...
}
public void SetCurrentMarket(MarketId marketId)
{
... implementation ...
}
}
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton();
}
}
```
--------------------------------
### List All Warehouses
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/warehouses-and-inventories-examples.md
Retrieves a list of all warehouses using the IWarehouseRepository.List() method. This function depends on the ServiceLocator to resolve the IWarehouseRepository instance.
```csharp
// Get list Warehouse
public IEnumerable ListAllWarehouses()
{
var warehouseRepository = ServiceLocator.Current.GetInstance();
return warehouseRepository.List();
}
```
--------------------------------
### NuGet Package Installation for Optimizely Commerce
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/deploying-commerce-to-azure-web-apps.md
Steps to install necessary Optimizely Commerce NuGet packages for an EPiServer CMS site. This includes the core Commerce package and the Azure-specific package for cloud deployment.
```csharp
Install-Package EPiServer.Commerce
Install-Package EPiServer.Commerce.Azure
```
--------------------------------
### AuthorizeTokenEx Project DLLs
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/authorizetokenex-installation-and-configuration.md
After rebuilding the AuthorizeTokenEx project, the following assemblies should be generated: EPiServer.Commerce.Payment.AuthorizeTokenEx.dll and AuthorizeNet.dll. These are essential for the payment provider's functionality.
```csharp
// EPiServer.Commerce.Payment.AuthorizeTokenEx.dll
// AuthorizeNet.dll
```
--------------------------------
### Create Optimizely Commerce Project
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/creating-your-project.md
Commands to create a new empty Optimizely Commerce project, navigate into the project directory, create the CMS database, create the Commerce database, and add an administrator user.
```bash
dotnet new epi-commerce-empty --name ProjectName
cd projectname
dotnet-episerver create-cms-database ProjectName.csproj -S . -E
dotnet-episerver create-commerce-database ProjectName.csproj -S . -E --reuse-cms-user
dotnet-episerver add-admin-user ProjectName.csproj -u username -p password -e [email\ protected] -c EcfSqlConnection
```
--------------------------------
### Get Current Market
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/multi-market-examples.md
Retrieves the currently active market. This function relies on the ICurrentMarket service.
```csharp
public IMarket GetCurrentMarket()
{
var currentMarketService = ServiceLocator.Current.GetInstance();
// Get current markets.
return currentMarketService.GetCurrentMarket();
}
```
--------------------------------
### Get MetaField Collection
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/metafield-class.md
Retrieves the collection of meta-fields associated with a MetaClass. This example iterates through the fields and writes their names to the trace output.
```C#
foreach (MetaField field in mc.Fields)
{
System.Diagnostics.Trace.WriteLine(field.Name);
}
```
--------------------------------
### Get IInventoryService Instance (Skip Cache)
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/warehouses-and-inventories-examples.md
Retrieves an instance of IInventoryService that bypasses the cache for read operations. This is useful when immediate, up-to-date inventory data is required.
```csharp
// Gets an instance of IInventoryService that will skip the cache on reads.
public IInventoryService GetCacheSkippingInstance()
{
var inventoryService= ServiceLocator.Current.GetInstance();
return inventoryService.GetCacheSkippingInstance();
}
```
--------------------------------
### List Prices with IPriceDetailService
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/pricing-examples.md
Demonstrates how to retrieve price details for catalog entries using the IPriceDetailService.List() method. This method handles different catalog entry types (variants, packages, products, bundles) and supports filtering and paging for more specific queries.
```csharp
public void ListPrices(IPriceDetailService priceDetailService, CatalogEntry catalogEntry)
{
// Example: Get prices for a specific catalog entry
var prices = priceDetailService.List(catalogEntry.CatalogEntryID);
// Example: Get prices with filtering and paging (overload)
// var filteredPrices = priceDetailService.List(filter: "someFilter", pageIndex: 0, pageSize: 10);
}
```
--------------------------------
### Get Warehouse by ID
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/warehouses-and-inventories-examples.md
Retrieves a single warehouse by its unique identifier using the IWarehouseRepository.Get(int) method. It requires the warehouse ID as input and relies on the ServiceLocator for repository instantiation.
```csharp
// Get a specific Warehouse by ID
public IWarehouse GetWarehouse(int warehouseId)
{
var warehouseRepository = ServiceLocator.Current.GetInstance();
return warehouseRepository.Get(warehouseId);
}
```
--------------------------------
### Get Warehouse by Code
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/warehouses-and-inventories-examples.md
Retrieves a single warehouse using its unique code via the IWarehouseRepository.Get(string) method. The warehouse code is provided as a string parameter, and the ServiceLocator is used to obtain the repository.
```csharp
// Get a specific Warehouse by Code
public IWarehouse GetWarehouse(string warehouseCode)
{
var warehouseRepository = ServiceLocator.Current.GetInstance();
return warehouseRepository.Get(warehouseCode);
}
```
--------------------------------
### List All Price Details
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/pricing-examples.md
Retrieves all price details for a given catalog entry using the IPriceDetailService.List method. This is a basic retrieval without any specific filtering or paging.
```csharp
public IList ListAllPriceDetailValue(ContentReference catalogContentReference)
{
var priceDetailService = ServiceLocator.Current.GetInstance();
// Gets the price details of a CatalogEntry
return priceDetailService.List(catalogContentReference);
}
```
--------------------------------
### Get Single Inventory Record
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/warehouses-and-inventories-examples.md
Fetches a specific inventory record for a given catalog entry and warehouse. This method requires the catalog entry and warehouse identifiers to pinpoint the exact inventory data.
```csharp
// Gets a single inventory record.
public InventoryRecord GetAnInventory()
{
var inventoryService = ServiceLocator.Current.GetInstance();
return inventoryService.Get();
}
```
--------------------------------
### Sample Initialization Module for Catalog Routes
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/initialization.md
This C# code sample demonstrates how to create an initialization module for Optimizely Commerce Connect. It depends on the EPiServer.Commerce.Initialization.InitializationModule and registers default hierarchical catalog routes using CatalogRouteHelper.MapDefaultHierarchialRouter.
```csharp
using System.Web.Routing;
using EPiServer.Framework;
using EPiServer.Commerce.Routing;
using EPiServer.Framework.Initialization;
namespace CodeSamples.EPiServer.Commerce.Catalog
{
[ModuleDependency(typeof(global::EPiServer.Commerce.Initialization.InitializationModule))]
public class RegisterRoutingModuleSample : IInitializableModule
{
public void Initialize(InitializationEngine context)
{
MapRoutes(RouteTable.Routes);
}
private static void MapRoutes(RouteCollection routes)
{
CatalogRouteHelper.MapDefaultHierarchialRouter(routes, true);
}
public void Uninitialize(InitializationEngine context) { /*uninitialize*/}
public void Preload(string[] parameters) { }
}
}
```
--------------------------------
### Get All Price Type Definitions in C#
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/pricetype-examples.md
Provides a C# method to retrieve all defined price types, including both predefined and those configured in the application's settings. It utilizes the PriceTypeConfiguration class to access the PriceTypeDefinitions.
```csharp
namespace CodeSamples.Mediachase.Commerce.Pricing
{
public class PriceTypeConfigurationSample
{
#region GetPriceTypeFromEnumAndConfiguration
public IDictionary GetAllPriceTypeDefinitions()
{
// Get all price types - included predefined and price types from configuration file.
var priceTypeDefinitions = PriceTypeConfiguration.Instance.PriceTypeDefinitions;
return priceTypeDefinitions;
}
#endregion
}
}
```
--------------------------------
### SEO Best Practices
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/deployment.md
Outlines Search Engine Optimization (SEO) strategies for Optimizely Commerce Connect sites. This includes setting up web analytics, using XML sitemaps, understanding HTTP redirect codes, and configuring robots.txt.
```text
SEO Configuration:
- Set up and configure Web Analytics.
- Use an XML site map for search engine crawling.
- Understand the difference between 301 and 302 redirects.
- Set up a robots.txt file.
```
--------------------------------
### Customize Catalog Feed Settings
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/customizing-exported-product-information.md
Demonstrates how to retrieve and set properties on the default CatalogFeedSettings instance to customize exported product information. This involves accessing the service locator to get the instance and then modifying properties like DescriptionPropertyName.
```csharp
var catalogFeedSettings = ServiceLocator.Current.GetInstance();
catalogFeedSettings.DescriptionPropertyName = "...";
```
--------------------------------
### Campaign Initialization Module
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/marketing.md
An EPiServer initialization module that configures custom routes for campaign content. It registers a 'campaignroot' route and sets up a custom URL segment router for campaign content, ensuring proper routing within the EPiServer Commerce framework.
```csharp
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;
using EPiServer.Web.Routing;
using EPiServer.Web.Routing.Segments;
using System.Linq;
using System.Web.Routing;
namespace EPiServer.Commerce.Sample.Business.Initialization
{
///
/// Initialization module to handle the initialization of Commerce.
///
[ModuleDependency(typeof(EPiServer.Commerce.Initialization.InitializationModule))]
[InitializableModule]
public class CampaignInitalization : IConfigurableModule
{
///
/// Initializes Commerce using the specified context.
///
/// The context.
public void Initialize(InitializationEngine context)
{
EPiServer.Global.RoutesRegistered += Global_RoutesRegistered;
}
private void Global_RoutesRegistered(object sender, RouteRegistrationEventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
private static void RegisterRoutes(RouteCollection routes)
{
// Route for editing commerce content (which has a root not connected to the global root)
MapCampaignRoute(routes,
name: "campaignroot",
url: "Campaigns/{language}/{nodeedit}/{partial}/{action}",
defaults: new { action = "index" });
}
private static void MapCampaignRoute(RouteCollection routes, string name, string url, object defaults, object constraints = null)
{
var contentRootService = ServiceLocator.Current.GetInstance();
var root = ServiceLocator.Current.GetInstance()
.GetItems(contentRootService.List(), new LoaderOptions())
.SingleOrDefault(x => x.Name.Equals("SysCampaignRoot"));
var segmentRouter = ServiceLocator.Current.GetInstance();
segmentRouter.RootResolver = (sd) => root.ContentLink;
var parameters =
new MapContentRouteParameters
{
UrlSegmentRouter = segmentRouter,
BasePathResolver = null,//Use Cms default
Direction = SupportedDirection.Both,
Constraints = constraints
};
routes.MapContentRoute(
name,
url,
defaults,
parameters);
}
public void Uninitialize(InitializationEngine context)
{
// Uninitialize catalog content version
}
public void ConfigureContainer(ServiceConfigurationContext context)
{
}
}
}
```
--------------------------------
### Get Sale Price for Entry
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/multi-market-examples.md
Calculates and returns the sale price for a given entry and quantity, considering the current market, currency, and customer pricing tiers. This function requires ICurrentMarket and IPriceService. It orders prices by unit price and returns the lowest available.
```csharp
public Price GetSalePrice(Entry entry, decimal quantity)
{
var currentMarketService = ServiceLocator.Current.GetInstance();
var currentMarket = currentMarketService.GetCurrentMarket();
var currency = currentMarket.DefaultCurrency;
List customerPricing = new List();
customerPricing.Add(CustomerPricing.AllCustomers);
var principal = PrincipalInfo.CurrentPrincipal;
if (principal != null)
{
if (!string.IsNullOrEmpty(principal.Identity.Name))
{
customerPricing.Add(new CustomerPricing(CustomerPricing.PriceType.UserName, principal.Identity.Name));
}
CustomerContact currentUserContact = principal.GetCustomerContact();
if (currentUserContact != null && !string.IsNullOrEmpty(currentUserContact.EffectiveCustomerGroup))
{
customerPricing.Add(new CustomerPricing(CustomerPricing.PriceType.PriceGroup, currentUserContact.EffectiveCustomerGroup));
}
}
IPriceService priceService = ServiceLocator.Current.GetInstance();
PriceFilter filter = new PriceFilter()
{
Quantity = quantity,
Currencies = new Currency[] { currency },
CustomerPricing = customerPricing
};
// return less price value
IPriceValue priceValue = priceService.GetPrices(currentMarket.MarketId, DateTime.UtcNow, new CatalogKey(entry.ID), filter)
.OrderBy(pv => pv.UnitPrice)
.FirstOrDefault();
if (priceValue != null)
{
return new Mediachase.Commerce.Catalog.Objects.Price(priceValue.UnitPrice);
}
return null;
}
```
--------------------------------
### Create New Warehouse
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/warehouses-and-inventories-examples.md
Demonstrates how to create a new warehouse by instantiating a Warehouse object, populating its properties including contact information, and saving it using the IWarehouseRepository. This method assumes the necessary ServiceLocator and IWarehouseRepository are available.
```csharp
public void CreateNewWarehouse()
{
var warehouseRepository = ServiceLocator.Current.GetInstance();
var warehouse = new Warehouse
{
Code = "NY",
Name = "New York store",
IsActive = true,
IsPrimary = false,
IsFulfillmentCenter = false,
IsPickupLocation = true,
IsDeliveryLocation = true,
ContactInformation = new WarehouseContactInformation
{
FirstName = "First Name",
LastName = "Last Name",
Line1 = "Address Line 1",
Line2 = "Address Line 2",
City = "City",
State = "State",
CountryCode = "Country Code",
PostalCode = "Postal Code",
RegionCode = "Region Code",
DaytimePhoneNumber = "Daytime Phone Number",
EveningPhoneNumber = "Evening Phone Number",
FaxNumber = "Fax Number",
Email = "Email"
}
};
warehouseRepository.Save(warehouse);
}
```
--------------------------------
### Create Meta-fields using MetaFieldBuilder
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/metafieldbuilder-class.md
This example demonstrates how to use the MetaFieldBuilder in C# to create several meta-fields: a DateTime field, a Text field, a Guid field, and an Integer field. It initializes the builder with a metaClass, calls the respective Create methods with appropriate parameters, and finally saves the changes.
```C#
using (MetaFieldBuilder builder = new MetaFieldBuilder(metaClass))
{
builder.CreateDateTime(CreatedFieldName, CreatedFriendlyName, false, true);
builder.CreateText(CreatorFieldNameText, CreatorFriendlyName, false, 50, false);
builder.CreateGuid(CreatorFieldNameGuid, CreatorFriendlyName, false);
builder.CreateInteger(CreatorFieldNameInteger, CreatorFriendlyName, false, -1);
builder.SaveChanges();
}
```
--------------------------------
### Create Return Order Form
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/using-the-return-order-form.md
Demonstrates how to create a return order form for a given purchase order using the IPurchaseOrderFactory and IOrderRepository.
```csharp
var purchaseOrderFactory = ServiceLocator.Current.GetInstance();
var orderRepository = ServiceLocator.Current.GetInstance();
var orderLink = new OrderReference(1, "Default", Guid.NewGuid(), typeof(IPurchaseOrder));
var purchaseOrder = orderRepository.Load(orderLink.OrderGroupId);
var returnOrderForm = purchaseOrderFactory.CreateReturnOrderForm(purchaseOrder);
```
--------------------------------
### List Price Details with Paging
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/pricing-examples.md
Retrieves price details for a catalog entry with support for paging. It allows specifying an offset and the number of items to retrieve, and returns the total count of available price details.
```csharp
public IList ListPriceDetailValueWithPaging(ContentReference catalogContentReference, int offset, int numberOfItems, out int totalCount)
{
var priceDetailService = ServiceLocator.Current.GetInstance();
// Gets price details for the CatalogEntry with paging
return priceDetailService.List(catalogContentReference, offset, numberOfItems, out totalCount);
}
```
--------------------------------
### Percentage Promotion Processor Sample - Constructor and Evaluation
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/custom-promotions.md
Demonstrates the constructor and the main Evaluate method for a `PercentagePromotionProcessorSample`. The constructor injects necessary services like `CollectionTargetEvaluator` and `FulfillmentEvaluator`. The Evaluate method orchestrates the promotion evaluation process.
```csharp
using EPiServer.Commerce.Extensions;
using EPiServer.Commerce.Marketing;
using EPiServer.Framework.Localization;
using EPiServer.ServiceLocation;
using System.Collections.Generic;
using System.Linq;
namespace CodeSamples.EPiServer.Commerce.Marketing
{
///
/// Sample of a promotion processor for .
///
[ServiceConfiguration(Lifecycle = ServiceInstanceScope.Singleton)]
public class PercentagePromotionProcessorSample : EntryPromotionProcessorBase
{
private readonly CollectionTargetEvaluator _targetEvaluator;
private readonly FulfillmentEvaluator _fulfillmentEvaluator;
private readonly LocalizationService _localizationService;
///
/// Creates a new instance of a .
///
/// The service that is used to evaluate an order against a promotion's target properties.
/// The service that is used to evaluate the fulfillment status of the promotion.
/// The service that is used to get localized strings.
public PercentagePromotionProcessorSample(
CollectionTargetEvaluator targetEvaluator,
FulfillmentEvaluator fulfillmentEvaluator,
LocalizationService localizationService)
{
_targetEvaluator = targetEvaluator;
_fulfillmentEvaluator = fulfillmentEvaluator;
_localizationService = localizationService;
}
///
/// Evaluates a promotion against an order form.
///
/// The promotion to evaluate.
/// The promotion processor context.
///
/// A telling whether the promotion was fulfilled,
/// which items the promotion was applied to and to which discount percentage.
///
protected override RewardDescription Evaluate(PercentagePromotionSample promotionData, PromotionProcessorContext context)
{
var lineItems = GetLineItems(context.OrderForm);
var condition = promotionData.Condition;
var applicableCodes = _targetEvaluator.GetApplicableCodes(lineItems, condition.Items, condition.MatchRecursive);
// ... rest of the evaluation logic
```
--------------------------------
### Install AuthorizeNet NuGet Package
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/authorizetokenex-installation-and-configuration.md
Installs the AuthorizeNet NuGet package version 1.9.4 using the Package Manager Console. This is a prerequisite for the AuthorizeTokenEx payment provider.
```powershell
Install-Package AuthorizeNet -version 1.9.4
```
--------------------------------
### Custom ICurrentMarket Implementation Example (Commerce 10-13)
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/markets.md
An example of a custom implementation of the ICurrentMarket interface for Optimizely Commerce Connect versions 10-13. This implementation is registered using IConfigurableModule.
```csharp
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.Framework.ServiceLocation;
using Mediachase.Commerce;
// The custom implementation of ICurrentMarket
public class MyCurrentMarketImplementation : ICurrentMarket
{
public IMarket GetCurrentMarket()
{
... implementation ...
}
public void SetCurrentMarket(MarketId marketId)
{
... implementation ...
}
}
[ModuleDependency(typeof(Mediachase.Commerce.Initialization.CommerceInitialization))]
[InitializableModule]
public class MyCurrentMarketModule : IConfigurableModule
{
public void ConfigureContainer(ServiceConfigurationContext context)
{
context.Container.Configure(ce =>
{
ce.For().Singleton().Use();
});
}
public void Initialize(InitializationEngine context) { }
public void Preload(string[] parameters) { }
public void Uninitialize(InitializationEngine context) { }
}
```
--------------------------------
### Tracking Recommended Item Clicks (C#)
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/an-api-overview.md
Explains how to track user clicks on recommended items using the IRecommendationContext interface in C#. It highlights the use of a specific implementation class from the Quicksilver template for this purpose.
```csharp
EPiServer.Tracking.Commerce.IRecommendationContext
EPiServer.Reference.Commerce.Site.Features.Recommendations.Services.RecommendationContext
```
--------------------------------
### Configure Catalog Cache via Startup.cs
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/caching.md
Provides an example of configuring cache settings for the Catalogs subsystem programmatically within the ConfigureServices method of the Startup class. It utilizes `TimeSpan` to define cache expiration durations.
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.Configure(o =>
{
o.Cache.UseCache = true;
o.Cache.ContentVersionCacheExpiration = TimeSpan.FromMinutes(05);
o.Cache.CollectionCacheExpiration = TimeSpan.FromMinutes(05);
o.Cache.EntryCacheExpiration = TimeSpan.FromMinutes(05);
o.Cache.NodeCacheExpiration = TimeSpan.FromMinutes(05);
});
}
```
--------------------------------
### Create Guid MetaField
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/metafield-class.md
Creates a new Guid meta-field for a meta-class. It handles null arguments and sets a default value based on whether the field is nullable.
```C#
public MetaField CreateGuid(string name, string friendlyName, bool isNullable)
{
if (name == null)
throw new ArgumentNullException("name");
if (friendlyName == null)
throw new ArgumentNullException("friendlyName");
AttributeCollection attr = new AttributeCollection();
string defaultValue = isNullable ? string.Empty : "newid()";
MetaField retVal = this.MetaClass.CreateMetaField(name, friendlyName, MetaFieldType.Guid, isNullable, defaultValue, attr);
return retVal;
}
```
--------------------------------
### Prerequisites for Optimizely Graph Integration
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/optimizely-graph-for-commerce-connect.md
Lists the essential software and version requirements for setting up Optimizely Graph with Optimizely Commerce Connect. This includes .NET, NodeJS, yarn, and the Optimizely Commerce Connect package.
```text
- .NET 6
- NodeJS equal or greater than v20.14.0
- yarn
- Optimizely Commerce Connect equal or greater than v14.26.0
```
--------------------------------
### IIS Configuration for Performance and Reliability
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/deployment.md
Provides guidance on configuring Internet Information Services (IIS) for Optimizely Commerce Connect. This includes creating separate application pools, managing memory limits, enabling GZIP compression, and verifying permissions.
```APIDOC
Internet Information Services (IIS) Configuration:
1. Application Pool:
- Create a new Application Pool for your website to increase its reliability.
2. Memory Management:
- Set the memory limit for your Application Pool.
- Specify the memory time limit instead of using the default.
- Configure the memory recycling feature in IIS.
3. Compression:
- Enable GZIP in IIS to reduce the size of pages, CSS, and JavaScript files.
4. Permissions:
- Double-check IIS permissions for the website and its resources.
```
--------------------------------
### Order Search Parameters and Options Setup
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/searching-for-orders-using-ordercontext.md
Initializes OrderSearchOptions with basic retrieval settings and specifies the namespace for order searches. This is a common setup for subsequent search operations.
```csharp
OrderSearchOptions searchOptions = new OrderSearchOptions();
searchOptions.StartingRecord = 0;
searchOptions.RecordsToRetrieve = 10000;
searchOptions.Namespace = "Mediachase.Commerce.Orders";
```
--------------------------------
### Customize Facet Groups
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/custom-facets-in-the-marketing-overview.md
Example of customizing facet groups by inheriting from FacetGroupModifier and overriding the ModifyFacetGroups method. This example sets the default number of items to show for the market facet group to four.
```csharp
public class CustomFacetGroupModifier : FacetGroupModifier
{
public override IEnumerable ModifyFacetGroups(IEnumerable facetGroups)
{
var marketFacetGroup = facetGroups.FirstOrDefault(f => f.Id == CampaignFacetConstants.MarketGroupId);
if (marketFacetGroup != null)
{
marketFacetGroup.Settings.ItemsToShow = 4;
}
return facetGroups;
}
}
```
--------------------------------
### Campaign Initialization and Routing
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/marketing.md
Initialization module for setting up campaign-specific routes in EPiServer Commerce. It registers a custom route for campaign content, ensuring proper URL resolution.
```csharp
using EPiServer.Core;
using EPiServer.DataAbstraction;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;
using EPiServer.Web.Routing;
using EPiServer.Web.Routing.Segments;
using System.Linq;
using System.Web.Routing;
namespace EPiServer.Commerce.Sample.Business.Initialization
{
///
/// Initialization module to handle the initialization of Commerce.
///
[ModuleDependency(typeof(EPiServer.Commerce.Initialization.InitializationModule))]
[InitializableModule]
public class CampaignInitalization : IConfigurableModule
{
///
/// Initializes Commerce using the specified context.
///
/// The context.
public void Initialize(InitializationEngine context)
{
EPiServer.Global.RoutesRegistered += Global_RoutesRegistered;
}
private void Global_RoutesRegistered(object sender, RouteRegistrationEventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
private static void RegisterRoutes(RouteCollection routes)
{
// Route for editing commerce content (which has a root not connected to the global root)
MapCampaignRoute(routes,
name: "campaignroot",
url: "Campaigns/{language}/{nodeedit}/{partial}/{action}",
defaults: new { action = "index" });
}
private static void MapCampaignRoute(RouteCollection routes, string name, string url, object defaults, object constraints = null)
{
var contentRootService = ServiceLocator.Current.GetInstance();
var root = ServiceLocator.Current.GetInstance()
.GetItems(contentRootService.List(), new LoaderOptions())
.SingleOrDefault(x => x.Name.Equals("SysCampaignRoot"));
var segmentRouter = ServiceLocator.Current.GetInstance();
segmentRouter.RootResolver = (sd) => root.ContentLink;
var parameters =
new MapContentRouteParameters
{
UrlSegmentRouter = segmentRouter,
BasePathResolver = null,//Use Cms default
Direction = SupportedDirection.Both,
```
--------------------------------
### Start Purchase Order Processing
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/order-processing.md
Illustrates how to initiate the processing of a purchase order using the ProcessOrder method from IPurchaseOrderProcessor. The purchase order is loaded using IOrderRepository before processing.
```csharp
IOrderRepository orderRepository;
IPurchaseOrderProcessor purchaseOrderProcessor;
(…)
var orderGroupId = 123;
var purchaseOrder = orderRepository.Load(orderGroupId);
purchaseOrderProcessor.ProcessOrder(purchaseOrder);
```
--------------------------------
### Bolt Payment Provider Configuration (C# Startup)
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/bolt-installation.md
This C# code snippet demonstrates how to configure the Bolt payment provider options programmatically in the application's startup file using `services.Configure()`. It allows setting various Bolt-specific parameters.
```csharp
services.Configure(x =>
{
x.EnvironmentType = EnvironmentType.Sandbox;
x.PublishableKey = "Key";
x.ApiKey = "Api Key";
x.DivisionPublicId = "Public Id";
x.SigningSecret = "signing secret";
x.AutoCapture = true;
});
```
--------------------------------
### Get Database Object
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/sql-meta-model.md
Initializes the SqlContext and retrieves the Database object, which represents the SQL database. The Database object allows for operations like getting, creating, or dropping tables and relationships.
```csharp
// Step 0. Connection String
string connectionString = "Data Source=(local);Initial Catalog=TestDatabase;User ID=sa;Password=;";
// Step 1. Initiaze Sql Meta Model
using (SqlContext.Current = new SqlContext(connectionString))
{
// Step 2. Get Database
Database database = SqlContext.Current.Database;
}
```
--------------------------------
### File Synchronization for .NET Deployment
Source: https://github.com/quan-tran-niteco/optimizelycommerceconnect/blob/main/docs/deployment.md
Details the files to transfer when deploying .NET sites to a production server. It specifies which file types are necessary (e.g., compiled code, non-compiled assets) and which should be excluded (e.g., source code, debug files).
```text
Include:
*.gif; *.jpg; *.html; *.js; *.xml; *.png; *.css
/bin directory (compiled code)
Updated configuration files
Exclude:
*.cs
*.resx
*.pdb (debug files in /bin)
```