repo_id
stringclasses
36 values
file_path
stringlengths
63
188
content
stringlengths
62
41.5k
__index_level_0__
int64
0
0
Dynamics365Commerce.InStore
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/global.json
{ "sdk": { "allowPrerelease": false, "rollForward": "latestPatch", "version": "8.0.402" } }
0
Dynamics365Commerce.InStore
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/repo.props
<Project> <PropertyGroup> <BuildNumber Condition="'$(BuildNumber)' == ''">0.0</BuildNumber> <MajorVersion>9.52</MajorVersion> <Version>$(MajorVersion).$(BuildNumber)</Version> </PropertyGroup> <PropertyGroup> <Publisher Condition="'$(Publisher)' == ''">CN=Contoso Ltd.</Publisher> <PublisherDisplayName Condition="'$(PublisherDisplayName)' == ''">Contoso Ltd.</PublisherDisplayName> </PropertyGroup> <PropertyGroup> <!-- Workaround for breaking changes in PackageDefinitions metadata. https://github.com/dotnet/sdk/issues/30809 --> <!-- TODO: avoid of the PackageDefinitions usage. --> <EmitLegacyAssetsFileItems>true</EmitLegacyAssetsFileItems> </PropertyGroup> <PropertyGroup> <CommerceSdkPackagesVersion>[9.52.*-*,9.53)</CommerceSdkPackagesVersion> <CommercePosPackagesVersion>[9.52.*-*,9.53)</CommercePosPackagesVersion> <CommerceChannelPackagesVersion>[9.52.*-*,9.53)</CommerceChannelPackagesVersion> <CommerceHwsPackagesVersion>[9.52.*-*,9.53)</CommerceHwsPackagesVersion> <CommerceToolsPackagesVersion>[10.34.*-*,10.35)</CommerceToolsPackagesVersion> <CommercePaymentsPackagesVersion>[10.52.*-*,10.53)</CommercePaymentsPackagesVersion> <TypeScriptPackagesVersion>4.7.*</TypeScriptPackagesVersion> <MauiVersion>8.0.82</MauiVersion> </PropertyGroup> </Project>
0
Dynamics365Commerce.InStore
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/LICENSE
MICROSOFT SOFTWARE LICENSE TERMS MICROSOFT DYNAMICS 365 FOR COMMERCE SOFTWARE DEVELOPMENT KIT (SDK) These license terms are an agreement between you and Microsoft Corporation (or one of its affiliates). They apply to the software named above and any Microsoft services or software updates (except to the extent such services or updates are accompanied by new or additional terms, in which case those different terms apply prospectively and do not alter your or Microsoft’s rights relating to pre-updated software or services). IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW. BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS. 1. INSTALLATION AND USE RIGHTS. a) General. You may install and use any number of copies of the software to develop and test your applications. b) Package Managers. The software includes package managers that give you the option to download other Microsoft and third party software packages to use with your application. Those packages are under their own licenses, and not this agreement. Microsoft does not distribute, license, or provide any warranties for any of the third party packages. 2. DISTRIBUTABLE CODE. The software may contain code you are permitted to distribute (i.e. make available for third parties) in applications you develop that work with Dynamics 365 for Commerce, as described in this Section. a) Distribution Rights. The sample source code files described below are distributable if included with the software. https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/retail-sdk/retail-sdk-overview#extension-components-in-the-retail-sdk i. Distributables. You may copy, modify, and distribute the sample source code listed in the distributables file list in the software; and ii. Third Party Distribution. You may permit distributors of your applications to copy and distribute any of this distributable code you elect to distribute with your applications. b) Distribution Requirements. For any code you distribute, you must: i. add significant primary functionality to it in your applications; ii. require distributors and external end users to agree to terms that protect it and Microsoft at least as much as this agreement; and iii. indemnify, defend, and hold harmless Microsoft from any claims, including attorneys’ fees, related to the distribution or use of your applications, except to the extent that any claim is based solely on the unmodified distributable code. c) Distribution Restrictions. You may not: i. use Microsoft’s trademarks or trade dress in your application in any way that suggests your application comes from or is endorsed by Microsoft; or ii. modify or distribute the source code of any distributable code so that any part of it becomes subject to any license that requires that the distributable code, any other part of the software, or any of Microsoft’s other intellectual property be disclosed or distributed in source code form, or that others have the right to modify it. 3. SCOPE OF LICENSE. The software is licensed, not sold. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you will not (and have no right to): a) work around any technical limitations in the software that only allow you to use it in certain ways; b) reverse engineer, decompile or disassemble the software, or otherwise attempt to derive the source code for the software, except and to the extent required by third party licensing terms governing use of certain open source components that may be included in the software; c) remove, minimize, block, or modify any notices of Microsoft or its suppliers in the software; d) use the software in any way that is against the law or to create or propagate malware; or e) share, publish, distribute, or lease the software (except for any distributable code, subject to the terms above), provide the software as a stand-alone offering for others to use, or transfer the software or this agreement to any third party. 4. DATA. a) Data Collection. The software may collect information about you and your use of the software, and send that to Microsoft. Microsoft may use this information to provide services and improve our products and services. You may opt-out of many of these scenarios, but not all, as described in the product documentation.  There are also some features in the software that may enable you to collect data from users of your applications. If you use these features to enable data collection in your applications, you must comply with applicable law, including providing appropriate notices to users of your applications. You can learn more about data collection and use in the help documentation and the privacy statement at https://aka.ms/privacy. Your use of the software operates as your consent to these practices. b) Processing of Personal Data. To the extent Microsoft is a processor or subprocessor of personal data in connection with the software, Microsoft makes the commitments in the European Union General Data Protection Regulation Terms of the Online Services Terms to all customers effective May 25, 2018, at https://docs.microsoft.com/en-us/legal/gdpr. 5. EXPORT RESTRICTIONS. You must comply with all domestic and international export laws and regulations that apply to the software, which include restrictions on destinations, end users, and end use. For further information on export restrictions, visit https://aka.ms/exporting. 6. SUPPORT SERVICES. Microsoft is not obligated under this agreement to provide any support services for the software. Any support provided is “as is”, “with all faults”, and without warranty of any kind. 7. UPDATES. The software may periodically check for updates, and download and install them for you. You may obtain updates only from Microsoft or authorized sources. Microsoft may need to update your system to provide you with updates. You agree to receive these automatic updates without any additional notice. Updates may not include or support all existing software features, services, or peripheral devices. 8. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you fail to comply with any of its terms or conditions. In such event, you must destroy all copies of the software and all of its component parts. 9. ENTIRE AGREEMENT. This agreement, and any other terms Microsoft may provide for supplements, updates, or third-party applications, is the entire agreement for the software. 10. APPLICABLE LAW AND PLACE TO RESOLVE DISPUTES. If you acquired the software in the United States or Canada, the laws of the state or province where you live (or, if a business, where your principal place of business is located) govern the interpretation of this agreement, claims for its breach, and all other claims (including consumer protection, unfair competition, and tort claims), regardless of conflict of laws principles. If you acquired the software in any other country, its laws apply. If U.S. federal jurisdiction exists, you and Microsoft consent to exclusive jurisdiction and venue in the federal court in King County, Washington for all disputes heard in court. If not, you and Microsoft consent to exclusive jurisdiction and venue in the Superior Court of King County, Washington for all disputes heard in court. 11. CONSUMER RIGHTS; REGIONAL VARIATIONS. This agreement describes certain legal rights. You may have other rights, including consumer rights, under the laws of your state or country. Separate and apart from your relationship with Microsoft, you may also have rights with respect to the party from which you acquired the software. This agreement does not change those other rights if the laws of your state or country do not permit it to do so. For example, if you acquired the software in one of the below regions, or mandatory country law applies, then the following provisions apply to you: a) Australia. You have statutory guarantees under the Australian Consumer Law and nothing in this agreement is intended to affect those rights. b) Canada. If you acquired this software in Canada, you may stop receiving updates by turning off the automatic update feature, disconnecting your device from the Internet (if and when you re-connect to the Internet, however, the software will resume checking for and installing updates), or uninstalling the software. The product documentation, if any, may also specify how to turn off updates for your specific device or software. c) Germany and Austria. i. Warranty. The properly licensed software will perform substantially as described in any Microsoft materials that accompany the software. However, Microsoft gives no contractual guarantee in relation to the licensed software. ii. Limitation of Liability. In case of intentional conduct, gross negligence, claims based on the Product Liability Act, as well as, in case of death or personal or physical injury, Microsoft is liable according to the statutory law. Subject to the foregoing clause ii., Microsoft will only be liable for slight negligence if Microsoft is in breach of such material contractual obligations, the fulfillment of which facilitate the due performance of this agreement, the breach of which would endanger the purpose of this agreement and the compliance with which a party may constantly trust in (so-called "cardinal obligations"). In other cases of slight negligence, Microsoft will not be liable for slight negligence. 12. DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED “AS IS.” YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS. TO THE EXTENT PERMITTED UNDER APPLICABLE LAWS, MICROSOFT EXCLUDES ALL IMPLIED WARRANTIES, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. 13. LIMITATION ON AND EXCLUSION OF DAMAGES. IF YOU HAVE ANY BASIS FOR RECOVERING DAMAGES DESPITE THE PRECEDING DISCLAIMER OF WARRANTY, YOU CAN RECOVER FROM MICROSOFT AND ITS SUPPLIERS ONLY DIRECT DAMAGES UP TO U.S. $5.00. YOU CANNOT RECOVER ANY OTHER DAMAGES, INCLUDING CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT, OR INCIDENTAL DAMAGES. This limitation applies to (a) anything related to the software, services, content (including code) on third party Internet sites, or third party applications; and (b) claims for breach of contract, warranty, guarantee, or condition; strict liability, negligence, or other tort; or any other claim; in each case to the extent permitted by applicable law. It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your state, province, or country may not allow the exclusion or limitation of incidental, consequential, or other damages. Please note: As this software is distributed in Canada, some of the clauses in this agreement are provided below in French. Remarque: Ce logiciel étant distribué au Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français. EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert « tel quel ». Toute utilisation de ce logiciel est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection des consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues. LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES DOMMAGES. Vous pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices. Cette limitation concerne: • tout ce qui est relié au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers; et • les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur. Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage. Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre égard. EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.
0
Dynamics365Commerce.InStore
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/README.md
--- page_type: sample languages: - csharp products: - dynamics-365 - dynamics-commerce name: Extend Commerce POS, HWS and Headless Commerce APIs and Commerce runtime. description: This repo contains the sample code on how to extend the Dynamics 365 Commerce POS, Hardware station, Headless Commerce APIs, and Commerce runtime. --- # Dynamics365Commerce.InStore repo This repo contains the sample code for how to customize the POS, Hardware Station(HWS) and Commerce runtime (CRT), Headless Commerce APIs and channel database. Please note that these are only samples and it is not required to clone this repo to develop Dynamics 365 Commerce extensions. This topic applies to Dynamics 365 commerce application version 10.0.18 or greater. This file explains the structure of the InStore samples repo and explains how to set up a repo to reference the Commerce SDK nuget packages from the public feed for Dynamics 365 Commerce extension development. Please visit our [docs site](aka.ms/Dynamics365CommerceDevDocs) for additional resources about Dynamics 365 Commerce development. ## Prerequisites This process doesn't require a specific pre-configured environment or virtual machine. Development and testing can be done on any machine with relatively modern version of Windows. If you don't require Modern POS development you can leverage Windows 10, Windows Server 2016/2019. If you require Sealed Modern POS development, install these prerequisites. For more details on the development environment prerequisites please refer to [this article](https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/pos-extension/pos-extension-getting-started#prerequisites) ## Repo folder and solution structure The sample InStore repo contains nuget.config, repo.props, CustomizationPackage.props and build pipelines script which provide guidance on how extension can setup the repo metadata files. | Folder | Description | | --------------------- | ------------------------------------------------------------------------------------------------------------------------ | | HardwareStationSample | This project contains samples on how to create Hardware station, Payment extensions and extension installers. | | [StoreCommerceSamples](./src/StoreCommerceSamples/readme.md) | This folder contains samples demonstrating how to extend the Store Commerce App to achieve various customization scenarios. | | PackagingSamples | This folder contains samples that demonstrate how to structure your Commerce SDK solution to create packages/installers for the appropriate Commerce components. | | Pipeline | YAML and PowerShell script files | This folder/project contains sample scripts and YAML files to setup the build automation in Azure DevOps build pipeline. | The [Dynamics365Commerce.ScaleUnit](https://github.com/microsoft/Dynamics365Commerce.ScaleUnit) repo contains additional samples focused on Headless Commerce extension development scenarios like Headless Commerce APIs and Commerce Runtime. ## What to expect with each sample Each sample in this repo is accompanied by a readme.md file with the following information: - A description of its functionality - The steps to build and run the sample - The list of Commerce APIs and extension points used in the sample and a description of what they do. - A link to relevant documentation of the Commerce APIs and feature area - A gif or a screenshot of the functionality, if applicable ## Troubleshooting Build & Other Development Issues The Commerce team has build automation that validates that all the samples in this repo build successfully, but that doesn't guarantee that these samples will always build and run without issues that are common during software development. If you encounter an issue with the InStore samples or the Commerce SDK in please search the issues section of this Github repo to see if it is a known issue. There may already be a fix or workaround available. If you don't see your issue listed in the issues section please create a new issue to with details about the issue you're facing. This will help ensure that everyone using the Commerce SDK and these samples has the best experience possible, and that all known issues will be searchable online. We will monitor these issues and help as soon as we possibly can. Note: For the best experience, please limit the use of the issues section to report problems with the Commerce SDK and the InStore samples. ## Branches The branches in the repo are organized by Dynamics 365 Commerce application release, each branch in the repo points to an application release of Dynamics 365 Commerce, use the right release branch based on your go-live version. | Release branch name | version | Application release version | | ------------------------------------------------------------------------------------------ | ------- | --------------------------- | | [Release/9.49](https://github.com/microsoft/Dynamics365Commerce.InStore/tree/release/9.49) | 9.49.\* | 10.0.39 | | [Release/9.50](https://github.com/microsoft/Dynamics365Commerce.InStore/tree/release/9.50) | 9.50.\* | 10.0.40 | | [Release/9.51](https://github.com/microsoft/Dynamics365Commerce.InStore/tree/release/9.51) | 9.51.\* | 10.0.41 | | [Release/9.52](https://github.com/microsoft/Dynamics365Commerce.InStore/tree/release/9.52) | 9.52.\* | 10.0.42 | ## Referencing Commerce SDK Nuget packages Commerce contracts, messages, entities, and request packages are published in this public feed for commerce extension code to consume and customize existing functionalities or build new functionalities for Dynamics 365 Commerce product. Consume the commerce packages from this [location](https://pkgs.dev.azure.com/commerce-partner/Registry/_packaging/dynamics365-commerce/nuget/v3/index.json), extension can add package source location in the nuget.config of their extension project file. ```xml <packageSources> <add key="dynamics365-commerce" value="https://pkgs.dev.azure.com/commerce-partner/Registry/_packaging/dynamics365-commerce/nuget/v3/index.json" /> <add key="nuget.org" value="https://api.nuget.org/v3/index.json" /> </packageSources> ``` ## Commerce packages available in the public feed | Package name | Description | | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Microsoft.Dynamics.Commerce.Sdk.ChannelDatabase | This package is required to generate the DB packages with CSU. | | Microsoft.Dynamics.Commerce.Sdk.Runtime | This package contains all commerce runtime libraries | | Microsoft.Dynamics.Commerce.Sdk.ScaleUnit | This package is required to generate the CSU package for deployment. | | Microsoft.Dynamics.Commerce.Sdk.Installers.ScaleUnit | This package is required to generate the ScaleUnit package for deployment | | Microsoft.Dynamics.Commerce.Sdk.HardwareAndPeripherals | This package contains all commerce Hardware station and peripherals libraries | | Microsoft.Dynamics.Commerce.Sdk.Installers | This package contains all the installers libraries | | Microsoft.Dynamics.Commerce.Sdk.Installers.HardwareStation | This package is required to generate the Hardware station package for deployment | | Microsoft.Dynamics.Commerce.Sdk.Installers.StoreCommerce | This package is required to generate the Store Commerce extensions installer. | | Microsoft.Dynamics.Commerce.Sdk.Pos | This package contains all POS libraries | | Microsoft.Dynamics.Commerce.Sdk.Installers.ModernPos | This package is required to generate the POS extension installer for deployment | | Microsoft.Dynamics.Commerce.Diagnostics | This package contains all the diagnostic libraries | | Microsoft.Dynamics.Commerce.Runtime.Data | This package contains all data contract libraries | | Microsoft.Dynamics.Commerce.Runtime.DataServices.Messages | This package contains all data services message libraries | | Microsoft.Dynamics.Commerce.Runtime.Entities | This package contains all commerce entities definition | | Microsoft.Dynamics.Commerce.Runtime.Framework | This package contains all commerce framework libraries | | Microsoft.Dynamics.Commerce.Runtime.Hosting.Contracts | This package contains all commerce controller libraries | | Microsoft.Dynamics.Commerce.Runtime.Messages | This package contains all commerce runtime messages libraries | | Microsoft.Dynamics.Commerce.Runtime.RealtimeServices.Messages | This package contains all the commerce real runtime libraries | | Microsoft.Dynamics.Commerce.Runtime.Services.Messages | This package contains all the commerce service messages libraries | | Microsoft.Dynamics.Commerce.HardwareStation.Core | This package contains all the HWS libraries | | Microsoft.Dynamics.Commerce.HardwareStation.PeripheralRequests | This package contains all the HWS peripherals request libraries | | Microsoft.Dynamics.Commerce.HardwareStation.Peripherals.Contracts | This package contains all the HWS peripherals contracts libraries | | Microsoft.Dynamics.Commerce.HardwareStation.Peripherals.Entities | This package contains all the HWS peripherals entities libraries | | Microsoft.Dynamics.Commerce.Installers.Framework | This package contains all the installers framework libraries | | Microsoft.Dynamics.Commerce.KeyVault.Contracts | This package contains all the key vault contract libraries | | Microsoft.Dynamics.Commerce.PaymentSDK.Extensions.Portable | This package contains all the payment extension libraries | | Microsoft.Dynamics.Commerce.PaymentSDK.Portable | This package contains all the payment libraries | | Microsoft.Dynamics.Commerce.Runtime.FIF.Connector.Messages | This package contains all the FIF connector libraries | | Microsoft.Dynamics.Commerce.Runtime.FIF.DocumentProvider.Messages | This package contains all the FIF document provider libraries | | Microsoft.Dynamics.Commerce.Installers.Framework.DatabaseExtensions | This package contains all the database installer framework libraries | | Microsoft.Dynamics.Commerce.Tools.DbUtilities | This package contains all the DB utilities libraries | | Microsoft.Dynamics.Commerce.Tools.ExtensionsProxyGenerator.AspNetCore | This package contains all the extensions proxy generator utilities | | Microsoft.Dynamics.Commerce.Proxy.ScaleUnit | This package contains all the proxies class for extension applications to consume the Headless Commerce APIs in online mode (connected to Headless Commerce). | ## Package versioning | Package version | Application release | | ---------------- | ------------------------ | | 9.49.x.x-preview | 10.0.39 PEAP release | | 9.49.x.x | 10.0.39 Customer preview | | 9.49.x.x | 10.0.39 GA | | 9.50.x.x-preview | 10.0.40 PEAP release | | 9.50.x.x | 10.0.40 Customer preview | | 9.50.x.x | 10.0.40 GA | | 9.51.x.x-preview | 10.0.41 PEAP release | | 9.51.x.x | 10.0.41 Customer preview | | 9.51.x.x | 10.0.41 GA | | 9.52.x.x-preview | 10.0.42 PEAP release | | 9.52.x.x | 10.0.42 Customer preview | | 9.52.x.x | 10.0.42 GA | Extension project can consume the correct version by adding the package reference to the project with full version number or use wild card to always get the latest version, recommend option is to use the full version number and update the version based on your go-live version. ```xml <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.Pos " Version="9.52.x.x" /> ``` Or ```xml <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.Pos " Version="9.52.*" /> ``` With every hotfix and new application release, new version of the package will be published in the same public feed, consume the right package version based on the version required for your go live. Consuming the higher version of the package than your go-live application version may result in runtime and deployment failures. **Setup Azure DevOps pipeline for build automation and package generation:** [Set up a build pipeline for the Commerce SDK](https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/build-pipeline) **Best practice and branching strategies:** Detailed information on git branching strategy refer [Git branching strategy](https://docs.microsoft.com/en-us/azure/devops/repos/git/git-branching-guidance?view=azure-devops) doc. The following branching strategies are based on the way we use Git here at Microsoft. For more information, see [How we use Git at Microsoft](https://docs.microsoft.com/en-us/azure/devops/learn/devops-at-microsoft/use-git-microsoft). Keep your branch strategy simple. Build your strategy from these three concepts: - Use feature branches for all new features and bug fixes. - Merge feature branches into the main branch using pull requests. - Keep a high quality, up-to-date main branch. **Create a new feature branch for development and bug fixes:** Create a new feature main branch for our extension, follow the proper naming convention (refer the [Git branching doc for sample naming convention](https://docs.microsoft.com/en-us/azure/devops/repos/git/git-branching-guidance?view=azure-devops#name-your-feature-branches-by-convention)) **Create a new development branch:** Create a private branch for the development: - git checkout -b private/{username}/{feature/description} Add and commit new changes to the development branch using git -add . and git commit -m&quot; commit message.&quot; After the development is completed, tested, and validated push the changes to the main branch by doing git push \&lt;remote\&gt; \&lt;branch\&gt; - git push origin {private branch name} **Create a release branch after development:** After the development changes pushed into the main branch, create a new release branch, and create the deployable packages from the release branch. - Git checkout -b release/x.x.x Merge the changes from the release branch back to main branch if any changes done in the release branch. ```text - git checkout master git merge release/x.x.x ``` **Extension hotfix branch:** Like release branch, create hotfix branch for extension from main branch and release the fix and later merge the changes back to the main branch. **Merge new release branch to main and development branch:** After a new version of the samples released, if required merge your development branch with the new branch. The repo contains only samples, so it&#39;s not required to always get the updated changes from the branch. ```text - git checkout master git merge release/x.x.x ```
0
Dynamics365Commerce.InStore
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/nuget.config
<?xml version="1.0" encoding="UTF-8"?> <configuration> <config> <add key="repositoryPath" value="src/Dependencies" /> </config> <packageSources> <clear /> <add key="dynamics365-commerce" value="https://pkgs.dev.azure.com/commerce-partner/Registry/_packaging/dynamics365-commerce/nuget/v3/index.json" /> <add key="nuget.org" value="https://api.nuget.org/v3/index.json" /> </packageSources> <disabledPackageSources> <clear /> </disabledPackageSources> </configuration>
0
Dynamics365Commerce.InStore
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/SECURITY.md
<!-- BEGIN MICROSOFT SECURITY.MD V0.0.7 BLOCK --> ## Security Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. ## Reporting Security Issues **Please do not report security vulnerabilities through public GitHub issues.** Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). If you prefer to submit without logging in, send email to [[email protected]](mailto:[email protected]). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) * Full paths of source file(s) related to the manifestation of the issue * The location of the affected source code (tag/branch/commit or direct URL) * Any special configuration required to reproduce the issue * Step-by-step instructions to reproduce the issue * Proof-of-concept or exploit code (if possible) * Impact of the issue, including how an attacker might exploit the issue This information will help us triage your report more quickly. If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. ## Preferred Languages We prefer all communications to be in English. ## Policy Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). <!-- END MICROSOFT SECURITY.MD BLOCK -->
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/README.md
## Hardware Station(HWS) Extension Hardware Station is used by Store Commerce, Modern POS (MPOS) and Cloud POS(CPOS) to connect to hardware peripherals, such as printers, cash drawers, scanners, and payment terminals. This project contains sample code on how to create HWS extensions and extension installers for shared HWS. The Sealed Shared HWS installer must be installed before running the extension installer, follow this doc to [install HWS](https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/enhanced-mass-deployment) For detailed steps on how to create extension HWS installer, follow the [Generate an extension installer for the shared Hardware station](https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/hardware-device-extension#generate-an-extension-installer-for-the-shared-hardware-station-for-application-release-10018-or-later) ## HWS docs: [Integrate the POS with a new hardware device](https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/hardware-device-extension) [Create an end-to-end payment integration for a payment terminal](https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/end-to-end-payment-extension) ### Consume extension in MPOS local HWS To consume the HWS extension in local/dedicated HWS, the HWS extension must be packaged with the MPOS, in the modern pos JavaScript project add reference to your HWS projects and then use the POS installer project to create the extension installer. Refer the sample JavaScript project available in the [Dynamics 365 Commerce InStore samples repo](https://github.com/microsoft/Dynamics365Commerce.InStore) - [src/PosSample/ModernPos/ModernPos.jsproj] folder for more details. If you have only HWS extension, then remove all the other unwanted project references from the sample. ModernPos.jsproj creates the msix installer and then the installer project consumes it and creates the exe installer, HWS extensions will be deployed as UWP app extension. ## Using the samples You can download the sample as zip and open it in Visual Studio (VS 2022). After opening in VS 2022, build the project. After successful build, output installer package will be created. To deploy the Shared Hardware station extension for POS and to test it, follow the below steps. 1. Run the extension installer generated using command prompt. Ex: C:\HardwareStation.Installer\bin\Debug\net472> .\HardwareStation.Installer.exe install 2. Close POS if it's running. 3. Open POS and configure it to use the Shared Hardware Station. 4. Validate the extension scenario. To deploy the Dedicated Hardware station extensions (OPOS and Windows printer samples) for POS and to test them, follow the steps below: 1. Close POS if it's running. 2. Rebuild the Contoso.HardwareStation.Samples solution. Verify that in the build output, the installer completed successfully by seeing the message: `InstallStoreCommerceExtensions: Running the StoreCommerce extensions installer completed successfully.` 3. Copy the CommerceRuntime DLL (HardwareStationSamples\CommerceRuntime\bin\Debug\netstandard2.0\Contoso.HardwareStationSamples.CommerceRuntime.dll) into your dev environment's Retail Server extension folder (\Pkg\bin\Ext). 4. In the same folder, open the CommerceRuntime.Ext.config and add a line for the extension assembly: ` <add source="assembly" value="Contoso.HardwareStationSamples.CommerceRuntime" />` 5. Open POS and configure it to use the Local Hardware Station. 6. Validate the extension scenarios.
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/CustomizationPackage.props
<Project> <Import Project="..\..\repo.props" /> <PropertyGroup> <PackagePublisher Condition="'$(PackagePublisher)' == ''">$(Publisher)</PackagePublisher> <PackagePublisherDisplayName Condition="'$(PackagePublisherDisplayName)' == ''">$(PublisherDisplayName)</PackagePublisherDisplayName> <PackageVersion Condition="'$(PackageVersion)' == ''">$(Version)</PackageVersion> <PackageName Condition="'$(PackageName)' == ''">Contoso.Commerce.PaymentDevice</PackageName> <PackageDisplayName Condition="'$(PackageDisplayName)' == ''">Contoso Payment Device Commerce Customization</PackageDisplayName> <PackageDescription Condition="'$(PackageDescription)' == ''">Contoso Payment Device Commerce Customization</PackageDescription> </PropertyGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PeripheralCustomizations/Contoso.PeripheralCustomizations.csproj
<Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\CustomizationPackage.props" /> <PropertyGroup> <RootNamespace>Contoso.HardwareStation.Peripherals.PeripheralCustomizations</RootNamespace> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.HardwareAndPeripherals" Version="$(CommerceSdkPackagesVersion)" /> </ItemGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PeripheralCustomizations/README.md
# HardwareStation Peripherals Customization Sample This sample shows how to customize the handling of peripherals by the Hardware Station server. ## How the Sample works This sample implements Request Handlers for key peripheral requests showcasing how to tailor the behavior of the hardware station to meet your specific needs. Below is a brief explanation of each scenario supported by this sample. ### Custom Magnetic Card Swipe Parsing The CustomMsrTrackParser class shows how to override the custom MSR track information parsing done by the Hardware Station, which makes it possible to handle any format of MSR tracks. ### Custom handling of signature capture point array Certain signature capture devices might require a different handling of the point array returned by the device. The CustomSignatureCaptureDevice class customizes the parsing of the point array to encode each coordinates in ANSI as might be required by a few devices. ### Custom OPOS device execution While the previous samples allow handling a specific part of the peripheral processing, when handling OPOS devices there might be the need to fully customize the device's behavior by accessing methods and properties only accessible to the OPOS device instance. The CustomOposPrinterDevice class utilizes three Requests that showcases how to customize the behavior of OPOS devices without having direct access to the OPOS device instance. This allows more flexibility on customizing the OPOS workflow for each device. - ExecuteOposDeviceMethodRequest executes a method on the OPOS device with a list of parameters. The method must exist and the parameters will be sent in the same order that they are given. - GetOposDevicePropertyValueRequest gets the value of a property on the OPOS Device. The property getter must be publicly accessible. - SetOposDevicePropertyValueRequest sets the value of a property on the OPOS Device. The property setter must be publicly accessible. ### Custom Windows Printer Request Windows printer requests can be overriden to modify the receipt content, for example to center fixed-width 40-character receipts on a standard sheet of paper.
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PeripheralCustomizations
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PeripheralCustomizations/MSR/CustomMsrTrackParser.cs
namespace Contoso.Commerce.HardwareStation.Peripherals { using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Dynamics.Commerce.HardwareStation.Models; using Microsoft.Dynamics.Commerce.HardwareStation.Peripherals.Entities; using Microsoft.Dynamics.Commerce.Runtime; using Microsoft.Dynamics.Commerce.Runtime.Messages; /// <summary> /// Handles requests for getting the parsed magnetic card reader swipe information. /// </summary> public class CustomMsrTrackParser : SingleAsyncRequestHandler<GetParsedMagneticCardSwipeInfoRequest> { /// <summary> /// Gets the parsed magnetic card reader swipe information using a custom regular expression. /// </summary> /// <param name="request">The request to get the parsed magnetic card swipe information.</param> /// <returns>A response containing the parsed magnetic card swipe information.</returns> protected override Task<Response> Process(GetParsedMagneticCardSwipeInfoRequest request) { var swipeInfo = new MagneticCardSwipeInfo(); swipeInfo.ParseTracks(request.Track1Data, request.Track2Data); // Custom track2 regular expression to extract the primary account number. Regex track2Regex = new Regex("^;?(?<PrimaryAccountNumber>[0-9]{1,19})<>((?<ExpiryDate>[0-9]{4})|((?<ExpiryDate>)=)).*$"); var track2Match = track2Regex.Match(request.Track2Data); var group = track2Match.Groups["PrimaryAccountNumber"]; swipeInfo.AccountNumber = group.Value; GetParsedMagneticCardSwipeInfoResponse response = new GetParsedMagneticCardSwipeInfoResponse(swipeInfo); return Task.FromResult<Response>(response); } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PeripheralCustomizations
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PeripheralCustomizations/Printer/CustomWindowsPrinterDevice.cs
namespace Microsoft.Dynamics { namespace Contoso.HardwareStation.Peripherals { using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Dynamics.Commerce.HardwareStation; using Microsoft.Dynamics.Commerce.HardwareStation.Peripherals; using Microsoft.Dynamics.Commerce.Runtime.Handlers; using Microsoft.Dynamics.Commerce.Runtime.Messages; /// <summary> /// Class implements windows based printer driver for hardware station. /// </summary> #pragma warning disable CS0618 // JUSTIFICATION: Pending migration to asynchronous APIs. public class CustomWindowsPrinterDevice : INamedRequestHandlerAsync #pragma warning restore CS0618 { /// <summary> /// Gets the unique name for this request handler. /// </summary> public string HandlerName { get { return PeripheralType.Windows; } } /// <summary> /// Gets the collection of supported request types by this handler. /// </summary> public IEnumerable<Type> SupportedRequestTypes { get { return new[] { typeof(OpenPrinterDeviceRequest), typeof(PrintPrinterDeviceRequest), typeof(ClosePrinterDeviceRequest) }; } } /// <summary> /// Gets or sets the printer name. /// </summary> protected string PrinterName { get; set; } /// <summary> /// Represents the entry point for the printer device request handler. /// </summary> /// <param name="request">The incoming request message.</param> /// <returns>The outgoing response message.</returns> public async Task<Response> Execute(Request request) { ThrowIf.Null(request, nameof(request)); switch (request) { case OpenPrinterDeviceRequest openPrinterRequest: this.Open(openPrinterRequest.DeviceName); return await openPrinterRequest.RequestContext.Runtime.ExecuteNextAsync<Response>( this, openPrinterRequest, openPrinterRequest.RequestContext, true, HandlerName).ConfigureAwait(false); case PrintPrinterDeviceRequest printRequest: // If print request is for X- or Z-report then center receipt content if (printRequest.Header.Contains("X-Report") || printRequest.Header.Contains("Z-Report")) { // Receipt content is read only, so create a new request instead of modifing original PrintPrinterDeviceRequest customRequest = new PrintPrinterDeviceRequest( CenterReceiptContent(printRequest.Header), CenterReceiptContent(printRequest.Lines), CenterReceiptContent(printRequest.Footer)); customRequest.RequestContext = printRequest.RequestContext; printRequest = customRequest; } return await printRequest.RequestContext.Runtime.ExecuteNextAsync<Response>( this, printRequest, printRequest.RequestContext, true, HandlerName).ConfigureAwait(false); case ClosePrinterDeviceRequest closePrinterRequest: this.Close(); return await closePrinterRequest.RequestContext.Runtime.ExecuteNextAsync<Response>( this, closePrinterRequest, closePrinterRequest.RequestContext, true, HandlerName).ConfigureAwait(false); default: throw new NotSupportedException(string.Format("Request '{0}' is not supported.", request.GetType())); } } /// <summary> /// Centers receipt content on a standard size sheet of paper /// </summary> /// <param name="input">Left justified receipt content</param> /// <returns>Centered receipt content</returns> private string CenterReceiptContent(string input) { string newLine = "\r\n"; string[] seperator = { newLine }; string output = string.Empty; // Split receipt content on new line seperator and loop through each line string[] lines = input.Split(seperator, StringSplitOptions.None); foreach (string line in lines) { // Pad right to total width 55 (longest line in z-report) to keep content left justified // then pad left to total width 98 to center on standard sheet of paper. string paddedLine = line.PadRight(55); output += paddedLine.PadLeft(98) + newLine; } // Prevent printer from adding extra blank line between receipt segments by removing trailing new line character return output.Remove(output.Length - newLine.Length); } /// <summary> /// Opens a peripheral. /// </summary> /// <param name="peripheralName">Name of the peripheral.</param> private void Open(string peripheralName) { this.PrinterName = peripheralName; } /// <summary> /// Closes a peripheral. /// </summary> private void Close() { this.PrinterName = null; } } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PeripheralCustomizations
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PeripheralCustomizations/Printer/CustomOposPrinterDevice.cs
namespace Microsoft.Dynamics { namespace Contoso.HardwareStation.Peripherals { using System; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; using Microsoft.Dynamics.Commerce.HardwareStation; using Microsoft.Dynamics.Commerce.HardwareStation.PeripheralRequests.Opos; using Microsoft.Dynamics.Commerce.HardwareStation.Peripherals; using Microsoft.Dynamics.Commerce.HardwareStation.Peripherals.Entities.Opos; using Microsoft.Dynamics.Commerce.Runtime; using Microsoft.Dynamics.Commerce.Runtime.Handlers; using Microsoft.Dynamics.Commerce.Runtime.Messages; using Microsoft.Dynamics.Retail.Diagnostics; using Microsoft.Dynamics.Retail.Diagnostics.Extensions; using ThrowIf = Commerce.HardwareStation.ThrowIf; /// <summary> /// A custom OPOS based printer device handler. /// </summary> public class CustomOposPrinterDevice : INamedRequestHandlerAsync { private const string BarcodeRegex = "<B: (.+?)>"; private const string EscMarker = "&#x1B;"; private const string EscCharacter = "\x1B"; private const string ImageTagStart = "<I:"; private const string ImageTagEnd = ">"; private const string OPOSMarkersForSplitRegEx = @"(&#x1B;\|1C|&#x1B;\|2C|&#x1B;\|3C|&#x1B;\|4C|\r\n|\|1C)"; private static string peripheralName = "OposPrinter"; private static int characterSet = -1; private enum Events { InvalidImage, PrintBitmapConfiguration, PrintBitmapException, PrintBitmapNotSupported, CapRecPapercutException, } /// <summary> /// Gets the unique name for this request handler. /// </summary> public string HandlerName { get { return PeripheralType.Opos; } } /// <summary> /// Gets the collection of supported request types by this handler. /// </summary> public IEnumerable<Type> SupportedRequestTypes { get { return new[] { typeof(OpenPrinterDeviceRequest), typeof(PrintPrinterDeviceRequest), typeof(ClosePrinterDeviceRequest), }; } } /// <summary> /// Represents the entry point for the printer device request handler. /// </summary> /// <param name="request">The incoming request message.</param> /// <returns>The outgoing response message.</returns> public async Task<Response> Execute(Request request) { ThrowIf.Null(request, nameof(request)); switch (request) { case OpenPrinterDeviceRequest openPrinterRequest: peripheralName = openPrinterRequest.DeviceName; return await openPrinterRequest.RequestContext.Runtime.ExecuteNextAsync<Response>( this, openPrinterRequest, openPrinterRequest.RequestContext, true, HandlerName).ConfigureAwait(false); case PrintPrinterDeviceRequest printRequest: if (peripheralName == null) { return await printRequest.RequestContext.Runtime.ExecuteNextAsync<Response>( this, printRequest, printRequest.RequestContext, true, HandlerName).ConfigureAwait(false); } await PrintAsync(printRequest.RequestContext, printRequest.Header, printRequest.Lines, printRequest.Footer).ConfigureAwait(false); break; case ClosePrinterDeviceRequest closePrinterRequest: peripheralName = null; return await closePrinterRequest.RequestContext.Runtime.ExecuteNextAsync<Response>( this, closePrinterRequest, closePrinterRequest.RequestContext, true, HandlerName).ConfigureAwait(false); default: throw new NotSupportedException(string.Format("Request '{0}' is not supported.", request.GetType())); } return NullResponse.Instance; } /// <summary> /// Print the text to the Printer. /// </summary> /// <param name="context">The OPOS printer.</param> /// <param name="textToPrint">The text to print on the receipt.</param> private async Task PrintTextAsync(RequestContext context, string textToPrint) { int resultCode; int resultCodeExtended; string oposPrinterMethod; string[] textToPrintSplit = Regex.Split(textToPrint, BarcodeRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase); for (int i = 0; i < textToPrintSplit.Length; i++) { // Grab text to print from the split array. string toPrint = textToPrintSplit[i]; // Check if printer run out of paper after previous print call. await this.CheckPaperStatusAsync(context).ConfigureAwait(false); // Text is barcode if it doesn't contain any special escape characters found in normal receipt strings for OPS (e.g., '&#x1B;|1C' or '1C'). bool isBarcode = !Regex.IsMatch(toPrint, OPOSMarkersForSplitRegEx, RegexOptions.Compiled | RegexOptions.Multiline); // If it is barcode, print it using special OPOS PrintBarCode method. if (isBarcode) { oposPrinterMethod = "PrintBarCode"; await ExecuteOposMethodAsync( context, oposPrinterMethod, 2 /* PTR_S_RECEIPT */, toPrint, 110 /* PTR_BCS_Code128 */, 80, 80, -2 /* PTR_BC_CENTER */, -13 /* PTR_BC_TEXT_BELOW */).ConfigureAwait(false); resultCode = (int)await GetOposPropertyValueAsync(context, "ResultCode").ConfigureAwait(false); resultCodeExtended = (int)await GetOposPropertyValueAsync(context, "ResultCodeExtended").ConfigureAwait(false); } else { // Print normal text using OPOS PrintNormal method. oposPrinterMethod = "PrintNormal"; await this.ExecuteOposMethodAsync(context, oposPrinterMethod, 2 /* PTR_S_RECEIPT */, toPrint).ConfigureAwait(false); resultCode = (int)await GetOposPropertyValueAsync(context, "ResultCode").ConfigureAwait(false); resultCodeExtended = (int)await GetOposPropertyValueAsync(context, "ResultCodeExtended").ConfigureAwait(false); await SetOposPropertyValueAsync(context, "BinaryConversion", 0).ConfigureAwait(false); // OposBcNone } CheckResultCode(oposPrinterMethod, resultCode, resultCodeExtended); } } /// <summary> /// Print the data on printer. /// </summary> /// <param name="header">The header.</param> /// <param name="lines">The lines.</param> /// <param name="footer">The footer.</param> private async Task PrintAsync(RequestContext context, string header, string lines, string footer) { header = header.Replace(EscMarker, EscCharacter); lines = lines.Replace(EscMarker, EscCharacter); footer = footer.Replace(EscMarker, EscCharacter); var getReceiptPartsRequest = new GetPrinterReceiptPartsRequest(peripheralName, characterSet, header, lines, footer); var receiptPartsResponse = await context.Runtime.ExecuteAsync<GetPrinterReceiptPartsResponse>(getReceiptPartsRequest, context: null).ConfigureAwait(false); await PrintReceiptParts(context, receiptPartsResponse.ReceiptHeaderParts).ConfigureAwait(false); await PrintReceiptParts(context, receiptPartsResponse.ReceiptLinesParts).ConfigureAwait(false); await PrintReceiptParts(context, receiptPartsResponse.ReceiptFooterParts).ConfigureAwait(false); // Avoid paper cut when noting is printed. if (!string.IsNullOrEmpty(header + lines + footer) && await ShouldCutPaperAsync(context).ConfigureAwait(false)) { // The number of lines that must be advanced before the receipt paper is cut. string extraLinesToBeCut = string.Empty; var linesToPaperCut = (int)await GetOposPropertyValueAsync(context, "RecLinesToPaperCut").ConfigureAwait(false); for (int i = 0; i < linesToPaperCut; ++i) { extraLinesToBeCut += Environment.NewLine; } // Includes the new lines before cutting the paper. await this.PrintTextAsync(context, extraLinesToBeCut).ConfigureAwait(false); // CutPaper() will be blocked if printer is run out of paper, so it's important to check paper status beforehand. await CheckPaperStatusAsync(context).ConfigureAwait(false); // PERCENTAGE VALUE: // 0 No cut // 100 Full cut // 1 - 99 Partial cut (will always leave small amount of paper uncut irrespective of actual value) await ExecuteOposMethodAsync(context, "CutPaper", 95).ConfigureAwait(false); } } /// <summary> /// Print the receipt parts. /// </summary> /// <param name="context">The request context.</param> /// <param name="partsToPrint">The receipt parts to print.</param> private async Task PrintReceiptParts(RequestContext context, IReadOnlyCollection<ReceiptPart> partsToPrint) { foreach (var part in partsToPrint) { switch (part.Type) { case ReceiptPartType.LegacyLogo: case ReceiptPartType.LogoWithBytes: case ReceiptPartType.Image: var imageText = part.Value; var data = Convert.FromBase64String(imageText.Substring(ImageTagStart.Length, imageText.Length - ImageTagStart.Length - ImageTagEnd.Length)); await this.PrintImageAsync(context, data).ConfigureAwait(false); break; case ReceiptPartType.Text: await this.PrintTextAsync(context, part.Value).ConfigureAwait(false); break; default: break; } } } /// <summary> /// Method to print the raw bytes of a BMP-formatted image. /// </summary> /// <param name="context">The OPOS printer.</param> /// <param name="image">Image bytes to print.</param> private async Task PrintImageAsync(RequestContext context, byte[] image) { // Check if printer run out of paper after previous print call. await this.CheckPaperStatusAsync(context).ConfigureAwait(false); if ((bool)await GetOposPropertyValueAsync(context, "CapRecBitmap").ConfigureAwait(false)) { if (image != null && image.Length > 0) { int conversion = (int)await GetOposPropertyValueAsync(context, "BinaryConversion").ConfigureAwait(false); // Save current conversion mode await SetOposPropertyValueAsync(context, "BinaryConversion", 2).ConfigureAwait(false); // OposBcDecimal int resultCode; try { string imageFilePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "logo.bmp"); System.IO.File.WriteAllBytes(imageFilePath, image); await ExecuteOposMethodAsync(context, "PrintBitmap", 2 /* PTR_S_RECEIPT */, imageFilePath, -11 /* PTR_BM_ASIS */, -2 /* PTR_BC_CENTER */).ConfigureAwait(false); resultCode = (int)await GetOposPropertyValueAsync(context, "ResultCode").ConfigureAwait(false); } catch (Exception ex) { RetailLogger.Log.LogError(Events.PrintBitmapException, "PrintBitmap() failed due to following exception: {ex}", ex.ToString().AsSystemMetadata()); } await SetOposPropertyValueAsync(context, "BinaryConversion", conversion).ConfigureAwait(false); // restore previous conversion mode resultCode = (int)await GetOposPropertyValueAsync(context, "ResultCode").ConfigureAwait(false); int resultCodeExtended = (int)await GetOposPropertyValueAsync(context, "ResultCodeExtended").ConfigureAwait(false); CheckResultCode("PrintBitmap", resultCode, resultCodeExtended); } else { RetailLogger.Log.LogWarning(Events.InvalidImage, "Logo image is invalid or null."); } } else { RetailLogger.Log.LogWarning(Events.PrintBitmapNotSupported, "The printer '{printerName}' can't print bitmaps.", peripheralName.AsObjectMetadata()); } } /// <summary> /// Check the OPOS printer result code. /// </summary> /// <param name="oposMethod">The OPOS method called.</param> /// <param name="resultCode">The result code from OPOS method.</param> /// <param name="resultCodeExtended">The extended result code from OPOS method.</param> private static void CheckResultCode(string oposMethod, int resultCode, int resultCodeExtended) { if (string.IsNullOrEmpty(oposMethod)) { throw new ArgumentException(string.Format("'Argument '{0}' can't be null or empty", nameof(oposMethod))); } if (resultCode != 0) { string message = string.Format( "OPOS printer failed to execute '{0}' with error '{1}', extended error code - {2}", oposMethod, resultCode, resultCodeExtended); throw new PeripheralException(PeripheralException.PrinterError, message); } } /// <summary> /// Check the OPOS printer paper status. /// </summary> /// <param name="context">The OPOS printer.</param> private async Task CheckPaperStatusAsync(RequestContext context) { var emptySensor = (bool)await GetOposPropertyValueAsync(context, "CapRecEmptySensor").ConfigureAwait(false); var recEmpty = (bool)await GetOposPropertyValueAsync(context, "RecEmpty").ConfigureAwait(false); if (emptySensor && recEmpty) { RetailLogger.Log.HardwareStationPrinterOutOfPaper(peripheralName, PeripheralType.Opos); throw new PeripheralException(PeripheralException.PrinterOutOfPaperError); } } /// <summary> /// Determines if the printer should cut the receipt paper based on the hardware station configuration and if it is supported on the OPOS printer. /// </summary> /// <param name="context">The OPOS printer.</param> /// <returns>True if the receipt paper should be cut. False otherwise.</returns> private async Task<bool> ShouldCutPaperAsync(RequestContext context) { try { return (bool)await GetOposPropertyValueAsync(context, "CapRecPapercut").ConfigureAwait(false);; } catch (Exception ex) { // If there is an exception thrown when checking the RecPapercut property log an error and return false to skip paper cutting. RetailLogger.Log.LogError(Events.CapRecPapercutException, "context.CapRecPapercut failed due to following exception: {ex}", ex.AsSystemMetadata()); return false; } } /// <summary> /// Executes a method on the given OPOS device. /// </summary> /// <param name="context">The request context.</param> /// <param name="methodName">The name of the method to execute.</param> /// <param name="args">The list of arguments to send.</param> /// <returns></returns> private async Task ExecuteOposMethodAsync(RequestContext context, string methodName, params object[] args) { var request = new ExecuteOposDeviceMethodRequest(OposDeviceType.Printer, peripheralName, methodName, args); await context.Runtime.ExecuteAsync<Response>(request, context: context).ConfigureAwait(false); } /// <summary> /// Gets the value of a property from the given OPOS device. /// </summary> /// <param name="context">The request context.</param> /// <param name="propertyName">The name of the property.</param> /// <returns></returns> private async Task<object> GetOposPropertyValueAsync(RequestContext context, string propertyName) { var request = new GetOposDevicePropertyValueRequest(OposDeviceType.Printer, peripheralName, propertyName); GetOposDevicePropertyValueResponse response = await context.Runtime.ExecuteAsync<GetOposDevicePropertyValueResponse>(request, context: context).ConfigureAwait(false); return response.PropertyValue; } /// <summary> /// Sets the value of a property on the given OPOS device. /// </summary> /// <param name="context">The request context.</param> /// <param name="propertyName">The name of the property.</param> /// <param name="value">The value to set on the property.</param> /// <returns></returns> private async Task SetOposPropertyValueAsync(RequestContext context, string propertyName, object value) { var request = new SetOposDevicePropertyValueRequest(OposDeviceType.Printer, peripheralName, propertyName, value); await context.Runtime.ExecuteAsync<Response>(request, context: context).ConfigureAwait(false); } } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PeripheralCustomizations
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PeripheralCustomizations/SignatureCapture/CustomSignatureCaptureDevice.cs
using Microsoft.Dynamics.Commerce.HardwareStation; using Microsoft.Dynamics.Commerce.HardwareStation.Peripherals; using Microsoft.Dynamics.Commerce.Runtime.Handlers; using Microsoft.Dynamics.Commerce.Runtime.Messages; using System; using System.Collections.Generic; using System.Drawing; using System.Text; using System.Threading.Tasks; namespace Contoso.HardwareStation.Peripherals.DeviceCustomizations { /// <summary> /// A custom OPOS signature capture device handler. /// </summary> public sealed class CustomSignatureCaptureDevice : INamedRequestHandlerAsync { /// <summary> /// Gets the unique name for this request handler. /// </summary> public string HandlerName { get { return PeripheralType.Opos; } } /// <summary> /// Gets the collection of supported request types by this handler. /// </summary> public IEnumerable<Type> SupportedRequestTypes { get { return new[] { typeof(GetParsedSignatureCaptureResultRequest), }; } } /// <summary> /// Represents the entry point for the signature capture device request handler. /// </summary> /// <param name="request">The incoming request message.</param> /// <returns>The outgoing response message.</returns> public Task<Response> Execute(Request request) { ThrowIf.Null(request, nameof(request)); switch (request) { case GetParsedSignatureCaptureResultRequest parseSignatureCaptureResultRequest: return Task.FromResult<Response>(new GetParsedSignatureCaptureResultResponse(ParseResults(parseSignatureCaptureResultRequest))); default: throw new NotSupportedException(string.Format("Request '{0}' is not supported.", request.GetType())); } } /// <summary> /// Parses the result of the signature capture device. /// </summary> /// <param name="request">The parse signature capture result request.</param> /// <returns>The parsed signature capture results.</returns> private SignatureCaptureResults ParseResults(GetParsedSignatureCaptureResultRequest request) { return ParsePointArray(request.PointArray); } /// <summary> /// Convert point array string into array of points. /// </summary> /// <param name="pointArray">Point array string.</param> /// <returns>Returns ISignatureCaptureInfo.</returns> public SignatureCaptureResults ParsePointArray(string pointArray) { SignatureCaptureResults signatureCaptureInfo = new SignatureCaptureResults(); if (!string.IsNullOrWhiteSpace(pointArray)) { Point point; int step = 4; // process 4 characters each step List<Point> points = new List<Point>(pointArray.Length / step); // Each point is represented by four characters: x(low 8 bits), x(high 8 bits), y(low 8 bits), y(high 8 bits) for (int i = 0; i + step <= pointArray.Length; i += step) { point = GetPoint(pointArray[i], pointArray[i + 1], pointArray[i + 2], pointArray[i + 3]); points.Add(point); } signatureCaptureInfo.Signature = ToByteArrayString(points); } return signatureCaptureInfo; } /// <summary> /// Gets a point object from the next four character points received from the signature capture device. /// </summary> /// <param name="lowXchar">A character representing the lower bits from the X axis.</param> /// <param name="highXchar">A character representing the higher bits from the X axis.</param> /// <param name="lowYchar">A character representing the lower bits from the Y axis.</param> /// <param name="highYchar">A character representing the higher bits from the Y axis.</param> /// <returns>A point object containing X and Y coordinates.</returns> private static Point GetPoint(char lowXchar, char highXchar, char lowYchar, char highYchar) { int x = EncodeANSI(highXchar) << 8 | EncodeANSI(lowXchar); int y = EncodeANSI(highYchar) << 8 | EncodeANSI(lowYchar); if (x == 0xffff && y == 0xffff) { // End point x = -1; y = -1; } return new Point(x, y); } /// <summary> /// Convert collection of points into byte array base 64 string. /// </summary> /// <param name="points">Collection of points.</param> /// <returns>Encoded string.</returns> public static string ToByteArrayString(ICollection<Point> points) { if (points == null || points.Count < 1) { return null; } return Convert.ToBase64String(ToByteArray(points)); } /// <summary> /// Convert collection of points into byte array. /// </summary> /// <param name="points">Collection of points.</param> /// <returns>Byte array.</returns> public static byte[] ToByteArray(ICollection<Point> points) { if (points == null || points.Count < 1) { return null; } // Size of int times number of values. Two values per point. List<byte> bytes = new List<byte>(points.Count * sizeof(int) * 2); foreach (Point point in points) { bytes.AddRange(BitConverter.GetBytes(point.X)); bytes.AddRange(BitConverter.GetBytes(point.Y)); } return bytes.ToArray(); } /// <summary> /// Encodes the given charater in ANSI encoding. /// </summary> /// <param name="value">The chracter being encoded.</param> /// <returns>A numeric representation of the character in ANSI encoding.</returns> private static int EncodeANSI(char value) { int int32 = Convert.ToInt32(value); if (int32 < 128) { return int32; } Encoding encoding = Encoding.Default; char[] chars = new char[1] { value }; byte[] bytes1 = new byte[chars.Length * 2]; int bytes2 = encoding.GetBytes(chars, 0, chars.Length, bytes1, 0); int int16; if (encoding.IsSingleByte || bytes2 == 1) { int16 = bytes1[0]; } else { if (BitConverter.IsLittleEndian) { byte num = bytes1[0]; bytes1[0] = bytes1[1]; bytes1[1] = num; } int16 = BitConverter.ToInt16(bytes1, 0); } return int16; } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/StoreCommerce.Installer/Contoso.HardwareStationSamples.StoreCommerce.Installer.csproj
<Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\CustomizationPackage.props" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net472</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.Installers.StoreCommerce" Version="$(CommerceSdkPackagesVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\CommerceRuntime\Contoso.HardwareStationSamples.CommerceRuntime.csproj"> <ReferenceOutputAssembly>false</ReferenceOutputAssembly> </ProjectReference> <ProjectReference Include="..\PeripheralCustomizations\Contoso.PeripheralCustomizations.csproj"> <ReferenceOutputAssembly>false</ReferenceOutputAssembly> </ProjectReference> </ItemGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/CommerceRuntime/DefinePosExtensionPackageTrigger.cs
namespace TriggerSamples.CommerceRuntime { using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Dynamics.Commerce.Runtime; using Microsoft.Dynamics.Commerce.Runtime.DataModel; using Microsoft.Dynamics.Commerce.Runtime.Messages; /// <summary> /// Class that implements a post trigger for the GetExtensionPackageDefinitionsRequest request type. /// </summary> public class DefinePosExtensionPackageTrigger : IRequestTriggerAsync { /// <summary> /// Gets the supported requests for this trigger. /// </summary> public IEnumerable<Type> SupportedRequestTypes { get { return new[] { typeof(GetExtensionPackageDefinitionsRequest) }; } } /// <summary> /// Post trigger to retrieve extension package. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> public Task OnExecuted(Request request, Response response) { ThrowIf.Null(request, "request"); ThrowIf.Null(response, "response"); var getExtensionsResponse = (GetExtensionPackageDefinitionsResponse)response; var extensionPackageDefinition = new ExtensionPackageDefinition(); // Should match the PackageName used when packaging the customization package (i.e. in CustomizationPackage.props). extensionPackageDefinition.Name = "Contoso.Commerce.PaymentDevice"; extensionPackageDefinition.Publisher = "Contoso"; extensionPackageDefinition.IsEnabled = true; getExtensionsResponse.ExtensionPackageDefinitions.Add(extensionPackageDefinition); return Task.CompletedTask; } /// <summary> /// Pre trigger code. /// </summary> /// <param name="request">The request.</param> public Task OnExecuting(Request request) { return Task.CompletedTask; } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/CommerceRuntime/Contoso.HardwareStationSamples.CommerceRuntime.csproj
<Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\CustomizationPackage.props" /> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.Runtime" Version="$(CommerceSdkPackagesVersion)" /> </ItemGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/HardwareStation.Installer/Contoso.HardwareStationSamples.Installer.csproj
<Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\CustomizationPackage.props" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net472</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.Installers.HardwareStation" Version="$(CommerceSdkPackagesVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\PaymentDevice\Contoso.PaymentDeviceSample.csproj"> <ReferenceOutputAssembly>false</ReferenceOutputAssembly> </ProjectReference> <ProjectReference Include="..\PeripheralCustomizations\Contoso.PeripheralCustomizations.csproj" /> </ItemGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/HardwareStation.Installer/TestExtensionInstallerPostInstallStep.cs
namespace Contoso.HardwareStation.Installer { using System.Threading.Tasks; using Microsoft.Dynamics.Commerce.Sdk.Installers; using Microsoft.Dynamics.Retail.Diagnostics; [ExtensionInstallerStepExecutionPosition(ExtensionInstallerStepExecutionPhase.PostInstall, 1)] public class TestExtensionInstallerPostInstallStep : IExtensionInstallerStep { private enum Events { ExecutingPostInstallStep, ConfigurationValueFound } public string Name { get; } = "TestExtensionInstallerPostInstallStep"; public string DisplayName { get; } = "TestExtensionInstallerPostInstallStep"; public string Description { get; } = "A sample extension installer step that is executed after the standard installation steps."; public Task Run(IExtensionInstallerStepContext context) { RetailLogger.Log.LogInformation(Events.ExecutingPostInstallStep, "************** Executing extension installer extension PostInstall step **************"); context.PowerShellService.Run("echo 'About to print the value received from the PreInstallStep'"); RetailLogger.Log.LogInformation(Events.ConfigurationValueFound, $"Found configuration value: {context.GetConfigurationValue(ConfigurationKeys.SampleKey)}"); return Task.CompletedTask; } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/HardwareStation.Installer/ConfigurationKeys.cs
namespace Contoso.HardwareStation.Installer { /// <summary> /// Class containing sample configuration key name constant values. /// </summary> internal static class ConfigurationKeys { /// <summary> /// The key name for a sample key, /// </summary> public const string SampleKey = "SampleKey"; } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/HardwareStation.Installer/TestExtensionInstallerPreInstallStep.cs
namespace Contoso.HardwareStation.Installer { using System.Threading.Tasks; using Microsoft.Dynamics.Commerce.Sdk.Installers; using Microsoft.Dynamics.Retail.Diagnostics; [ExtensionInstallerStepExecutionPosition(ExtensionInstallerStepExecutionPhase.PreInstall, 1)] public class TestExtensionInstallerPreInstallStep : IExtensionInstallerStep { private enum Events { ExecutingPreInstallStep } public string Name { get; } = "TestExtensionInstallerPreInstallStep"; public string DisplayName { get; } = "TestExtensionInstallerPreInstallStep"; public string Description { get; } = "A sample extension installer step that is executed before the standard installation steps."; public Task Run(IExtensionInstallerStepContext context) { RetailLogger.Log.LogInformation(Events.ExecutingPreInstallStep, "************** Executing extension installer extension PreInstall step **************"); context.SetConfigurationValue(ConfigurationKeys.SampleKey, "SampleValueSetDuringPre-Install"); return Task.CompletedTask; } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/HardwareStation.Installer
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/HardwareStation.Installer/Properties/launchSettings.json
{ "profiles": { "Contoso.HardwareStation.Installer": { "commandName": "Project", "commandLineArgs": "install" } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PaymentDevice/README.md
# HardwareStation Payment Device Sample This sample shows how to add support for a new Payment Device through the implementation of a handler that will accept the messages received by the Hardware Station server. ## How the Sample works This sample intentionally implements a no-op Payment device handler as a way to demonstrate the capabilities that it provides and also the information that it requires to work with the Hardware Station infrastructure. The implemented Request Handler includes the following list of Supported Requests: - Device management: Lock/Release, Open/Close, Begin/End Transaction, Cancel Operation and Update Line Items These requests are responsible for managing the connection and state of the device - Payment operations: Authorize, Capture, Void and Refund payment - Gift operations: Get Gift Card Balance, Add Balance to Gift Card, Activate Gift Card Should be implemented in the case that the Payment Device supports Gift Cards. - Duplicated Payment Protection: Get Transaction Reference, Get Transaction by Transaction Reference Requests used to match the curent active transaction reference and prevent duplicated payments from happening. - Misc operations: Get Private Tender, Execute Task, Fetch Token In the case of unsupported operations by the Payment Device, the request must still be supported, but an error should be thrown. A real implementation should replace all mock and hard-coded information with properties retrieved from the actual device.
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PaymentDevice/Contoso.PaymentDeviceSample.csproj
<Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\CustomizationPackage.props" /> <PropertyGroup> <RootNamespace>Contoso.HardwareStation.Peripherals.PaymentDevice</RootNamespace> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.HardwareAndPeripherals" Version="$(CommerceSdkPackagesVersion)" /> </ItemGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PaymentDevice/PaymentDeviceSample.cs
/* SAMPLE CODE NOTICE THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. */ /* IMPORTANT!!! THIS IS SAMPLE CODE ONLY. THE CODE SHOULD BE UPDATED TO WORK WITH THE APPROPRIATE PAYMENT PROVIDERS. PROPER MEASURES SHOULD BE TAKEN TO ENSURE THAT THE PA-DSS AND PCI DSS REQUIREMENTS ARE MET. */ namespace Contoso.Commerce.HardwareStation.PaymentSample { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.Dynamics.Commerce.HardwareStation; using Microsoft.Dynamics.Commerce.HardwareStation.CardPayment; using Microsoft.Dynamics.Commerce.HardwareStation.PeripheralRequests; using Microsoft.Dynamics.Commerce.HardwareStation.Peripherals; using Microsoft.Dynamics.Commerce.HardwareStation.Peripherals.Entities; using PaySdk = Microsoft.Dynamics.Retail.PaymentSDK.Portable; using Microsoft.Dynamics.Commerce.Runtime.Handlers; using Microsoft.Dynamics.Commerce.Runtime.Messages; using Microsoft.Dynamics.Commerce.Runtime.DataModel; /// <summary> /// A sample class that handles all messages that a Payment Device is responsible for. /// </summary> /// <remarks> /// This class intentionally implements a no-op Payment device handler as a way to demonstrate the capabilities that this handler provides /// and also the information that it requires to work with the hardware station infrastructure. /// The functionalities supported by this handler are the following: /// - Device management: /// LockPaymentTerminalDeviceRequest, ReleasePaymentTerminalDeviceRequest, OpenPaymentTerminalDeviceRequest, /// ClosePaymentTerminalDeviceRequest, BeginTransactionPaymentTerminalDeviceRequest, EndTransactionPaymentTerminalDeviceRequest, /// CancelOperationPaymentTerminalDeviceRequestCancel Operation and UpdateLineItemsPaymentTerminalDeviceRequest /// - Payment operations: /// AuthorizePaymentTerminalDeviceRequest, CapturePaymentTerminalDeviceRequest, VoidPaymentTerminalDeviceRequest, RefundPaymentTerminalDeviceRequest /// - Gift operations: /// GetGiftCardBalancePaymentTerminalRequest, AddBalanceToGiftCardPaymentTerminalRequest, ActivateGiftCardPaymentTerminalRequest /// - Duplicated Payment Protection: /// GetTransactionReferencePaymentTerminalDeviceRequest, GetTransactionByTransactionReferencePaymentTerminalDeviceRequest /// - Misc operations: /// GetPrivateTenderPaymentTerminalDeviceRequest, ExecuteTaskPaymentTerminalDeviceRequest, FetchTokenPaymentTerminalDeviceRequest /// In the case of unsupported operations by the Payment Device, the request must still be supported, but an exception should be thrown. /// A real implementation should replace all mock and hard-coded information with properties retrieved from the actual device. /// </remarks> #pragma warning disable CS0618 // Type or member is obsolete. JUSTIFICATION: TODO: transform to asynchronous handler public class PaymentDeviceSample : INamedRequestHandler, IDisposable #pragma warning restore CS0618 // Type or member is obsolete { private PaySdk.PaymentProperty[] merchantProperties; private string paymentConnectorName; private SettingsInfo terminalSettings; private CancellationTokenSource timeoutTask; /// <summary> /// Gets the collection of supported request types by this handler. /// </summary> public IEnumerable<Type> SupportedRequestTypes { get { return new[] { typeof(LockPaymentTerminalDeviceRequest), typeof(ReleasePaymentTerminalDeviceRequest), typeof(OpenPaymentTerminalDeviceRequest), typeof(ClosePaymentTerminalDeviceRequest), typeof(BeginTransactionPaymentTerminalDeviceRequest), typeof(EndTransactionPaymentTerminalDeviceRequest), typeof(CancelOperationPaymentTerminalDeviceRequest), typeof(UpdateLineItemsPaymentTerminalDeviceRequest), typeof(AuthorizePaymentTerminalDeviceRequest), typeof(CapturePaymentTerminalDeviceRequest), typeof(VoidPaymentTerminalDeviceRequest), typeof(RefundPaymentTerminalDeviceRequest), typeof(GetPrivateTenderPaymentTerminalDeviceRequest), typeof(ExecuteTaskPaymentTerminalDeviceRequest), typeof(FetchTokenPaymentTerminalDeviceRequest), typeof(ActivateGiftCardPaymentTerminalRequest), typeof(AddBalanceToGiftCardPaymentTerminalRequest), typeof(GetGiftCardBalancePaymentTerminalRequest), typeof(GetTransactionReferencePaymentTerminalDeviceRequest), typeof(GetTransactionByTransactionReferencePaymentTerminalDeviceRequest) }; } } /// <summary> /// Gets the unique name for this request handler. /// </summary> public string HandlerName => "SAMPLEDEVICE"; /// <summary> /// Represents the entry point of the request handler. /// </summary> /// <param name="request">The incoming request message.</param> /// <returns>The outgoing response message.</returns> public Response Execute(Request request) { ThrowIf.Null(request, nameof(request)); switch (request) { case OpenPaymentTerminalDeviceRequest openPaymentTerminalDeviceRequest: return this.Open(openPaymentTerminalDeviceRequest); case ClosePaymentTerminalDeviceRequest closePaymentTerminalDeviceRequest: return this.Close(); case BeginTransactionPaymentTerminalDeviceRequest beginTransactionPaymentTerminalDeviceRequest: return this.BeginTransaction(beginTransactionPaymentTerminalDeviceRequest); case EndTransactionPaymentTerminalDeviceRequest endTransactionPaymentTerminalDeviceRequest: return this.EndTransaction(); case CancelOperationPaymentTerminalDeviceRequest cancelOperationPaymentTerminalDeviceRequest: return this.CancelOperation(); case UpdateLineItemsPaymentTerminalDeviceRequest updateLineItemsPaymentTerminalDeviceRequest: return this.UpdateLineItems(updateLineItemsPaymentTerminalDeviceRequest); case AuthorizePaymentTerminalDeviceRequest authorizePaymentTerminalDeviceRequest: return this.AuthorizePayment(authorizePaymentTerminalDeviceRequest); case CapturePaymentTerminalDeviceRequest capturePaymentTerminalDeviceRequest: return this.CapturePayment(capturePaymentTerminalDeviceRequest); case VoidPaymentTerminalDeviceRequest voidPaymentTerminalDeviceRequest: return this.VoidPayment(voidPaymentTerminalDeviceRequest); case RefundPaymentTerminalDeviceRequest refundPaymentTerminalDeviceRequest: return this.RefundPayment(refundPaymentTerminalDeviceRequest); case GetPrivateTenderPaymentTerminalDeviceRequest getPrivateTenderPaymentTerminalDeviceRequest: return this.GetPrivateTender(getPrivateTenderPaymentTerminalDeviceRequest); case ExecuteTaskPaymentTerminalDeviceRequest executeTaskPaymentTerminalDeviceRequest: return this.ExecuteTask(executeTaskPaymentTerminalDeviceRequest); case FetchTokenPaymentTerminalDeviceRequest fetchTokenPaymentTerminalDeviceRequest: return this.FetchToken(fetchTokenPaymentTerminalDeviceRequest); case ActivateGiftCardPaymentTerminalRequest activateGiftCardPaymentTerminalRequest: return this.ActivateGiftCard(activateGiftCardPaymentTerminalRequest); case AddBalanceToGiftCardPaymentTerminalRequest addBalanceToGiftCardPaymentTerminalRequest: return this.AddBalanceToGiftCard(addBalanceToGiftCardPaymentTerminalRequest); case GetGiftCardBalancePaymentTerminalRequest getGiftCardBalancePaymentTerminalRequest: return this.GetGiftCardBalance(getGiftCardBalancePaymentTerminalRequest); case GetTransactionReferencePaymentTerminalDeviceRequest getTransactionReferencePaymentTerminalDeviceRequest: return this.GetTransactionReferenceId(getTransactionReferencePaymentTerminalDeviceRequest); case GetTransactionByTransactionReferencePaymentTerminalDeviceRequest getTransactionByTransactionReferencePaymentTerminalDeviceRequest: return this.GetTransactionByTransactionReference(getTransactionByTransactionReferencePaymentTerminalDeviceRequest); default: throw new NotSupportedException($"Request '{request.GetType().FullName}' is not supported."); } } /// <summary> /// The dispose implementation. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose the Native and Managed resources. /// </summary> /// <param name="disposeAll">Whether to dispose both Native and Managed resources.</param> protected virtual void Dispose(bool disposeAll) { } /// <summary> /// Initialize settings. /// </summary> /// <param name="paymentConnectorName">The payment connector name.</param> /// <param name="merchantPaymentPropertiesXml">The merchant properties.</param> /// <param name="terminalSettings">The terminal settings.</param> private void InitializeSettings(string paymentConnectorName, string merchantPaymentPropertiesXml, SettingsInfo terminalSettings) { this.terminalSettings = terminalSettings; this.paymentConnectorName = paymentConnectorName; // Convert the connector properties to local this.merchantProperties = !string.IsNullOrWhiteSpace(merchantPaymentPropertiesXml) ? PaySdk.PaymentProperty.ConvertXMLToPropertyArray(merchantPaymentPropertiesXml) : null; } /// <summary> /// Resets the card payment info. /// </summary> private void ResetCardPaymentInfo() { this.merchantProperties = null; this.paymentConnectorName = null; this.terminalSettings = null; this.timeoutTask = null; } /// <summary> /// Gets an array of payment properties using an initial list. /// </summary> /// <param name="paymentConnectorName">The payment connector name to use.</param> /// <param name="initialPropertyList">The initial list of properties to add to the array.</param> /// <returns></returns> private static PaySdk.PaymentProperty[] GetPaymentPropertiesWithInitialList(string paymentConnectorName, PaySdk.PaymentProperty[] initialPropertyList) { // Several below values are hardcoded, real implementations should take this data from real device. List<PaySdk.PaymentProperty> properties = new List<PaySdk.PaymentProperty>(initialPropertyList); properties.AddRange(GetPaymentProperties(paymentConnectorName)); return properties.ToArray(); } /// <summary> /// Gets an array of payment properties. /// </summary> /// <param name="paymentConnectorName">The payment connector name to use.</param> /// <returns></returns> private static PaySdk.PaymentProperty[] GetPaymentProperties(string paymentConnectorName) { // Several below values are hardcoded, real implementations should take this data from real device. PaySdk.PaymentProperty assemblyNameProperty = new PaySdk.PaymentProperty(); assemblyNameProperty.Namespace = PaySdk.Constants.GenericNamespace.MerchantAccount; assemblyNameProperty.Name = PaySdk.Constants.MerchantAccountProperties.AssemblyName; assemblyNameProperty.ValueType = PaySdk.DataType.String; assemblyNameProperty.StoredStringValue = typeof(PaymentDeviceSample).Assembly.GetName().Name; PaySdk.PaymentProperty connectorNameProperty = new PaySdk.PaymentProperty(); connectorNameProperty.Namespace = PaySdk.Constants.GenericNamespace.Connector; connectorNameProperty.Name = PaySdk.Constants.ConnectorProperties.ConnectorName; connectorNameProperty.StoredStringValue = paymentConnectorName; PaySdk.PaymentProperty[] properties = new PaySdk.PaymentProperty[] { assemblyNameProperty, connectorNameProperty }; return properties; } /// <summary> /// Creates a mocked success authorization payment info with the approved amount. /// </summary> /// <param name="amount">The approved amount to add to the authorization.</param> /// <returns>The mocked payment info.</returns> private PaymentInfo CreateAuthorizationSuccessPaymentInfo(decimal amount) { // Several below values are hardcoded, real implementations should take this data from real device. PaySdk.PaymentProperty[] properties = GetPaymentProperties(this.paymentConnectorName); var paymentInfo = new PaymentInfo() { CardNumberMasked = "411111******1111", CardType = Microsoft.Dynamics.Commerce.HardwareStation.CardPayment.CardType.InternationalCreditCard, SignatureData = "AAgEAAQALP4hvpJrK/UfKvlX7ABkIfJFnxoZbaXC2vmnzYB8ItM1rBYwzRrw0IdLF3Qv89lwBfgGn5gBwKkFSoguAft6w8ZAJATwSYNMGJTlqmorxYYyN2BZvtGmroCuKygDAJoBkAyDAr46bUZ4kOFG7P9GmjcA", PaymentSdkData = PaySdk.PaymentProperty.ConvertPropertyArrayToXML(properties), CashbackAmount = 0.0m, ApprovedAmount = amount, IsApproved = true, Errors = null }; return paymentInfo; } /// <summary> /// Construct the Payment Device class and open the connection from it. /// </summary> /// <returns>The response.</returns> /// <param name="request">Open payment terminal device request.</param> private NullResponse Open(OpenPaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); // Open the device for payments Utilities.WaitAsyncTask(() => Task.Run(async () => { await this.OpenAsync(request.DeviceName, request.TerminalSettings, request.DeviceConfig).ConfigureAwait(false); })); return NullResponse.Instance; } /// <summary> /// Close the connection to the payment terminal. /// </summary> /// <returns>The response.</returns> private NullResponse Close() { // Close the device for payments Utilities.WaitAsyncTask(() => Task.Run(async () => { await this.CloseAsync().ConfigureAwait(false); })); return NullResponse.Instance; } /// <summary> /// Begins the transaction. /// </summary> /// <param name="request">The begin transaction request.</param> /// <returns>The response.</returns> private NullResponse BeginTransaction(BeginTransactionPaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); Utilities.WaitAsyncTask(() => Task.Run(async () => { await this.BeginTransactionAsync(request.PaymentConnectorName, request.MerchantInformation).ConfigureAwait(false); })); return NullResponse.Instance; } /// <summary> /// Ends the transaction. /// </summary> /// <returns>The response.</returns> private NullResponse EndTransaction() { Utilities.WaitAsyncTask(() => this.EndTransactionAsync()); if (this.timeoutTask != null) { this.timeoutTask.Cancel(); } this.ResetCardPaymentInfo(); return NullResponse.Instance; } /// <summary> /// Cancel current operation on payment terminal. /// </summary> /// <returns>The response.</returns> private NullResponse CancelOperation() { // Cancel current operation on payment terminal Utilities.WaitAsyncTask(() => Task.Run(async () => { await this.CancelOperationAsync().ConfigureAwait(false); })); return NullResponse.Instance; } /// <summary> /// Update the line items. /// </summary> /// <param name="request">The update line items request.</param> /// <returns>The response.</returns> private NullResponse UpdateLineItems(UpdateLineItemsPaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); Utilities.WaitAsyncTask(() => this.UpdateLineItemsAsync(request)); return NullResponse.Instance; } /// <summary> /// Authorize payment. /// </summary> /// <param name="request">The authorize payment request.</param> /// <returns>The authorize payment response.</returns> private AuthorizePaymentTerminalDeviceResponse AuthorizePayment(AuthorizePaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); PaymentInfo paymentInfo = Utilities.WaitAsyncTask(() => this.AuthorizePaymentAsync(request.PaymentConnectorName, request.Amount, request.Currency, request.TenderInfo, request.ExtensionTransactionProperties)); return new AuthorizePaymentTerminalDeviceResponse(paymentInfo); } /// <summary> /// Capture payment. /// </summary> /// <param name="request">The capture payment request.</param> /// <returns>The capture payment response.</returns> private CapturePaymentTerminalDeviceResponse CapturePayment(CapturePaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); PaymentInfo paymentInfo = Utilities.WaitAsyncTask(() => this.CapturePaymentAsync(request.Amount, request.Currency, request.PaymentPropertiesXml, request.ExtensionTransactionProperties)); return new CapturePaymentTerminalDeviceResponse(paymentInfo); } /// <summary> /// Void payment. /// </summary> /// <param name="request">The void payment request.</param> /// <returns>The void payment response.</returns> private VoidPaymentTerminalDeviceResponse VoidPayment(VoidPaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); PaymentInfo paymentInfo = Utilities.WaitAsyncTask(() => this.VoidPaymentAsync(request.PaymentConnectorName, request.Amount, request.Currency, request.TenderInfo, request.PaymentPropertiesXml, request.ExtensionTransactionProperties)); return new VoidPaymentTerminalDeviceResponse(paymentInfo); } /// <summary> /// Make refund payment. /// </summary> /// <param name="request">Request for refund.</param> /// <returns>A task that can await until the refund has completed.</returns> private RefundPaymentTerminalDeviceResponse RefundPayment(RefundPaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); PaymentInfo paymentInfo = Utilities.WaitAsyncTask(() => this.RefundPaymentAsync(request.Amount, request.Currency, request.IsManualEntry, request.ExtensionTransactionProperties)); return new RefundPaymentTerminalDeviceResponse(paymentInfo); } /// <summary> /// Executes Task. /// </summary> /// <param name="request">The request.</param> /// <returns>The response.</returns> private ExecuteTaskPaymentTerminalDeviceResponse ExecuteTask(ExecuteTaskPaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); List<CommerceProperty> commerceProperties = new List<CommerceProperty>(); ExtensionTransaction transaction; // Add/substitute 'case' matching your task and put there the business logic you need for your specific task. switch (request.Task) { case "Echo": // 1. Copying original properties into the response. commerceProperties.AddRange(request.ExtensionTransactionProperties.ExtensionProperties); // 2. Adding some new properties commerceProperties.AddRange(new CommerceProperty[] { new CommerceProperty("Key" + Guid.NewGuid(), "Value1"), new CommerceProperty("Key" + Guid.NewGuid(), "Value2") }); transaction = new ExtensionTransaction { EntityName = request.ExtensionTransactionProperties.EntityName, ExtensionProperties = commerceProperties }; break; default: throw new NotSupportedException($"The task{request.Task} is not supported"); } return new ExecuteTaskPaymentTerminalDeviceResponse(transaction); } /// <summary> /// Gets the private tender. /// </summary> /// <param name="request">The get private tender request.</param> /// <returns>Returns the private tender response.</returns> private GetPrivateTenderPaymentTerminalDeviceResponse GetPrivateTender(GetPrivateTenderPaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); TenderInfo tenderInfo = Utilities.WaitAsyncTask(() => this.GetPrivateTenderAsync(request.Amount, request.Declined, request.IsSwipe)); return new GetPrivateTenderPaymentTerminalDeviceResponse(tenderInfo); } /// <summary> /// Fetch token. /// </summary> /// <param name="request">The fetch token request.</param> /// <returns>The fetch token response.</returns> private FetchTokenPaymentTerminalDeviceResponse FetchToken(FetchTokenPaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); PaymentInfo paymentInfo = Utilities.WaitAsyncTask(() => this.FetchTokenAsync(request.IsManualEntry, request.ExtensionTransactionProperties)); return new FetchTokenPaymentTerminalDeviceResponse(paymentInfo); } /// <summary> /// Activate gift card. /// </summary> /// <param name="request">The activate gift card payment request.</param> /// <returns>The gift card payment response.</returns> private GiftCardPaymentResponse ActivateGiftCard(ActivateGiftCardPaymentTerminalRequest request) { ThrowIf.Null(request, nameof(request)); PaymentInfo paymentInfo = Utilities.WaitAsyncTask(() => this.ActivateGiftCardAsync(request.PaymentConnectorName, request.Amount, request.Currency, request.TenderInfo, request.ExtensionTransactionProperties)); return new GiftCardPaymentResponse(paymentInfo); } /// <summary> /// Add balance to gift card. /// </summary> /// <param name="request">The add balance to gift card payment request.</param> /// <returns>The add balance to gift card payment response.</returns> private GiftCardPaymentResponse AddBalanceToGiftCard(AddBalanceToGiftCardPaymentTerminalRequest request) { ThrowIf.Null(request, nameof(request)); PaymentInfo paymentInfo = Utilities.WaitAsyncTask(() => this.AddBalanceToGiftCardAsync(request.PaymentConnectorName, request.Amount, request.Currency, request.TenderInfo, request.ExtensionTransactionProperties)); return new GiftCardPaymentResponse(paymentInfo); } /// <summary> /// Get gift card balance. /// </summary> /// <param name="request">The get gift card balance payment request.</param> /// <returns>The get gift card balance payment response.</returns> private GiftCardPaymentResponse GetGiftCardBalance(GetGiftCardBalancePaymentTerminalRequest request) { ThrowIf.Null(request, nameof(request)); PaymentInfo paymentInfo = Utilities.WaitAsyncTask(() => this.GetGiftCardBalanceAsync(request.PaymentConnectorName, request.Currency, request.TenderInfo, request.ExtensionTransactionProperties)); return new GiftCardPaymentResponse(paymentInfo); } /// <summary> /// Gets Transaction Reference ID. /// </summary> /// <param name="request">The request.</param> /// <returns>The response.</returns> private GetTransactionReferencePaymentTerminalDeviceResponse GetTransactionReferenceId(GetTransactionReferencePaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); string id = $"{request.PosTerminalId}_{request.EftTerminalId}_{Guid.NewGuid()}"; return new GetTransactionReferencePaymentTerminalDeviceResponse(id); } /// <summary> /// Gets payment transaction by the Transaction Reference ID. /// </summary> /// <param name="request">The request.</param> /// <returns>The response.</returns> private GetTransactionByTransactionReferencePaymentTerminalDeviceResponse GetTransactionByTransactionReference(GetTransactionByTransactionReferencePaymentTerminalDeviceRequest request) { ThrowIf.Null(request, nameof(request)); return new GetTransactionByTransactionReferencePaymentTerminalDeviceResponse(CreateAuthorizationSuccessPaymentInfo(5)); } /// <summary> /// Construct the Payment Device class and open the connection from it. /// </summary> /// <param name="peripheralName">Name of peripheral device.</param> /// <param name="terminalSettings">The terminal settings for the peripheral device.</param> /// <param name="deviceConfig">Device Configuration parameters.</param> /// <returns>A task that can be awaited until the connection is opened.</returns> [SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Suppressed on adding CA for backward compatibility")] private async Task OpenAsync(string peripheralName, SettingsInfo terminalSettings, PeripheralConfiguration deviceConfig) { // Open the device for payments await Task.Delay(500).ConfigureAwait(false); } /// <summary> /// Close the connection to the payment terminal. /// </summary> /// <returns>A task that can be awaited until the connection is closed.</returns> private async Task CloseAsync() { // Close the device for payments await Task.Delay(500).ConfigureAwait(false); } /// <summary> /// Begins the transaction. /// </summary> /// <param name="paymentConnectorName">The payment connector name for payment.</param> /// <param name="merchantPaymentPropertiesXml">The merchant provider payment properties.</param> /// <returns>A task that can be awaited until the operation is completed.</returns> private async Task BeginTransactionAsync(string paymentConnectorName, string merchantPaymentPropertiesXml) { await Task.Run(() => this.InitializeSettings(paymentConnectorName, merchantPaymentPropertiesXml, this.terminalSettings)).ConfigureAwait(false); } /// <summary> /// Ends the transaction. /// </summary> /// <returns>A task that can be awaited until the operation has completed.</returns> private async Task EndTransactionAsync() { // Close the device for payments await Task.Delay(500).ConfigureAwait(false); } /// <summary> /// Cancel current operation on payment terminal. /// </summary> /// <returns>A task that can be awaited until the cancel operation has completed.</returns> private async Task CancelOperationAsync() { // Cancel current operation on the payment device await Task.Delay(500).ConfigureAwait(false); } /// <summary> /// Update the line items on the current open session. This method will compare against previous lines specified and make the appropriate device calls. /// </summary> /// <param name="request">The update line items request.</param> /// <returns>A task that can be awaited until the text is displayed on the screen.</returns> [SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Suppressed on adding CA for backward compatibility")] private async Task UpdateLineItemsAsync(UpdateLineItemsPaymentTerminalDeviceRequest request) { // Display item to the payment terminal await Task.Delay(500).ConfigureAwait(false); } /// <summary> /// Authorize payment. /// </summary> /// <param name="paymentConnectorName">The payment connector name.</param> /// <param name="amount">The amount.</param> /// <param name="currency">The currency.</param> /// <param name="tenderInfo">Tender information.</param> /// <param name="extensionTransactionProperties">Optional extension transaction properties.</param> /// <returns>A task that can await until the authorization has completed.</returns> [SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Suppressed on adding CA for backward compatibility")] private async Task<PaymentInfo> AuthorizePaymentAsync(string paymentConnectorName, decimal amount, string currency, TenderInfo tenderInfo, ExtensionTransaction extensionTransactionProperties) { // Several below values are hardcoded, real implementations should take this data from real device. var paymentInfo = CreateAuthorizationSuccessPaymentInfo(amount); return await Task.FromResult(paymentInfo).ConfigureAwait(false); } /// <summary> /// Make settlement of a payment. /// </summary> /// <param name="amount">The amount.</param> /// <param name="currency">The currency.</param> /// <param name="paymentPropertiesXml">The payment properties of the authorization response.</param> /// <param name="extensionTransactionProperties">Optional extension transaction properties.</param> /// <returns>A task that can await until the settlement has completed.</returns> [SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Suppressed on adding CA for backward compatibility")] private async Task<PaymentInfo> CapturePaymentAsync(decimal amount, string currency, string paymentPropertiesXml, ExtensionTransaction extensionTransactionProperties) { ThrowIf.Null(this.merchantProperties, nameof(this.merchantProperties)); PaySdk.PaymentProperty[] properties = GetPaymentPropertiesWithInitialList(this.paymentConnectorName, this.merchantProperties); // Several below values are hardcoded, real implementations should take this data from real device. return await Task.FromResult(new PaymentInfo() { CardNumberMasked = string.Empty, CardType = Microsoft.Dynamics.Commerce.HardwareStation.CardPayment.CardType.Unknown, SignatureData = string.Empty, PaymentSdkData = PaySdk.PaymentProperty.ConvertPropertyArrayToXML(properties), CashbackAmount = 0.0m, ApprovedAmount = amount, IsApproved = true, Errors = null }).ConfigureAwait(false); } /// <summary> /// Make reversal/void a payment. /// </summary> /// <param name="paymentConnectorName">The payment connector name.</param> /// <param name="amount">The amount.</param> /// <param name="currency">The currency.</param> /// <param name="tenderInfo">The tender information.</param> /// <param name="paymentPropertiesXml">The payment properties of the authorization response.</param> /// <param name="extensionTransactionProperties">Optional extension transaction properties.</param> /// <returns>A task that can await until the void has completed.</returns> [SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Suppressed on adding CA for backward compatibility")] private async Task<PaymentInfo> VoidPaymentAsync(string paymentConnectorName, decimal amount, string currency, TenderInfo tenderInfo, string paymentPropertiesXml, ExtensionTransaction extensionTransactionProperties) { ThrowIf.Null(this.merchantProperties, nameof(this.merchantProperties)); PaySdk.PaymentProperty[] properties = GetPaymentPropertiesWithInitialList(paymentConnectorName, this.merchantProperties); // Several below values are hardcoded, real implementations should take this data from real device. return await Task.FromResult(new PaymentInfo() { CardNumberMasked = string.Empty, CardType = Microsoft.Dynamics.Commerce.HardwareStation.CardPayment.CardType.Unknown, SignatureData = string.Empty, PaymentSdkData = PaySdk.PaymentProperty.ConvertPropertyArrayToXML(properties), CashbackAmount = 0.0m, ApprovedAmount = amount, IsApproved = false, Errors = null }).ConfigureAwait(false); } /// <summary> /// Make refund payment. /// </summary> /// <param name="amount">The amount.</param> /// <param name="currency">The currency.</param> /// <param name="isManualEntry">If manual credit card entry is required.</param> /// <param name="extensionTransactionProperties">Optional extension transaction properties.</param> /// <returns>A task that can await until the refund has completed.</returns> [SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Suppressed on adding CA for backward compatibility")] private async Task<PaymentInfo> RefundPaymentAsync(decimal amount, string currency, bool isManualEntry, ExtensionTransaction extensionTransactionProperties) { return await Task.FromResult(CreateAuthorizationSuccessPaymentInfo(amount)).ConfigureAwait(false); } /// <summary> /// Get private tender async. /// </summary> /// <param name="amount">The amount field.</param> /// <param name="declined">Specify the boolean flag whether previous card is declined.</param> /// <param name="isSwipe">Specify the boolean flag whether it is swipe / manual.</param> /// <returns>Returns the tender information.</returns> [SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Suppressed on adding CA for backward compatibility")] private async Task<TenderInfo> GetPrivateTenderAsync(decimal amount, bool declined, bool isSwipe) { // Several below values are hardcoded, real implementations should take this data from real device. return await Task.FromResult(new TenderInfo() { CardNumber = "9123456", Track2 = "%B9123456^FDCSGift/Gift^10110001111A123456789012?;9123456=1011000001234567?", CardTypeId = (int)Microsoft.Dynamics.Commerce.HardwareStation.CardPayment.CardType.GiftCard, IsSwipe = false }).ConfigureAwait(false); } /// <summary> /// Fetch token for credit card. /// </summary> /// <param name="isManualEntry">The value indicating whether credit card should be entered manually.</param> /// <param name="extensionTransactionProperties">Optional extension transaction properties.</param> /// <returns>A task that can await until the token generation has completed.</returns> [SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Suppressed on adding CA for backward compatibility")] private async Task<PaymentInfo> FetchTokenAsync(bool isManualEntry, ExtensionTransaction extensionTransactionProperties) { await Task.Delay(10).ConfigureAwait(false); throw new PeripheralException(PeripheralException.PaymentTerminalError, "Operation is not supported by payment terminal.", inner: null); } /// <summary> /// Activate gift card. /// </summary> /// <param name="paymentConnectorName">The payment connector name.</param> /// <param name="amount">The amount.</param> /// <param name="currencyCode">The currency.</param> /// <param name="tenderInfo">The tender information.</param> /// <param name="extensionTransactionProperties">Optional extension transaction properties.</param> /// <returns>A task that can await until the void has completed.</returns> [SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Suppressed on adding CA for backward compatibility")] private async Task<PaymentInfo> ActivateGiftCardAsync(string paymentConnectorName, decimal? amount, string currencyCode, TenderInfo tenderInfo, ExtensionTransaction extensionTransactionProperties) { await Task.Delay(10).ConfigureAwait(false); throw new PeripheralException(PeripheralException.PaymentTerminalError, "Operation is not supported by payment terminal.", inner: null); } /// <summary> /// Add balance to gift card. /// </summary> /// <param name="paymentConnectorName">The payment connector name.</param> /// <param name="amount">The amount.</param> /// <param name="currencyCode">The currency.</param> /// <param name="tenderInfo">The tender information.</param> /// <param name="extensionTransactionProperties">Optional extension transaction properties.</param> /// <returns>A task that can await until the void has completed.</returns> [SuppressMessage("Microsoft.Usage", "CA1801", Justification = "Suppressed on adding CA for backward compatibility")] private async Task<PaymentInfo> AddBalanceToGiftCardAsync(string paymentConnectorName, decimal? amount, string currencyCode, TenderInfo tenderInfo, ExtensionTransaction extensionTransactionProperties) { await Task.Delay(10).ConfigureAwait(false); throw new PeripheralException(PeripheralException.PaymentTerminalError, "Operation is not supported by payment terminal.", inner: null); } /// <summary> /// Get gift card balance. /// </summary> /// <param name="paymentConnectorName">The payment connector name.</param> /// <param name="currencyCode">The currency.</param> /// <param name="tenderInfo">The tender information.</param> /// <param name="extensionTransactionProperties">Optional extension transaction properties.</param> /// <returns>A task that can await until the void has completed.</returns> [SuppressMessage("Microsoft.Using", "CA1801", Justification = "Suppressed on adding CA for backward compatibility")] private async Task<PaymentInfo> GetGiftCardBalanceAsync(string paymentConnectorName, string currencyCode, TenderInfo tenderInfo, ExtensionTransaction extensionTransactionProperties) { await Task.Delay(10).ConfigureAwait(false); throw new PeripheralException(PeripheralException.PaymentTerminalError, "Operation is not supported by payment terminal.", inner: null); } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PaymentDevice
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/HardwareStationSamples/PaymentDevice/Properties/AssemblyInfo.cs
using System; using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Marking CLS compliant as false due to incompatibility with Prism library. [assembly: CLSCompliant(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d3d37d0b-21d2-4cac-8c97-d29f90794284")]
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/readme.md
# Store Commerce Samples ## Overview This folder contains sample solutions that demonstrate how to customize the Store Commerce (and POS) App in various scenarios. Each sample contains a solution containing a Commerce Runtime project to enable the POS extension package and the POS extension package with the sample extensions. The samples are organized based on the type of customizations. - Create: These extensions supplement POS by introducing new pages, dialogs or workflows that do not exist “out of the box” - Extend: These extensions modify POS by adding additional functionality to existing pages, workflows or other functionality - Solutions: These samples showcase a variety of extension types to enable a more complete feature or solution. ## Samples List - Create/ - Dialogs/ - [BarcodeMsrDialogSample](./Create/Dialogs/BarcodeMsrDialogSample/readme.md) - Extend/ - Triggers/ - [TriggerSamples](./Extend/Triggers/TriggerSamples/readme.md) - Solutions/ - [GasStation](./Solutions/GasStation/README.md) - Accessing Static Resources in Extensions - The [StaticResourcesAccessSample](https://msazure.visualstudio.com/D365/_git/Commerce-Samples-InStore?path=/src/StoreCommerceSamples/PosExtensionSamples/Pos/Extend/Triggers/BeepSoundPostProductSaleTrigger.ts&version=GBmain&line=17&lineEnd=17&lineStartColumn=9&lineEndColumn=89&lineStyle=plain&_a=contents) demonstrates how to access static resources in POS extensions.
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode/readme.md
# Printing QR Code Sample ## Overview This sample showcases a sample Store Commerce extension that prints a QR code on the receipt. The QR code can be scanned by a mobile device to open the receipt in the browser. ## Configuring the sample > For more details on how to extend Commerce Store receipts, see [Extend Commerce Store receipts](https://learn.microsoft.com/en-us/dynamics365/commerce/dev-itpro/retail-sdk/retail-sdk-samples). 1. Sign in to HQ. 2. Got to Retail and Commerce > Channel setup > POS setup > POS profiles > Language text. 3. On the POS tab, select Add to add new POS language text. 4. Enter the following values: - Language ID: en-us - Text ID: 10001 - Text: QR Code 5. On the Action Pane, select Save to save your changes. 6. Go to Retail and Commerce > Channel setup > POS setup > POS profiles > Custom fields. 7. On the Action Pane, select Add to add a new custom field, and specify the following information: - Name: QRCODESAMPLE - Type: Receipt - Caption text ID: 10001 8. On the Action Pane, select Save to save your changes. 9. Go to Retail and Commerce > Channel setup > POS setup > POS profiles > Receipt formats. 10. Select an existing or create a new receipt format and then select Designer on the Action Pane. 11. If you're prompted to confirm that you want to open the application, select Open, and then follow the installation instructions. 12. After the designer is installed, you're asked for Azure Active Directory (Azure AD) credentials. Enter the information to start the designer. 13. In the designer, drag and drop the **QR Code** field from the left pane to the receipt designer. 14. Save the changes. 15. Go to Retail and Commerce > Retail and Commerce IT > Distribution schedule. 16. Select the Channel configuration (1070) job, and then select Run now. ## Running the sample - Open the Developer Command Prompt for Visual Studio 2022 - Restore the nuget packages for the solution by running "nuget restore QRCode.sln" - Initialize Store Commerce development for the solution by running "msbuild QRCode.sln /t:InitDev" - Open Visual Studio Code in the solution root directory - Build the solution using the "Build & Install Store Commerce Extension" task in VSCode - Open PowerShell as Admin in the ScaleUnit.Installer bin directory & run ".\Contoso.QRCode.ScaleUnit.Installer.exe install" - Open the "Run & Debug Tab" in VSCode and use the "Debug Store Commerce" option to launch Store Commerce app with the debugger attached. - Sign in to Store Commerce. - Navigate to the transaction page and add a product to the cart. - Complete the transaction and print the receipt. - Verify that the receipt contains a QR code. ## Additional Resources - [Extend Commerce Store receipts](https://learn.microsoft.com/en-us/dynamics365/commerce/dev-itpro/retail-sdk/retail-sdk-samples) - [Generate QR codes and print them on receipts](https://learn.microsoft.com/en-us/dynamics365/commerce/localizations/ind-generate-qr-code-print-receipt) - [Set up and design receipt formats](https://learn.microsoft.com/en-us/dynamics365/commerce/receipt-templates-printing)
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode/CustomizationPackage.props
<Project> <Import Project="..\..\..\..\repo.props" /> <PropertyGroup> <PackagePublisher Condition="'$(PackagePublisher)' == ''">$(Publisher)</PackagePublisher> <PackagePublisherDisplayName Condition="'$(PackagePublisherDisplayName)' == ''">$(PublisherDisplayName)</PackagePublisherDisplayName> <PackageVersion Condition="'$(PackageVersion)' == ''">$(Version)</PackageVersion> <PackageName Condition="'$(PackageName)' == ''">Contoso.QRCode</PackageName> <PackageDisplayName Condition="'$(PackageDisplayName)' == ''">QR Code Sample</PackageDisplayName> <PackageDescription Condition="'$(PackageDescription)' == ''">A sample showcasing a solution how to print QR code on a receipt.</PackageDescription> </PropertyGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode/ScaleUnit.Installer/Contoso.QRCode.ScaleUnit.Installer.csproj
<Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\CustomizationPackage.props" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net472</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.Installers.ScaleUnit" Version="$(CommerceSdkPackagesVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\CommerceRuntime\Contoso.QRCode.CommerceRuntime.csproj"> <ReferenceOutputAssembly>false</ReferenceOutputAssembly> </ProjectReference> </ItemGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode/StoreCommerce.Installer/Contoso.QRCode.StoreCommerce.Installer.csproj
<Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\CustomizationPackage.props" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net472</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.Installers.StoreCommerce" Version="$(CommerceSdkPackagesVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\CommerceRuntime\Contoso.QRCode.CommerceRuntime.csproj"> <ReferenceOutputAssembly>false</ReferenceOutputAssembly> </ProjectReference> </ItemGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode/CommerceRuntime/DefinePosExtensionPackageTrigger.cs
/** * SAMPLE CODE NOTICE * * THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, * OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. * THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. * NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. */ namespace QRCode.CommerceRuntime { using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Dynamics.Commerce.Runtime; using Microsoft.Dynamics.Commerce.Runtime.DataModel; using Microsoft.Dynamics.Commerce.Runtime.Messages; /// <summary> /// Class that implements a post trigger for the GetExtensionPackageDefinitionsRequest request type. /// </summary> public class DefinePosExtensionPackageTrigger : IRequestTriggerAsync { /// <summary> /// Gets the supported requests for this trigger. /// </summary> public IEnumerable<Type> SupportedRequestTypes => new[] { typeof(GetExtensionPackageDefinitionsRequest) }; /// <summary> /// Post trigger to retrieve extension package. /// </summary> /// <param name="request">The request.</param> /// <param name="response">The response.</param> public Task OnExecuted(Request request, Response response) { ThrowIf.Null(request, "request"); ThrowIf.Null(response, "response"); var getExtensionsResponse = (GetExtensionPackageDefinitionsResponse)response; var extensionPackageDefinition = new ExtensionPackageDefinition(); // Should match the PackageName used when packaging the customization package (i.e. in CustomizationPackage.props). extensionPackageDefinition.Name = "Contoso.QRCode"; extensionPackageDefinition.Publisher = "Contoso"; extensionPackageDefinition.IsEnabled = true; getExtensionsResponse.ExtensionPackageDefinitions.Add(extensionPackageDefinition); return Task.CompletedTask; } /// <summary> /// Pre trigger code. /// </summary> /// <param name="request">The request.</param> public Task OnExecuting(Request request) { return Task.CompletedTask; } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode/CommerceRuntime/ReceipSampleService.cs
/** * SAMPLE CODE NOTICE * * THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, * OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. * THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. * NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. */ namespace QRCode.CommerceRuntime { using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Dynamics.Commerce.Runtime; using Microsoft.Dynamics.Commerce.Runtime.Localization.Services.Messages; using Microsoft.Dynamics.Commerce.Runtime.Messages; using Microsoft.Dynamics.Commerce.Runtime.Services.Messages; /// <summary> /// The extended service to get custom sales receipt field. /// </summary> public class GetSalesTransactionCustomReceiptFieldService : IRequestHandlerAsync { /// <inheritdoc/> public IEnumerable<Type> SupportedRequestTypes => new[] { typeof(GetLocalizationCustomReceiptFieldServiceRequest) }; /// <summary> /// Default QR code width. /// </summary> internal const int DefaultQrCodeWidth = 100; /// <summary> /// Default QR code height. /// </summary> internal const int DefaultQrCodeHeight = 100; /// <summary> /// Executes the requests. /// </summary> /// <param name="request">The request parameter.</param> /// <returns>The GetReceiptServiceResponse that contains the formatted receipts.</returns> public async Task<Response> Execute(Request request) { ThrowIf.Null(request, nameof(request)); ThrowIf.Null(request.RequestContext, $"{nameof(request)}.{nameof(request.RequestContext)}"); switch (request) { case GetLocalizationCustomReceiptFieldServiceRequest receiptRequest: return await GetCustomReceiptFieldForSalesTransactionReceiptsAsync(receiptRequest).ConfigureAwait(false); default: throw new NotSupportedException(string.Format("Request '{0}' is not supported.", request.GetType())); } } /// <summary> /// Gets the custom receipt field value for sales receipt. /// </summary> /// <param name="request">The service request to get custom receipt field value.</param> /// <returns>The value of custom receipt field.</returns> private static async Task<Response> GetCustomReceiptFieldForSalesTransactionReceiptsAsync(GetLocalizationCustomReceiptFieldServiceRequest request) { ThrowIf.Null(request.SalesOrder, $"{nameof(request)},{nameof(request.SalesOrder)}"); string receiptFieldName = request.CustomReceiptField; string receiptFieldValue; switch (receiptFieldName) { case "QRCODESAMPLE": receiptFieldValue = await GetQRCode(request).ConfigureAwait(false); break; default: return NotHandledResponse.Instance; } return new GetCustomReceiptFieldServiceResponse(receiptFieldValue); } /// <summary> /// Gets the QR code for the receipt. /// </summary> /// <param name="request">The service request to get custom receipt field value.</param> /// <returns>QR code custom field value.</returns> private static async Task<string> GetQRCode(GetLocalizationCustomReceiptFieldServiceRequest request) { string receiptFieldValue = string.Empty; string qrCodeContent = "https://microsoft.com"; if (!string.IsNullOrEmpty(qrCodeContent)) { string encodedQrCode = await EncodeQrCode(qrCodeContent, request.RequestContext).ConfigureAwait(false); if (!string.IsNullOrEmpty(encodedQrCode)) { // Wrapping QR Code string with L: tag to indicate that it is a Logo for the peripheral. receiptFieldValue = $"<L:{encodedQrCode}>"; } } return receiptFieldValue; } /// <summary> /// Encodes QR code. /// </summary> /// <param name="qrCodeContent">The QR code content.</param> /// <param name="requestContext">The request context.</param> /// <returns>The QR code in base64 format.</returns> private static async Task<string> EncodeQrCode(string qrCodeContent, RequestContext requestContext) { EncodeQrCodeServiceRequest qrCodeEncodeRequest = new EncodeQrCodeServiceRequest(qrCodeContent) { Width = DefaultQrCodeWidth, Height = DefaultQrCodeHeight, }; EncodeQrCodeServiceResponse qrCodeEncodeResponse = await requestContext.ExecuteAsync<EncodeQrCodeServiceResponse>(qrCodeEncodeRequest).ConfigureAwait(false); return qrCodeEncodeResponse.QRCode; } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode/CommerceRuntime/Contoso.QRCode.CommerceRuntime.csproj
<Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\CustomizationPackage.props" /> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Dynamics.Commerce.Runtime.Localization.Services.Messages" Version="$(CommerceChannelPackagesVersion)" /> <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.Runtime" Version="$(CommerceSdkPackagesVersion)" /> </ItemGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/QRCode/ScaleUnit/Contoso.QRCode.ScaleUnit.csproj
<Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\CustomizationPackage.props" /> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.ScaleUnit" Version="$(CommerceSdkPackagesVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\CommerceRuntime\Contoso.QRCode.CommerceRuntime.csproj" /> </ItemGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/README.md
# Gas Station Pump Control Sample ## Overview This sample showcases a sample where the Store Commerce App is extended to support common gas station scenarios. This sample extends the Store Commerce header to add a custom item that will provide users with information about the gas pump statuses on all views. The sample also adds a new view to display the complete status information for all gas pumps in the station. The view is divided into two pivot sections: Active pumps and Out of service pumps. This view is reached by clicking the header extension and can be used to control the pumps and add gasoline to the cart. To simulate a customer pumping gas the sample adds an extension command to the SimpleProductDetailsView that is displayed when the details page is shown for a gasoline product. ![Demo](./Demo.gif) ## Configuring the sample - [Create & configure a new product](https://docs.microsoft.com/en-us/dynamics365/commerce/create-new-product-commerce) with item id "gasoline" in HQ - Set the "Key in quantity" setting to "Must key in quantity" on the product under the "Commerce" tab - Set the unit of measure to gallons and configure base price on the product (See the "Configure a released product" section of the linked document.) - Edit the gallons unit of measure and set the decimal precision to 3 - [Assort the product](https://docs.microsoft.com/en-us/dynamics365/commerce/tasks/manage-assortments-2016-11) to your store - Run the download jobs (1040, 1070 or 9999) ## Running the sample - Open the Developer Command Prompt for Visual Studio 2022 - Restore the nuget packages for the solution by running "nuget restore GasStation.sln" - Initialize Store Commerce development for the solution by running "msbuild GasStation.sln /t:InitDev" - Open Visual Studio Code in the solution root directory - Build the solution using the "Build & Install Store Commerce Extension" task in VSCode - Open PowerShell as Admin in the ScaleUnit.Installer bin directory & run ".\Contoso.GasStation.ScaleUnit.Installer.exe install" - Open the "Run & Debug Tab" in VSCode and use the "Debug Store Commerce" option to launch Store Commerce app with the debugger attached. - Sign in to Store Commerce or Cloud POS - Navigate to the product details page for the gasoline product created in the previous section and click the pump gas command to launch the gas pump dialog. ## APIs and extension points used ### "PosApi/Create/Dialogs" - ExtensionTemplatedDialogBase: The base class for all dialogs created by extensions. - openDialog: This protected method on the ExtensionTemplatedDialogBase class opens the dialog. - closeDialog: This protected method on the ExtensionTemplatedDialogBase class closes the dialog. - onReady: The onReady function is called after the extension dialog element has been added to the DOM and is ready to be used. ### "PosApi/Create/Views" - CustomViewControllerBase: - super(context, config): The GasPumpStatusView calls the constructor for the base class with the context it is provided and its configuration object. See below for more information on the ICustomViewControllerConfiguration. - onReady: The POS framework calls the view's onReady method when the page has been added to the Document Object Model (DOM). This method is responsible for rendering the view inside the HTML element that is provided. - onShown: This method is called every time that the view is shown. - onHidden: This method is called every time that the view is hidden. - dispose: The POS framework calls the view's dispose method when the view is removed from the DOM and the POS navigation history. This method should release any resources that the view created. - ICustomViewControllerConfiguration: - title: The title of the view. This will be displayed on the header. - commandBar: The command bar configuration containing the commands that should be displayed. - ICommand: The ICommand interface the view controller to interact with app bar commands and update the command state. - canExecute: Setting the canExecute property to true enables the command on the UI and setting it to false disables the command. - isVisible: Setting the isVisible property controls whether or not the command is visible on the UI. - Icons: The icons enum is used to set the icon that will be displayed for a command. ### "PosApi/Consume/Controls" - IControlFactory: The interface representing the POS control factory. The control factory instance is provided to extensions in the ExtensionContext. - Used by the GasPumpStatusView to create and display a datalist showing the gas pumps. - IDataList: The interface for the POS datalist control. - addEventListener: Used to add event listeners for the events listed below. Adding event listeners allows the extension to know when the datalist received input from the user. - "SelectionChanged": Event raised when a datalist row is selected or deselected. - IPivot: The interface for the POS pivot control. - addEventListener: Used to add event listeners for the events listed below. Adding event listeners allows the extension to know when the pivot received input from the user. - "SelectionChanged": Event raised when a pivot item selection is changed. ### "PosApi/Consume/Dialogs" - ShowListInputDialogClientRequest/ShowListInputDialogClientResponse: This API is used to show a list of options to the user and to get their selection. This sample uses the API to select a gas pump in the PumpGasExtensionCommand class. - ShowMessageDialogClientRequest/ShowMessageDialogClientResponse: This API is used to show a message in POS and in this sample it is used to display an error message. ### "PosApi/Consume/Formatters" - CurrencyFormatter: The currency formatter API is used to format currency values for display on the UI. - DateFormatter: The date formatter API is used to format date values for display on the UI. ### "PosApi/Extend/Views/SimpleProductDetailsView" - SimpleProductDetailsExtensionCommandBase: The base class for all extension commands for the simple product details view - productChangedHandler: Setting the "productChangedHandler" function enables the extension command to update when the product changes. ### "PosApi/Extend/Header" - CustomPackingItem: The custom packing item class is the base class for all Store Commerce header bar extensions. In this sample, the GasPumpStatusPackingItem extends this class to add a button to the header to view the pump status. - position: CustomPackingItemPosition : The position field tells the Store Commerce extensibility framework where to place the custom header item. This can be before or after the out of the box Store Commerce packing items. - onReady(packedElement: HTMLElement, unpackedElement: HTMLElement): The Store Commerce framework calls the onReady method when the packing item elements have been added to the DOM. Each header packing item has two elements. The first is the "packedElement" this is the element that is displayed in the packing items overflow menu when it is expanded. This menu is used when there is not enough room in the header UI to show all of the packing items. The second element is the "unpackedElement" this is the element that is displayed in the Store Commerce header bar. - init(state: ICustomPackingItemState): The Store Commerce framework calls the init method to initialize the header packing item when the header is created. - dispose(): This method disposes all of the header packing item resources. ### "PosApi/TypeExtensions" - ArrayExtensions: The array extensions class provides utility methods that make it easier to work with arrays. - ObjectExtensions: The object extensions class provides utility methods that make it easier to work with javascript objects. ## Additional Resources - [Debugging POS Extensions](https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/pos-extension/debug-pos-extension#run-and-debug-cloud-pos) - [Create a custom view in POS](https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/pos-extension/custom-pos-view) - [Using POS Controls](https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/pos-extension/controls-pos-extension) - [Use knockout.js in POS Extensions](https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/pos-extension/knockout-pos-extension) - [Consume custom headless Commerce APIs in POS](https://docs.microsoft.com/en-us/dynamics365/commerce/dev-itpro/pos-extension/consume-apis-pos)
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/CustomizationPackage.props
<Project> <Import Project="..\..\..\..\repo.props" /> <PropertyGroup> <PackagePublisher Condition="'$(PackagePublisher)' == ''">$(Publisher)</PackagePublisher> <PackagePublisherDisplayName Condition="'$(PackagePublisherDisplayName)' == ''">$(PublisherDisplayName)</PackagePublisherDisplayName> <PackageVersion Condition="'$(PackageVersion)' == ''">$(Version)</PackageVersion> <PackageName Condition="'$(PackageName)' == ''">Contoso.GasStation</PackageName> <PackageDisplayName Condition="'$(PackageDisplayName)' == ''">Gas Station Sample</PackageDisplayName> <PackageDescription Condition="'$(PackageDescription)' == ''">A sample showcasing a solution to create a user interface to control gas pumps and pay for gas.</PackageDescription> </PropertyGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/ScaleUnit.Installer/Contoso.GasStation.ScaleUnit.Installer.csproj
<Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\CustomizationPackage.props" /> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>net472</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.Installers.ScaleUnit" Version="$(CommerceSdkPackagesVersion)" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\CommerceRuntime\Contoso.GasStation.CommerceRuntime.csproj"> <ReferenceOutputAssembly>false</ReferenceOutputAssembly> </ProjectReference> <ProjectReference Include="..\POS\Contoso.GasStation.Pos.csproj"> <ReferenceOutputAssembly>false</ReferenceOutputAssembly> </ProjectReference> </ItemGroup> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/tsconfig.json
{ "extends": "./devDependencies/pos-tsconfig-base.json", "compilerOptions": { "baseUrl": ".", "paths": { "knockout": [ "Libraries/knockout" ] }, "noImplicitAny": false } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/NumberFormattingHelper.ts
export abstract class NumberFormattingHelper { /** * Gets the rounded value as a formatted string. * @param {number} value The value. * @param {number} decimalPrecision The decimal precision. * @returns {string} The formatted string value. */ public static getRoundedStringValue(value: number, decimalPrecision: number): string { return NumberFormattingHelper.roundToNDigits(value, decimalPrecision).toFixed(decimalPrecision); } /** * Gets the rounded value. * @param {number} value The value to be rounded. * @param {number} decimalPrecision The decimal precision. * @returns {number} The rounded value. */ public static roundToNDigits(value: number, decimalPrecision: number): number { if (decimalPrecision === 0) { return Math.round(value); } // Use this instead of toFixed otherwise it will not round anything, simply lose digits return Math.round(value * Math.pow(10, decimalPrecision)) / Math.pow(10, decimalPrecision); } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/GasStationDataStore.ts
import { IExtensionContext } from "PosApi/Framework/ExtensionContext"; import { ArrayExtensions, ObjectExtensions } from "PosApi/TypeExtensions"; import { GasPumps } from "./DataService/DataServiceRequests.g" import { Entities } from "./DataService/DataServiceEntities.g"; import { ProxyEntities, ClientEntities } from "PosApi/Entities"; import { GetDeviceConfigurationClientRequest, GetDeviceConfigurationClientResponse } from "PosApi/Consume/Device"; import GasPump = Entities.GasPump; import GasPumpState = Entities.GasPumpState; export type PumpStatusChangedHandler = (updatedPumps: GasPump[]) => void; type StatusChangedHandlerWithId = { readonly handler: PumpStatusChangedHandler, readonly id: number }; /** * Gas station data store (Singleton that holds the data used in the sample). */ export class GasStationDataStore { private static _instance: GasStationDataStore; private _pumps: GasPump[]; private _gasStationDetails: Entities.GasStationDetails; private _storeNumber: string; private readonly _pumpStatusChangedHandlers: StatusChangedHandlerWithId[]; /** * Initializes a new instance of the GasStationDataStore class. */ private constructor() { this._pumps = []; this._pumpStatusChangedHandlers = []; } /** * Returns the instance of the singleton. * @returns {GasStationDataStore} The singleton of class GasStationDataStore. */ public static get instance(): GasStationDataStore { if (ObjectExtensions.isNullOrUndefined(GasStationDataStore._instance)) { GasStationDataStore._instance = new GasStationDataStore(); } return GasStationDataStore._instance; } /** * Gets the gas pumps. * @returns {GasPump[]} The gas pumps. */ public get pumps(): GasPump[] { return ObjectExtensions.clone(this._pumps); } /** * Gets the gas station details * @returns {Readonly<Entities.GasStationDetails>} The gas station details. */ public get gasStationDetails(): Readonly<Entities.GasStationDetails> { return this._gasStationDetails; } /** * Gets the store number. * @returns {string} The store number. */ public get storeNumber(): string { return this._storeNumber; } /** * Initializes the gas station data store. * @returns {Promise<void>} The resulting promise. */ public initAsync(context: IExtensionContext): Promise<void> { return context.runtime.executeAsync(new GetDeviceConfigurationClientRequest()) .then((response: ClientEntities.ICancelableDataResult<GetDeviceConfigurationClientResponse>): ProxyEntities.DeviceConfiguration => { return response.data.result; }) .then((deviceConfiguration: ProxyEntities.DeviceConfiguration) => { if (ObjectExtensions.isNullOrUndefined(deviceConfiguration)) { return Promise.resolve(); } this._storeNumber = deviceConfiguration.StoreNumber; let request = new GasPumps.GetGasPumpsByStoreRequest(this._storeNumber); return context.runtime.executeAsync(request).then((result): void => { if (!result.canceled) { this._pumps = result.data.result; } }); }).then((): Promise<void> => { let stationDetailsRequest = new GasPumps.GetGasStationDetailsByStoreRequest(this._storeNumber); return context.runtime.executeAsync(stationDetailsRequest) .then((result: ClientEntities.ICancelableDataResult<GasPumps.GetGasStationDetailsByStoreResponse>): void => { if (!result.canceled) { this._gasStationDetails = result.data.result; } }); }).then((): void => { // Start the interval timer to poll the gas pump status from CSU. setInterval((): void => { let request = new GasPumps.GetGasPumpsByStoreRequest(this._storeNumber); context.runtime.executeAsync(request).then((result): void => { if (!result.canceled) { let pumpsById: { [id: number]: Entities.GasPump } = Object.create(null); let statusChanged: boolean = false; this._pumps.forEach((pump) => { pumpsById[pump.Id] = pump; }); result.data.result.forEach((pump) => { let previousPump: Entities.GasPump = pumpsById[pump.Id]; if (ObjectExtensions.isNullOrUndefined(previousPump)) { statusChanged = true; } else if (JSON.stringify(previousPump) !== JSON.stringify(pump)) { statusChanged = true; } }); if (this._pumps.length !== result.data.result.length || statusChanged) { this._pumps = result.data.result; this._pumpStatusChangedHandlers.forEach((pair: StatusChangedHandlerWithId): void => { pair.handler(this.pumps); }); } } }); }, 4000); }); } public stopAllPumpsAsync(context: IExtensionContext): Promise<ReadonlyArray<GasPump>> { let stopRequest: GasPumps.StopAllPumpsRequest<GasPumps.StopAllPumpsResponse> = new GasPumps.StopAllPumpsRequest(this._storeNumber); return context.runtime.executeAsync(stopRequest).then((result: ClientEntities.ICancelableDataResult<GasPumps.StopAllPumpsResponse>): ReadonlyArray<GasPump> => { if (!result.canceled) { this._pumps = result.data.result; this._pumpStatusChangedHandlers.forEach((pair: StatusChangedHandlerWithId): void => { pair.handler(this.pumps); }); } return this.pumps; }); } public startAllPumpsAsync(context: IExtensionContext): Promise<ReadonlyArray<GasPump>> { let stopRequest: GasPumps.StartAllPumpsRequest<GasPumps.StartAllPumpsResponse> = new GasPumps.StartAllPumpsRequest(this._storeNumber); return context.runtime.executeAsync(stopRequest).then((result: ClientEntities.ICancelableDataResult<GasPumps.StartAllPumpsResponse>): ReadonlyArray<GasPump> => { if (!result.canceled) { this._pumps = result.data.result; this._pumpStatusChangedHandlers.forEach((pair: StatusChangedHandlerWithId): void => { pair.handler(this.pumps); }); } return this.pumps; }); } /** * Updates the pump with the specified identifier with the specified status. * @param {number} id The pump's identifier. * @param {IGasPumpStatus} status The updated status. */ public updatePumpStatusAsync(context: IExtensionContext, id: number, state: GasPumpState): Promise<GasPump> { let pumpIndex: number = this._pumps.map(p => p.Id).indexOf(id); if (pumpIndex < 0) { return Promise.reject(new Error("Invalid pump identifier provided.")); } let stopRequest: GasPumps.UpdatePumpStateRequest<GasPumps.UpdatePumpStateResponse> = new GasPumps.UpdatePumpStateRequest(this._storeNumber, id, state); return context.runtime.executeAsync(stopRequest).then((result: ClientEntities.ICancelableDataResult<GasPumps.UpdatePumpStateResponse>): GasPump => { if (result.canceled) { return null; } this._pumps.splice(pumpIndex, 1, result.data.result); this._pumpStatusChangedHandlers.forEach((pair): void => { pair.handler(this.pumps); }); return result.data.result; }); } /** * Adds a handler to be executed when the pump status changes. * @param {(pump: IGasPump, previousStatus: IGasPumpStatus) => void} handler The handler to execute after the pump status change. */ public addPumpStatusChangedHandler(handler: (updatedPumps: GasPump[]) => void): number { if (!ObjectExtensions.isFunction(handler)) { throw new Error("GasStationDataStore.addPumpStatusChangedHandler the provided handler must be a function."); } let handlerId: number = new Date().getTime(); this._pumpStatusChangedHandlers.push({ handler: handler, id: handlerId }); return handlerId; } public removePumpStatusChangedHandler(id: number) { let handlerIndex: number = ArrayExtensions.findIndex(this._pumpStatusChangedHandlers, (pair) => pair.id === id); if (handlerIndex > 0) { this._pumpStatusChangedHandlers.splice(handlerIndex, 1); } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/GlobalConstants.ts
export const GASOLINE_QUANTITY_EXTENSION_PROPERTY_NAME: string = "Contoso.GasStation.PumpedGasolineQuantity";
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/Contoso.GasStation.Pos.csproj
<Project Sdk="Microsoft.NET.Sdk"> <Import Project="..\CustomizationPackage.props" /> <PropertyGroup> <TargetFramework>netstandard2.0</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.Dynamics.Commerce.Sdk.Pos" Version="$(CommerceSdkPackagesVersion)" /> <PackageReference Include="Microsoft.TypeScript.MSBuild" Version="$(TypeScriptPackagesVersion)" /> <PackageReference Include="knockoutjs" Version="3.5.*" /> </ItemGroup> <ItemGroup> <ProjectReference Include="..\CommerceRuntime\Contoso.GasStation.CommerceRuntime.csproj" /> </ItemGroup> <Target Name="ContentIncludeKnockoutLibrary" BeforeTargets="AssignTargetPaths" DependsOnTargets="RunResolvePackageDependencies"> <PropertyGroup> <KnockoutLibraryFilePath Condition="'%(PackageDefinitions.Name)' == 'knockoutjs'">%(PackageDefinitions.ResolvedPath)\Content\Scripts\knockout-%(PackageDefinitions.Version).js</KnockoutLibraryFilePath> <KnockoutjsFile>Libraries/knockout.js</KnockoutjsFile> </PropertyGroup> <Copy SourceFiles="$(KnockoutLibraryFilePath)" DestinationFiles="$(KnockoutjsFile)" SkipUnchangedFiles="true" /> <!-- Necessary for CPOS --> <ItemGroup> <Content Include="$(KnockoutjsFile)"></Content> </ItemGroup> </Target> </Project>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/manifest.json
{ "$schema": "./devDependencies/schemas/manifestSchema.json", "name": "GasStation", "publisher": "Contoso", "version": "1.0.0.0", "minimumPosVersion": "9.32.0.0", "dependencies": [ { "alias": "knockout", "format": "amd", "modulePath": "Libraries/knockout" } ], "components": { "extend": { "header": { "customPackingItems": [ { "name": "Gas Pump Status Header Item", "description": "An item showing the gas pump status on the POS header.", "modulePath": "Extend/Header/GasPumpStatusPackingItem", "htmlPath": "Extend/Header/GasPumpStatusPackingItem.html" } ] }, "triggers": [ { "triggerType": "ApplicationStart", "modulePath": "Extend/Triggers/InitializeStationTrigger", "name": "Initialize Gas Pumps Trigger", "description": "An application start trigger to initialize the gas pump status." } ], "requestHandlers": [ { "name": "Auto Key in Gas Quantity Request Handler", "description": "An extension for the get keyed in quantity request handler that automatically keys in the gasoline quantity", "modulePath": "Extend/RequestHandlers/KeyInGasolineQuantityRequestHandler" } ], "views": { "SimpleProductDetailsView": { "appBarCommands": [ { "modulePath": "Extend/Views/PumpGasExtensionCommand" } ] } } }, "create": { "views": [ { "name": "Gas Pump Status View", "description": "The view showing the status of the gas pumps", "pageName": "GasPumpStatusView", "phonePageName": "GasPumpStatusView", "viewDirectory": "Create/Views/", "viewControllerPath": "Create/Views/GasPumpStatusView" } ], "templatedDialogs": [ { "name": "Gas Station Details Dialog", "description": "A dialog showing the details of the gas station.", "modulePath": "Create/Dialogs/GasStationDetailsDialog", "htmlPath": "Create/Dialogs/GasStationDetailsDialog.html" }, { "name": "Gas Pump Simulator Dialog", "description": "A dialog showing a gas pump simulator.", "modulePath": "Create/Dialogs/PumpGasDialog", "htmlPath": "Create/Dialogs/PumpGasDialog.html" } ] } } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/GasStationTypes.ts
/** * The states of a gas pump. */ export enum GasPumpStatus { Unknown, Idle, Pumping, PumpingComplete, Stopped, Emergency }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/Extend
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/Extend/Views/PumpGasExtensionCommand.ts
import { Entities } from "DataService/DataServiceEntities.g"; import { GasPumpStatus } from "../../GasStationTypes"; import { NumberFormattingHelper } from "../../NumberFormattingHelper"; import { ShowListInputDialogClientRequest, ShowListInputDialogClientResponse } from "PosApi/Consume/Dialogs"; import { ClientEntities } from "PosApi/Entities"; import { IExtensionCommandContext } from "PosApi/Extend/Views/AppBarCommands"; import { ISimpleProductDetailsToExtensionCommandMessageTypeMap, SimpleProductDetailsExtensionCommandBase, SimpleProductDetailsProductChangedData } from "PosApi/Extend/Views/SimpleProductDetailsView"; import { GasStationDataStore } from "../../GasStationDataStore"; import PumpGasDialog from "../../Create/Dialogs/PumpGasDialog"; import { StringExtensions } from "PosApi/TypeExtensions"; /** * An extension command for the Simple Product details view that will display the pump gas dialog. */ export default class PumpGasExtensionCommand extends SimpleProductDetailsExtensionCommandBase { constructor(context: IExtensionCommandContext<ISimpleProductDetailsToExtensionCommandMessageTypeMap>) { super(context); this.extraClass = "iconDeliveryTruck" this.id = "startStopPumpingGasExtensionCommand"; this.label = "Start/stop pumping gas"; this.productChangedHandler = (data: SimpleProductDetailsProductChangedData): void => { if (StringExtensions.compare(data.product.ItemId, GasStationDataStore.instance.gasStationDetails.GasolineItemId, true) === 0) { this.isVisible = true; this.canExecute = true; } }; } protected init(state: Commerce.Extensibility.ISimpleProductDetailsExtensionCommandState): void { if (StringExtensions.compare(state.product?.ItemId, GasStationDataStore.instance.gasStationDetails.GasolineItemId, true) === 0) { this.isVisible = true; this.canExecute = true; } } protected execute(): void { this.isProcessing = true; let dialogOptions: ClientEntities.Dialogs.IListInputDialogOptions = { title: "Select gas pump", items: GasStationDataStore.instance.pumps.filter((pump: Entities.GasPump): boolean => { return pump.State.GasPumpStatusValue === GasPumpStatus.Idle }).map((pump): ClientEntities.Dialogs.IListInputDialogItem => { return { value: pump.Id, label: pump.Name }; }) }; let selectPumpRequest: ShowListInputDialogClientRequest<ShowListInputDialogClientResponse> = new ShowListInputDialogClientRequest(dialogOptions); this.context.runtime.executeAsync(selectPumpRequest).then((result: ClientEntities.ICancelableDataResult<ShowListInputDialogClientResponse>) => { if (result.canceled) { return; } let dialog = new PumpGasDialog(); dialog.open({ pumpId: result.data.result.value.value }).then((pumpResult: ClientEntities.ICancelableDataResult<number>): Promise<any> => { if (result.canceled) { return Promise.resolve(); } return GasStationDataStore.instance.updatePumpStatusAsync( this.context, result.data.result.value.value, { GasPumpStatusValue: GasPumpStatus.PumpingComplete, LastUpdateTime: new Date(), SaleVolume: pumpResult.data, SaleTotal: NumberFormattingHelper.roundToNDigits(GasStationDataStore.instance.gasStationDetails.GasBasePrice * pumpResult.data, 3) }); }); }).catch((reason: any): void => { }).then((): void => { this.isProcessing = false; }); } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/Extend
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/Extend/Triggers/InitializeStationTrigger.ts
/** * SAMPLE CODE NOTICE * * THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, * OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. * THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. * NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. */ import { ApplicationStartTrigger, IApplicationStartTriggerOptions } from "PosApi/Extend/Triggers/ApplicationTriggers"; import { GasStationDataStore } from "../../GasStationDataStore"; import ko from "knockout"; /** * Example implementation of an ApplicationStart trigger that initiates the Gas Station Data Store. */ export default class InitializeStationTrigger extends ApplicationStartTrigger { /** * Executes the trigger functionality. * @param {Triggers.IApplicationStartTriggerOptions} options The options provided to the trigger. */ public execute(options: IApplicationStartTriggerOptions): Promise<void> { /* This implementation is necessary to make POS controls behave properly when a custom version of knockout is used on extensions. * - The 'controlsDescendantBindings = true' tells knockout to not bind the descendants of the element that has it. * - All POS controls which use knockout have the __posStopExtensionBinding binding. * Then, the code below is telling to the 'ko' imported by the extension to not rebind elements inside POS controls. * Otherwise using a POS data list would result in error because the data list defines new bindings to its descendants and * the local 'ko' doesn't know their implementation, only the 'ko' imported in the POS code knows. */ ko.bindingHandlers.__posStopExtensionBinding = { init: () => { return { controlsDescendantBindings: true }; } }; return GasStationDataStore.instance.initAsync(this.context); } }
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/Extend
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/Extend/Header/GasPumpStatusPackingItem.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Gas Pumps Status Item Templates</title> <link href="GasPumpStatusPackingItem.css" rel="stylesheet" /> </head> <body> <script id="Microsoft_Pos_GasStationHeaderExtensionSample_UnpackedGasPumpStatusItem" type="text/html"> <button class="pad0 center row" data-bind="click: onItemClickedHandler, style: { 'background-color' : backgroundColor }, attr: {'aria-label': label}"> <div class="iconTrackers buttonIcon width48 height20"></div> </button> </script> <script id="Microsoft_Pos_GasStationHeaderExtensionSample_PackedGasPumpStatusItem" type="text/html"> <button id="gasPumpPackedButton" class="row pad0" data-bind="click: onItemClickedHandler, style: { 'background-color' : backgroundColor }, attr: {'aria-label': label}"> <div class="iconTrackers buttonIcon height20 margin12"> </div> <div class="grow col marginLeft8 padTop12"> <div class="h4 row" data-bind="text: label"></div> </div> </button> </script> </body> </html>
0
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/Extend
Dynamics365Commerce.InStore/Dynamics365Commerce.InStore/src/StoreCommerceSamples/Solutions/GasStation/Pos/Extend/Header/GasPumpStatusPackingItem.css
#gasPumpPackedButton { width: inherit; color: #fff; }
0
README.md exists but content is empty.
Downloads last month
59