Microsoft GP 10 (WSProgrammersGuide)
Microsoft GP 10 (WSProgrammersGuide)
Copyright
Copyright 2008 Microsoft Corporation. All rights reserved. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. Notwithstanding the foregoing, the licensee of the software with which this document was provided may make a reasonable number of copies of this document solely for internal use.
Trademarks
Microsoft, Microsoft Dynamics, Visual Basic, Visual Studio, Windows, and Windows Server are either registered trademarks or trademarks of Microsoft Corporation or its affiliates in the United States and/or other countries. The names of actual companies and products mentioned herein may be trademarks or registered marks - in the United States and/or other countries - of their respective owners. Unless otherwise noted, the example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious. No association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred.
Intellectual property
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. Microsoft Corporation disclaims any warranty regarding the sample code contained in this documentation, including the warranties of merchantability and fitness for a particular purpose. The content of this document is furnished for informational use only, is subject to change without notice, and should not be construed as a commitment by Microsoft Corporation. Microsoft Corporation assumes no responsibility or liability for any errors or inaccuracies that may appear in this manual. Neither Microsoft Corporation nor anyone else who has been involved in the creation, production or delivery of this documentation shall be liable for any indirect, incidental, special, exemplary or consequential damages, including but not limited to any loss of anticipated profit or benefits, resulting from the use of this documentation or sample code. Use of this product is covered by a license agreement provided with the software product. If you have any questions, please call the Microsoft Dynamics GP Customer Assistance Department at 800-456-0025 (in the U.S. or Canada) or +1-701-281-6500.
Warranty disclaimer
Limitation of liability
License agreement
Publication date
Contents
Introduction ................................................................................................................................................. 2
Whats in this manual...................................................................................................................................2 Whats new in this release? .........................................................................................................................2 Prerequisites...................................................................................................................................................3 Symbols and conventions ............................................................................................................................3 Product support ............................................................................................................................................4
WEB
SERVICE
PROGRAMMERS
GUIDE
C O N T E N T S
ii
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C O N T E N T S
WEB
SERVICE
PROGRAMMERS
GUIDE
iii
C O N T E N T S
iv
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
INTRODUCTION
Introduction
Welcome to Web Services for Microsoft Dynamics GP. This documentation explains how you can use these web services from within your own applications. Before you begin using the web services for Microsoft Dynamics GP, take a few moments to review the information presented here. Understanding the information provided here will help you learn about what the web services provide.
In addition, the Microsoft Dynamics GP Web Service Reference is an online help file that contains detailed information about the web methods, classes, enumerations, and policies provided by the web service. You will use this reference frequently as you develop your application that uses the Dynamics GP web service.
1. Entity ID Filtering
Several objects in the Dynamics GP web service have identity information associated with them. For example, each sales order has a salesperson ID. Entity ID filtering allows restricting access to these objects, based on the Windows User ID of the person accessing the web service. Refer to Chapter 14, Entity ID Filtering, for details about this feature.
2. Additional classes
Several classes have been added to the Dynamics GP web service for this release. Most of the new classes provide access to objects for the Field Service module in Microsoft Dynamics GP. Refer to the Dynamics GP Web Service Reference online help file for a complete list of the new classes.
WE B
S E R V I C E
P R O G R A M M E R S
G U I D E
IN T RO D U C T IO N
Prerequisites
Since you will be working with information from Microsoft Dynamics GP, knowledge of the accounting system will be helpful. Consult the Microsoft Dynamics GP documentation resources to learn more about the product. It is assumed that you have already installed and configured the Web Services for Microsoft Dynamics GP. If you havent done so, consult the Web Services for Microsoft Dynamics GP Installation and Administration Guide for information about performing the installation. The information provided in this documentation will help you understand how to use the web services for Microsoft Dynamics GP. It is assumed that you are familiar with the development system that you will be using to create your application that accesses the web services. This guide uses Visual Studio 2005 to demonstrate the various techniques for web service development. If youre using another development tool, the general techniques will be similar. Refer to the documentation for your development tool for details about accessing web services.
The light bulb symbol indicates helpful tips, shortcuts, and suggestions. Warnings indicate situations you should be aware of when completing tasks.
Margin notes summarize important information.
Margin notes call attention to critical information and direct you to other areas of the documentation where a topic is explained.
Description
Convention
Part 1, Web Service Basics Bold type indicates a part name. Chapter 5, Web Methods Quotation marks indicate a chapter name. Creating a web reference
using System.IO;
Italicized type indicates a section name. This font is used to indicate script examples. Acronyms are spelled out the first time theyre used. Small capital letters indicate a key or a key sequence.
or ALT+M
WEB
SERVICE
PROGRAMMERS
GUIDE
I N T R O D U C T I O N
Product support
Microsoft Dynamics GP developer technical support can be accessed online or by telephone. Go to www.microsoft.com/BusinessSolutions and click the CustomerSource or PartnerSource link, or call 888-477-7877 (in the US and Canada) or 701-281-0555.
WE B
S E R V I C E
P R O G R A M M E R S
G U I D E
WE B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 1:
ASP .NET is used as the foundation to implement the Web Services for Microsoft Dynamics GP. It provides the support for the standard protocols that make the web services accessible.
WEB
SERVICE
PROGRAMMERS
GUIDE
PA RT
W E B
S E R V I C E
B A S I C S
Through the web service, integrating applications can retrieve documents, create new documents, update existing documents, and delete or void documents. The web service for Microsoft Dynamics GP is fully integrated with the Dynamics Security Service. The administrator of the web service can configure security so only specified users are allowed to perform actions like creating or updating sales documents.
WE B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 2:
Configurations
Two common configurations are used with Web Services for Microsoft Dynamics GP. In the basic configuration, IIS with ASP .NET and the Web Services for Microsoft Dynamics GP are installed on the same server that is hosting SQL Server and managing Microsoft Dynamics GP data. This is shown in the following illustration:
SQL Server with Dynamics GP Data and eConnect + IIS Server with ASP .NET and Web Services for Microsoft Dynamics GP
WEB
SERVICE
PROGRAMMERS
GUIDE
PA RT
W E B
S E R V I C E
B A S I C S
The following illustration shows the second common configuration for the Web Services for Microsoft Dynamics GP. In this configuration, the web services are installed on a separate server, and access the SQL Server that manages Microsoft Dynamics GP data over the local network.
Local Network
IIS Server with ASP .NET and Web Services for Microsoft Dynamics GP
Which configuration you choose will depend on how extensively you will be using the Web Services for Microsoft Dynamics GP, and what server resources you have available. The two-server configuration will provide better performance if the web service will be heavily used.
10
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
W E B
S E R V I C E
A R C HI TE C T U R E
Exception logging
The Dynamics GP web service maintains a record of all exceptions (errors) that occur for web service operations. The web service administrator will use this information to help diagnose and resolve any issues for applications that use the web service. You can use the Dynamics GP Web Services Exceptions console to view the exception information. This is a snap-in for Microsoft Management Console (MMC) that retrieves and displays the exceptions logged by the Dynamics GP web service. The console is shown in the following illustration.
The exception information can also be queried by applications that access the Dynamics GP web service. Retrieving exception information allows the client applications to display helpful error messages for the user, or to respond appropriately to exceptions that occur. You will learn more about working with exceptions in Chapter 12, Exceptions.
WEB
SERVICE
PROGRAMMERS
GUIDE
11
12
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
14
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 3:
Click the individual operations to see the SOAP messages that are sent when the operations are performed and results are returned. Click Service Description to see the entire Web Service Description Language (WSDL) file that completely describes the web service. The WSDL file is in XML format. Typically, the WSDL file isnt used directly by the developer. It is designed to be read by development tools so they can learn about the definitions of the operations, objects, and enumerations provided by the web service.
WEB
SERVICE
PROGRAMMERS
GUIDE
15
PA RT
G E TT I N G
S T A R TE D
Throughout this documentation, the web reference to the Dynamics GP web service is named DynamicsGPService. 4. Add the web reference. Click Add Reference to create the proxy for the web service.
16
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
C O N N E C T I N G
T O
T H E
W E B
S ER V I C E
The following illustration shows the web reference to the Dynamics GP web service that was added to a Visual C# project.
Most development tools will have a browsing tool that allows you to view the details of the proxy created for the web service. In Visual Studio 2005 or later you can view the web service proxy with the Object Browser. The Object Browser shows the details of the classes in the proxy. Its a good way to see the details of the Dynamics GP web service.
The Dynamics GP web service is large, and uses some web service standards that are not fully supported by some development tools and applications that can access web services. You may not be able to create web references to the Dynamics GP web service from some of these tools.
WEB
SERVICE
PROGRAMMERS
GUIDE
17
PA RT
G E TT I N G
S T A R TE D
Adding the using statement will keep you from having to fully-qualify the classes, methods, and enumerations you refer to in the web service proxy.
Throughout the code examples in this documentation, the web service instance is named wsDynamicsGP. The web service instance also provides access to properties that control how the web service is called. For instance, when accessing the Dynamics GP web service you can specify that the current users login credentials will be used for the web service call. The following C# code shows how this is done for a project created in Visual Studio 2005.
// Be sure that default credentials are being used wsDynamicsGP.UseDefaultCredentials = true;
The following C# code shows how this is done for Visual Studio 2003.
// Be sure that default credentials are being used wsDynamicsGP.Credentials = System.Net.CredentialCache.DefaultCredentials;
The Timeout property is another important property of the web service instance. It specifies how long the client application will wait for a web service request to be completed. If your web service application is working with a large number of documents, it may encounter timeout errors. You can use the Timeout property to increase the timeout value. The following C# example sets the timeout to infinite.
wsDynamicsGP.Timeout = System.Threading.Timeout.Infinite;
Refer to the troubleshooting information in the Web Services Installation and Administration Guide for more information about timeout issues.
18
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 4:
Object categories
The number of objects available through the Dynamics GP web service is quite large. To understand how all of these objects are used, it helps to divide them into three categories.
Other objects are parts of business documents or define a set of properties for a business document. Example of this type of object include: Address SalesLine Tax
The vast majority of objects in the Dynamics GP web service are business documents or some part of a business document.
Base objects
Many objects in the Dynamics GP web service share common characteristics. Rather than repeat these characteristics for every individual object, a single base object is used. This object serves as the basis for each specific type of object. The following are some common base objects: BusinessObject Key Criteria Restriction
For instance, all business documents such as Customer and SalesInvoice are based on BusinessObject. Every key object used to uniquely identify an object is based on the Key object. You will never work with the base objects directly. They are used only by the web service to implement the other objects.
WEB
SERVICE
PROGRAMMERS
GUIDE
19
PA RT
G E TT I N G
S T A R TE D
Helper objects
Some objects are included simply to help you work with the Dynamics GP web service. They perform actions such as controlling how the web service is called, or dealing with errors that occur during processing. The following are some of the helper objects: Context Policy ExceptionInformation ValidationItem
Inheritance
As described in Object categories on page 19, many of the business document objects you will use as you work with the web service inherit characteristics from other objects. For instance, the CustomerAddress object, which completely describes the address information for a customer, inherits from a series of other objects. The inheritence hierarchy for the CustomerAddress object is shown in the following illustration:
CustomerAddress
ConstituentAddress
BusinessAddress
InternationalAddress
Address
Address Base
BusinessObject
Base Object
The CustomerAddress object has all of the characteristics (properties) of each of the objects it inherits from. Notice that BusinessObject serves as the base object for the inheritence hierarchy.
20
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
W E B
S E R V I C E
O B J E C T
M O D E L
As you work with the Customer object, you will see that it references some additional objects including: CustomerKey CustomerClassKey CustomerAddressKey CustomerCreditLimit
As you learn about these related objects, you will expand your understanding of the object model for the Customer object you are creating.
WEB
SERVICE
PROGRAMMERS
GUIDE
21
22
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 5:
Web Methods
To perform tasks with the Dynamics GP web service, you must call the web methods provided. The following sections introduce the web methods available in the web service: Web method categories Framework methods
Get
Get operations retrieve individual documents from Microsoft Dynamics GP. To retrieve a document, you specify the documents key (unique identifier). If the document can be found, it will be returned from the web service. You will learn more about Get operations in Chapter 9, Retrieving Objects.
GetList
GetList operations retrieve collections of summary objects that meet the specified set of search criteria. A summary object is a special version of a business document, containing only the most important properties of the document. For example, the CustomerSummary object contains only the most important properties of the Customer object. You will learn more about criteria and GetList operations in Chapter 9, Retrieving Objects.
Create
Create operations create new documents in Microsoft Dynamics GP. To create a new document, you will first create a new instance of the document object. After you specify the details for the object, you will call the Create method to create the new object. You will learn more about creating new documents in Chapter 8, Creating Objects.
Update
Update operations modify existing documents in Microsoft Dynamics GP. For most documents, you can create an instance of the document type, specify the properties to update, and supply the key value to indicate which document will be updated. Other types of documents, specifically sales documents, require you to first retrieve an instance of the document before you can update it. You will learn more about updating documents in Chapter 10, Updating Objects.
Delete or void
Delete operations permanently delete existing documents from Microsoft Dynamics GP. Some documents cannot be deleted, but can be voided instead. Void operations perform this action. Chapter 11, Deleting or Voiding Objects, describes how to do this in detail.
WEB
SERVICE
PROGRAMMERS
GUIDE
23
PA RT
G E TT I N G
S T A R TE D
Framework methods
The web service also provides several methods that help you work with the Dynamics GP web service framework.
Exceptions
Code that accesses the Dynamics GP web service must be able to handle any exceptions that occur while web methods are processed. Several web methods are included in the Dynamics GP web service that your application can use to retrieve information about an exception that occurred. The exception information can be used to present a helpful error message to the user, explaining an issue such as a data validation exception. The information might also be used directly by the code to handle an error, such as retrying the web service call after a timeout exception. You will learn more about exceptions in Chapter 12, Exceptions.
Policy
Policy allows the administrator of the Dynamics GP web service to control how create, update, and delete or void operations are performed. The individual characteristics that can be controlled are called behaviors. For instance, the policy for the UpdateSalesOrder web method has a behavior that can specify how quantity shortages are to be handled for the sales order document. Your application that uses the Dynamics GP web service must retrieve and use the appropriate policies when it calls web methods that require them. The Dynamics GP web service contains special web methods that retrieve policy information for the specified web methods. You will learn more about policy in Chapter 13, Policy.
24
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 6:
Data types
Several types of data are represented in the properties defined in the objects for the Dynamics GP web service. This portion of the documentation provides details you will need to know as you work with these different data types in your own applications. The following topics are discussed: Standard data types Enumerations Account numbers Choice types
String values
String values in the Dynamics GP web service must be handled carefully to avoid truncation issues. String properties for the business documents in the Dynamics GP web service have a defined length that is detailed in the Dynamics GP Web Service Reference online documentation. Its essential that you dont exceed the stated string length for these properties. Any strings that exceed the specified length will be truncated, resulting is data corruption. No exception will be logged when a string value is truncated by the Dynamics GP web service. The empty string ("") is considered the empty value for a string property.
Integer values
The value 0 (zero) is considered the empty value for an integer property.
Decimal values
The value 0.0 is considered the empty value for a decimal property.
DateTime values
The value 1/1/1900 12:00:00am is considered the empty value for a DateTime property.
MoneyAmount values
The MoneyAmount data type maintains three pieces of data: The currency used for the amount The value of the amount (as a decimal) The number of decimal digits in the amount
The currency corresponds to the ISO code for the currency represented. Refer to Appendix B, ISO Currency Codes, for a list of the standard ISO codes used for currencies in Microsoft Dynamics GP. The value is considered empty when when the currency hasnt been specified, the decimal value is 0.0, and the number of digits is 0.
WEB
SERVICE
PROGRAMMERS
GUIDE
25
PA RT
G E TT I N G
S T A R TE D
Percent values
The Percent data type maintains two pieces of data: The value of the amount (as a decimal) The number of decimal digits in the amount
The value is considered empty when the value amount is 0.0 and the number of digits is 0.
Enumerations
To make using the Dynamics GP web service easier, several properties have enumerations (a predefined set of values) defined for them. For example, the Customer class has the StatementCycle property that defines when the customer will be billed. This property has the type StatementCycle, which is an enumeration defined by the web service. It has the following values:
Constant
No Statement Weekly Bi-Weekly Semi-Monthly Monthly Bi-Monthly Quarterly
Description
No statements sent Statements sent weekly Statements sent once every two weeks Statements sent twice each month Statements sent once each month Statements sent once every two months Statements sent once each quarter
The proxy created when the web reference for the Dynamics GP web service will contain all of the enumerations. These simplify working with these properties. For example, the following C# statement shows how the StatementCycle property can be set for a customer object.
customer.StatementCycle = DynamicsGPService.StatementCycle.Monthly;
For some properties that use an enumeration, the value of the property isnt a single value from the enumeration. Instead, it is the summation of zero or more of the values from the enumeration. For instance, the Company class has the CompanyOptions property. The CompanyOptions enumeration is used to set the value of this property. The value of the property is the sum of the enumeration items that apply to the company.
Account numbers
The format for account numbers is defined at the time Microsoft Dynamics GP is installed. The Dynamics GP web service uses the account number format that was defined. The web service will return account numbers in this format. When your web service application uses account numbers, it must supply them in the format that matches the current Microsoft Dynamics GP installation.
Refer to Chapter 9, Retrieving Objects, for information about how to retreive data from the Dynamics GP web service.
Since the account format may not be known at the time you write your application, the Dynamics GP web service includes the GetGLAccountFormatList web method to retrieve information about the account number format. This web method retrieves a collection of GLAccountFormat objects, each of which describes one segment of the account number. Examine each of these objects to determine the length of the account segment.
26
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
DA TA
T Y P E S
The separator character that appears between the segments of the account number is available from the AccountSegmentSeparator property of the Company object. Use the GetCompanyByKey method to retrieve this object. With this information, you can construct the format needed for account numbers to be processed by the web service.
Choice types
Of the data types used for the Dynamics GP web service, choice types require the most additional work to reference from your web service application. The choice type allows a single parameter to contain one of several different types of data. For instance, the FinanceCharge property for a customer is of type MoneyPercentChoice. It can contain either a money value or a percent value. When you look at the MoneyPercentChoice in the generated proxy, you will see that that it apprears with a single Item property, which has the type Object.
The MoneyPercentChoice type has only one property, which is named Item.
When your code reads the value of a parameter that uses the choice type, it must determine what type of value to read. When your code writes a choice parameter, it must specify which type of data it is writing. You can get this type information from the generated proxy code, or from the WSDL file for the Dynamics GP web service. In Visual Studio 2005 or later, you can double-click the Item property in the Object Browser to view its implementation details in the generated proxy. The following is the generated code for the MoneyPercentChoice type in the proxy for the Dynamics GP web service:
public partial class MoneyPercentChoice { private object itemField; [System.Xml.Serialization.XmlElementAttribute("Amount", typeof(MoneyAmount))] [System.Xml.Serialization.XmlElementAttribute("Percent", typeof(Percent))] public object Item { get { return this.itemField; } set { this.itemField = value; } } }
Notice in the XML serialization that the type for the Item property can be MoneyAmount or Percent, which are standard types for the Dynamics GP web service.
WEB
SERVICE
PROGRAMMERS
GUIDE
27
PA RT
G E TT I N G
S T A R TE D
28
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 7:
Context
The Context object is used for every web service method in the Dynamics GP web service. It provides important details that specify how the web service call should be performed. Information about the Context object is divided into the following sections: Organization key Culture Currency Role key WorkOnBehalfOf
Organization key
The organization key property of the Conext object specifies the company in Microsoft Dynamics GP that the web service method should be performed in. Specifying the company allows the web service to perform requests in the correct company database in SQL Server. The value corresponds to the numeric Company ID value in Microsoft Dynamics GP. The following C# example demonstrates setting the OrganizationKey property.
// Create a context with which to call the web service context = new Context(); // Specify which company companyKey = new CompanyKey(); companyKey.Id = 1; // Set up the context context.OrganizationKey = companyKey;
If the web method is to be performed in the context of the system (DYNAMICS database) then the OrganizationKey should be set to null.
Culture
The Culture property of the Context object is optional. It is a string property that specifies the culture (locale) of the user who is making the web service call. Based on the locale specified, the web service could return values in a format specific to that locale. Refer to Appendix A, Culture Codes, for a list of the culture codes.
Currency
The Currency property of the Context object specifies how currency information is be be handled for the web service call. The following options are available:
Constant
Transactional Local
Description
The transaction currency (originating) amount will be used. The local currency (functional) amount will be used.
This property is used only for documents that support multicurrency. If multicurrency isnt supported for a document, the Local (functional) currency amount will be used.
WEB
SERVICE
PROGRAMMERS
GUIDE
29
PA RT
G E TT I N G
S T A R TE D
Role key
The role key property of the Context object is optional. If supplied, the role specified will be used to choose the policy instance and appropriate behavior options for the web service call. If you dont supply a role key, the Dynamics GP web service will attempt to find a role for the user and company specified in the context object. If only one role can be found, that role will be used. If more than one role is found, or no roles are found, the default role will be used.
WorkOnBehalfOf
The WorkOnBehalfOf property of the Context object is used in the special cases where one user is running the web service methods, but the security privileges for a second user should be used. The WorkOnBehalfOf property will be set to the login name for this second user. For typical web service calls, you shouldnt set this property. It should be set only in the special cases where one web service user is performing actions on behalf of a different user. The value for the property will have the following form: DOMAIN\USERNAME or COMPUTERNAME\USERNAME Refer to Working on behalf of another user on page 81 for more details about the special situations where the property is used.
30
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
32
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 8:
Creating Objects
The Dynamics GP web service allows new objects to be created in Dynamics GP. Information about creating objects is divided into the following sections: Create methods Create policy
Create methods
The Create web methods add new data to Dynamics GP. Create methods use objects to specify the type of data being created and the values to be saved. To create an object, use the following basic steps: Instantiate an object of the type to be created. Populate the objects properties with values. All required properties must be assigned a value. All non-required properties that are not populated will receive a default value when the Create method is run. The required properties for each object are indicated in bold in the Microsoft Dynamics GP Web Service Reference online help file. Create a policy object for the create operation. A policy object provides additional control for the create operation. You will learn more about the policies in Create policy on page 34. Use the object as a parameter for the Create method.
The following example demonstrates creating a new vendor. The vendor object requires a vendor key to uniquely identify this vendor. Notice how a vendor key object is created and used to populate the required property. The Name property is also populated. The vendor objects remaining properties will use default values. The vendor object is then passed as the first parameter to the CreateVendor method. The CreateVendor method also requires context and policy objects to be created and passed as the second and third parameters. Notice how the GetPolicyByOperation method instantiates the vendorPolicy object and retrieves the policy for the operation. The CreateVendor parameter specifies the default create policy for a vendor object. GetPolicyByOperation also requires a context object for its second parameter.
using System; using System.Collections.Generic; using System.Text; using DynamicsGPWebServiceSample.DynamicsGPService; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context;
WEB
SERVICE
PROGRAMMERS
GUIDE
33
PA RT
U S I N G
T H E
W E B
S ER V I C E
Vendor vendor; VendorKey vendorKey; Policy vendorPolicy; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Be sure the default credential are used wsDynamicsGP.UseDefaultCredentials = true; // Create a context object with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context context.OrganizationKey = companyKey; context.CultureName = "en-US"; // Create a new vendor key vendorKey = new VendorKey(); vendorKey.Id = "TstVndr0001"; // Populate the vendor object vendor = new Vendor(); vendor.Key = vendorKey; vendor.Name = "TestVendor0001"; // Get the create policy for the vendor vendorPolicy = wsDynamicsGP.GetPolicyByOperation("CreateVendor", context); // Create the vendor wsDynamicsGP.CreateVendor(vendor, context, vendorPolicy); } } }
Create policy
Refer to Chapter 13, Policy, for more information about using policies.
A Create method requires an instance of the create policy for the object being created. The create policy contains a set of behaviors that control various aspects of the create operation, such as how certain properties will be set, or whether additional actions will be performed. The web service administrator controls all of the internal behavior options throught the Dynamics Security console. The external behaviors can be set by the application that is calling the create method. When you call a Create method for the Dynamics GP service, you must retrieve an instance of the policy used for that method. Do this using either the GetPolicyByOperation web method or the GetPolicyByKey web method. If the context object you pass to either method specifies a valid role for the user, the policy that is configured for that role will be returned. Otherwise, the default policy for the operation will be returned.
34
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
C R EA T I N G
O B J E C T S
Once the policy for the create operation has been retrieved, any external behaviors for the policy can be changed, if needed. The policy object will be passed to the web service Create method. In the following C# example, a new GL transaction is created. The policy for the CreateGLTransaction web method is retrieved. One behavior for this policy controls whether a reversing transaction is also created. The ID (GUID) for this behavior is looked up from the Dynamics GP Web Service Reference and used to locate the behavior. The behavior option specifying that a reversing transaction should be created is also looked up in the reference. The parameter for this behavior option is set to the reversing transaction date. Finally, the selected option for the behavior is set to the option to create the reversing transaction.
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using DynamicsGPWebServiceSample.DynamicsGPService; using System.Xml; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; BatchKey batchKey; GLTransactionKey transactionKey; GLTransaction transaction; GLTransactionLineKey glTransactionLineKey; GLTransactionLine transactionDebitLine; GLTransactionLine transactionCreditLine; GLAccountNumberKey debitAccountKey; GLAccountNumberKey creditAccountKey; MoneyAmount debitAmount; MoneyAmount creditAmount; MoneyAmount zeroAmount; Policy transactionCreatePolicy; Behavior reversingTrxBehavior; BehaviorOption reversingTrxBehaviorOption; Guid behaviorGUID; int behaviorOptionID; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Be sure the default credentials are used wsDynamicsGP.UseDefaultCredentials = true; // Create a context with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1);
WEB
SERVICE
PROGRAMMERS
GUIDE
35
PA RT
U S I N G
T H E
W E B
S ER V I C E
// Set up the context object context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Create a batch key object to specify the batch batchKey = new BatchKey(); batchKey.Id = "RMCSH00000011"; // Create a GL transaction key object to identify the transaction transactionKey = new GLTransactionKey(); transactionKey.JournalId = 3372; transactionKey.Date = new DateTime(2007, 4, 12); // Create the transaction object transaction = new GLTransaction(); // Populate the GL transaction object's key property transaction.Key = transactionKey; // Populate the batch key and reference properties transaction.BatchKey = batchKey; transaction.Reference = "Receivables Cash Receipts"; // Create a GL transaction line key glTransactionLineKey = new GLTransactionLineKey(); // Create two GL transaction lines: // Create the debit transaction line transactionDebitLine = new GLTransactionLine(); // Populate the transaction line key transactionDebitLine.Key = glTransactionLineKey; // Create a GL account number key object to specify the account debitAccountKey = new GLAccountNumberKey(); debitAccountKey.Id = "000-1100-00"; // Populate the debit line GL account key property transactionDebitLine.GLAccountKey = debitAccountKey; // Create a money object zeroAmount = new MoneyAmount(); zeroAmount.Value = 0m; zeroAmount.Currency = "USD"; // Create a money object for the debit amount debitAmount = new MoneyAmount(); debitAmount.Value = 500m; debitAmount.Currency = "USD"; // Populate the transaction line debit and credit amounts transactionDebitLine.DebitAmount = debitAmount; transactionDebitLine.CreditAmount = zeroAmount; // Create the credit transaction line transactionCreditLine = new GLTransactionLine();
36
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
C R EA T I N G
O B J E C T S
// Populate the transaction line key transactionCreditLine.Key = glTransactionLineKey; // Create a GL account number key object to specify the account creditAccountKey = new GLAccountNumberKey(); creditAccountKey.Id = "000-1200-00"; // Populate the credit line GL account key property transactionCreditLine.GLAccountKey = creditAccountKey; // Create a money amount object for the credit creditAmount = new MoneyAmount(); creditAmount.Value = 500m; creditAmount.Currency = "USD"; // Populate the transaction line debit and credit amounts transactionCreditLine.DebitAmount = zeroAmount; transactionCreditLine.CreditAmount = creditAmount; // Create an array to hold the two GL transaction line objects GLTransactionLine[] lines = { transactionDebitLine, transactionCreditLine }; // Add the array of GL transaction line objects to the transaction transaction.Lines = lines; // Get the create policy for GL transactions transactionCreatePolicy = wsDynamicsGP.GetPolicyByOperation( "CreateGLTransaction", context); // Find the behavior in the list (from Web Service Reference) behaviorGUID = new Guid("b0c9fe57-c4f0-4d6a-b0aa-ab4d6d7596c8"); reversingTrxBehavior = new Behavior(); foreach (Behavior b in transactionCreatePolicy.Behaviors) { if (b.Key.Id == behaviorGUID) { // Behavior was found reversingTrxBehavior = b; break; } } // Set the parameter (reversing date) for the behavior option DateTime reversingTrxDate; reversingTrxDate = new DateTime(2007, 5, 31); // Find the behavior option (from Web Service Reference) behaviorOptionID = 2; reversingTrxBehaviorOption = new BehaviorOption(); foreach (BehaviorOption bo in reversingTrxBehavior.Options) { if (bo.Key.Id == behaviorOptionID) { // Behavior option was found reversingTrxBehaviorOption = bo; break; } }
WEB
SERVICE
PROGRAMMERS
GUIDE
37
PA RT
U S I N G
T H E
W E B
S ER V I C E
// Set the reversing date for the behavior option reversingTrxBehaviorOption.Parameters[0].Value = reversingTrxDate.ToShortDateString(); // Set selected behavior option to create a reversing transaction reversingTrxBehavior.SelectedOption = reversingTrxBehaviorOption; // Create the GL transaction wsDynamicsGP.CreateGLTransaction(transaction, context, transactionCreatePolicy); } } }
38
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 9:
Retrieving Objects
An individual object or list of objects can be retrieved through the Dynamics GP web service. The objects returned by the web service will be populated with data from Microsoft Dynamics GP. Information about retrieving objects is divided into the following sections: Retrieve methods Individual objects Lists of objects Restriction reference
Retrieve methods
There are two ways to retrieve objects from the Dynamics GP web service. Objects can be retrieved individually or as a list. When objects are retrieved individually, you must specify the unique key value for the object you want to retrieve. The GetByKey web methods in the Dynamics GP web service are used to retrieve individual objects. When objects are returned as a list, you will supply a set of criteria that indicate which objects you want to retrieve. The Dynamics GP web service has criteria objects that you will use to specify criteria. The GetList web methods in the Dynamics GP web service are used to retrieve lists of objects. Individual objects in the Dynamics GP web service can contain a significant amount of data. When a list of objects is retrieved from the web service, a large amount of data would need to be returned. A summary object contains the most important details of the main object. For example, the CustomerSummary object contains the important details of a Customer object. To speed the request for a list of objects, the summary version of the object is returned by most of the GetList web methods in the Dynamics GP web service. For some of the smaller objects, the corresponding GetList methods return the actual objects in the list.
Individual objects
A GetByKey web method returns a single object specified by a key. You will create an instance of the key object for the type of object you want to retrieve. The key objects identification property must be set to the value that uniquely identifies the object to be retrieved. The following example demonstrates retrieving a customer object. Notice how the customer key object is created and its Id property populated with a specific customer ID value. The customer key object is then passed as the first parameter to the GetCustomerByKey method. The GetCustomerByKey method also requires a context object to be created and passed as the methods second parameter.
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using DynamicsGPWebServiceSample.DynamicsGPService;
WEB
SERVICE
PROGRAMMERS
GUIDE
39
PA RT
U S I N G
T H E
W E B
S ER V I C E
namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; Customer customer; CustomerKey customerKey; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Be sure that default credentials are being used wsDynamicsGP.UseDefaultCredentials = true; // Create a context with which to call the web service context = new Context(); // Specify which company to use (lesson company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Create a customer key customerKey = new CustomerKey(); customerKey.Id = "AARONFIT0001"; // Retrieve the customer object customer = wsDynamicsGP.GetCustomerByKey(customerKey, context); MessageBox.Show(customer.Name); } } }
If the object specified cannot be found, the Dynamics GP web service will raise a Business object not found. exception. You may want to trap for this exception in in your code and display an appropriate message for the user.
Lists of objects
A GetList web method returns a collection of summary objects, or in certain special cases, the collection of objects themselves. The content of the list is controlled by a criteria object. The list will contain only summary objects that meet the restrictions set by the criteria object. By default, only the first 1000 items that meet the specified criteria will be returned in the list. This limit prevents the web service from being overloaded by a query that returns an extremely large collection.
40
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
R ET R I EV IN G
O B J E C T S
List examples
GetList method Example 1
The following example demonstrates how to retrieve a list of vendor summaries. The vendor summary list produced by the example contains only vendors with the specified vendor class property. Notice how the object named classIdRestriction of the LikeRestrictionOfString class is used to specify the vendor class name. The classIdRestriction object is then used to populate the ClassId property of the vendor criteria object named vendorCriteria. The vendorCriteria object is passed as the first parameter in the GetVendorList method. The GetVendorList method also requires a context object to be created and passed as the methods second parameter.
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using DynamicsGPWebServiceSample.DynamicsGPService; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; VendorCriteria vendorCriteria; VendorSummary[] vendorSummaryList; LikeRestrictionOfString classIdRestriction; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Be sure that default credentials are being used wsDynamicsGP.UseDefaultCredentials = true; // Create a context object with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1);
WEB
SERVICE
PROGRAMMERS
GUIDE
41
PA RT
U S I N G
T H E
W E B
S ER V I C E
// Set up the context object context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Specify the criteria for the vendor summaries to retrieve classIdRestriction = new LikeRestrictionOfString(); classIdRestriction.EqualValue = "USA-US-I"; // Create a vendor criteria object and set the restriction vendorCriteria = new VendorCriteria(); vendorCriteria.ClassId = classIdRestriction; // Retrieve the list of vendor summaries vendorSummaryList = wsDynamicsGP.GetVendorList(vendorCriteria, context); MessageBox.Show("Total vendors in class: " + vendorSummaryList.Length); } } }
The following example demonstrates how to retrieve a list of vendor summaries that were modified during a specific time period. Notice how the object named modifiedDateRestriction of the BetweenRestrictionOfNullableOfDateTime class is used to specify the time period to be examined. The ModifiedDate property of the criteria object requires that both the date and time portion of the value be specified. The values for this criteria property must also be converted to Universal Coordinated Time (UTC). The modifiedDateRestriction object is then used to populate the ModifiedDate property of the vendor criteria object named vendorCriteria. The vendorCriteria object is passed as the first parameter in the GetVendorList method. The GetVendorList method also requires a context object to be created and passed as the methods second parameter.
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using DynamicsGPWebServiceSample.DynamicsGPService; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; VendorCriteria vendorCriteria; VendorSummary[] vendorSummaryList; BetweenRestrictionOfNullableOfDateTime modifiedDateRestriction; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP();
42
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
R ET R I EV IN G
O B J E C T S
// Make sure that default credentials are being used wsDynamicsGP.UseDefaultCredentials = true; // Create a context object with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context object context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Specify the criteria for the vendor summaries to retrieve modifiedDateRestriction = new BetweenRestrictionOfNullableOfDateTime(); DateTime startDate = new DateTime(2007, 4, 9, 8, 0, 0).ToUniversalTime(); DateTime endDate = new DateTime(2007, 4, 9, 17, 0, 0).ToUniversalTime(); modifiedDateRestriction.From = startDate; modifiedDateRestriction.To = endDate; vendorCriteria = new VendorCriteria(); vendorCriteria.ModifiedDate = modifiedDateRestriction; // Retrieve the list of vendor summaries vendorSummaryList = wsDynamicsGP.GetVendorList(vendorCriteria, context); MessageBox.Show("Total vendors modified today: " + vendorSummaryList.Length); } } }
WEB
SERVICE
PROGRAMMERS
GUIDE
43
PA RT
U S I N G
T H E
W E B
S ER V I C E
Restriction reference
Several types of restrictions used with criteria objects. Some restriction types correspond to the various types of data, such as string values, integers, and booleans. Other restriction types are based on how the restriction is structured. For instance a list restriction specifies a collection of possible values for a property. The restriction types are part of a hierarchy, with more complex restriction types being constructed from the simpler types. All restriction objects derive from the Restriction class in the Dynamics GP web service.
Basic restrictions
The most basic restriction contains a single value of a specific type. These restrictions have a name with the form: RestrictionOfNullableOfType Some restrictions of this type are for primitive types. For example the restriction RestrictionOfNullableOfInt32 represents a single integer value. Other restrictions of this type represent a single instance of a more complex piece of information. For instance, the restriction RestrictionOfNullableOfSalesDocumentType represents a single type of sales document. The following C# example shows how to create and use a basic restriction for a criteria object. This example creates a boolean restriction for the IsOnHold property of the customer criteria object.
CustomerCriteria customerCriteria; RestrictionOfNullableOfBoolean onHoldRestriction; onHoldRestriction = new RestrictionOfNullableOfBoolean(); onHoldRestriction.EqualValue = true; customerCriteria = new CustomerCriteria(); customerCriteria.IsOnHold = onHoldRestriction;
List restrictions
The list restrictions specify a distinct set of values. These restrictions have a name with the form: ListRestrictionOfNullableOfType Like the basic restrictions, some of these list restrictions are for primitive types and others for more complex types. List restrictions represent a distinct set of values of the specific types. The following C# example shows how to create and use a list restriction for a criteria object. This example creates a list restriction for the Type property of the item criteria object. The restriction contains a list of two item types, for Service and SalesItem. Notice how an array is created that contains the two possible values for the list restriction.
44
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
R ET R I EV IN G
O B J E C T S
ItemCriteria itemCriteria; ListRestrictionOfNullableOfItemType typeRestriction; ItemType?[] itemTypes; typeRestriction = new ListRestrictionOfNullableOfItemType(); itemTypes = new ItemType?[2]; itemTypes[0] = ItemType.Service; itemTypes[1] = ItemType.SalesItem; typeRestriction.Items = itemTypes; itemCriteria = new ItemCriteria(); itemCriteria.Type = typeRestriction;
Between restrictions
The between restrictions specify a range of values. You can specify a GreaterThan value, a LessThan value, or From and To values to specify a range. These restrictions have a name with the form: BetweenRestrictionOfNullableOfType The between restrictions are available only for primitive types, like date/time or string values. The following C# example shows how to create and use a between restriction for a criteria object. This example creates a between restriction for the Date property of a GL transaction criteria object. The property is set to a range between April 25, 2007 and April 26, 2007.
GLTransactionCriteria transactionCriteria; BetweenRestrictionOfNullableOfDateTime dateRestriction; dateRestriction = new BetweenRestrictionOfNullableOfDateTime(); DateTime startDate = new DateTime(2007, 4, 25); DateTime endDate = new DateTime(2007, 4, 26); dateRestriction.From = startDate; dateRestriction.To = endDate; transactionCriteria = new GLTransactionCriteria(); transactionCriteria.Date = dateRestriction;
Like restriction
String properties for criteria object have unique behavior. A Like expression, similar to those used in Transact-SQL can be used to define the restriction. The LikeRestrictionOfString restriction inherits from the between and list restriction types, so restrictions of this type can also be used as well. The following C# example shows how to create and use a Like restriction for a string property of a criteria object. This example creates a restriction for the State property of the customer criteria object. Notice how the Like clause is used to specify customers from the state ND.
CustomerCriteria customerCriteria; LikeRestrictionOfString stateRestriction; stateRestriction = new LikeRestrictionOfString(); stateRestriction.Like = "%ND%"; customerCriteria = new CustomerCriteria(); customerCriteria.State = stateRestriction;
WEB
SERVICE
PROGRAMMERS
GUIDE
45
46
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 10:
Updating Objects
The Dynamics GP web service can be used to change the values of individual properties for existing objects in Dynamics GP. Information about updating objects is divided into the following sections: Update methods Update policy Concurrency
Update methods
The Update web methods are used to change the values of an existing objects properties. Most updates can be performed using the following steps: Instantiate an object of the type to be updated. Create and set the key value for the object being updated. Populate only the properties that are to be updated. Create a policy object for the update operation. A policy object provides additional control for the update operation. You will learn more about the policies in Update policy on page 50. Use the object as a parameter for the Update method.
The following example demonstrates updating a vendor object. Notice how the vendor key objects Id property is populated with the ID of an existing vendor. A new vendor object will use this vendor key to specify which vendor to update. A value is supplied for the vendor objects Name property. The vendor object is then passed as the first parameter of the UpdateVendor method. The UpdateVendor method also requires context and policy objects to be created and passed as the second and third parameters. Notice how the GetPolicyByOperation method instantiates the vendorPolicy object. The UpdateVendor parameter specifies the default update policy for a vendor object. GetPolicyByOperation also requires a context object for its second parameter.
using System; using System.Collections.Generic; using System.Text; using DynamicsGPWebServiceSample.DynamicsGPService; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; VendorKey vendorKey;
WEB
SERVICE
PROGRAMMERS
GUIDE
47
PA RT
U S I N G
T H E
W E B
S ER V I C E
Vendor vendor; Policy vendorPolicy; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Make sure the default credentials are being used wsDynamicsGP.UseDefaultCredentials = true; // Create a context object with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context context.OrganizationKey = companyKey; context.CultureName = "en-US"; // Specify the vendor to be updated vendorKey = new VendorKey(); vendorKey.Id = "ACETRAVE0001"; // Create the vendor object and set the value of // the field to be updated vendor = new Vendor(); vendor.Name = "A Travel Company, Inc."; vendor.Key = vendorKey; // Get the update policy for vendor vendorPolicy = wsDynamicsGP.GetPolicyByOperation("UpdateVendor", context); // Update the vendor information wsDynamicsGP.UpdateVendor(vendor, context, vendorPolicy); } } }
When performing an update on a sales document (backorder, fulfillment order, invoice, order, quote, or return), the object must first be populated by a retrieve method. Retrieving the object ensures no data fields will be lost when the update is completed. The following example demonstrates how to update a sales return object. Notice how the sales document key object specifies the sales document to be updated. The GetSalesReturnByKey method uses the key object along with a context object to return the specified sales return object. The sales return objects Comment property is populated with a new value. The update occurs when the sales return object is passed as the first parameter to the UpdateSalesReturn method. The UpdateSalesReturn method also requires context and policy objects to be created and passed as the second and third parameters.
48
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A PT E R
1 0
U P D A T I N G
O B J E C T S
Notice how the GetPolicyByOperation method instantiates the salesReturnPolicy object with the default policy for updating sales returns.
using System; using System.Collections.Generic; using System.Text; using DynamicsGPWebServiceSample.DynamicsGPService; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Be sure that default credentials are used wsDynamicsGP.UseDefaultCredentials = true; // Create a context with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context object context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Set up a policy object Policy salesReturnPolicy = wsDynamicsGP.GetPolicyByOperation ("UpdateSalesReturn",context); // Create a Sales Return key SalesDocumentKey salesReturnKey = new SalesDocumentKey(); salesReturnKey.Id = "RTN10010"; // Retrieve the sales return object SalesReturn salesReturn = wsDynamicsGP.GetSalesReturnByKey (salesReturnKey, context); // Update the comment property salesReturn.Comment = "Update test comment"; // Update the sales return object wsDynamicsGP.UpdateSalesReturn(salesReturn, context, salesReturnPolicy); } } }
WEB
SERVICE
PROGRAMMERS
GUIDE
49
PA RT
U S I N G
T H E
W E B
S ER V I C E
Update policy
Refer to Chapter 13, Policy, for more information about using policies.
An Update method requires an instance of the update policy for the object being updated. The update policy contains a set of behaviors that control various aspects of the update operation, such as how certain properties will be set, or whether additional actions will be performed. The web service administrator controls all of the internal behavior options throught the Dynamics Security console. The external behaviors can be set by the application that is calling the update method. When you call an Update method for the Dynamics GP service, you must retrieve an instance of the policy used for that method. Do this using either the GetPolicyByOperation web method or the GetPolicyByKey web method. If the context object you pass to either method specifies a valid role for the user, the policy that is configured for that role will be returned. Otherwise, the default policy for the operation will be returned. Once the policy for the update operation has been retrieved, any external behaviors for the policy can be changed, if needed. The policy object will be passed to the web service Update method. In the following C# example, a quantity for a line item in a sales order document is updated. The policy for the UpdateSalesOrder web method is retrieved. One behavior for this policy controls whether promotions are to be used. The ID (GUID) for this behavior is looked up from the Dynamics GP Web Service Reference and used to locate the behavior. The behavior option that indicates that promotions should be used is located, based on the ID from the Dynamics GP Web Service Reference. The selected behavior option for the behavior is set to this specific behavior option.
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using DynamicsGPWebServiceSample.DynamicsGPService; using System.Xml; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; SalesDocumentKey salesOrderKey; SalesOrder salesOrder; Policy salesOrderUpdatePolicy; Behavior promotionBehavior; BehaviorOption includePromotionsBehaviorOption; Guid behaviorGUID; int behaviorOptionID; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Be sure the default credentials are used wsDynamicsGP.UseDefaultCredentials = true;
50
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A PT E R
1 0
U P D A T I N G
O B J E C T S
// Create a context with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context object context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Create a sales document key salesOrderKey = new SalesDocumentKey(); salesOrderKey.Id = "ORDST2227"; // Retrieve the sales order salesOrder = wsDynamicsGP.GetSalesOrderByKey(salesOrderKey, context); // Update the first line of the sales order salesOrder.Lines[0].Quantity.Value = 2; // Retrieve the update policy for sales orders salesOrderUpdatePolicy = wsDynamicsGP.GetPolicyByOperation ("UpdateSalesOrder", context); // Find the behavior in the list (from Web Service Reference) behaviorGUID = new Guid("2e58b57c-8fe1-4e98-bf04-371621f8e8b7"); promotionBehavior = new Behavior(); foreach (Behavior b in salesOrderUpdatePolicy.Behaviors) { if (b.Key.Id == behaviorGUID) { // Behavior was found promotionBehavior = b; break; } } // Find the behavior option (from Web Service Reference) behaviorOptionID = 1; includePromotionsBehaviorOption = new BehaviorOption(); foreach (BehaviorOption bo in promotionBehavior.Options) { if (bo.Key.Id == behaviorOptionID) { // Behavior option was found includePromotionsBehaviorOption = bo; break; } } // Set the selected behavior option promotionBehavior.SelectedOption = includePromotionsBehaviorOption;
WEB
SERVICE
PROGRAMMERS
GUIDE
51
PA RT
U S I N G
T H E
W E B
S ER V I C E
Concurrency
When update operations are performed, the Dynamics GP web service must handle any concurrency issues that occur. These issues happen because other users have locked the same rows in the database that the update operation is trying to change. Documents for which the Microsoft Dynamics GP client application actively locks rows, such as sales document, can produce these situations. Typically, other users in Microsoft Dynamics GP wont see concurrency issues caused by web service operations. The update operations occur quickly, and hold row locks for only the time necessary to perform the update. If a concurrency issue is caused by a Dynamics GP web service update operation, the other user affected will see the standard message displayed that indicates another user has updated a record. The most likely scenario in which a web service update operations will encounter concurrency issues occurs when the web service application is updating a large number of rows that the Microsoft Dynamics GP client can actively lock. For example, if a web service application was updating all of the sales orders created on a specific date, and other users are accessing the Microsoft Dynamics GP system, it is possible the web service application will encounter one of the sales documents being locked (in use). If this occurs, a validation exception will occur, indicating the sales order being updated was in use. Your web service code must be able to handle concurrency exceptions that occur. The following C# example demonstrates one way this can be done. This example updates the comment for all sales orders created on 4/12/07. If a concurrency exception occurs because a sales order is being edited by another user, the following message is displayed. The user can choose to try updating the sales order again, or canceling the update and moving to the next document.
In this example, a list of the sales orders for the specific date is retrieved. The comment for each of these order is updated. Note the try...catch block that handles the validation error if a concurrency issue occurs. If the user chooses to retry the update operation, the goto statement causes the update operation to be run again.
52
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A PT E R
1 0
U P D A T I N G
O B J E C T S
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using DynamicsGPWebServiceSample.DynamicsGPService; using System.Xml; using System.Web.Services.Protocols; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; BetweenRestrictionOfNullableOfDateTime transactionDateRestriction; SalesOrderCriteria salesOrderCriteria; SalesOrderSummary[] salesOrderSummary; DateTime dateValue; SalesDocumentKey salesOrderKey; SalesOrder salesOrder; Policy salesOrderUpdatePolicy; ValidationResult validationResult; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Be sure the default credentials are used wsDynamicsGP.UseDefaultCredentials = true; // Create a context with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context object context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Create a date restriction object transactionDateRestriction = new BetweenRestrictionOfNullableOfDateTime(); dateValue = new DateTime(2007, 4, 12); transactionDateRestriction.EqualValue = dateValue; // Create a sales order criteria object salesOrderCriteria = new SalesOrderCriteria(); salesOrderCriteria.Date = transactionDateRestriction; // Retrieve the sales order summaries specified by the criteria salesOrderSummary = wsDynamicsGP.GetSalesOrderList( salesOrderCriteria, context);
WEB
SERVICE
PROGRAMMERS
GUIDE
53
PA RT
U S I N G
T H E
W E B
S ER V I C E
// Retrieve the update policy for sales orders salesOrderUpdatePolicy = wsDynamicsGP.GetPolicyByOperation( "UpdateSalesOrder", context); // Update the comment for each of the documents found foreach (SalesOrderSummary a in salesOrderSummary) { // Create a sales document key salesOrderKey = new SalesDocumentKey(); salesOrderKey = a.Key; // Retrieve the sales order salesOrder = wsDynamicsGP.GetSalesOrderByKey(salesOrderKey, context); // Set the comment property salesOrder.Comment = "Customer notified - April 12"; // Update the sales order object UpdateSalesDocument: try { wsDynamicsGP.UpdateSalesOrder(salesOrder, context, salesOrderUpdatePolicy); } catch (SoapException soapErr) { if (soapErr.Detail.HasChildNodes == true) { // Create a guid for the logid value Guid guid = new Guid(soapErr.Detail.InnerText); // Get the validation result object validationResult = wsDynamicsGP. GetLoggedValidationResultByKey(guid, context); if (validationResult.Errors[0].Id == "EConnectError-2079") { // It is a concurrency error, with record in use if (MessageBox.Show(null, "Document: " + a.Key.Id + ". "Sales Document Update", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1) == DialogResult.Retry) { goto UpdateSalesDocument; } } else { // It is a different error " + validationResult.Errors[0].Message + ".",
54
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A PT E R
1 0
U P D A T I N G
O B J E C T S
WEB
SERVICE
PROGRAMMERS
GUIDE
55
56
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 11:
The following example demonstrates deleting a customer. Notice how a customer key object is created and populated with the unique ID value CONTOSO for the customer. The DeleteCustomer policy is retrieved to populate the policy object. The customer key object is passed as the first parameter to the DeleteCustomer method. The DeleteCustomer method also requires the context and policy objects to be passed as the second and third parameters.
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using DynamicsGPWebServiceSample.DynamicsGPService; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; CustomerKey customerKey; Policy customerPolicy; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Be sure that default credentials are being used wsDynamicsGP.UseDefaultCredentials = true; // Create a context with which to call the web service context = new Context();
WEB
SERVICE
PROGRAMMERS
GUIDE
57
PA RT
U S I N G
T H E
W E B
S ER V I C E
// Specify which company to use (lesson company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Create a customer key customerKey = new CustomerKey(); customerKey.Id = "CONTOSO"; // Get the delete policy for the customer customerPolicy = wsDynamicsGP.GetPolicyByOperation ("DeleteCustomer", context); // Delete the customer wsDynamicsGP.DeleteCustomer(customerKey,context,customerPolicy); } } }
A Delete or Void method requires an instance of the delete policy for the object being deleted or the void policy for the object being voided. The delete or void policy contains a set of behaviors that control various aspects of how the operation will be performed. The web service administrator controls all of the internal behavior options throught the Dynamics Security console. The external behaviors can be set by the application that is calling the delete or void method. When you call a Delete or Void method for the Dynamics GP service, you must retrieve an instance of the policy used for that method. Do this using either the GetPolicyByOperation web method or the GetPolicyByKey web method. If the context object you pass to either method specifies a valid role for the user, the policy that is configured for that role will be returned. Otherwise, the default policy for the operation will be returned. Once the policy for the delete or void operation has been retrieved, any external behaviors for the policy can be changed, if needed. The policy object will be passed to the web service Delete or Void method. In the following C# example, a sales order is deleted. The policy for the DeleteSalesOrder web method is retrieved. One behavior for this policy controls whether posted deposits will be removed. The ID (GUID) for this behavior is looked up from the Dynamics GP Web Service Reference and used to locate the behavior. The behavior option specifying that posted deposits should not be removed is also looked up in the reference. Finally, the selected option for the behavior is set to the option to not remove posted deposits.
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using DynamicsGPWebServiceSample.DynamicsGPService; using System.Xml;
58
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 1
D E L ET I N G
O R
V O I D I N G
O B J E C T S
namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; SalesDocumentKey salesOrderKey; Policy salesOrderDeletePolicy; Behavior removePostedDepositsBehavior; BehaviorOption doNotRemoveBehaviorOption; Guid behaviorGUID; int behaviorOptionID; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Be sure the default credentials are used wsDynamicsGP.UseDefaultCredentials = true; // Create a context with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context object context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Create a sales document key salesOrderKey = new SalesDocumentKey(); salesOrderKey.Id = "ORDST2226"; // Get the sales order delete policy salesOrderDeletePolicy = wsDynamicsGP.GetPolicyByOperation( "DeleteSalesOrder", context); // Find the behavior in the list (from Web Service Reference) behaviorGUID = new Guid("0f2c414b-fd12-4d83-940b-2bc0d65c3b77"); removePostedDepositsBehavior = new Behavior(); foreach (Behavior b in salesOrderDeletePolicy.Behaviors) { if (b.Key.Id == behaviorGUID) { // Behavior was found removePostedDepositsBehavior = b; break; } } // Find the behavior option (from Web Service Reference) behaviorOptionID = 0;
WEB
SERVICE
PROGRAMMERS
GUIDE
59
PA RT
U S I N G
T H E
W E B
S ER V I C E
doNotRemoveBehaviorOption = new BehaviorOption(); foreach (BehaviorOption bo in removePostedDepositsBehavior.Options) { if (bo.Key.Id == behaviorOptionID) { // Behavior option was found doNotRemoveBehaviorOption = bo; break; } } // Set selected behavior option to create a reversing transaction removePostedDepositsBehavior.SelectedOption = doNotRemoveBehaviorOption; // Delete the specified sales order wsDynamicsGP.DeleteSalesOrder(salesOrderKey, context, salesOrderDeletePolicy); } } }
60
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 12:
Exceptions
The Dynamics GP web service returns errors as SOAP exceptions. The web service classifies SOAP exception as either system exceptions or validation exceptions. System exceptions are events that prevent normal completion of web service methods. Validation exceptions occur when data passed into a web service method violates the data validation rules for an object. The web service maintains an exception log that contains detailed information for each exception that occurs. You can view the exception log entries to help you troubleshoot problems encountered by web service methods. Web methods also provide access to validation exception log entries so they can be handled or displayed by the application calling the web service. Information about exceptions is divided into the following sections: Exceptions console System exceptions Validation exceptions
Exceptions console
To view exceptions that have been logged, you can use the Dynamics GP Web Services Exceptions console. This is a snap-in for Microsoft Management Console (MMC) that retrieves and displays the exceptions logged by the Dynamics GP web service. The console is shown in the following illustration.
WEB
SERVICE
PROGRAMMERS
GUIDE
61
PA RT
U S I N G
T H E
W E B
S ER V I C E
Some exceptions will have additional details that you can view when you click the View Exception Detail button. Use the additional information provided, such as the messages and stack trace, to help you determine what caused the exception to occur.
There may be several levels of inner-exception details that you can drill down into. Be sure to examine all of the levels for useful troubleshooting details. You can click View Request XML to see the complete XML message that was sent to the web service to be processed.
62
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 2
EX C E P T IO N S
Click View Validation Results to see further details about the validation error and validation warnings that were logged. This additional detail can help you determine what validation rules have been broken.
WEB
SERVICE
PROGRAMMERS
GUIDE
63
PA RT
U S I N G
T H E
W E B
S ER V I C E
System exceptions
A system exception occurs when an unexpected event prevents the normal completion of a web method. The web service returns a SOAP exception to indicate the error occurred, and logs the details in the exception log. To improve security, a generic system exception message will be returned, telling the user to contact the system administrator for more details about the error. The details of the exception must be examined by the web service administrator.
A logged data exception object represents a system exception. The GetLoggedExceptionDataByKey method uses the exceptions log ID to retrieve a logged data exception object. The GetLoggedExceptionDataList method returns a list of logged exception summary objects. The method returns the list of exceptions logged during a specified time period.
Validation exceptions
A validation exception occurs when an object contains data that violates the web services data validation rules. A validation result object contains the detailed exception information from the exception log. Your application that uses the Dynamics GP web service can trap these validation exceptions, and display an appropriate message describing the validation issues. The following example demonstrates catching and retrieving a validation exception. Notice how the vendor object and the UpdateVendor method creates data that causes two validation exceptions. The try/catch block traps and handles the SOAP exception. The System.Web.Services.Protocols namespace is referenced so that the SoapException class is available to the code. The SOAP exception contains an ID which identifies the exception in the web service exception log. The GetLoggedValidationResultByKey method retrieves the validation result object for the specified log ID. The GetLoggedValidationResultByKey method also requires a context object to be passed as the second parameter.
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Web.Services.Protocols; using DynamicsGPWebServiceSample.DynamicsGPService; namespace DynamicsGPWebServiceSample { class Program {
64
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 2
EX C E P T IO N S
static void Main(string[] args) { CompanyKey companyKey; Context context; VendorKey vendorKey; Vendor vendor; Policy policy; ValidationResult validationResult; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Make sure that default credentials are being used wsDynamicsGP.UseDefaultCredentials = true; // Create a context with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Create a vendor key of the vendor to be updated vendorKey = new VendorKey(); vendorKey.Id = "ACETRAVE0001"; // Create a vendor object vendor = new Vendor(); vendor.Key = vendorKey; // Set a pair of properties to create two validation errors vendor.DiscountGracePeriod = 100; vendor.DueDateGracePeriod = 100; try { // Create a policy object policy = wsDynamicsGP.GetPolicyByOperation ("UpdateVendor", context); // Attempt to update the vendor wsDynamicsGP.UpdateVendor(vendor, context, policy); } catch(SoapException soapErr) { // If a validation exception occurred, the logid will // be in a child node if(soapErr.Detail.HasChildNodes == true) { // Create a guid for the logid value in the soap exception Guid guid = new Guid(soapErr.Detail.InnerText);
WEB
SERVICE
PROGRAMMERS
GUIDE
65
PA RT
U S I N G
T H E
W E B
S ER V I C E
// Get the validation result object validationResult = wsDynamicsGP. GetLoggedValidationResultByKey(guid, context); // Display the number of validation exceptions MessageBox.Show("Number of validation exceptions: " + validationResult.Errors.Length.ToString()); } } } } }
66
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 13:
Policy
Policy is a security-related feature for the Dynamics GP web service. The policy system allows the web service administrator and the application using the web service to control how business objects are created, updated, or deleted. Information about policy is divided into the following sections: Policy overview Configuring from the Dynamics Security Console Configuring from code Using policy in a web service application
Policy overview
Each create, update, and delete web service operation has a policy object that is passed with the operation. This policy object specifies the set of behaviors for the operation. Each behavior controls one characteristic for the operation being performed. For instance, the policy for the CreateCustomer web method has the behavior named Create Active Behavior. This behavior controls whether the customer being created is set to the active or inactive state. Behaviors are classified as internal or external. An internal behavior is one that can be specified by only the web service administrator. An external behavior is one that can be specified by the application that is calling the web method and passing in the policy object. Some policies do not have any behaviors, but the policy object must still be passed with the call to the web service operation.
Policy instances
Each company has a set of default policies that are always available. There is one default policy for each web service operation that requires a policy. Within a company, additional versions of the policy (with different behavior settings) can be created for each role defined in the Dynamics Security Service. Each of these is called a policy instance. When a web service application retrieves a policy to use, the Dynamics GP web service applies logic to ensure the appropriate policy instance is returned. You will learn more about this in Using policy in a web service application on page 69.
Policy reference
The Dynamics GP Web Service Reference help file contains a complete list of the default policies that are defined for the operations in the web service. All of the behaviors (including internal and external) are listed, including a description of what the behavior does.
WEB
SERVICE
PROGRAMMERS
GUIDE
67
PA RT
U S I N G
T H E
W E B
S ER V I C E
Information about configuring policy using this console can be found in the Web Services for Microsoft Dynamics GP Installation and Administration Guide.
68
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 3
P O LI C Y
Typically, policy instances for the various web service roles are managed using the Policy node in the Dynamics Security Console.
Which you choose depends on whether you prefer to have GUIDs in your code that identify policies, or string values for operation names. When a web service application retrieves the policy instance, the appropriate one will be returned, based on the context object that was used. The policy information will come from the company specified by the context object. If the context object has a role specified, the policy instance defined for that role will be returned. If no policy instance exists for that role within the specified company, the default policy for that operation will be returned. If you dont supply a role key, the Dynamics GP web service will attempt to find a role for the user and company specified in the context object. If only one role can be found, that role will be used. If more than one role is found, or no roles are found, the default role will be used. If you want to use a policy instance for a specific role, be sure that you specify the role key for the context object. Otherwise, its best to leave the role key property empty. This allows the web service administrator to control which policy instances are used based on the role a user is assigned to.
WEB
SERVICE
PROGRAMMERS
GUIDE
69
PA RT
U S I N G
T H E
W E B
S ER V I C E
You will need to use the Dynamics GP Web Service Reference to find the GUID value that identifies the behavior you want to set. The reference will also provide the ID of the behavior option you want to use. For example, the following mutlipart C# example demonstrates how the Create Reversing Transaction behavior for the Create GL Transaction policy is used. First, the behavior is found within the policy instance:
Policy transactionCreatePolicy; Behavior reversingTrxBehavior; Guid behaviorGUID; BehaviorOption reversingTrxBehaviorOption; int behaviorOptionID; // Get the create policy for GL transactions transactionCreatePolicy = wsDynamicsGP.GetPolicyByOperation( "CreateGLTransaction", context); // Find the behavior in the list (from Web Service Reference) behaviorGUID = new Guid("b0c9fe57-c4f0-4d6a-b0aa-ab4d6d7596c8"); reversingTrxBehavior = new Behavior(); foreach (Behavior b in transactionCreatePolicy.Behaviors) { if (b.Key.Id == behaviorGUID) { // Behavior was found reversingTrxBehavior = b; break; } }
The next portion of the C# code demontrates how the behavior option to create a reversing transaction is found:
// Find the behavior option (from Web Service Reference) behaviorOptionID = 2; reversingTrxBehaviorOption = new BehaviorOption(); foreach (BehaviorOption bo in reversingTrxBehavior.Options) { if (bo.Key.Id == behaviorOptionID) { // Behavior option was found reversingTrxBehaviorOption = bo; break; } }
70
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 3
P O LI C Y
Some behavior options have a parameter that can be set. In this case, the date of the reversing transaction can be set. The next portion of the C# code shows how the parameter for the reversing date is set:
// Set the reversing date for the behavior option reversingTrxBehaviorOption.Parameters[0].Value = reversingTrxDate.ToShortDateString();
Finally, the selected behavior option must be set for the behavior. The remainder of the C# code shows how the selected behavior is set for the Create Reversing Transaction behavior:
// Set selected behavior option to create a reversing transaction reversingTrxBehavior.SelectedOption = reversingTrxBehaviorOption;
The policy instance for the Create GL Transaction policy is ready to be passed to the CreateGLTransaction web method.
WEB
SERVICE
PROGRAMMERS
GUIDE
71
72
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 14:
Entity ID Filtering
Several objects in Dynamics GP have identity information associated with them. Examples include the Customer ID for customer objects, or the Salesperson ID for sales document objects. The Dynamics GP web service can use entity ID filtering to restrict access to these objects, based on the Windows User ID of the person accessing the web service. Information about entity ID filtering is divided into the following sections: Setting up entity ID filtering Security for entity ID filtering Implementing entity ID filtering Filtering limitations Entity ID filtering example
These objects are referred to as user-assignable business objects. Administrators of the Dynamics GP web service use the Microsoft Dynamics Security Administration Console to create entity ID assignments. These assign Windows User IDs to specific objects in Microsoft Dynamics GP. For example, the following illustration shows the entity ID assignment that assigns the Windows user CORPORATE\imarsh to the salesperson object in Microsoft Dynamics GP with the ID value IAN M..
Applications that access the Dynamics GP web service can use these entity ID assignments when retrieving data. When applied, the user will be able retrieve only those objects for which their Windows User ID is associated. For instance, the user can be restricted to retrieve sales documents where the primary Salesperson ID for the document is associated with the users Windows User ID.
WEB
SERVICE
PROGRAMMERS
GUIDE
73
PA RT
U S I N G
T H E
W E B
S ER V I C E
Yes
No
No
Access is denied.
Yes
No
Yes
No
Yes
Operation is performed.
74
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
When entity ID filtering is used for GetList operations, the Scope property of the criteria used for the operation also affects what values are returned. You will learn more about using the Scope property in Implementing entity ID filtering on page 75. The following diagram shows how the Scope property and security settings for entity ID filtering control access for a GetList operation in the Dynamics GP web service:
Application calls GetList
No
Was the Scope property supplied and set to a value other than All?
Yes
Access is denied.
No
No
Access is denied.
Yes
Yes
No
Yes
Operation is performed.
WEB
SERVICE
PROGRAMMERS
GUIDE
75
PA RT
U S I N G
T H E
W E B
S ER V I C E
For example, the CustomerCriteria object supports entity ID filtering, so it contains the Scope property. This property can be set to Return All to return all customers. It can be set to Return Based on Customer Id to return the customer with an ID that matches the Customer ID assigned to the current user. It can also be set to Return Based on Salesperson Id to return the customers that have the Salesperson ID that matches the Salesperson ID assigned to the current user. If a Windows User ID is assigned to multiple entity IDs in Microsoft Dynamics GP, the GetList operation will return values for each of the entities that are mapped. If you use the entity ID filtering for GetList operations, be sure to handle the access denied exceptions that can occur if the web service administrator hasnt given access to the proper roles. Be sure to document the restricted operations that are required for your application. Its a good idea to test your web service applications with the roles that provide full access to web service operations and also the restricted roles that implement the entity ID filtering. If your application uses the WorkOnBehalfOf property for the Context object, be aware that this changes the user for entity ID filtering. The WorkOnBehalfOf user, not the user running the application, will be used for the entity ID filtering.
Filtering limitations
The entity ID filtering restricts which documents will be returned based on a primary ID associated with a document in Microsoft Dynamics GP. The entity ID filtering does not restrict documents based on the additional data they contain, such as line items. For example, when sales documents are returned based on the Windows User ID that is mapped to a salesperson ID, the documents are filtered based on the salesperson ID in the document header. The line items for the sales document are not filtered based on the salesperson ID. The document may contain line items that were added by other salespeople. These line items could contain information you dont want the restricted user to see. If your web service application relies on entity ID filtering, be aware of situations when your application could retrieve documents that contain sensitive data in the document. Consider using your applications user interface to filter out the data, such as the commission information for sales document line items.
76
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 4
E N T IT Y
I D
FI LT E R IN G
using System.Web.Services.Protocols; using DynamicsGPWebServiceSample.DynamicsGPService; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; ListRestrictionOfNullableOfSalesTransactionState transactionStateRestriction; SalesOrderCriteria salesOrderCriteria; SalesOrderSummary[] salesOrderSummary; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Be sure the default credentials are used wsDynamicsGP.UseDefaultCredentials = true; // Create a context with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context object context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Create a transaction state restriction object transactionStateRestriction = new ListRestrictionOfNullableOfSalesTransactionState(); transactionStateRestriction.EqualValue = SalesTransactionState.History; // Create a sales order criteria object // Retrieve summary objects for historical sales orders salesOrderCriteria = new SalesOrderCriteria(); salesOrderCriteria.TransactionState = transactionStateRestriction; // Specify the scope so that transactions for only the current // user are retrieved salesOrderCriteria.Scope = SalesDocumentScope.ReturnBasedonSalespersonId; try { // Retrieve the sales order summaries specified salesOrderSummary = wsDynamicsGP.GetSalesOrderList(salesOrderCriteria, context);
WEB
SERVICE
PROGRAMMERS
GUIDE
77
PA RT
U S I N G
T H E
W E B
S ER V I C E
// Display the ID and amount of each summary object StringBuilder summaryList = new StringBuilder(); foreach (SalesOrderSummary a in salesOrderSummary) { summaryList.AppendLine("Order number: " + a.Key.Id + " } MessageBox.Show(summaryList.ToString()); } catch (SoapException soapErr) { MessageBox.Show(soapErr.Message); } } } } Order amount: " + a.TotalAmount.Value.ToString("C"));
78
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 15:
WEB
SERVICE
PROGRAMMERS
GUIDE
79
PA RT
U S I N G
T H E
W E B
S ER V I C E
// Create a context with which to call the web service context = new Context(); // Specify which company to use (sample company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Create the criteria customerCriteria = new CustomerCriteria(); // Specify the criteria for the customer summaries to retrieve stateRestriction = new LikeRestrictionOfString(); stateRestriction.Like = "%IL%"; customerCriteria.State = stateRestriction; nameRestriction = new LikeRestrictionOfString(); nameRestriction.Like = "A%"; customerCriteria.Name = nameRestriction; activeRestriction = new RestrictionOfNullableOfBoolean(); activeRestriction.EqualValue = true; customerCriteria.IsActive = activeRestriction; // Use an event handler for the asynchronous web method wsDynamicsGP.GetCustomerListCompleted += new GetCustomerListCompletedEventHandler (wsDynamicsGP_GetCustomerListCompleted); // Retrieve the list of customer summaries (asynchronously) wsDynamicsGP.GetCustomerListAsync(customerCriteria, context); Console.WriteLine("Do additional work while waiting for result."); Console.ReadLine(); } // The event handler that responds to the completed event static private void wsDynamicsGP_GetCustomerListCompleted(object sender, GetCustomerListCompletedEventArgs e) { if (e.Error == null) { // Display the number of customers matching the criteria MessageBox.Show("Active IL customers beginning with 'A': " + e.Result.Length.ToString()); } } } }
80
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 5
O T H E R
PR O G R A M M I N G
T E C H N I Q U E S
The Work on Behalf of Other Users task must be added to the new role you are creating.
WEB
SERVICE
PROGRAMMERS
GUIDE
81
PA RT
U S I N G
T H E
W E B
S ER V I C E
When your application calls web methods in the Dynamics GP web service, you will set the default credentials on the web service instance to be the local user that is actually running the application. For the Context object, you will set the WorkOnBehalfOf property to the login name for the user that is accessing the application. The security settings for that user will be used by the Dynamics GP web service.
2. Create a Visual Studio project. In Visual Studio, choose to create a new project. Specify C# as the project type and Class Library as the template to use. Supply a name for the project that describes which web methods are being made available. For example, the name CustomersWebService could be used for the optimized access point that provides access to web methods for customer documents. 3. Add a reference to the system web services assembly. Add a reference to the System.Web.Services assembly that is part of the .NET framework. 4. Add references to the Dynamics GP web service assemblies. Add references to the following assemblies from the Bin folder for the Dynamics GP web service. Microsoft.Dynamics.Common Microsoft.Dynamics.Common.Types Microsoft.Dynamics.GP.BusinessLogic Microsoft.Dynamics.GP.WebServices Microsoft.Dynamics.Security
These assemblies are typically found in this location: C:\Program Files\Microsoft Dynamics\GPWebServices\WebServices\Bin
82
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 5
O T H E R
PR O G R A M M I N G
T E C H N I Q U E S
5. Add namespace references. Add using statements to provide convenient access to the classes and methods needed for the optimized access point. Include the following:
using Microsoft.Dynamics.GP; using Microsoft.Dynamics.GP.WebServices; using Microsoft.Dynamics.Common; using System.Web.Services;
6. Change the namespace. The namespace for the project will default to the name you supplied for the project. Change the namespace for the project to the following: Microsoft.Dynamics.GP.WebServices 7. Add the web service class. The web service class defines the web methods that you are making available through the optimized access point. You can add a new class, or rename the class that was added when you created the Visual Studio project. Use the same name that you did for the project. In this example, the name CustomersWebService was used for the project, so this name should also be used for the web service class. This is shown in the following code:
namespace Microsoft.Dynamics.GP.WebServices { public class CustomersWebService { } }
8. Specify the inheritance for the web service class. The web service class must inherit from the System.Web.Services.WebService class. This is shown in the following example.
public class CustomersWebService : System.Web.Services.WebService { }
9. Add attributes for the web service class. Add the following attributes to the web service class to define its characteristics.
[WebService(Name = "Dynamics GP", Namespace = "http:// schemas.microsoft.com/dynamics/gp/2006/01", Description = @"Optimized web service.")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1, EmitConformanceClaims = true)] public class CustomersWebService : System.Web.Services.WebService { }
WEB
SERVICE
PROGRAMMERS
GUIDE
83
PA RT
U S I N G
T H E
W E B
S ER V I C E
10. Add code to create an instance of the web service class. Add the following code to the web service class to create an instance of the class. Be sure to use the name of the web service class you are creating.
private static WebServices.WebService ws = new WebService(); public CustomersWebService() { }
11. Add the web methods. In the web service class, add the web methods that you want to include in the optimized access point. The parameter lists for the web methods will closely match the documentation for those web methods in the Dynamics GP web service. The following example shows the web methods added for the customer operations: CreateCustomer DeleteCustomer GetCustomerByKey GetCustomerList UpdateCustomer
Use the example as a template for the various operation types available in the Dynamics GP web service, such as Create, Delete, GetByKey, GetList, and Update. The complete code for the web service class is shown.
public class CustomersWebService : System.Web.Services.WebService { private static WebServices.WebService ws = new WebService(); public CustomersWebService() { } [WebMethod] public void CreateCustomer(Customer customer, Context context, Policy policy) { try { ws.CreateCustomer(customer, context, policy);} catch { throw; } } [WebMethod] public void DeleteCustomer(CustomerKey customerKey, Context context, Policy policy) { try { ws.DeleteCustomer(customerKey, context, policy); } catch { throw; } } [WebMethod] public Customer GetCustmerByKey(CustomerKey key, Context context) { try { return ws.GetCustomerByKey(key, context); } catch { throw; } } [WebMethod] public List<CustomerSummary> GetCustomerList(CustomerCriteria criteria, Context context) { try { return ws.GetCustomerList(criteria, context); } catch { throw; } }
84
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 5
O T H E R
PR O G R A M M I N G
T E C H N I Q U E S
[WebMethod] public void UpdateCustomer(Customer customer, Context context, Policy policy) { try { ws.UpdateCustomer(customer, context, policy); } catch { throw; } } }
12. Build and deploy the assembly. After the assembly for the optimized access point has been built, copy it to the Bin folder for the Dynamics GP web service installation. Typically this will be in the following location: C:\Program Files\Microsoft Dynamics\GPWebServices\WebServices\Bin 13. Create an active server methods (.asmx) file. The .asmx file specifies which class contains the web methods that are being made available through the access point. You can use a text editor such as Notepad to create the .asmx file. Use a filename that indicates what is being made available through the access point. For example, Customers.asmx would indicate customer information is being accessed. 14. Specify the content of the .asmx file. The .asmx file contains a single line that specifies the language and the complete name of the class that contains the web methods. The complete name consists of the namespace and the class name. For this example, the namespace is Microsoft.Dynamics.GP.WebServices and the class that contains the web methods is CustomersWebService. These names are used in the content for the Customers.asmx file.
<%@ WebService Language="C#" Class="Microsoft.Dynamics.GP.WebServices.CustomersWebService" %>
15. Deploy the .asmx file. The .asmx file for the optimized access point is added to the same location as the .asmx file for the Dynamics GP web service. Typically this will be in the following location: C:\Program Files\Microsoft Dynamics\GPWebServices\WebServices 16. Set the security properties for the .asmx file. After you have deployed the .asmx file, select it in Windows Explorer. Display the security properties for the file. Add the Authenticated Users group and allow that group to have Read and Read & Execute permissions for the .asmx file. The security permissions for your .asmx file should match those of the DynamicsGPService.asmx file.
WEB
SERVICE
PROGRAMMERS
GUIDE
85
PA RT
U S I N G
T H E
W E B
S ER V I C E
When you access your .asmx file through a web browser, you should see only the web methods that you made available. The following illustration shows the web methods that are made available through the Customers.asmx that was created in this example.
To use the optimized access point, create a web reference the same way you typically would. Instead of specifying the DynamicsGPService.asmx file, specify the .asmx file you created. The proxy created will contain only the web methods you made available through the optimized access point. Use the web methods in exactly the same way you would use those from the Dynamics GP web service. The security settings you specified for the Dynamics GP web methods also apply to the web methods you make available through the optimized access point.
86
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
88
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 16:
Overview
Before extending objects for the Dynamics GP web service, its helpful to understand how the objects can be extended and the steps involved. The following topics are discussed: How objects can be extended Parts of a web service extension Creating a web service extension
WEB
SERVICE
PROGRAMMERS
GUIDE
89
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
3. Create the extension assembly. This assembly contains the processing code for the events that you are extending in the Dynamics GP web service. Refer to Chapter 18, Extension Assembly, for details about creating this assembly. 4. Register the events to process. Add entries to the BusinessObjectFile.config file so that the Dynamics GP web service will process the additional events. Refer to Chapter 19, Registering Events, for more information.
90
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 17:
Event list
The following table lists the events available for each extensible object in the Dynamics GP web service. You will use this information when planing which events to use for your extension, and when you edit the BusinessObjectFile.config to register the actual events.
Event
Retrieved
Occurs
After the object has been retrieved from the database, but before it has been returned from the web service. Before the object has been saved to the database. After the defaulting event, but before the object is saved to the database.
Typical use
Retrieve additional data for a web service object.
EventHandlerType
BusinessObjectEventHandler
Comments
None
DefaultingForCreate
Apply defaulting logic for the extended data. Apply validation rules for the extended data.
BusinessObjectEventHandler
None
ValidatingForCreate
BusinessObjectValidateEvent Handler
All validation events run, allowing all validation exceptions to be logged. If validation errors have been logged, further processing stops.
WEB
SERVICE
PROGRAMMERS
GUIDE
91
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
Event
Creating
Occurs
Immediately after the object is created in the database. After the object has been created successfully in the database. Before the object has been updated in the database. After the defaulting event, but before the object is updated in the database.
Typical use
Save extended data to the appropriate tables in the database. None
EventHandlerType
BusinessObjectEventHandler
Comments
This event is included in the database transaction that creates the base object. None
Created
BusinessObjectEventHandler
DefaultingForUpdate
Apply defaulting logic for the extended data. Apply validation rules for the extended data.
Has access to the original version of the core business object. Has access to the previous version (before update) of the core business object. All validation events run, allowing all validation exceptions to be logged. If validation errors have been logged, further processing stops. Has access to the original version of the core business object. This event is included in the database transaction that updates the base object. Has access to the original version of the core business object. None
ValidatingForUpdate
Updating
BusinessObjectUpdateEvent Handler
Updated
After the object has been updated successfully in the database. Before the object has been deleted from the database. After the defaulting event, but before the object has been deleted from the database.
None
BusinessObjectUpdateEvent Handler
DefaultingForDelete
None
BusinessObjectEventHandler
ValidatingForDelete
BusinessObjectValidateEvent Verifies any preconditions required for the object to be Handler deleted.
All validation events run, allowing all validation exceptions to be logged. If validation errors have been logged, further processing stops. This event is included in the database transaction that deletes the base object. None
Deleting
Immediately after the object has been deleted from the database. After the object has been deleted successfully from the database. Before the object has been voided. After the defaulting event, but before the object has been voided.
Delete extended data from the appropriate tables in the database. None
BusinessObjectEventHandler
Deleted
BusinessObjectEventHandler
DefaultingForVoid ValidatingForVoid
None
BusinessObjectEventHandler
None All validation events run, allowing all validation exceptions to be logged. If validation errors have been logged, further processing stops. None
BusinessObjectValidateEvent Verifies any preconditions required for the object to be Handler voided.
Voiding
BusinessObjectEventHandler
92
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 7
W E B
S E R V IC E
E V E N T S
Event
Voided
Occurs
After the object has been voided successfully.
Typical use
None
EventHandlerType
BusinessObjectEventHandler
Comments
None
WEB
SERVICE
PROGRAMMERS
GUIDE
93
94
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 18:
Extension Assembly
The extension assembly contains the processing code for the events you register for your web service extension. Its important that this assembly be created properly so that the Dynamics GP web service can call the static methods in the assembly. Information about creating an extension assembly is divided into the following sections: Creating an extension assembly Event handler methods Sample: Retrieved event handler method Sample: ValidatingForCreate event handler method Sample: Creating event handler method Sample: ValidatingForUpdate event handler method Sample: Updating event handler method Sample: Deleting event handler method
These assemblies are typically found in this location: C:\Program Files\Microsoft Dynamics\GPWebServices\WebServices\Bin 3. Add namespace references. Add using (C#) or Imports (Visual Basic) statements to provide convenient access to the classes and methods needed for the extension assembly. Include the following: Microsoft.Dynamics.Common Microsoft.Dynamics.GP System.Data System.Data.SqlClient System.Xml
The Data, SqlClient, and Xml namespaces are added to provide access to resources you will need when you write your event handling methods. 4. Specify the name for the namespace. In the code for the class library, specify the name for the namespace. Use a name that indicates what who created the web service extension or what type of extended data is being made available.
WEB
SERVICE
PROGRAMMERS
GUIDE
95
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
5. Add a public static class. This new class in the extension assembly will contain the static methods that respond to web service events. Be sure the class is marked public and static. The following C# code is an example of a public class for an extension assembly:
using System; using System.Data; using System.Data.SqlClient; using System.Xml; using Microsoft.Dynamics.Common; using Microsoft.Dynamics.GP; namespace ExtensionExample { public static class ContactHistory { // Event handler methods are added here } }
6. Add the event handler methods. These public static method will respond to the events from the Dynamics GP web service. For more information about these methods, refer to Event handler methods on page 96. 7. Build and deploy the extension assembly. Once the extension assembly has been built, copy it to the Bin folder for the Dynamics GP web service installation. Typically this will be in the following location: C:\Program Files\Microsoft Dynamics\GPWebServices\WebServices\Bin
In place of EventArgsType you must specify the appropriate type for the type of event the static method is responding to. The following table lists the event types and the event arguments type that should be used.
Event
Retrieved DefaultingForCreate ValidatingForCreate
96
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 8
EX T EN S I O N
A S S E M B L Y
Event
Creating Created DefaultingForUpdate ValidatingForUpdate Updating Updated DefaultingForDelete ValidatingForDelete Deleting Deleted DefaultingForVoid ValidatingForVoid Voiding Voided
For example, the static event handler method that responds to an Updating event from the Dynamics GP web service would look like the following:
public static void UpdateItem(object sender, BusinessObjectUpdateEventArgs e)
Description
The complete business object for which the web service event is occurring. The Context object passed with the web service call. This object contains information used in processing the event, such as the OrganizationKey. For update events, the complete business object as it existed before it was updated. The Policy object passed with the web service call. For validation events, the collection of validation warning and errors. If the event handler encounters a validation issues, it must add them to this collection.
Event handler methods frequently need to access the Dynamics GP database to complete their actions. Objects available from the Microsoft.Dynamics.Common assembly are provided to help with these tasks. The examples provided in the following sections demonstrate how to perform these database actions. The event handler methods also need to work with the Extension objects that contain extended data for business objects. The examples provided show the techniques needed to work with the ExtensionList collection, as well as the XML element included with each Extension object.
WEB
SERVICE
PROGRAMMERS
GUIDE
97
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
98
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 8
EX T EN S I O N
A S S E M B L Y
// Build the Extension object to return from the web service Extension ContactHistory = new Extension(); ContactHistory.ExtensionId = "ContactHistory"; // Make the XML extension document doc = new XmlDocument(); contactHistoryXML = doc.CreateElement("ContactHistory"); // First Contact Date firstContactDateXML = doc.CreateElement("FirstContactDate"); text = doc.CreateTextNode(firstContactDate); firstContactDateXML.AppendChild(text); contactHistoryXML.AppendChild(firstContactDateXML); // First Contact Salesperson firstContactSalespersonXML = doc.CreateElement("FirstContactSalesperson"); text = doc.CreateTextNode(firstContactSalesperson); firstContactSalespersonXML.AppendChild(text); contactHistoryXML.AppendChild(firstContactSalespersonXML); // Last Contact Date lastContactDateXML = doc.CreateElement("LastContactDate"); text = doc.CreateTextNode(lastContactDate); lastContactDateXML.AppendChild(text); contactHistoryXML.AppendChild(lastContactDateXML); // Last Contact Salesperson lastContactSalespersonXML = doc.CreateElement("LastContactSalesperson"); text = doc.CreateTextNode(lastContactSalesperson); lastContactSalespersonXML.AppendChild(text); contactHistoryXML.AppendChild(lastContactSalespersonXML); // Add the extension to the Customer object ContactHistory.DocExtension = contactHistoryXML; e.BusinessObject.Extensions.Add(ContactHistory); } } }
WEB
SERVICE
PROGRAMMERS
GUIDE
99
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
// Declare private variable of type Microsoft.Dynamics.Common.Connection private static Connection connection; public static void ValidateCreateContactHistory(object sender, BusinessObjectValidateEventArgs e) { bool found; string firstContactDate; string firstContactSalesperson; string lastContactDate; string lastContactSalesperson; string selectStatement; Customer customer; Extension ContactHistoryExtension = new Extension(); if (e.BusinessObject.GetType() == typeof(Customer)) { customer = (Customer)e.BusinessObject; // Look at the Extension list passed along found = false; foreach (Extension ext in customer.Extensions) { if (ext.ExtensionId == "ContactHistory") { ContactHistoryExtension = ext; found = true; break; } } if (found == true) { // Found an extension, so it should be processed XmlElement contactHistory; contactHistory = ContactHistoryExtension.DocExtension; XmlNodeList nodeList; nodeList = contactHistory.ChildNodes; // First contact date firstContactDate = nodeList[0].InnerText.ToString(); // First contact salesperson firstContactSalesperson = nodeList[1].InnerText.ToString(); // Last contact date lastContactDate = nodeList[2].InnerText.ToString(); // Last contact salesperson lastContactSalesperson = nodeList[3].InnerText.ToString(); // Get the connection to the database for the current company connection = Connection.GetInstance(); SqlCommand command = new SqlCommand(); command.Connection = (SqlConnection)connection.GetConnection (e.Context.OrganizationKey);
100
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 8
EX T EN S I O N
A S S E M B L Y
SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable table = new DataTable(); // Verify that the First Contact Salesperson and Last Contact // Salesperson are valid // The SQL statement to verify the First Contact Salesperson selectStatement = "SELECT SLPRSNID FROM RM00301 WHERE SLPRSNID = '" + firstContactSalesperson + "'"; command.CommandText = selectStatement; adapter.Fill(table); if (table.Rows.Count < 1) { // Add an exception, because the First Contact salesperson was // not found ValidationError validationError = new ValidationError(); validationError.Id = "1001"; validationError.Message = "Invalid First Contact Salesperson specified in Contact History."; validationError.ObjectType = typeof(Customer).ToString(); validationError.PropertyNames.Add("FirstContactSalesperson"); e.ValidationResult.Errors.Add(validationError); } // The SQL statement to verify the Last Contact Salesperson selectStatement = "SELECT SLPRSNID FROM RM00301 WHERE SLPRSNID = '" + lastContactSalesperson + "'"; command.CommandText = selectStatement; adapter.SelectCommand = command; table.Clear(); adapter.Fill(table); if (table.Rows.Count < 1) { // Add an exception, because the Last Contact salesperson was // not found ValidationResult validationResult = new ValidationResult(); ValidationError validationError = new ValidationError(); validationError.Id = "1002"; validationError.Message = "Invalid Last Contact Salesperson specified in Contact History."; validationError.ObjectType = typeof(Customer).ToString(); validationError.PropertyNames.Add("LastContactSalesperson"); e.ValidationResult.Errors.Add(validationError); } } } }
WEB
SERVICE
PROGRAMMERS
GUIDE
101
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
102
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 8
EX T EN S I O N
A S S E M B L Y
//First contact salesperson firstContactSalesperson = nodeList[1].InnerText.ToString(); //Last contact date lastContactDate = nodeList[2].InnerText.ToString(); //Last contact salesperson lastContactSalesperson = nodeList[3].InnerText.ToString(); // Get the connection to the database for the current company connection = Connection.GetInstance(); // The SQL statement to update contact history information updateStatement = "UPDATE IG003 SET ContactSalespersonID1='" + firstContactSalesperson + "', FirstContactDate='" + firstContactDate + "', ContactSalespersonID2='" + lastContactSalesperson + "', LastContactDate='" + lastContactDate + "' WHERE CUSTNMBR = '" + customer.Key.Id + "'"; // Create the SQL connection SqlCommand command = new SqlCommand(updateStatement); SqlConnection sqlConnection = new SqlConnection (connection.GetConnectionString(e.Context.OrganizationKey)); command.Connection = sqlConnection; // Open the SQL connection sqlConnection.Open(); // Execute the SQL statement rowsAffected = command.ExecuteNonQuery(); if (rowsAffected == 0) { // The row did not exist, so try creating it. // Is the ContactPerson specified? If not, set it to empty. if (customer.Addresses.Count == 0) contact = ""; else contact = customer.Addresses[0].ContactPerson; insertStatement = "INSERT IG003 VALUES ('" + firstContactSalesperson + "', '" + lastContactSalesperson + "', '" + contact + "', '" + lastContactDate + "', '" + firstContactDate + "', '" + customer.Name + "', '" + customer.Key.Id + "')"; command.CommandText = insertStatement; rowsAffected = command.ExecuteNonQuery(); } // Close the SQL connection sqlConnection.Close(); } } }
WEB
SERVICE
PROGRAMMERS
GUIDE
103
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
104
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 8
EX T EN S I O N
A S S E M B L Y
// Last contact salesperson lastContactSalesperson = nodeList[3].InnerText.ToString(); // Get the connection to the database for the current company connection = Connection.GetInstance(); SqlCommand command = new SqlCommand(); command.Connection = (SqlConnection) connection.GetConnection(e.Context.OrganizationKey); SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable table = new DataTable(); // Verify that the First Contact Salesperson and Last Contact // Salesperson are valid // The SQL statement to verify the First Contact Salesperson selectStatement = "SELECT SLPRSNID FROM RM00301 WHERE SLPRSNID = '" + firstContactSalesperson + "'"; command.CommandText = selectStatement; adapter.Fill(table); if (table.Rows.Count < 1) { // Add an exception, because the First Contact salesperson was // not found ValidationError validationError = new ValidationError(); validationError.Id = "1001"; validationError.Message = "Invalid First Contact Salesperson specified in Contact History."; validationError.ObjectType = typeof(Customer).ToString(); validationError.PropertyNames.Add("FirstContactSalesperson"); e.ValidationResult.Errors.Add(validationError); } // The SQL statement to verify the Last Contact Salesperson selectStatement = "SELECT SLPRSNID FROM RM00301 WHERE SLPRSNID = '" + lastContactSalesperson + "'"; command.CommandText = selectStatement; adapter.SelectCommand = command; table.Clear(); adapter.Fill(table); if(table.Rows.Count < 1) { // Add an exception, because the Last Contact salesperson was // not found ValidationResult validationResult = new ValidationResult(); ValidationError validationError = new ValidationError(); validationError.Id = "1002"; validationError.Message = "Invalid Last Contact Salesperson specified in Contact History."; validationError.ObjectType = typeof(Customer).ToString(); validationError.PropertyNames.Add("LastContactSalesperson"); e.ValidationResult.Errors.Add(validationError); } } } }
WEB
SERVICE
PROGRAMMERS
GUIDE
105
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
106
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 8
EX T EN S I O N
A S S E M B L Y
//Last contact date lastContactDate = nodeList[2].InnerText.ToString(); //Last contact salesperson lastContactSalesperson = nodeList[3].InnerText.ToString(); // Get the connection to the database for the current company connection = Connection.GetInstance(); // The SQL statement to update contact history information updateStatement = "UPDATE IG003 SET ContactSalespersonID1='" + firstContactSalesperson + "', FirstContactDate='" + firstContactDate + "', ContactSalespersonID2='" + lastContactSalesperson + "', LastContactDate='" + lastContactDate + "' WHERE CUSTNMBR = '" + customer.Key.Id + "'"; // Create the SQL connection SqlCommand command = new SqlCommand(updateStatement); SqlConnection sqlConnection = new SqlConnection (connection.GetConnectionString(e.Context.OrganizationKey)); command.Connection = sqlConnection; // Open the SQL connection sqlConnection.Open(); // Execute the SQL statement rowsAffected = command.ExecuteNonQuery(); if (rowsAffected == 0) { // The row did not exist, so try creating it. // Has a ContactPerson been specified? If not, set it to empty. if (customer.Addresses.Count == 0) contact = ""; else contact = customer.Addresses[0].ContactPerson; insertStatement = "INSERT IG003 VALUES ('" + firstContactSalesperson + "', '" + lastContactSalesperson + "', '" + contact + "', '" + lastContactDate + "', '" + firstContactDate + "', '" + customer.Name + "', '" + customer.Key.Id + "')"; command.CommandText = insertStatement; rowsAffected = command.ExecuteNonQuery(); } // Close the SQL connection sqlConnection.Close(); } } }
WEB
SERVICE
PROGRAMMERS
GUIDE
107
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
108
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 19:
Registering Events
To have events for the Dynamics GP web service be run, they must be registered. Information about registering events is divided into the following sections: Business object configuration file Modifying the configuration file Event registration example
DictionaryEntry elements
The BusinessObjectFile.config contains one <DictionaryEntry> element for each web service object that can have events registered for it. The web service objects that can raise events are those that inherit from BusinessObject. For convenience, the entries are in alphabetical order so they can be found easily. Not all objects have <DictionaryEntry> entries in this configuration file. For instance, the Customer object isnt included in the default version of this file. If you want to register events for an object that is not in the file, you will need to add a <DictionaryEntry> element for it. The easiest way to do this is by copying an existing element. The <Key> for the <DictionaryEntry> element is the complete name of the business object. The complete name has the prefix Microsoft.Dynamics.GP, followed by the name of the object. The name of the object corresponds to the class name you see in the Dynamics GP Web Service Reference. As an example, the complete name for the customer object is: Microsoft.Dynamics.GP.Customer.
Event elements
A <DictionaryEntry> element will have one or more <Event> elements, each describing an event for the business object. Each <Event> element has the following: EventName The name of the event being registered. This corresponds to one of the events listed in Event list on page 91. EventHandlerType Specifies the type of event handler needed for the event. The handler type for each event type is also listed in Event list on page 91. SoftwareVendor Identifies who added the event. Type The qualified name that indicates the namespace and static class containing the event handler method for the event. StaticMethod The name of the static method that will be run for the event. The signature for this static method must be appropriate for the type of event. Refer to Event handler methods on page 96 for more information.
WEB
SERVICE
PROGRAMMERS
GUIDE
109
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
Assembly The name of the extension assembly that contains the static method for the event. Execute A boolean value that allows an event to be turned on or off. The value must be set to true for an event to be processed.
Configuration errors
Any configuration errors in the file, such as invalid class or method names, can cause system exceptions that prevent the Dynamics GP web service from running. When a web method is processed, system exceptions will be logged that describe the problem. Use the Exception Management Console to view the exceptions logged.
Issues with the extension assembly and web service events will be logged as exceptions.
Other modifications
Be aware that other modifications may have been made by other applications that are extending the Dynamics GP web service. The file may not be in the default state. Any automation you use to modify this file will need to account for this possibility.
110
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
1 9
R E G I S T ER IN G
E V E N T S
WEB
SERVICE
PROGRAMMERS
GUIDE
111
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
<Assembly>ExtensionExample</Assembly> <Execute>true</Execute> </EventHandler> </Event> <Event> <EventName>ValidatingForCreate</EventName> <EventHandlerType> <Type>Microsoft.Dynamics.Common.BusinessObjectValidate EventHandler</Type> <Assembly>Microsoft.Dynamics.Common</Assembly> </EventHandlerType> <EventHandler> <SoftwareVendor>MicrosoftDocumentation</SoftwareVendor> <Type>ExtensionExample.ContactHistory</Type> <StaticMethod>ValidateCreateContactHistory</StaticMethod> <Assembly>ExtensionExample</Assembly> <Execute>true</Execute> </EventHandler> </Event> <Event> <EventName>Creating</EventName> <EventHandlerType> <Type>Microsoft.Dynamics.Common.BusinessObjectEventHandler </Type> <Assembly>Microsoft.Dynamics.Common</Assembly> </EventHandlerType> <EventHandler> <SoftwareVendor>MicrosoftDocumentation</SoftwareVendor> <Type>ExtensionExample.ContactHistory</Type> <StaticMethod>CreateContactHistory</StaticMethod> <Assembly>ExtensionExample</Assembly> <Execute>true</Execute> </EventHandler> </Event> <Event> <EventName>Deleting</EventName> <EventHandlerType> <Type>Microsoft.Dynamics.Common.BusinessObjectEventHandler </Type> <Assembly>Microsoft.Dynamics.Common</Assembly> </EventHandlerType> <EventHandler> <SoftwareVendor>MicrosoftDocumentation</SoftwareVendor> <Type>ExtensionExample.ContactHistory</Type> <StaticMethod>DeleteContactHistory</StaticMethod> <Assembly>ExtensionExample</Assembly> <Execute>true</Execute> </EventHandler> </Event> </Value> </DictionaryEntry>
112
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 20:
It is the responsibility of developer who extended the web service to provide information about the format of the XML element containing the extended data. The following C# example demonstrates retrieving the contact history information that is being included with the Customer object in the ExtensionList collection. Note how the ExtensionList collection is examined to determine whether the contact history information has been included. The XML element containing the contact history data is processed to retrieve the individual items.
using System; using System.Collections.Generic; using System.Text; using System.Xml; using DynamicsGPWebServiceSample.DynamicsGPService; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args)
WEB
SERVICE
PROGRAMMERS
GUIDE
113
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
{ CompanyKey companyKey; Context context; Customer customer; CustomerKey customerKey; string firstContactDate; string firstContactSalesperson; string lastContactDate; string lastContactSalesperson; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Make sure that default credentials are being used wsDynamicsGP.UseDefaultCredentials = true; // Create a context with which to call the web service context = new Context(); // Specify which company to use (lesson company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Create a customer key customerKey = new CustomerKey(); customerKey.Id = "WORLDENT0001"; // Retrieve the customer object customer = wsDynamicsGP.GetCustomerByKey(customerKey, context); // Look for the contact history extension foreach (Extension ext in customer.Extensions) { if (ext.ExtensionId == "ContactHistory") { XmlElement contactHistory; contactHistory = customer.Extensions[0].DocExtension; XmlNodeList nodeList; nodeList = contactHistory.ChildNodes; //First contact date firstContactDate = nodeList[0].InnerText.ToString(); //First contact salesperson firstContactSalesperson= nodeList[1].InnerText.ToString(); //Last contact date lastContactDate = nodeList[2].InnerText.ToString(); //Last contact salesperson lastContactSalesperson = nodeList[3].InnerText.ToString();
114
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
2 0
U S I N G
W E B
S E R V I C E
E X T EN S I O N S
} } } } }
The following C# example demonstrates creating the contact history information that is being included with the Customer object in the ExtensionList collection. An XML element is created that contains the contact history information. A new Extension object is created with the ExtensionId value ContactHistory. The XML element containing the contact history data is added as the DocExtension for the object. Finally, the new customer object is saved.
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using DynamicsGPWebServiceSample.DynamicsGPService; using System.Xml; using System.Globalization; namespace DynamicsGPWebServiceSample { class Program { static void Main(string[] args) { CompanyKey companyKey; Context context; Customer customer; CustomerKey customerKey; Policy customerPolicy; DateTime today;
WEB
SERVICE
PROGRAMMERS
GUIDE
115
PA RT
E XT E N DI N G
T HE
WE B
S ER V IC E
XmlDocument doc; XmlElement contactHistoryXML; XmlElement firstContactDateXML; XmlElement firstContactSalespersonXML; XmlElement lastContactDateXML; XmlElement lastContactSalespersonXML; XmlText text; // Create an instance of the web service DynamicsGP wsDynamicsGP = new DynamicsGP(); // Make sure that default credentials are being used wsDynamicsGP.UseDefaultCredentials = true; // Create a context with which to call the web service context = new Context(); // Specify which company to use (lesson company) companyKey = new CompanyKey(); companyKey.Id = (-1); // Set up the context context.OrganizationKey = (OrganizationKey)companyKey; context.CultureName = "en-US"; // Create a new customer object customer = new Customer(); // Create a customer key customerKey = new CustomerKey(); customerKey.Id = "CONTOSO"; customer.Key = customerKey; // Set properties for the new customer customer.Name = "Contoso, Ltd"; // Customer Address Key CustomerAddressKey customerAddressKey = new CustomerAddressKey(); customerAddressKey.CustomerKey = customerKey; customerAddressKey.Id = "PRIMARY"; // Customer Address List with Contact Person CustomerAddress[] customerAddresses = new CustomerAddress[1]; customerAddresses[0] = new CustomerAddress(); customerAddresses[0].Key = customerAddressKey; customerAddresses[0].ContactPerson = "Steve"; customer.DefaultAddressKey = customerAddressKey; customer.Addresses = customerAddresses; // Set today's date today = DateTime.Today; // Get the create policy for the customer customerPolicy = wsDynamicsGP.GetPolicyByOperation ("CreateCustomer", context);
116
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
2 0
U S I N G
W E B
S E R V I C E
E X T EN S I O N S
// Add the Contact History (extended data) for the new customer // Make a new Extension Extension ext = new Extension(); ext.ExtensionId = "ContactHistory"; // Make the XML extension document doc = new XmlDocument(); contactHistoryXML = doc.CreateElement("ContactHistory"); // First Contact Date firstContactDateXML = doc.CreateElement("FirstContactDate"); text = doc.CreateTextNode(today.ToString("G", DateTimeFormatInfo.InvariantInfo)); firstContactDateXML.AppendChild(text); contactHistoryXML.AppendChild(firstContactDateXML); // First Contact Salesperson firstContactSalespersonXML = doc.CreateElement("FirstContactSalesperson"); text = doc.CreateTextNode("PAUL W."); firstContactSalespersonXML.AppendChild(text); contactHistoryXML.AppendChild(firstContactSalespersonXML); // Last Contact Date lastContactDateXML = doc.CreateElement("LastContactDate"); text = doc.CreateTextNode(today.ToString("G", DateTimeFormatInfo.InvariantInfo)); lastContactDateXML.AppendChild(text); contactHistoryXML.AppendChild(lastContactDateXML); // Last Contact Salesperson lastContactSalespersonXML = doc.CreateElement("LastContactSalesperson"); text = doc.CreateTextNode("PAUL W."); lastContactSalespersonXML.AppendChild(text); contactHistoryXML.AppendChild(lastContactSalespersonXML); // Add the extension to the Customer object ext.DocExtension = contactHistoryXML; Extension[] extensionList = new Extension[1]; extensionList[0] = ext; customer.Extensions = extensionList; // Create the customer wsDynamicsGP.CreateCustomer(customer, context, customerPolicy); } } }
WEB
SERVICE
PROGRAMMERS
GUIDE
117
118
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
These samples have been created using Visual Studio 2005. To use them with Visual Studio 2008, allow the upgrade wizard to convert each project when you open the solution file.
120
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 21:
Sales Documents
The Sales Document sample is a C# .NET application that retrieves data using Web Services for Microsoft Dynamics GP. The application displays sales document summary information for a customer. The following topics are discussed: Overview of Sales Documents sample Running the Sales Documents sample How the Sales Documents sample works Web Service use for Sales Documents sample
The sample application requires the computer to have Visual Studio 2005 or later and the 2.0 .NET framework installed.
WEB
SERVICE
PROGRAMMERS
GUIDE
121
PA RT
W E B
S E R V I C E
S A M P L E S
2. Start Visual Studio and open the solution file for the sample application. The solution file for this sample is named SalesDocumentSample.sln. The solution file is in the SalesDocument folder inside the Samples folder. 3. Update the web reference. Open Visual Studio's Solution Explorer and select the Web References folder. Select the DynamicsGPService web reference to view its properties. Change the Web Reference URL property to use the URL for the Dynamics GP web service. 4. Choose Start Debugging from the Debug menu. To build the solution, choose Start Debugging in the Debug menu. The sales document sample application loads the web service proxy which may take several seconds to complete. The application will not be visible until loading the web service proxy has completed. 5. Select a company from the Company drop-down list. Once a company is selected, the Customer drop-down list contains all the customers for that company. 6. Select a customer from the Customer drop-down list. After a customer is selected, the data grid displays all the sales documents for that customer. 7. Mark one or more of the check boxes in the Sales Documents list. Use the check boxes to restrict the types of sales documents displayed in the data grid. 8. Click the Refresh button. The Refresh button forces the data grid to update and display only the specified document types for the customer.
122
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
2 1
S A L E S
D O C U M E N T S
WEB
SERVICE
PROGRAMMERS
GUIDE
123
124
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 22:
Import GL Transactions
The Import GL Transaction sample is a C# .NET application that creates new GL transactions from an XML source file. The application uses a Windows Forms-based interface to identify the XML source file and to report progress. The following topics are discussed: Overview of Import GL Transactions sample Running the Import GL Transactions sample How the Import GL Transactions sample works Web Service use for Import GL Transactions sample
Click the file button to specify the location of the XML file.
The sample XML file contains only data required by this solution. This allows the sample to focus on how to use web services in a batch handling solution, and to omit steps to validate the XML and identify missing data. The sample application requires the computer to have Visual Studio 2005 or later and the 2.0 .NET framework installed.
WEB
SERVICE
PROGRAMMERS
GUIDE
125
PA RT
W E B
S E R V I C E
S A M P L E S
3. Update the web reference. Open Visual Studio's Solution Explorer and select the Web References folder. Select the DynamicsGPService web reference to view its properties. Change the Web Reference URL property to use the URL for the Dynamics GP web service. 4. Choose Start Debugging from the Debug menu. To build the solution, choose Start Debugging in the Debug menu. 5. Click the Open file button. An open file dialog box appears. Navigate to the file named TransactionBatchFile.xml located in the BatchApplication folder found inside the ImportGLTransactions folder. 6. Select the XML source file. Select the TransactionBatchFile.xml file. The textbox on the user interface displays the XML file's contents. 7. Click the Begin button. This button starts the batch processing of the GL transaction from the XML file.
126
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Chapter 23:
Update Customers
The Update Customers sample is a C# .NET application that updates existing customer information. The application uses a Windows Forms-based interface to add or update comments about a customer. Overview of Update Customers sample Running the Update Customers sample How the Update Customers sample works Web Service use for Update Customers sample
The comment editing process begins with the selection of a company and one of its customers. The Comment textbox displays the existing comment and allows the comment text to be edited. The Update button saves the new comment in Microsoft Dynamics GP. The sample application requires the computer to have Visual Studio 2005 or later and the 2.0 .NET framework installed.
WEB
SERVICE
PROGRAMMERS
GUIDE
127
PA RT
W E B
S E R V I C E
S A M P L E S
4. Choose Start Debugging from the Debug menu. To build the solution, choose Start Debugging in the Debug menu. 5. Click the Connect button. The Connect button loads the web service proxy which may take several seconds to complete. The Company drop-down list displays the list of available companies. 6. Select a company from the Company drop-down list. Once a company is selected, the Customer drop-down list contains all the customers for that company. 7. Select a customer from the Customer drop-down list. After a customer is selected, the Comment textbox displays any existing comment information. 8. Add or edit the comment information. Edit the existing comment or add a new comment. 9. Click the Update button. The Update button saves the new comment to Microsoft Dynamics GP.
128
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
C H A P T E R
2 3
U P D A T E
C U S T O M E R S
The GetCustomerByKey method retrieves a single customer object. The Id property of the CustomerKey object is used to specify the customer to retrieve. A customer object and customer key object identify the customer to be updated. The contents of the user interface's Comment textbox populates the customer object's Comment1 property. The UpdateCustomer method saves the updated customer object to the database.
WEB
SERVICE
PROGRAMMERS
GUIDE
129
130
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
APPENDIX
Appendix
The following appendix is included for this manual: Appendix A, Culture Codes, lists the culture codes used for the Context object in the Dynamics GP web service. Appendix B, ISO Currency Codes, lists the standard 3-letter ISO currency codes used to identify currency types in the Dynamics GP web service. Appendix C, Troubleshooting, provides information about resolving issues you may encounter with Web Services for Microsoft Dynamics GP.
132
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Appendix A:
Culture Codes
The following chart lists the culture codes commonly used for the Context object in the Dynamics GP web service.
Culture
"" (empty string) de-DE da-DK nl-BE nl-NL en-AU en-CA en-NZ en-GB en-US fr-CA fr-FR pl-PL pt-BR es-CO es-MX es-ES
Language-Country/Region
invariant culture German - Germany Danish - Denmark Dutch - Belgium Dutch - The Netherlands English - Australia English - Canada English - New Zealand English - United Kingdom English - United States French - Canada French - France Polish - Poland Portuguese - Brazil Spanish - Colombia Spanish - Mexico Spanish - Spain
WEB
SERVICE
PROGRAMMERS
GUIDE
133
134
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Appendix B:
Country/Region
Australia Canada European Union Japan Mexico New Zealand Poland Singapore South Africa United Kingdom United States
Currency
Dollars Dollars Euros Yen Pesos Dollars Zlotych Dollars Rand Pounds Dollars
WEB
SERVICE
PROGRAMMERS
GUIDE
135
136
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Appendix C:
Troubleshooting
You may encounter problems that prevent the Dynamics GP web service from working properly. The following is a list of common issues you may encounter, and possible solutions. Exceptions The stored data differs from what was submitted Performance Web service does not respond Security Policy
Exceptions
The following exceptions may occur when working with the Dynamics GP web service:
WEB
SERVICE
PROGRAMMERS
GUIDE
137
A P PE N D I X
T R O U B L ES HO O T I N G
To enable web service tracing, edit the web.config file and add the following <system.diagnostic> element between the web.config files </ system.web> and </ configuration> nodes:
<system.diagnostics> <switches> <add name="ApplicationTraceSwitch" value="4" /> </switches> <trace autoflush="false" indentsize="4"> <listeners> <add name="myListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="DGPWSTrace.log" /> </listeners> </trace> </system.diagnostics>
This will create a log file name DGPWSTrace.log in the same folder as the web.config file. The value assigned to the trace switch enables or disables tracing. It also controls the level of detail recorded in the log. The following table contains the possible values for the trace switch:
Value
0 1 2 3 4
Description
Disable logging. Log only error messages. Log warning messages and error messages. Log informational messages, warning messages, and error messages. Log all messages including informational messages, warning messages, and error messages.
To disable tracing, set the trace switch values to value="0" or remove the switches and listeners from the web.config file. Tracing should be disabled immediately after completing your research. If tracing is allowed to run, web service performance will diminish and the log file will quickly become quite large. Use a text editor to view the contents of the log. The log contains a series of text messages detailing the activities performed by the web service. Look for actions and operations surrounding the error. The logs help identify the actions of the service leading to the exception and may contain additional exception information that is not available in the exception console.
eConnect tracing
To trace eConnect activity related to the web services, you must add listeners for each of the operation types you want to log. You can choose to log create operations, get operations, or both. Any update operations are logged the same way as create operations. To log eConnect events, place the following <system.diagnostic> element between the web.config files </ system.web> and </ configuration> nodes:
138
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
A PP E N D I X
TR O U B L E S H O O T I N G
<system.diagnostics> <switches> <add name="eConnectXMLTraceSwitch" value="3" /> <add name="ApplicationTraceSwitch" value="1" /> </switches> <trace autoflush="false" indentsize="0"> <listeners> <add name="eConnectCreateListener" type="Microsoft.Dynamics.Common.EConnectCreateXmlTraceListener, Microsoft.Dynamics.Common.Types" initializeData="c:\eConnectCreateOperations.log" /> <add name="eConnectGetListener" type="Microsoft.Dynamics.Common.EConnectGetXmlTraceListener, Microsoft.Dynamics.Common.Types" initializeData="c:\eConnectGetOperations.log" /> </listeners> </trace> </system.diagnostics>
This addition to the web.config creates two log files in the C:\ location. The first is named eConnectCreateOperations.log, which logs all create operations performed by eConnect. Any update operations are also included in this log. The second file is named eConnectGetOperations.log. This file logs all of the get operations performed by eConnect. You may need to give the user identity that runs the web service write privileges to the specified folder. The value assigned to the eConnextXMLTraceSwitch specifies which types of operations will be logged. The following table lists the possible values for this trace switch:
Value
1 2 3
Description
Log only create operations. Log only get operations. Log both create and get operations.
You must include the ApplicationTraceSwitch in this configuration setting. It must be set to a valid value (1 to 4) for eConnect tracing to produce output. This is the same trace switch setting used when logging web service events.
WEB
SERVICE
PROGRAMMERS
GUIDE
139
A P PE N D I X
T R O U B L ES HO O T I N G
If the URL for the web service has changed, applications need to use the new URL. An application typically stores the web service URL in the application setting section of its configuration file. The following example shows the URL from a configuration file:
<applicationSettings> <DynamicsGPWebServiceSample.Properties.Settings> <setting name="DynamicsGPWebServiceSample" serializeAs="String"> <value> http://server/DynamicsGPWebServices/DynamicsGPService.asmx </value> </setting> </DynamicsGPWebServiceSample.Properties.Settings> </applicationSettings>
A web application stores the web service URL in the <appSettings> section of its Web.Config file. The following example shows the URL for a web application:
<appSettings> <add key="DynamicsGPWebService.GreatPlainsService" value="http://server/DynamicsGPWebService/DynamicsGPService.asmx"/> </appSettings>
Ensure the URL correctly specifies the location of the Dynamics GP web service. If the URL does not identify the web service, you will need to update the URL. Visual Studio can update the configuration file. Open the applications project file in Visual Studio. Update the URL property of the web reference and rebuild the application. Test the application to verify the error no longer occurs. A text editor can also update the URL in the configuration file. Always create a backup copy of the configuration file prior to editing the file. Update the value in the configuration file to the correct URL for the web service. Save the changes and test the application to verify the error no longer occurs.
140
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
A PP E N D I X
TR O U B L E S H O O T I N G
This error may also occur when using the working on behalf of another user" option. This option allows the user and role performing the operation to be different from the logged-on user. The exception occurs when the user specified by the WorkingOnBehalfOf property of the Context object does not have authorization to perform the requested operation. Use the Security console to view the role or roles assigned to the user. The working on behalf of another user option may also produce this exception if the current user that is attempting to work on behalf of another user has not been granted access to the Work on Behalf of Other Users task. Use the Security console to determine whether the user has been assigned the Work on Behalf of Other Users task and to assign the role to the user. Entity ID filtering is another possible source of this error. If the application is requesting filtered results, users can receive this error if they dont have access to the restricted operation used for the entity ID filtering. They may also receive this error if the entity ID assignment that maps a Windows User ID to a back office object ID cannot be found.
Policy-related changes
You find the data values written or updated were not what you expected after a Create or Update operation saves the object to the database. A policy and its behaviors may be controlling some characteristics of the operation. Refer to Chapter 13, Policy, for additional information on policies and behaviors. In some instances, the unexpected data changes occur when a specific policy instance associated with the users role does not run. Use the Dynamics Security console to view the users role assignments. If the user is assigned to more than one role, the web services will use the systems default policy instead of a specific policy instance associated with an assigned role. Review the specific behaviors associated with a policy by opening the Dynamics Security console and navigating to the policy. The middle-pane of the console will list the behaviors for the policy. Highlight a policy and select Properties from the Action menu in the right-pane. The Policy Instance Property window will display the behavior and behavior options. View the behavior options to determine whether the policy is the source of specific data change.
WEB
SERVICE
PROGRAMMERS
GUIDE
141
A P PE N D I X
T R O U B L ES HO O T I N G
Check the policy for a behavior option with a behavior type of External. An external policy allows the application calling the web method to specify a behavior option. If the application uses an external behavior, the applications behavior choice produces data that was not submitted by the user. eConnect tracing may help by showing the actual data sent to Dynamics GP. The Exceptions topic describes the steps to enable eConnect tracing. Review the eConnect trace log to see the data eConnect used to create or update the record in the Dynamic GP database.
Extension-related changes
Another source of unexpected data changes includes extensions to the web service. Refer to Part 4, Extending the Web Service, for additional information on extensions. Other applications may react to the update or create event and add or change object properties. Review the BusinessObjectFile.config file to determine whether any assemblies are registered for the events associated with a create or update operation.
Performance
The following are suggestions for ensuring optimum performance from the Dynamics GP web service:
Extensions
Web service extensions require changes to the BusinessObjectsFile.config to register the extension for a web service event. If the edit creates an error in the contents of the configuration file, the web service may no longer respond. Always make a backup copy of the BusinessObjectsFile.config prior to editing the file. Store the copy to a safe location. Use the backup copy to restore the web service if problems occur.
142
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
A PP E N D I X
TR O U B L E S H O O T I N G
If changes to the BusinessObjectsFile.config prevent a web method from responding, open the Exception Management Console to identify the source of the error. Edit the BusinessObjectsFile.config to correct the specified error. Restart Internet Information Services (IIS) to ensure the changed BusinessObjectsFile.config is used. Refer to Chapter 19, Registering Events, for additional information about the business object configuration file.
Security
The following is a list of issues associated with the Dynamics Security Administration service:
WEB
SERVICE
PROGRAMMERS
GUIDE
143
A P PE N D I X
T R O U B L ES HO O T I N G
Policy
The following is an issue that occurs when using policies with the Dynamics GP web service:
144
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Glossary
Behavior
One characteristic for the web service operation being performed. A policy object has a collection of behaviors.
Web reference
A URL that points to the .asmx file that defines the web service.
Criteria object
An object that contains the restrictions that define what is to be returned from a GetList method in the Dynamics GP web service.
Web service
A software system that provides data and services to other applications. Web services use standard Internet transport protocols such as Hypertext Transfer Protocol (HTTP) and standard XML-based document formats such as Simple Object Access Protocol (SOAP) to exchange information.
eConnect
A set of SQL stored procedures and supporting code used by integrating applications to access data in Microsoft Dynamics GP.
Entity ID assignments
For the Dynamics GP web service, the things that assign Windows User IDs to specific objects in Microsoft Dynamics GP that have identity information. See also User-assignable business objects.
WSDL
Web Service Description Language. The XML-based language used to describe web services.
Extension assembly
An assembly that contains the processing code for a web service extension that is extending one or more business objects for the Dynamics GP web service.
External behavior
A behavior that can be specified by the application that is calling the web method for the Dynamics GP web service and passing the policy object.
Internal behavior
A behavior that can be specified by only the web service administrator.
Policy
A feature of the Dynamics GP web service that allows the web service administrator to control how business objects are created, updated, or deleted.
Policy instance
The set of behaviors for a policy, set a specific way for a particular role.
Proxy
A special set of classes that will act as a wrapper for the operations, objects, and enumerations defined by the web service.
SOAP
Simple Object Access Protocol. The XMLbased protocol used to communicate with a web service.
Summary object
An object that contains only the most important details of the main object. For example, the customer summary object contains only the most important details of the customer object. Summary objects are retuned by the GetList methods in the Dynamics GP web service.
WEB
SERVICE
PROGRAMMERS
GUIDE
145
146
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
Index
A
account numbers determining format of 26 length of 26 using in Dynamics GP web service 26 asynchronously calling web methods 79
B
base objects, described 19 basic restrictions described 44 example 44 behavior option finding in policy instance 70 parameters for 71 behaviors defined 145 described 11 external behaviors 11, 67 finding behavior option 70 finding in policy instance 70 setting selected behavior option 71 setting with code 70 internal behaviors 11, 67 setting selected behavior option 71 benefits, of web services 7 between restrictions described 45 example 45 business document objects described 19 user-assignable 73 BusinessObjectsFile.config configuration errors in 110 described 91, 109 editing 109 impact of Repair operation 110 modifications by other applications 110 modifying 110 structure of 109
configurations, for Dynamics GP web service 9 Connecting to the Web Service, chapter 15-18 context chapter 29-30 culture used 29 currency used 29 for web service call 29 organization 29 role used 30 WorkOnBehalfOf 30 conventions, in documentation 3 Create methods described 23, 33 example 33 Create policy described 34 example 35 retrieving 34 setting behaviors 35 Created, web service event 92 Creating sample event handler method 102 web service event 92 Creating Objects, chapter 33-38 credentials, for web service instance 18 criteria objects creating 41 defined 145 described 39 indexed columns 43 restrictions for 44 culture codes in web service context 29 list of for Context object 133 currency see also MoneyAmount values in web service context 29 ISO codes list 135
C
choice types described 27 determining types in 27 example 27 reading values from 28 writing values to 28 company, specifying with web service context 29 concurrency issues displaying messages for 52 example 52 for Update methods 52 when likely encountered 52
data types chapter 25-28 choice types 27 datetime values 25 decimal values 25 enumerations 26 integer values 25 MoneyAmount values 25 Percent values 26 standard types 25 string values 25 database transactions, events included in 91 date values, empty date values 25 datetime values, described 25 E eConnect decimal values defined 145 described 25 described 9 empty decimal values 25 DefaultingForCreate, web service event 91
DefaultingForDelete, web service event 92 DefaultingForUpdate, web service event 92 DefaultingForVoid, web service event 92 Delete methods described 23, 57 example 57 Delete policy described 58 example 58 retrieving 58 setting behaviors 58 Deleted, web service event 92 Deleting sample event handler method 108 web service event 92 Deleting or Voiding Objects, chapter 57-60 documentation, symbols and conventions 3 Dynamics GP web service architecture 9 capabilities 8 configurations 9 creating objects 33 data types 25 deleting objects 57 documentation for 21 enumerations 26 learning object model 21 not responding 142 object model 19 overview 7 policy 11 reference documentation 21 retrieving individual objects 39 retrieving list of summary objects 40 updating objects 47 URL 15 voiding objects 57 web reference 16 web service instance 18 WSDL file 15 Dynamics GP Web Service Reference, described 21 Dynamics GP Web Services Exceptions console, described 11 Dynamics Security Administration console creating entity ID assignments 73 described 10 illustration 10 Dynamics Security web service described 10 troubleshooting 143 DynamicsGPService.asmx 15
WEB
SERVICE
PROGRAMMERS
GUIDE
147
IN DEX
empty values for dates 25 for decimals 25 for integers 25 for MoneyAmounts 25 for Percents 26 for strings 25 entity ID assignments defined 145 described 73 entity ID filtering chapter 73-78 example 76 GetByKey operations described 74 GetList operations described 75 implementing 75 limitations 76 operations for 74 overview 73 roles for 74 Scope property 75 security settings for 74 setting up 73 tasks for 74 enumerations described 26 example 26 event handler argument types, list of for web service events 96 event handler methods event handler argument types 96 in extension assembly 96 properties passed with event arguments 97 writing code for 97 EventHandlerType, for web service events 91 events EventHandlerType 91 for web service operations 91 how processed for web service operations 91 inclusion in database transactions 91 list of 91 registering for web service operations 91 registration example 111 types of for web service operations 91 Exception console, see Dynamics GP Web Services Exceptions console Exception methods, described 24 exceptions caused by BusinessObjectsFile.config 110 chapter 61-66 Dynamics GP Web Services Exceptions console 61 exception log 61 for Dynamics GP web service 11 list of 137 overview 61
exceptions (continued) system exceptions 64 types of 61 unhandled system exceptions 137 validation exceptions 64 viewing list of 61 Extending the Web Service, part 88-117 extending web service objects how to extend 89 overview 89 parts of the extension 90 procedure 90 web service events 91 extension assembly chapter 95-108 creating 95 defined 145 deploying 96 described 90 event handler methods 96 namespaces required 95 public static class for 96 referenced assemblies 95 Extension objects, working with 113 ExtensionList collection for objects 89 working with 113 external behaviors defined 145 described 11, 67 finding behavior option 70 finding in policy instance 70 setting selected behavior option 71 setting with code 70
inheritance example 20 in web service object model 20 insufficient authorization errors, troubleshooting 140 integer values described 25 empty integer values 25 internal behaviors defined 145 described 11, 67 ISO codes for MoneyAmount values 25 list of 135
L
learning the Dynamics GP web service object model 21 light bulb symbol 3 like restrictions described 45 example 45 list restrictions described 44 example 44 locking rows, concurrency issues for 52 login credentials, for web service instance 18
M
margin notes 3 methods, see web methods MoneyAmount values described 25 empty MoneyAmount values 25 ISO codes for 25
F
filtering, see entity ID filtering format, for account numbers 26
N
namespace for web service proxy 18 required for extension assembly 95
G
Get List methods criteria objects for 41 described 23, 40 examples 41, 42 optimizing performance 43 using results 43 with entity ID filtering 75 Get methods described 23, 39 examples 39 with entity ID filtering 74 Getting Started, part 14-30
O
Object Browser, in Visual Studio 17 object model for Dynamics GP web service 19 inheritance 20 learning 21 object categories 19 objects creating 33 deleting 57 ExtensionList collection 89 filtering 73 how to extend 89 retrieving individual 39 updating 47 voiding 57 which can be extended 89 operations, for entity ID filtering 74 optimized access point, creating 82
H
helper objects, described 20
I
Import GL Transactions, sample application 125 indexed columns, using for criteria objects 43
148
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E
I N D E X
optimizing Get List methods 43 web service access 82 web service applications 142 organization, in web service context 29 Other Programming Techniques, chapter 79-86 overflow, for strings 25
P
parameters, for behavior option 71 Percent values described 26 empty Percent values 26 performance, optimizing for web service applications 142 policy behaviors for 11, 67 chapter 67-71 configuring from code 68 configuring with Dynamics Security Console 68 defined 145 described 11, 67 for Create operations 34 for Delete operations 58 for Update operations 50 for Void operations 58 impacting data 141 listing available policies 68 overview 67 policy instances 67 reference information for 67 roles for 69 troubleshooting 144 using in an application 69 Policy Administrator role, described 68 policy instances creating with code 69 defined 145 deleting with code 69 described 67 retrieving 69 roles for 69 updating with code 69 Policy methods, described 24 prerequisites, for using web services 3 product support, for Microsoft Dynamics GP web services 4 proxy defined 145 described 16 for web service 16 optimized proxy 82
restriction objects basic restrictions 44 between restrictions 45 like restrictions 45 list restrictions 44 types of 44 used with criteria 44 retrieve methods, described 39 Retrieved sample event handler method 98 web service event 91 Retrieving Objects, chapter 39-45 role key automatically assigned for context 30 in web service context 30 roles for entity ID filtering 74 for policy instances 69
tracing modes 138 to log eConnect issues 138 to log web service issues 137 troubleshooting, Dynamics GP web service 137 truncation, for strings 25
U
unhandled system exceptions 137 Update Customers, sample application 127 Update methods concurrency issues 52 described 23, 47 example 47 Update policy described 50 example 50 retrieving 50 setting behaviors 50 Updated, web service event 92 Updating sample event handler method 106 web service event 92 Updating Objects, chapter 47-55 URL, for web service 15 user IDs, for Dynamics GP objects 73 user-assignable business objects defined 145 described 73 Using the Web Service, part 32-86 Using Web Service Extensions, chapter 113-117
S
Sales Documents, sample application 121 samples Import GL Transactions 125 Sales Documents 121 Update Customers 127 Scope property, for criteria objects 75 Security web service, see Dynamics Security web service segments, for account numbers 26 separator character, for account numbers 27 SOAP defined 145 described 7 exceptions from web service operations 61 string values described 25 overflow issues 25 truncation issues 25 summary objects defined 145 described 39 retrieving list of 40 support, for Microsoft Dynamics GP web services 4 symbols in documentation 3 system database, specifying in web service context 29 system exceptions described 61, 64 handling in code 64 viewing details 62
V
ValidatingForCreate sample event handler method 99 web service event 91 ValidatingForDelete, web service event 92 ValidatingForUpdate sample event handler method 104 web service event 92 ValidatingForVoid, web service event 92 validation exceptions described 61, 64 example 64 handling in code 64 viewing details 63 Void methods, described 23, 57 Void policy described 58 retrieving 58 Voided, web service event 93 Voiding, web service event 92
Q
queries, see Get List methods
T
tasks, for entity ID filtering 74 technical support, for Microsoft Dynamics GP web services 4 timeout, specifying for web service instance 18
W
warning symbol 3 web methods calling asynchronously 79 categories 23 chapter 23-24
R
Registering Events, chapter 109-112 registration example, for web service events 111
WEB
SERVICE
PROGRAMMERS
GUIDE
149
IN DEX
web methods (continued) Create methods 23 Delete methods 23 Exception methods 24 framework methods 24 Get methods 23 GetList methods 23 Policy methods 24 Update methods 23 Void methods 23 web reference adding to Visual Studio project 16 creating 16 defined 145 described 16 in C# project 17 web service architecture 9 benefits 7 configurations 9 context 29 defined 145 described 7 instance 18 namespace for 18 not responding 142 object model 19 overview 7 proxy 16 technical support 4 troubleshooting 137 URL 15 Web Service Architecture, chapter 9-11 Web Service Basics, part 6-11 web service events chapter 91-93 defined 145 how processed 91 list of 91 registering 91, 109 registration example 111 types of 91 web service extensions creating or updating data 115 retrieving data from 113 using 113 Web Service Object Model, chapter 19-21 Web Service Samples, part 120-129 Windows User IDs, associating with Dynamics GP objects 73 Work on Behalf of Other Users task 81 WorkOnBehalfOf property for Context object 81 impact of entity ID filtering 76 in web service context 30 WSDL accessing for web service 15 defined 145
X
XML element, used for web service object extension 89
150
W E B
S E R V I C E
P R O G R A M M E R S
G U I D E