Skip to content

Instantly share code, notes, and snippets.

@Mozu-CS
Last active June 1, 2017 13:39
Show Gist options
  • Save Mozu-CS/24d66ba1241a015aa32d to your computer and use it in GitHub Desktop.
Save Mozu-CS/24d66ba1241a015aa32d to your computer and use it in GitHub Desktop.
Code exercises for the Mozu Back End Training Class
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
namespace Mozu_BED_Training_Exercise_8
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_8_Get_Tenant()
{
/* --Create a New Tenant Resource
* Resources are used to leverage the methods provided by the SDK to talk to the Mozu service
* via the Mozu REST API. Every resource takes an ApiContext object as a parameter.
*/
var tenantResource = new Mozu.Api.Resources.Platform.TenantResource(_apiContext);
/*
* --Utilize the Tenant Resource to Get Your Tenant
* Your tenant represents your overall Mozu store
* —the following properties are accessible from a Tenant object:
* tenant.Domain -- string
* tenant.Id -- int
* tenant.MasterCatalogs -- List<MasterCatalog>
* tenant.Sites -- List<Site>
* tenant.Name -- string
*
* See this site for more info:
* http://developer.mozu.com/content/api/APIResources/platform/platform.tenants/platform.tenants.htm
*/
var tenant = tenantResource.GetTenantAsync(_apiContext.TenantId).Result; ;
//Add Your Code:
//Write Tenant name
System.Diagnostics.Debug.WriteLine(string.Format("Tenant Name[{0}]: {1}", tenant.Id, tenant.Name));
//Add Your Code:
//Write Tenant domain
System.Diagnostics.Debug.WriteLine(string.Format("Tenant Domain[{0}]: {1}", tenant.Id, tenant.Domain));
//Add Your Code:
foreach (var masterCatalog in tenant.MasterCatalogs)
{
//Write Master Catalog info
System.Diagnostics.Debug.WriteLine(string.Format("Master Catalog[{0}]: {1}", masterCatalog.Id, masterCatalog.Name));
foreach (var catalog in masterCatalog.Catalogs)
{
//Write Catalog info
System.Diagnostics.Debug.WriteLine(string.Format("\tCatalog[{0}]: {1}", catalog.Id, catalog.Name));
}
}
//Add Your Code:
foreach (var site in tenant.Sites)
{
//Get Site and write Site info
System.Diagnostics.Debug.WriteLine(string.Format("Site[{0}]: {1}", site.Id, site.Name));
}
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
namespace Mozu_BED_Training_Exercise_9_1
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_9_1_Get_Attribute()
{
/* --Create a New Product Attribute Resource
* Resources are used to leverage the methods provided by the SDK to talk to the Mozu service
* via the Mozu REST API. Every resource takes an ApiContext object as a parameter.
*/
var productAttributeResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.Attributedefinition.AttributeResource(_apiContext);
/*
* --Utilize the Product Attribute Resource to Get All Product Attributes Returned as an AttributeCollection
* Product attributes are the properties of the product with differing types based on your needs.
* Define your product attribute as Options, Properties, or Extras
* —the following properties are accessible from a Product Attribute object:
* productAttribute.AdminName -- string
* productAttribute.AttributeCode -- string
* productAttribute.AttributeDataTypeSequence -- int
* productAttribute.AttributeFQN -- string
* productAttribute.AttributeMetadata -- List<AttributeMetadataItem>
* productAttribute.AttributeSequence -- int
* productAttribute.AuditInfo -- AuditInfo
* productAttribute.Conent -- Content (This object contains the name, description, and locale code for identifying language and country.)
* productAttribute.DataType -- string
*
* (Types include "List", "Text box", "Text area", "Yes/No", and "Date")
* productAttribute.InputType -- string
*
* (Used to identify the characteristics of an attribute)
* productAttribute.IsExtra -- bool
* productAttribute.IsOption -- bool
* productAttribute.IsProperty -- bool
*
* productAttribute.LocalizedContent -- List<AttributeLocalizedContent>
* productAttribute.MasterCatalogId -- int
* productAttribute.Namespace -- string
* productAttribute.SearchSettings -- SearchSettings
*
* (Used to store properties such as max/min date, max/min numeric value, max/min string length, or a regular expression)
* productAttribute.Validation -- Validation
* productAttribute.ValueType -- string
*
* (Used to store predefined values, such as options in a List)
* productAttribute.VocabularyValues -- List<AttributeVocabularyValue>
*
*
* See the following sites for more info:
* http://developer.mozu.com/content/learn/appdev/product-admin/product-attribute-definition.htm
* http://developer.mozu.com/content/api/APIResources/commerce/commerce.catalog/commerce.catalog.admin.attributedefinition.attributes.htm
*/
var productAttributes = productAttributeResource.GetAttributesAsync(startIndex: 0, pageSize: 200).Result;
//Add Your Code:
//Write Total Count of Attributes
System.Diagnostics.Debug.WriteLine(string.Format("Product Attributes Total Count: {0}", productAttributes.TotalCount));
//Add Your Code:
//Get an Attribute by Fully Qualified Name
var individualAttribute = productAttributeResource.GetAttributeAsync("tenant~rating").Result;
//Note: AttributeFQN (fully qualified name) follows the naming convention tenant~attributeName
//Add Your Code:
//Write the Attribute Data Type
System.Diagnostics.Debug.WriteLine(string.Format("Product Attribute Data Type[{0}]: {1}", individualAttribute.AttributeCode, individualAttribute.DataType));
//Add Your Code:
//Write the Attribute Input Type
System.Diagnostics.Debug.WriteLine(string.Format("Product Attribute Input Type[{0}]: {1}", individualAttribute.AttributeCode, individualAttribute.InputType));
//Add Your Code:
//Write the Attribute Characteristics
System.Diagnostics.Debug.WriteLine(string.Format("Product Attribute Characteristic [{0}]: An Extra? {1}, An Option? {2}, A Property? {3}", individualAttribute.AttributeCode, individualAttribute.IsExtra, individualAttribute.IsOption, individualAttribute.IsProperty));
//Or...
WriteAttributeCharacteristic(individualAttribute);
//Add Your Code:
if(individualAttribute.VocabularyValues != null)
{
foreach (var value in individualAttribute.VocabularyValues)
{
//Write vocabulary values
System.Diagnostics.Debug.WriteLine(string.Format("Product Attribute Vocabulary Values[{0}]: Value({1}) StringContent({2})", individualAttribute.AttributeCode, value.Value, value.Content.StringValue));
}
}
//Add Your Code:
//Get an Attribute filtered by name
//Note: See this page for more info about filters:
//http://developer.mozu.com/content/api/APIResources/StandardFeatures/FilteringAndSortingSyntax.htm
var filteredAttributes = productAttributeResource.GetAttributesAsync(filter: "adminName sw 'a'").Result;
var singleAttributeFromFiltered = new Mozu.Api.Contracts.ProductAdmin.Attribute();
if(filteredAttributes.TotalCount > 0)
{
singleAttributeFromFiltered = filteredAttributes.Items[0];
}
//Add Your Code:
if (singleAttributeFromFiltered.AttributeCode != null)
{
//Write the Attribute Data Type
System.Diagnostics.Debug.WriteLine(string.Format("Product Attribute Data Type[{0}]: {1}", singleAttributeFromFiltered.AttributeCode, singleAttributeFromFiltered.DataType));
//Write the Attribute Input Type
System.Diagnostics.Debug.WriteLine(string.Format("Product Attribute Input Type[{0}]: {1}", singleAttributeFromFiltered.AttributeCode, singleAttributeFromFiltered.InputType));
//Write the Attribute Characteristics
System.Diagnostics.Debug.WriteLine(string.Format("Product Attribute Characteristic [{0}]: An Extra? {1}, An Option? {2}, A Property? {3}", singleAttributeFromFiltered.AttributeCode, singleAttributeFromFiltered.IsExtra, singleAttributeFromFiltered.IsOption, singleAttributeFromFiltered.IsProperty));
//Or...
WriteAttributeCharacteristic(singleAttributeFromFiltered);
if (singleAttributeFromFiltered.VocabularyValues != null)
{
foreach (var value in singleAttributeFromFiltered.VocabularyValues)
{
//Write vocabulary values
System.Diagnostics.Debug.WriteLine(string.Format("Product Attribute Vocabulary Values[{0}]: Value({1}) StringContent({2})", singleAttributeFromFiltered.AttributeCode, value.Value, value.Content.StringValue));
}
}
}
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
namespace Mozu_BED_Training_Exercise_9_2
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_9_2_Add_New_Attribute_Extra()
{
//Once again, we'll be using a Product Attribute resource
var productAttributeResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.Attributedefinition.AttributeResource(_apiContext);
/*
* We use a contract to declare an empty Product Attribute that we will populate with our data and then send via the API.
*
* Contracts define the data model that each object adheres to -- each contract has different required fields.
* The API documentation is useful for viewing some required fields, but trial and error is needed in some cases as well.
*
* We viewed the Product Attribute model in Exercise 9.1, but here I'll define out the required fields for creating a new Attribute.
*
* newAttribute.AdminName -- string
* newAttribute.AttributeCode -- string
* newAttribute.DataType -- string (Types include "String", "ProductCode", and "Number"
* -- Not all combinations of DataType and InputType are valid)
* newAttribute.InputType -- string (Types include "List", "TextBox", "TextArea", "Yes/No", and "Date";
* -- Depending on the type you choose, other fields may be required)
*
* (One of these Characteristics must be true)
* newAttribute.isExtra -- bool
* newAttribute.isOption -- bool
* newAttribute.isProperty -- bool
*
* newAttribute.ValueType -- string (Types include "Predefined", "AdminEntered", and "ShopperEntered"
* -- "Predefined" cannot be used when creating a new attribute and exist only on attributes included with Mozu
* -- Use "AdminEntered" or "ShopperEntered" to tell Mozu who sets this attribute.
*
* You may encounter this error when creating Attributes:
* "Attribute must have a valid configuration for an Attribute Type Rule.
* The combination of the attribute's values if it is an option, extra, or property
* for the selected data type, input type, and value type is invalid."
*
* To solve for this error, continue to try changing the DataType, InputType, or Characteristics.
*
*/
var newAttribute = new Mozu.Api.Contracts.ProductAdmin.Attribute()
{
//A name used solely within Mozu Admin
AdminName = "monogram",
//Used to uniquely identify an Attribute -- Mozu creates the AttributeFQN by adding "tenant~" to the AttributeCode
//It's best practice to use lowercase for the AttributeCode
AttributeCode = "monogram",
//Defines the data entered by either Admin or Shopper users
DataType = "String",
//Defines the input form
InputType = "TextBox",
//Sets the Characteristic of the Attribute
IsExtra = true,
//Another contract -- AttributeLocalizedContent allows you to add a shopper-facing label
Content = new Mozu.Api.Contracts.ProductAdmin.AttributeLocalizedContent()
{
Name = "Monogram"
},
//Defines how the Attribute if an Admin or Shopper enters -- allows Shoppers to configure products with custom input.
ValueType = "ShopperEntered"
};
//Add Your Code:
//Create new attribute
//Best Practice Tip:
//Check if the attribute already exists before adding a new attribute.
//The responseFields parameter allows you to choose which particular fields the Mozu API will return.
var existingAttributes = productAttributeResource.GetAttributesAsync(filter: string.Format("AttributeCode sw '{0}'", newAttribute.AttributeCode), responseFields: "AttributeFQN").Result;
//Verify that the attribute doesn't already exist by checking the TotalCount.
if (existingAttributes.TotalCount == 0)
{
//Creating a new attribute returns an Attribute object if successful
var resultingAttribute = productAttributeResource.AddAttributeAsync(newAttribute).Result;
//Add Your Code:
//Update the attribute search settings
//Create the settings in your local model
resultingAttribute.SearchSettings = new Mozu.Api.Contracts.ProductAdmin.AttributeSearchSettings()
{
SearchableInAdmin = true,
SearchableInStorefront = true,
SearchDisplayValue = true
};
//And update the attribute via the API -- the responseField allows you to only return the AttributeFQN
//For later use, requests like GetAttributeAsync require the AttributeFQN
var resultingUpdatedAttribute = productAttributeResource.UpdateAttributeAsync(resultingAttribute, resultingAttribute.AttributeFQN, responseFields: "AttributeFQN").Result;
}
//Alternatively, you can use a try/catch block to handle errors returned from the Mozu API:
try
{
var resultingAttribute = productAttributeResource.AddAttributeAsync(newAttribute).Result;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
System.Diagnostics.Debug.WriteLine(e.InnerException.Message);
}
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
namespace Mozu_BED_Training_Exercise_9_3
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_9_3_Add_Attributes()
{
//Another usage of a ProductAttributeResource
var productAttributeResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.Attributedefinition.AttributeResource(_apiContext);
//We create a new attribute using a Contract just like in the previous exercise
var newAttribute = new Mozu.Api.Contracts.ProductAdmin.Attribute()
{
AdminName = "insulation",
AttributeCode = "insulation",
DataType = "String",
InputType = "List",
IsOption = true,
Content = new Mozu.Api.Contracts.ProductAdmin.AttributeLocalizedContent()
{
Name = "Insulation"
},
ValueType = "Predefined",
VocabularyValues = new List<Mozu.Api.Contracts.ProductAdmin.AttributeVocabularyValue>()
{
//Since this is an Option attribute, we must add VocabularyValues.
//Here, we can add one Value at a time
new Mozu.Api.Contracts.ProductAdmin.AttributeVocabularyValue()
{
Value = "Down",
Content = new Mozu.Api.Contracts.ProductAdmin.AttributeVocabularyValueLocalizedContent()
{
LocaleCode = "en-US",
StringValue = "Down"
}
}
}
};
//Or, we can automate the process a bit with a collection of sizes that we then iterate over.
var sizes = "Wool|Deer Skin".Split('|');
foreach(var size in sizes)
{
newAttribute.VocabularyValues.Add(new Mozu.Api.Contracts.ProductAdmin.AttributeVocabularyValue()
{
Value = size,
Content = new Mozu.Api.Contracts.ProductAdmin.AttributeVocabularyValueLocalizedContent()
{
LocaleCode = "en-US",
StringValue = size
}
});
}
//Add Your Code:
//Check if attribute already exists, return back only the attributeFQN
var existingAttributes = productAttributeResource.GetAttributesAsync(filter: string.Format("AttributeCode sw '{0}'", newAttribute.AttributeCode), responseFields: "AttributeFQN").Result;
//Verify that the attribute doesn't exist
if (existingAttributes.TotalCount == 0)
{
//Add Your Code: Add New Attribute
var createdAttribute = productAttributeResource.AddAttributeAsync(newAttribute).Result;
}
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
namespace Mozu_BED_Training_Exercise_10_1
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_10_1_Get_Product_Type()
{
//Create a new ProductType resource
var productTypeResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.Attributedefinition.ProductTypeResource(_apiContext);
//Now that you're more familiar with using the Mozu API documentation, I'll just give you the link for the ProductType JSON information
//http://developer.mozu.com/content/api/APIResources/commerce/commerce.catalog/commerce.catalog.admin.attributedefinition.producttypes.htm
//Add Your Code:
//Get list of attributes with max page size and starting index at the beginning
var productTypes = productTypeResource.GetProductTypesAsync(startIndex: 0, pageSize: 200).Result;
//Add Your Code:
//Write total count of producttypes to output window
System.Diagnostics.Debug.WriteLine(string.Format("Product Type Total Count: {0}", productTypes.TotalCount));
//Add Your Code:
//Get product type filtered by name
var typeJacket = productTypeResource.GetProductTypesAsync(filter: "Name sw 'Jacket'").Result.Items[0];
//Loop through List<AttributeInProductType>
foreach (var option in typeJacket.Options)
{
//Loop through List<AttributeVocabularyValueInProductType>
foreach (var value in option.VocabularyValues)
{
//Add Your Code:
//Write vocabulary values to output window
System.Diagnostics.Debug.WriteLine(string.Format("Product Type [{0}]: Value({1}) StringValue({2})",
typeJacket.Name, value.Value, value.VocabularyValueDetail.Content.StringValue));
}
}
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
namespace Mozu_BED_Training_Exercise_10_2
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_10_2_Update_ProductTypes()
{
#region Add "Monogram" as an Extra
//Create a new ProductType resource
var producttypeResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.Attributedefinition.ProductTypeResource(_apiContext);
//Add Your Code:
//Get product type filtered by name
var typeJacket = (producttypeResource.GetProductTypesAsync(filter: "name sw 'purse'").Result).Items[0];
//Create an Attribute resource
var productAttributeResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.Attributedefinition.AttributeResource(_apiContext);
//In case you've forgotten about Product Attributes:
//http://developer.mozu.com/content/api/APIResources/commerce/commerce.catalog/commerce.catalog.admin.attributedefinition.attributes.htm
//Add Your Code:
//Get a monogram attribute
var attrMonogram = productAttributeResource.GetAttributeAsync("tenant~monogram").Result;
//Add Your Code:
//Create new object defining new extra
var attributeInProductTypeMonogram = new Mozu.Api.Contracts.ProductAdmin.AttributeInProductType()
{
AttributeDetail = attrMonogram,
AttributeFQN = attrMonogram.AttributeFQN,
};
//Test if the Extra already exists
if (typeJacket.Extras.Find(x => x.AttributeFQN == "tenant~monogram") == null)
{
//Add Your Code:
//Update product type with new extra
typeJacket.Extras.Add(attributeInProductTypeMonogram);
//Update product type
var updatedTypeMonogram = producttypeResource.UpdateProductTypeAsync(typeJacket, (int)typeJacket.Id).Result;
}
#endregion
#region Add "Purse-Size" as an Option
//Add Your Code:
//Get a purse size attribute
var attrInsulation = productAttributeResource.GetAttributeAsync("tenant~insulation").Result;
//Add Your Code:
//Create new object defining new option
var attributeInProductTypeJacket = new Mozu.Api.Contracts.ProductAdmin.AttributeInProductType()
{
AttributeDetail = attrInsulation,
AttributeFQN = attrInsulation.AttributeFQN,
VocabularyValues = new List<Mozu.Api.Contracts.ProductAdmin.AttributeVocabularyValueInProductType>(),
Order = 0
};
//Add Your Code:
//Exclude "Alta" from sizes
var doNotInclude = "Deer Skin";
//A variable needed for Option types to providea hierarchical order for each value
var sortOrder = 0;
foreach (var value in attrInsulation.VocabularyValues)
{
if (!doNotInclude.ToLower().Contains(value.Content.StringValue.ToLower()))
{
attributeInProductTypeJacket.VocabularyValues.Add(new Mozu.Api.Contracts.ProductAdmin.AttributeVocabularyValueInProductType
{
Value = value.Value,
VocabularyValueDetail = value,
Order = sortOrder++
});
}
}
//Test if the Option already exists
if (typeJacket.Options.Find(x => x.AttributeFQN == "tenant~insulation") == null)
{
//update product type with new option
typeJacket.Options.Add(attributeInProductTypeJacket);
//update product type
var updatedTypePurse = producttypeResource.UpdateProductTypeAsync(typeJacket, (int)typeJacket.Id).Result;
}
#endregion
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
namespace Mozu_BED_Training_Exercise_11_1
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public async Task Exercise_11_1_Get_Products()
{
//create a new product resource
var productResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.ProductResource(_apiContext);
//Get products
var products = (productResource.GetProductsAsync(startIndex: 0, pageSize: 200).Result);
//Add Your Code:
//Write total number of products to output window
System.Diagnostics.Debug.WriteLine("Total Products: {0}", products.TotalCount);
//Add Your Code:
//Get all products that have options and are configurable
var configurableProducts = products.Items.Where(d => d.Options != null).ToList();
//Add Your Code:
//Write total number of configurable products to output window
System.Diagnostics.Debug.WriteLine("Total Configurable Products: {0}", configurableProducts.Count);
//Add Your Code:
//Get all products that do not have options and are not configurable
var nonConfigurableProducts = products.Items.Where(d => d.Options == null).ToList();
//Add Your Code:
//Write total number of non-configurable products to output window
System.Diagnostics.Debug.WriteLine("Total Non-Configurable Products: {0}", nonConfigurableProducts.Count);
//Add Your Code:
//Get all products that are scarfs
var jacketProducts = products.Items.Where(d => d.Content.ProductName.ToLower().Contains("jacket")).ToList();
//Add Your Code:
//Write total number of scarf products to output window
System.Diagnostics.Debug.WriteLine("Total Jacket Products: {0}", jacketProducts.Count);
//Add Your Code:
//Get product price
var jacketProduct = productResource.GetProductAsync("MS-JKT-008").Result;
//Add Your Code:
//Write product prices to output window
System.Diagnostics.Debug.WriteLine("Product Prices[{0}]: Price({1}) Sales Price({2})", jacketProduct.ProductCode, jacketProduct.Price.Price, jacketProduct.Price.SalePrice);
//Create a new location inventory resource
var inventoryResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.LocationInventoryResource(_apiContext);
//Add Your Code:
//Get inventory
var inventory = inventoryResource.GetLocationInventoryAsync("WRH001", "MS-JKT-008").Result;
//Demostrate utility methods
var allProducts = await GetAllProducts(productResource);
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
namespace Mozu_BED_Training_Exercise_11_2
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_11_2_Create_New_Product()
{
var productCode = "MS-JKT-016";
//Grouped our necessary resources for defining aspects of the new product
var productResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.ProductResource(_apiContext);
var productTypeResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.Attributedefinition.ProductTypeResource(_apiContext);
var categoryResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.CategoryResource(_apiContext);
var productAttributeResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.Attributedefinition.AttributeResource(_apiContext);
//Wrap the Delete call in a try/catch in case the product doesn't exist
try
{
productResource.DeleteProductAsync(productCode).Wait();
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
//Retrieve the objects for later use when constructing our product
var monogram = productAttributeResource.GetAttributeAsync("tenant~monogram").Result;
var insulation = productAttributeResource.GetAttributeAsync("tenant~insulation").Result;
var typeJacket = productTypeResource.GetProductTypesAsync(filter: "Name eq 'Jackets'").Result;
var jacketCategory = categoryResource.GetCategoryAsync(53).Result;
Assert.IsNotNull(monogram);
Assert.IsNotNull(insulation);
Assert.IsNotNull(typeJacket);
Assert.IsNotNull(jacketCategory);
//Define the monogram as a ProductExtra to use when defining the Product
var monogramContract = new Mozu.Api.Contracts.ProductAdmin.ProductExtra()
{
AttributeFQN = monogram.AttributeFQN
};
//The actual List<ProductExtra> object added to the Product Contract
var productExtraList = new List<Mozu.Api.Contracts.ProductAdmin.ProductExtra>()
{
monogramContract
};
//Construct a List<ProductOptionValue> using the insulation Attribute Values
var insulationValuesList = new List<Mozu.Api.Contracts.ProductAdmin.ProductOptionValue>();
//Use this option to catch each Value we want to add for this Product
var insulationOptionValue = new Mozu.Api.Contracts.ProductAdmin.ProductOptionValue();
//Include only the values specified in the if-clause within the foreach loop
foreach(var value in insulation.VocabularyValues)
{
//If we wanted to include all sizes, we would remove this if-clause
if (value.Content.StringValue.ToLower() == "petite" || value.Content.StringValue.ToLower() == "classic")
{
//We instantiate a new object each time to avoid reference errors
insulationOptionValue = new Mozu.Api.Contracts.ProductAdmin.ProductOptionValue();
insulationOptionValue.AttributeVocabularyValueDetail = value;
insulationOptionValue.Value = value.Value;
insulationValuesList.Add(insulationOptionValue);
}
}
//Define the insulation as a ProductOption to use when defining the Product -- we use the insulationValuesList to add Values for the ProdcutOption
var insulationContract = new Mozu.Api.Contracts.ProductAdmin.ProductOption()
{
AttributeFQN = insulation.AttributeFQN,
Values = insulationValuesList
};
//The actual Option object added to the Product Contract
var productOptionList = new List<Mozu.Api.Contracts.ProductAdmin.ProductOption>()
{
insulationContract
};
//Construct a Product contract to submit to the API
var product = new Mozu.Api.Contracts.ProductAdmin.Product()
{
Content = new Mozu.Api.Contracts.ProductAdmin.ProductLocalizedContent()
{
ProductName = "Outdoors Jacket",
LocaleCode = "en-US"
},
FulfillmentTypesSupported = new List<string>()
{
"DirectShip"
},
HasConfigurableOptions = true,
IsTaxable = true,
Extras = productExtraList,
Options = productOptionList,
PackageHeight = new Mozu.Api.Contracts.Core.Measurement()
{
Unit = "in",
Value = 7
},
PackageWidth = new Mozu.Api.Contracts.Core.Measurement()
{
Unit = "in",
Value = 3
},
PackageLength = new Mozu.Api.Contracts.Core.Measurement()
{
Unit = "in",
Value = 10.25m
},
PackageWeight = new Mozu.Api.Contracts.Core.Measurement()
{
Unit = "lbs",
Value = 2.25m
},
Price = new Mozu.Api.Contracts.ProductAdmin.ProductPrice()
{
Price = 175m,
SalePrice = 125m
},
ProductUsage = "Configurable",
ProductCode = productCode,
//Add the ProductType "jacket" that we retrieved earlier
ProductTypeId = typeJacket.Items.FirstOrDefault().Id,
HasStandAloneOptions = false,
InventoryInfo = new Mozu.Api.Contracts.ProductAdmin.ProductInventoryInfo()
{
ManageStock = true,
OutOfStockBehavior = "DisplayMessage"
},
MasterCatalogId = 1,
ProductInCatalogs = new List<Mozu.Api.Contracts.ProductAdmin.ProductInCatalogInfo>()
{
new Mozu.Api.Contracts.ProductAdmin.ProductInCatalogInfo()
{
CatalogId = 1,
IsActive = true,
IsContentOverridden = false,
IsPriceOverridden = false,
IsseoContentOverridden = false,
Content = new Mozu.Api.Contracts.ProductAdmin.ProductLocalizedContent()
{
LocaleCode = "en-US",
ProductName = "Outdoors Jacket",
},
ProductCategories = new List<Mozu.Api.Contracts.ProductAdmin.ProductCategory>()
{
new Mozu.Api.Contracts.ProductAdmin.ProductCategory()
{
//Add the product to the "jacket" category using what we retrieved earlier
CategoryId = jacketCategory.Id.Value,
}
}
}
},
};
//The API call used to add a new product
var newProduct = productResource.AddProductAsync(product).Result;
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
namespace Mozu_BED_Training_Exercise_11_3
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_11_3_Add_Inventory_For_Product()
{
//Create a new location inventory resource
var inventoryResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.LocationInventoryResource(_apiContext);
//Retrieve inventory from main warehouse
var inventory = inventoryResource.GetLocationInventoryAsync("WRH001", "MS-JKT-016").Result;
var locationInventoryList = new List<Mozu.Api.Contracts.ProductAdmin.LocationInventory>()
{
new Mozu.Api.Contracts.ProductAdmin.LocationInventory()
{
LocationCode = "WRH001",
//Use the ProductVariation ProductCode here
ProductCode = "MS-JKT-016-DOWN",
StockOnHand = 90
}
};
//Add inventory for product in location
var newInventory = inventoryResource.AddLocationInventoryAsync(locationInventoryList, "WRH001", true).Result;
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
namespace Mozu_BED_Training_Exercise_13_1
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_13_1_Get_Customers()
{
//Create a Customer Account resource
var customerAccountResource = new Mozu.Api.Resources.Commerce.Customer.CustomerAccountResource(_apiContext);
//Retrieve an Account by id
var account = customerAccountResource.GetAccountAsync(1001).Result;
//Write the Account email
System.Diagnostics.Debug.WriteLine("Account Email[{0}]: {1}", account.Id, account.EmailAddress);
//You can also filter the Accounts Get call by email
var accountByEmail = customerAccountResource.GetAccountsAsync(filter: "EmailAddress eq 'test@customer.com'").Result;
//write account email
System.Diagnostics.Debug.WriteLine("Account Email[{0}]: {1}", account.EmailAddress, account.Id);
//Now, create a Customer Contact resource
var customerContactResource = new Mozu.Api.Resources.Commerce.Customer.Accounts.CustomerContactResource(_apiContext);
var customerContactCollection = new Mozu.Api.Contracts.Customer.CustomerContactCollection();
if (accountByEmail.TotalCount > 0)
{
customerContactCollection = customerContactResource.GetAccountContactsAsync(accountByEmail.Items[0].Id).Result;
}
else
{
System.Diagnostics.Debug.WriteLine("No contact information -- Customer does not exist");
}
if (customerContactCollection.TotalCount > 0)
{
foreach (var contact in customerContactCollection.Items)
{
System.Diagnostics.Debug.WriteLine("Name:");
System.Diagnostics.Debug.WriteLine(contact.FirstName);
System.Diagnostics.Debug.WriteLine(contact.MiddleNameOrInitial);
System.Diagnostics.Debug.WriteLine(contact.LastNameOrSurname);
System.Diagnostics.Debug.WriteLine("Address:");
System.Diagnostics.Debug.WriteLine(contact.Address.Address1);
System.Diagnostics.Debug.WriteLine(contact.Address.Address2);
System.Diagnostics.Debug.WriteLine(contact.Address.Address3);
System.Diagnostics.Debug.WriteLine(contact.Address.Address4);
System.Diagnostics.Debug.WriteLine(contact.Address.CityOrTown);
System.Diagnostics.Debug.WriteLine(contact.Address.StateOrProvince);
System.Diagnostics.Debug.WriteLine(contact.Address.PostalOrZipCode);
System.Diagnostics.Debug.WriteLine(contact.Address.CountryCode);
System.Diagnostics.Debug.WriteLine(String.Format("Is a validated address? {0}", contact.Address.IsValidated));
}
}
//Create a Customer Credit resource
var creditResource = new Mozu.Api.Resources.Commerce.Customer.CreditResource(_apiContext);
//Get credits by customer account id
var customerCredits = creditResource.GetCreditsAsync(filter: "CustomerId eq '1001'").Result;
foreach (var customerCredit in customerCredits.Items)
{
System.Diagnostics.Debug.WriteLine(string.Format("Customer Credit[{0}]: Code({1})Balance ({2})", customerCredit.CustomerId, customerCredit.Code, customerCredit.CurrentBalance));
}
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
namespace Mozu_BED_Training_Exercise_13_2
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_13_2_Add_New_Customer()
{
//Create a Customer Account resource
var customerAccountResource = new Mozu.Api.Resources.Commerce.Customer.CustomerAccountResource(_apiContext);
var existingAcct = customerAccountResource.GetAccountsAsync(filter: "EmailAddress eq 'captainmal@serenitycorp.com'").Result;
if (existingAcct == null || existingAcct.TotalCount == 0)
{
//Create a new Account Info and Authorization Info contract
var customerAccountAndAuthInfo = new Mozu.Api.Contracts.Customer.CustomerAccountAndAuthInfo()
{
Account = new Mozu.Api.Contracts.Customer.CustomerAccount()
{
AcceptsMarketing = false,
CompanyOrOrganization = "Serenity Corp.",
EmailAddress = "captainmal@serenitycorp.com",
ExternalId = "A0001",
FirstName = "Malcolm",
LastName = "Reynolds",
IsActive = true,
IsAnonymous = false,
LocaleCode = "en-US",
TaxExempt = false,
IsLocked = false,
UserName = "captainmal@serenitycorp.com",
},
Password = "Password1",
IsImport = true
};
var newAccount = customerAccountResource.AddAccountAndLoginAsync(customerAccountAndAuthInfo).Result;
var contactMal = new Mozu.Api.Contracts.Customer.CustomerContact()
{
Email = "captainmal@serenitycorp.com",
FirstName = "Malcolm",
LastNameOrSurname = "Reynolds",
Label = "Capt.",
PhoneNumbers = new Mozu.Api.Contracts.Core.Phone()
{
Mobile = "555-555-0001"
},
Address = new Mozu.Api.Contracts.Core.Address()
{
Address1 = "03-K64 Firefly Transport",
AddressType = "Residential",
CityOrTown = "Austin",
CountryCode = "US",
PostalOrZipCode = "78759",
StateOrProvince = "TX"
},
Types = new System.Collections.Generic.List<Mozu.Api.Contracts.Customer.ContactType>()
{
new Mozu.Api.Contracts.Customer.ContactType()
{
IsPrimary = true,
Name = "Billing"
}
}
};
var contactInara = new Mozu.Api.Contracts.Customer.CustomerContact()
{
Email = "inara@serenitycorp.com",
FirstName = "Inara",
LastNameOrSurname = "Serra",
Label = "Ms.",
PhoneNumbers = new Mozu.Api.Contracts.Core.Phone()
{
Mobile = "555-555-0002"
},
Address = new Mozu.Api.Contracts.Core.Address()
{
Address1 = "03-K64 Firefly Transport -- Shuttle",
AddressType = "Residential",
CityOrTown = "Austin",
CountryCode = "US",
PostalOrZipCode = "78759",
StateOrProvince = "TX"
},
Types = new System.Collections.Generic.List<Mozu.Api.Contracts.Customer.ContactType>()
{
new Mozu.Api.Contracts.Customer.ContactType()
{
IsPrimary = false,
Name = "Billing"
}
}
};
//Create a Customer Contact resource
var contactResource = new Mozu.Api.Resources.Commerce.Customer.Accounts.CustomerContactResource(_apiContext);
//Add new contact
var newContactMal = contactResource.AddAccountContactAsync(contactMal, newAccount.CustomerAccount.Id).Result;
//Add additional contact
var newContactInara = contactResource.AddAccountContactAsync(contactInara, newAccount.CustomerAccount.Id).Result;
}
//Create a Customer Credit resource
var creditResource = new Mozu.Api.Resources.Commerce.Customer.CreditResource(_apiContext);
//Create a Credit object
var credit = new Mozu.Api.Contracts.Customer.Credit.Credit()
{
ActivationDate = DateTime.Now,
Code = Guid.NewGuid().ToString("N"),
CreditType = "GiftCard",
CurrencyCode = "USD",
CurrentBalance = 1000,
CustomerId = 1002,
InitialBalance = 1000
};
//Add credit
var newCredit = creditResource.AddCreditAsync(credit).Result;
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
namespace Mozu_BED_Training_Exercise_14_1
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_14_1_Get_Orders()
{
//Create an Order resource. This resource is used to get, create, update orders
var orderResource = new Mozu.Api.Resources.Commerce.OrderResource(_apiContext);
//Filter orders by statuses
var acceptedOrders = orderResource.GetOrdersAsync(filter: "Status eq 'Accepted'").Result;
var closedOrders = orderResource.GetOrdersAsync(filter: "Status eq 'Closed'").Result;
//Filter orders by acct number
var orderByCustId = orderResource.GetOrdersAsync(filter: "CustomerAccountId eq '1001'").Result;
//Filter orders by email
var orderByEmail = orderResource.GetOrdersAsync(filter: "Email eq 'test@customer.com'").Result;
//Filter orders by order number
var existingOrders = orderResource.GetOrdersAsync(filter: "OrderNumber eq '1'").Result;
//Initialize the Order variable
Mozu.Api.Contracts.CommerceRuntime.Orders.Order existingOrder = null;
//Check if an Order was returned
if (existingOrders.TotalCount > 0)
{
//Set the Order to the first occurance in the collection
existingOrder = existingOrders.Items[0];
}
if (existingOrder != null)
{
System.Diagnostics.Debug.WriteLine(string.Format("Order Status Values: "
+ Environment.NewLine +
"Status={0}"
+ Environment.NewLine +
"FulfillmentStatus={1}"
+ Environment.NewLine +
"PaymentStatus={2}"
+ Environment.NewLine +
"ReturnStatus={3}",
existingOrder.Status,
existingOrder.FulfillmentStatus,
existingOrder.PaymentStatus,
existingOrder.ReturnStatus));
//Write out payment statuses
foreach (var existingPayment in existingOrder.Payments)
{
System.Diagnostics.Debug.WriteLine(string.Format("Payment Status Value[{0}]: Status={1}",
existingPayment.Id,
existingPayment.Status));
//Write out payment interaction statuses
foreach (var existingInteraction in existingPayment.Interactions)
{
System.Diagnostics.Debug.WriteLine(string.Format("Payment Interaction Status Value[{0}]: Status={1}",
existingInteraction.Id,
existingInteraction.Status));
}
}
//Write out order package statuses
foreach (var existingPackage in existingOrder.Packages)
{
System.Diagnostics.Debug.WriteLine(string.Format("Package Status Value[{0}]: Status={1}",
existingPackage.Id,
existingPackage.Status));
}
}
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
namespace Mozu_BED_Training_Exercise_14_2
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_14_2_Auth_Capture_Order_Payment()
{
var orderNumber = 12;
//Create an Order resource. This resource is used to get, create, update orders
var orderResource = new Mozu.Api.Resources.Commerce.OrderResource(_apiContext);
var paymentResource = new Mozu.Api.Resources.Commerce.Orders.PaymentResource(_apiContext);
var existingOrder = (orderResource.GetOrdersAsync(filter: "OrderNumber eq '" + orderNumber + "'").Result).Items[0];
Mozu.Api.Contracts.CommerceRuntime.Payments.Payment authorizedPayment = null;
Mozu.Api.Contracts.CommerceRuntime.Payments.Payment pendingPayment = null;
#region Add BillingInfo from Customer Object
var customerResource = new Mozu.Api.Resources.Commerce.Customer.CustomerAccountResource(_apiContext);
var customerAccount = customerResource.GetAccountAsync(1002).Result;
var contactInfo = new Mozu.Api.Contracts.Core.Contact();
foreach (var contact in customerAccount.Contacts)
{
foreach (var type in contact.Types)
{
if (type.IsPrimary)
{
contactInfo.Address = contact.Address;
contactInfo.CompanyOrOrganization = contact.CompanyOrOrganization;
contactInfo.Email = contact.Email;
contactInfo.FirstName = contact.FirstName;
contactInfo.LastNameOrSurname = contact.LastNameOrSurname;
contactInfo.MiddleNameOrInitial = contact.MiddleNameOrInitial;
contactInfo.PhoneNumbers = contact.PhoneNumbers;
}
}
}
var billingInfo = new Mozu.Api.Contracts.CommerceRuntime.Payments.BillingInfo()
{
BillingContact = contactInfo,
IsSameBillingShippingAddress = true,
PaymentType = "Check",
};
#endregion
var action = new Mozu.Api.Contracts.CommerceRuntime.Payments.PaymentAction()
{
Amount = existingOrder.Total,
CurrencyCode = "USD",
InteractionDate = DateTime.Now,
NewBillingInfo = billingInfo,
ActionName = "CreatePayment",
ReferenceSourcePaymentId = null,
CheckNumber = "1234"
};
try
{
authorizedPayment = existingOrder.Payments.FirstOrDefault(d => d.Status == "Authorized");
pendingPayment = existingOrder.Payments.FirstOrDefault(d => d.Status == "Pending");
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
if(authorizedPayment != null)
{
action.ActionName = "CapturePayment";
var capturedPayment = paymentResource.PerformPaymentActionAsync(action, existingOrder.Id, authorizedPayment.Id).Result;
}
else if(pendingPayment != null)
{
action.ActionName = "CapturePayment";
var capturedPayment = paymentResource.PerformPaymentActionAsync(action, existingOrder.Id, pendingPayment.Id).Result;
}
else
{
var authPayment = paymentResource.CreatePaymentActionAsync(action, existingOrder.Id).Result;
}
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
namespace Mozu_BED_Training_Exercise_14_3
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_14_3_Fulfill_Order_Package()
{
var orderResource = new Mozu.Api.Resources.Commerce.OrderResource(_apiContext);
var packageResource = new Mozu.Api.Resources.Commerce.Orders.PackageResource(_apiContext);
var shipmentResource = new Mozu.Api.Resources.Commerce.Orders.ShipmentResource(_apiContext);
var fulfillmentInfoResource = new Mozu.Api.Resources.Commerce.Orders.FulfillmentInfoResource(_apiContext);
var fulfillmentActionResource = new Mozu.Api.Resources.Commerce.Orders.FulfillmentActionResource(_apiContext);
var orderNumber = 6;
var filter = string.Format("OrderNumber eq '{0}'", orderNumber);
var existingOrder = (orderResource.GetOrdersAsync(startIndex: 0, pageSize: 1, filter: filter).Result).Items[0];
var existingOrderItems = existingOrder.Items;
var packageItems = new List<Mozu.Api.Contracts.CommerceRuntime.Fulfillment.PackageItem>();
foreach (var orderItem in existingOrderItems)
{
packageItems.Add(new Mozu.Api.Contracts.CommerceRuntime.Fulfillment.PackageItem()
{
ProductCode = String.IsNullOrWhiteSpace(orderItem.Product.VariationProductCode) ? orderItem.Product.ProductCode : orderItem.Product.VariationProductCode,
Quantity = orderItem.Quantity,
FulfillmentItemType = "Physical"
//LineId = orderItem.LineId
});
}
var package = new Mozu.Api.Contracts.CommerceRuntime.Fulfillment.Package()
{
Measurements = new Mozu.Api.Contracts.CommerceRuntime.Commerce.PackageMeasurements()
{
Height = new Mozu.Api.Contracts.Core.Measurement()
{
Unit = "in",
Value = 10m
},
Length = new Mozu.Api.Contracts.Core.Measurement()
{
Unit = "in",
Value = 10m
},
Width = new Mozu.Api.Contracts.Core.Measurement()
{
Unit = "in",
Value = 10m
},
Weight = new Mozu.Api.Contracts.Core.Measurement()
{
Unit = "lbs",
Value = 10m
},
},
Items = packageItems,
PackagingType = "CUSTOM",
};
var availableShippingMethods = shipmentResource.GetAvailableShipmentMethodsAsync(existingOrder.Id).Result;
package.ShippingMethodCode = availableShippingMethods[0].ShippingMethodCode;
package.ShippingMethodName = availableShippingMethods[0].ShippingMethodName;
package.FulfillmentLocationCode = "WRH01";
package.Code = "Package-01";
Mozu.Api.Contracts.CommerceRuntime.Fulfillment.Package updatedPackage = null;
try
{
updatedPackage = packageResource.CreatePackageAsync(package, existingOrder.Id).Result;
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
}
var packageIds = new List<string>();
if(updatedPackage == null)
{
packageIds.Add(existingOrder.Packages[0].Id);
}
else
{
packageIds.Add(updatedPackage.Id);
}
//var updatedPackageShipment = shipmentResource.CreatePackageShipmentsAsync(packageIds, existingOrder.Id).Result;
var fulfilledShipment = fulfillmentActionResource.PerformFulfillmentActionAsync(
new Mozu.Api.Contracts.CommerceRuntime.Fulfillment.FulfillmentAction()
{
ActionName = "Ship", // {Ship,Fulfill}
DigitalPackageIds = new List<string>(),
PackageIds = packageIds,
PickupIds = new List<string>()
},
existingOrder.Id)
.Result;
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
namespace Mozu_BED_Training_Exercise_14_4
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_14_4_Duplicate_Order()
{
var filter = string.Format("OrderNumber eq '{0}'", "5");
var orderResource = new Mozu.Api.Resources.Commerce.OrderResource(_apiContext);
var existingOrder = (orderResource.GetOrdersAsync(startIndex: 0, pageSize: 1, filter: filter).Result).Items[0];
existingOrder.ExternalId = existingOrder.OrderNumber.ToString();
existingOrder.Id = Guid.NewGuid().ToString("N");
existingOrder.OrderNumber = null;
existingOrder.IsImport = true;
var newOrder = orderResource.CreateOrderAsync(existingOrder).Result;
var orderNoteResource = new Mozu.Api.Resources.Commerce.Orders.OrderNoteResource(_apiContext);
var orderNote = new Mozu.Api.Contracts.CommerceRuntime.Orders.OrderNote()
{
Text = string.Format("Duplicate of original order number: {0}", existingOrder.Id)
};
var newOrderNote = orderNoteResource.CreateOrderNoteAsync(orderNote, newOrder.Id).Result;
}
}
}
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Mozu.Api;
using Autofac;
using Mozu.Api.ToolKit.Config;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Threading;
using System.Linq;
namespace Mozu_BED_Training_Exercise_16
{
[TestClass]
public class MozuDataConnectorTests
{
private IApiContext _apiContext;
private IContainer _container;
[TestInitialize]
public void Init()
{
_container = new Bootstrapper().Bootstrap().Container;
var appSetting = _container.Resolve<IAppSetting>();
var tenantId = int.Parse(appSetting.Settings["TenantId"].ToString());
var siteId = int.Parse(appSetting.Settings["SiteId"].ToString());
_apiContext = new ApiContext(tenantId, siteId);
}
[TestMethod]
public void Exercise_16_Add_Discount_And_Customer_To_Segment()
{
var discountResource = new Mozu.Api.Resources.Commerce.Catalog.Admin.DiscountResource(_apiContext);
var customerSegmentResouce = new Mozu.Api.Resources.Commerce.Customer.CustomerSegmentResource(_apiContext);
var customerAccountResource = new Mozu.Api.Resources.Commerce.Customer.CustomerAccountResource(_apiContext);
var discount = (discountResource.GetDiscountsAsync(filter: "Content.Name eq '10% Off Scarves'").Result).Items[0];
var customerSegment = (customerSegmentResouce.GetSegmentsAsync(filter:"Name eq 'High Volume Customer'").Result).Items[0];
var segmentToAdd = new Mozu.Api.Contracts.ProductAdmin.CustomerSegment()
{
Id = customerSegment.Id
};
if (!(discount.Conditions.CustomerSegments.Exists(x => x.Id == segmentToAdd.Id)))
{
discount.Conditions.CustomerSegments.Add(segmentToAdd);
var updatedDiscount = discountResource.UpdateDiscountAsync(discount, (int)discount.Id).Result;
}
var customerAccountIds = new List<int>();
var customerAccount = (customerAccountResource.GetAccountsAsync(filter:"FirstName eq 'Malcolm'").Result).Items[0];
customerAccountIds.Add(customerAccount.Id);
if(!(customerAccount.Segments.Exists(x => x.Id == customerSegment.Id)))
{
customerSegmentResouce.AddSegmentAccountsAsync(customerAccountIds, customerSegment.Id).Wait();
}
}
}
}
/// <summary>
/// Helper method for returning a List<Products> from multiple Product Collections if the page size is greater than 1
/// </summary>
/// <param name="productResource">Apicontext-driven </param>
private async static Task<List<Mozu.Api.Contracts.ProductAdmin.Product>> GetAllProducts(Mozu.Api.Resources.Commerce.Catalog.Admin.ProductResource productResource)
{
var productCollectionsTaskList = new List<Task<Mozu.Api.Contracts.ProductAdmin.ProductCollection>>();
var productCollectionsList = new List<Mozu.Api.Contracts.ProductAdmin.ProductCollection>();
var productsList = new List<Mozu.Api.Contracts.ProductAdmin.Product>();
var totalProductCount = 0;
var startIndex = 0;
var pageSize = 1;
var productCollection = await productResource.GetProductsAsync(pageSize: pageSize, startIndex: startIndex);
totalProductCount = productCollection.TotalCount;
startIndex += pageSize;
productsList.AddRange(productCollection.Items);
while (totalProductCount > startIndex)
{
productCollectionsTaskList.Add(productResource.GetProductsAsync(pageSize: pageSize, startIndex: startIndex));
startIndex += pageSize;
}
while (productCollectionsTaskList.Count > 0)
{
var finishedTask = await Task.WhenAny(productCollectionsTaskList);
productCollectionsTaskList.Remove(finishedTask);
productsList.AddRange((await finishedTask).Items);
}
return productsList;
}
/// <summary>
/// Helper method for checking the characteristic of a returned Product Attribute
/// </summary>
/// <param name="Attribute"></param>
private void WriteAttributeCharacteristic(Mozu.Api.Contracts.ProductAdmin.Attribute individualAttribute)
{
System.Diagnostics.Debug.Write(string.Format("Product Attribute Characteristic[{0}]: ", individualAttribute.AttributeCode));
if ((bool)individualAttribute.IsExtra)
{
System.Diagnostics.Debug.Write("Is an Extra");
}
else if ((bool)individualAttribute.IsOption)
{
System.Diagnostics.Debug.Write("Is an Option");
}
else if ((bool)individualAttribute.IsProperty)
{
System.Diagnostics.Debug.Write("Is a Property");
}
else
{
System.Diagnostics.Debug.Write("Has no characteristic");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment