My blog has moved! Please visit the new blog at: https://blog.steveendow.com/ I will no longer be posting to Dynamics GP Land, and all new posts will be at https://blog.steveendow.com Thanks!
Monday, October 5, 2009
Develop with XML? You had better know XPath!!!
I started working with XML in 1999 with MSXML3, using DOM and XPath extensively, and then later using extremely elaborate XSLT to do presentation layer transformations for a large web site. Admittedly, back then XML was extremely overhyped, but since then, I haven't met a developer that is comfortable with XPath, let alone XSLT. I'm sure they are out there, I just haven't had the luck to meet them.
The app in question (an add on window for Dynamics GP) was developed by someone a few years ago, but was never really finished, and therefore the client never implemented it. I got the honor of finishing the required functionality and getting it to work properly.
I ignored the fact that this extremely simple, single window "application" with the most rudimentary functionality was completely over-engineered (i.e. 3 tiers). But when I came across code that read a hand coded XML configuration file, I stared in disbelief.
First, why the developer created a custom XML file instead of using the My.Settings feature in Visual Studio 2005 puzzles me. I'll give him the benefit of the doubt and assume that he was using an old version of Visual Studio for some reason. But then I saw this code, which should induce horror in any developer that knows how to work with XML:
Public Function getSQLConnection() As String
Dim xmlRdr As XmlTextReader
Dim sqlConn As String = ""
Dim sDirectory As String = System.Windows.Forms.Application.StartupPath()
Dim sXmlPath As String = sDirectory & "\xmlTrainTemplateConfig.xml"
Try
'create xml reader
xmlRdr = New XmlTextReader(sXmlPath)
'Disable whitespace so that you don't have to read over whitespaces
xmlRdr.WhitespaceHandling = WhitespaceHandling.None
'read the xml declaration
xmlRdr.Read()
'read the 'Configuration' tag
xmlRdr.Read()
'Read the 'Config' tag
xmlRdr.Read()
'Get the 'Config' Attribute Value
If xmlRdr.GetAttribute("type") = "SQL" Then
'Read element 'ConnStr'
xmlRdr.Read()
'Get the 'ConnStr' Element Value
sqlConn = xmlRdr.ReadElementString("ConnStr")
End If
'close the reader
xmlRdr.Close()
Catch EX As Exception
Dim exCustom As New Exception("Error reading xmlTrainTemplateConfig.xml: " & sXmlPath, EX)
Throw exCustom
Finally
getSQLConnection = sqlConn
End Try
End Function
Okay, very funny, I get it, practical joke, right? Seriously, so where is the real code that reads the config file?
So, let me summarize. Reading an XML file line by line, making assumptions about the order of each node/line, and then having to test attribute and element values to see if you are reading the correct node completely defeats the purpose of using an XML file. You might as well just use a text INI file and save yourself time and embarrassment.
The code sample above is, simply, how not to work with XML.
Now, let's try another approach. There are probably a dozen better ways to get the job done, but I'll throw out just one that didn't require any thought or design. Doesn't this look just a tad bit better?
Dim xmlDoc As New XmlDocument
xmlDoc.Load(sXmlPath)
sqlConn = xmlDoc.SelectSingleNode("//ConnStr").InnerText.Trim
This approach uses the most rudimentary XPath node selection expression ("//") that searches the entire XML document for any matching nodes. Technically, this is a very sloppy technique, but like I said, no thought required, and we're dealing with a private config file, so we don't need to be very rigorous.
If you aren't familiar with XPath but want to learn more, I would recommend reading this every good, very simple tutorial:
http://www.w3schools.com/XPath/default.asp
And here is the XPath chapter for the O'Reilly book "XML in a Nutshell" that appears to be available for free online:
http://oreilly.com/catalog/xmlnut/chapter/ch09.html
There are plenty of other XPath references, so it shouldn't be hard to at least learn the basics and bookmark some good references for later use.
To close, I'll leave you with a practical example of how XPath can be used with eConnect. I recently fielded an eConnect question on Experts Exchange where someone asked how they could delete specific taSopLineIvcInsert nodes from an XML document. So if you have an XML document with 500 SOP line items, and you need to delete just 5 specific items, how would you do it?
One way is to try looping through all of the 500 line nodes and check each one to see if it matches the 5 that you need to delete. But that means your code is wasting time checking 495 lines that do not need to be deleted. Wouldn't it be nice to just jump into the XML and select the 5 that you need to delete without having to read the other 495? How does this look?
xmlDoc.LoadXml(myXML)
xmlNode = xmlDoc.SelectSingleNode("//taSopLineIvcInsert[ITEMNMBR='X205']")
xmlNode.ParentNode.RemoveChild(xmlNode)
Pop Quiz: Knowing what you know about SOP lines in Dynamics GP, and now that you are an expert on XPath, what is potentially wrong with the sample code above?
I'll reward the person who gives the first correct answer with a cold beer, or hot cup of coffee, in Fargo at the GP Technical Conference in November. (Winner must be present to receive prize!)
Saturday, October 3, 2009
Using and Debugging SQL Triggers with Dynamics GP
On the other hand, triggers can be difficult to implement, debug, and manage, and can cause unintended consequences. Since I don't use them very often, I don't claim to be a trigger guru, but my interpretation is that SQL Server does not provide very good tools for managing, diagnosing, and debugging triggers. And when you are dealing with a moderately complex application like Dynamics GP, triggers can get you into trouble very quickly--for several different reasons. You have to really understand not only all of the tables, records, and underlying data, but you also need to very clearly understand the sequence of events that occur in those tables if you want to successfully implement a trigger.
I was recently asked to customize GP to automatically populate a single field on a SOP transaction. The client wanted a SOP User Defined field filled out automatically based on the customer and address ID assigned to the order. But they wanted this field to be populated without requiring additional user intervention, and they needed it populated even for orders that were imported from their e-commerce web site.
After weighing the pros and cons of different approaches, I chose to use triggers. I reasoned that triggers would be the most reliable, as they could most easily populate the field regardless of how the order was entered in GP, and a trigger could be fired without requiring any user intervention. One field, right? How hard could that be?
I think that triggers turned out to be a good choice, but I ran into a few surprising issues that required me to learn a few things about GP, and also how to debug triggers on SQL Server.
It turns out that modifying the SOP User Defined fields table was trickier than I thought. I chose to put a trigger on the SOP10100 table, because that table would contain the customer ID and address ID that I needed to lookup my user defined value that was stored in the Customer Master Address File (RM00102). But, of course, it wasn't that easy. There are dozens of things that occur in the database when GP creates a new SOP transaction, so I had to reverse engineer each step of that process to resolve a few errors that were occuring. Here is the trigger that I ended up creating.
-- =============================================
-- Author: Steve Endow
-- Create date: 7/22/2009
-- Description: On insert of SOP transaction, updates
-- the SOP UDF table (SOP10106) to store the 'End User ID'
-- value in the SOP UDF Text 3 field.
-- The End User ID value is stored in the UDF1 field of
-- the customer address record in RM10102.
--
-- Rev 1.0: 7/22/2009
--
-- Rev 1.0f: 7/23/2009
-- Corrected error that would cause SOP get next number to fail (SET @ENDUSERID = '')
-- Corrected error during Order transfer to Invoice: Trigger would insert SOP10106
-- record before GP did, causing GP to get dup index error
--
-- =============================================
IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[ctrStoreEndUserIDSOP10100]'))
BEGIN
DROP TRIGGER ctrStoreEndUserIDSOP10100;
END
GO
CREATE TRIGGER ctrStoreEndUserIDSOP10100
ON SOP10100
AFTER INSERT,UPDATE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for trigger here
DECLARE @SOPTYPE AS smallint
DECLARE @SOPNUMBE AS char(21)
DECLARE @ORIGTYPE AS smallint
DECLARE @ORIGNUMB AS char(21)
DECLARE @CUSTNMBR AS char(15)
DECLARE @ADRSCODE AS char(15)
DECLARE @ENDUSERID AS char(15)
DECLARE @UDFEXISTS AS smallint
DECLARE @ORIGUDFEXISTS AS smallint
SET @SOPTYPE = 0
SET @SOPNUMBE = ''
SET @ORIGTYPE = 0
SET @ORIGNUMB = ''
SET @CUSTNMBR = ''
SET @ADRSCODE = ''
SET @ENDUSERID = ''
--Retrieve the values from the inserted / updated record
SELECT @SOPTYPE = SOPTYPE, @SOPNUMBE = SOPNUMBE, @ORIGTYPE = ORIGTYPE, @ORIGNUMB = ORIGNUMB, @CUSTNMBR = CUSTNMBR, @ADRSCODE = PRSTADCD FROM inserted
--Do not fire if customer or address ID are empty
IF @CUSTNMBR <> '' AND @ADRSCODE <> ''
BEGIN
--Query the end user ID from the customer Ship To Address ID
SELECT @ENDUSERID = RTRIM(USERDEF1) FROM RM00102 WHERE CUSTNMBR = @CUSTNMBR AND ADRSCODE = @ADRSCODE
--Check to see if the UDF record exists for this SOP transaction
SELECT @UDFEXISTS = COUNT(*) FROM SOP10106 WHERE SOPTYPE = @SOPTYPE AND SOPNUMBE = @SOPNUMBE
--Also check to see if the UDF record exists for an originating transaction (in case of transfer to invoice)
SELECT @ORIGUDFEXISTS = COUNT(*) FROM SOP10106 WHERE SOPTYPE = @ORIGTYPE AND SOPNUMBE = @ORIGNUMB
IF @UDFEXISTS = 1
BEGIN
--Update the UDF Text 3 field with the End User ID based on the Ship To Address ID
UPDATE SOP10106 SET USRDEF03 = @ENDUSERID WHERE SOPTYPE = @SOPTYPE AND SOPNUMBE = @SOPNUMBE
END
ELSE
BEGIN
IF @ORIGUDFEXISTS = 0
BEGIN
--Insert a new record into the SOP UDF table, including the end user ID in UDF Text 3
INSERT INTO SOP10106
(SOPTYPE, SOPNUMBE, USRDAT01, USRDAT02, USRTAB01, USRTAB09, USRTAB03, USERDEF1, USERDEF2, USRDEF03, USRDEF04, USRDEF05, COMMENT_1, COMMENT_2, COMMENT_3, COMMENT_4, CMMTTEXT)
VALUES (@SOPTYPE, @SOPNUMBE, '1900.01.01', '1900.01.01', '', '', '', '', '', @ENDUSERID, '', '', '', '', '', '', '')
END
END
END
END
GO
After the trigger was installed, when transferring an order to an invoice, GP would throw a 'duplicate index' error. And when trying to create a new sales order, gp complained that it was unable to get the next document number. When we disabled the trigger, GP worked fine, so it was clear that the trigger code was causing the errors.
The errors were not very specific, so I had little to go on. After some digging, I found that I could debug the trigger code using Visual Studio. This allowed me step through each line of code in my trigger, much like a .NET program, and discover the cause of the errors.
To debug triggers on SQL 2005, you will need Visual Studio 2005 Professional. I'm only going to describe a basic process for debugging T-SQL triggers, but here is an MSDN web page that describes many options and caveats for debugging T-SQL and CLR with SQL 2005. There are several ways to debug T-SQL with Visual Studio, but this is one method that I stumbled on based on the limited instructions I could find.
1. Create a new stored procedure in your database that performs a very simple operation that will cause the trigger to fire. In my case, I had an INSERT, UPDATE trigger, so I created the following stored proc in TWO:
CREATE Procedure DebugTrigger
AS
UPDATE SOP10100 SET ORIGTYPE = ORIGTYPE WHERE SOPNUMBE = 'ORDST2230'
GO
2. Open Visual Studio 2005 Professional and create a new "Database Project".

3. When asked to choose a database reference, either add a new connection, or select an existing connection for your GP database.

4. Now that you have created a new project, expand your database connection on the left, and expand Stored Procedures. It will take a while and may warn you that there are alot of procedures to display (just click on Yes).

5. Right mouse click on your test stored procedure and select "Step Into Stored Procedure"

6. A new tab should open displaying your stored procedure code in debug mode, ready to step into the first line of your procedure.

7. Press F11 to Step Into the procedure line

8. A new tab will open showing your trigger code in debug mode

9. You can now press F11 to step through each line of your trigger
10. Note that the Locals window will allow you to easily see the values of all of the trigger parameters
In the case of my trigger, it turns out that I had two bugs. The first bug caused the insert of the SOP10106 record to fail (my code was trying to insert a NULL value). Because my trigger was on the SOP10100 table, this caused GP's update of the SOPNUMBE field to fail, resulting in the next number error. This 'cascade' effect of triggers is just one of the problems that can make them potentially dangerous, and difficult to debug in production environments. If your trigger fails, it may cause a train wreck as it causes other higher level operations to fail.
The second problem I had was that if an order is transferred to an invoice, GP would attempt to create a new record in SOP10106 for the invoice, but my trigger had already created one as soon as the SOP10100 record was updated. This caused GP to receive a duplicate index error. So my trigger was fighting with GP to insert the record. So in this case, understanding the exact sequence of events that occur under different circumstances is required to ensure that the trigger does not interfere with GP's normal operations.
Thursday, September 24, 2009
Sleuthing Scandalously Slow SmartLists
So BlueLock is hosting a 25 user GP system for an international company with offices around the globe, and they are looking to ensure that the performance will be sufficient. GP is working fine, but there is one strange issue: Some SmartLists take forever to run. A Sales Transaction SmartList might take 20 minutes to output 15,000 records. A GL Account list would take 5 minutes to display 10,000 records. But when the equivalent SQL query is run directly on the SQL Server, the query runs in a second or two.
When I timed a few SmartLists on a physical SQL Server, my results were much, much faster than BlueLock's test times. Additionally, when BlueLock ran certain SmartLists, the server IO and CPU utilization would shoot through the roof, and sometimes GP would stop responding.
We then became concerned that perhaps there was some obscure issue with SmartLists in a fully virtualized environment.
After some head scratching, the BlueLock team looked again at the SQL Profiler trace results for one of the SmartLists. Instead of a single query, SmartLists was issuing many different queries, and even calling stored procedures. Reviewing the additional queries and stored procedures, they found that they all related to Analytical Accounting (AA).
They then tested two scenarios:
1) Remove any columns in the SmartList that relate to AA
2) Remove the AA module so that it isn't loaded when GP starts
Apparently removing the AA columns from the SmartList only had a minor effect on performance. However, removing AA rom the Dynamics.set file resulted in a huge improvement.
Here are two stats they recorded:
SmartList with AA columns removed = 10K records in ~20 minutes.
SmartList with AA removed from Dynamics.set file = 10K records in ~25-30 seconds.
So, by removing Analytical Accounting from the mix, the SmartList went from 20 minutes to 25 seconds.
That's quite an improvement.
Tuesday, September 22, 2009
Attending the Dynamics GP Technical Conference?
If you are technically inclined but haven't registered yet, it's not too late!
http://www.microsoft.com/dynamics/fargodeveloperconference/
It is a trek and a sizeable investment of time and money, but since I haven't attended any of the major conferences in the last few years, I figure it makes sense to attend this one, which will hopefully focus on the technical topics that I work with daily. It looks like there will be several interesting sessions.
Based on a few recommendations, I have opted to stay at the Fargo Wingate instead of the MS recommended Ramada or Holiday Inn. It's only $69 a night for those frugally inclined, but I'll be getting a rental car--which is fine, as I'll then be able to venture out and experience the culinary delights that Fargo has to offer.
And, I admit, I have been looking for an excuse to cram into a Canadair jet and visit Fargo! In November. Average high: 35 F Average low: 19 F. That qualifies as cold in my book.
--Steve
Friday, September 18, 2009
Customizing RDP window size and position
For most of the RDP connections to my virtual servers, I choose to have them run full screen on my second monitor. I like to be able to use ALT+Tab and not have to memorize the RDP equivalent keyboard shortcuts for the non-full screen windows.
But I do have a few RDP connections to my physical servers that I don't like running full screen for various reasons. I liked the option to use 1152 x 864 on my 1680 x 1050 monitors, as it doesn't fill my screen, but gives me enough real estate to still launch a 1024 x 768 window.
Well, I recently upgraded both my laptop and desktop to Windows 7. One of the quirks I've found is that for some reason, I can no longer select the 1152 x 864 size for my remote desktop window. I'm sure there's some explanation having to do with video card drivers or monitor INF files, but I figured there had to be a simple way to get my RDP window sizes to be the same as before.
So I decided to open the RDP file in Notepad, and sure enough, I saw that there were some pretty self-explanatory parameters in the file: desktopwidth, desktopheight, and winposstr. Width and height were easy, but the after adjusting the winposstr parameter, I found that there is something else going on, as I couldn't get the windows to display properly (without the scroll bars).
Sure enough, plenty of people have already dealt with this issue, and I found this post explaining how to pad the window position parameters so that they work properly.
With this knowledge, I can now produce an RDP window with any size that I want--even a window that has a height greater than its width if you want to get fancy. I can also now specify the exact location that I want the window displayed, which is handy as well.
Happy RDP'ing.
Thursday, September 17, 2009
Oh, where, oh, where, is my overtime?
GP calculates overtime HOURS in a fairly simply fashion. You can specify a threshold for the pay period, and hours that exceed that threshold can automatically treated as overtime. Okay, fine. So let's look a the practical implication of that.
- Biweekly Pay Periods
- Automatic Overtime threshold set to 80 hrs
That works fine if the employee works 82 hrs in the pay period, it will automatically treat the 2 hrs over the threshold as overtime. But what about if the employee works only 80 hrs in the pay period, but it included one day that was 14 hrs long? In most states/jurisdictions, overtime is judged on a daily basis (or even sometimes on a duration basis, meaning if it crosses days if it exceeds a certain span of hours it is overtime) and on a weekly basis, but rarely on a pay period basis (in my experience). So GP does not recognize these measures, only the measure of hours per pay period.
So what to do? Yes, there is Overtime Rate Manager. But that only deals with the calculation of the rate used to pay the overtime, not the calculation of how many hours are to be paid. Every time a customer mentions overtime, I cringe, to be honest :) And I do the requisite third party product search. During that search, inevitably an ISV says "that would be a great product, but no, we don't have something that does that".
So it seems that I am left to hoping that the client's timeclock/timekeeping/timecard system will address the overtime calculation (and many do) but what about those that do not use a third party time solution?
Oh, and yes, there is customization of course. But I am still holding out for a simple solution :) Anyone want to comment and save me?
Monday, September 14, 2009
Sales Tax Simplified Part 2
1. Document Default
2. Line Item Default
3. Tax Schedule Comparison
So, step one works pretty much the same as it did in our earlier post. However, we need to take it a step further by considering the inventory site, like the following examples (assuming you are registered for inventory) in Sales Order Processing:
- Shipping Method Delivery: Default tax schedule assigned to Customer's Ship To Address
- Shipping Method Pickup: Default tax schedule assigned to the Site
Now, although I call this a "document" default, because Shipping Method and Site can vary by line item in Sales Order Processing and Purchase Order Processing, this default actually is stored by line item.
So, what about Step 2? Well Step 2 takes in to consideration the inventory item card (or the Sales Order/Purchase Order Setup when dealing with non-inventory items). There are three possible settings for inventory items for Sales and Purchase taxes:
- Nontaxable: No tax is ever charged for this item
- Base on Customer/Vendor: This will charge according to the shipping method
- Taxable: Specify a tax schedule that represents all possible tax details to be charged on this item, more on this later...
So, let's work through a couple examples. First, let's look at the Base on Customer setting. Let's assume that we have entered an invoice for our customer ABC AUTO. They want all items to be shipped to them (Shipping Method- Delivery) at their Missouri location which is assigned to the tax schedule MOTAX which includes the MOCITY and MOSTATE tax details.
Let's say that ABC AUTO buys two items from us, the first item is a gift basket, BASKETOFUN. BASKETOFUN is set with the sales tax option of Base on Customer. So what does that do? If we were to click the item number expansion arrow for this line in Sales Transaction Entry, we would see the following information being stored in the Sales Item Detail Entry window:
- Shipping Method: Delivery
- Ship To Tax Schedule: MOTAX
- Item Tax Option: Base on Customer
- Item Tax Schedule: n/a
Therefore, in this example, all details in MOTAX would be calculated. Now, let's shake it up and say that this particular line item changed to a Shipping Method of Pickup. Let's say that this line item is being sold from our NORTH site with the tax schedule NYTAX. We would then see the following in the Sales Item Detail Entry window:
- Shipping Method: Pickup
- Site Tax Schedule: NYTAX
- Item Tax Option: Base on Customer
- Item Tax Schedule: n/a
So, in this scenario, what taxes would be calculated? All details in the NYTAX schedule would be calculated. Sometimes this scenario is confusing to users, because the item is set to Base on Customers. But what that really means is that the item's taxability is based on the Shipping Method itself, and how the tax schedule defaults.
But, wait, I said that we sold two items right? So let's look at the next item that ABC AUTO bought. They bought our new virtual gift basket, VIRTUALBASKET. Now, some states tax the virtual gift basket, and others do not. So we have set up the VIRTUALBASKET with a sales tax option of Taxable. We have then assigned a special tax schedule to it called VIRTUAL, which includes the taxes that are calculated on virtual products. In our case, let's say that it includes the MOSTATE, KSSTATE, and COSTATE tax details.
If we look at the Sales Item Detail Entry, we would see:
- Shipping Method: Delivery
- Ship to Tax Schedule: MOTAX
- Item Tax Option: Taxable
- Item Tax Schedule: VIRTUAL
Which taxes would be calculated? Only those that are common between MOTAX and VIRTUAL, in this case the MOSTATE detail would be calculated.
But, let's mix it up and say that the customer has asked that this item be shipped to their California location which is assigned to the CATAX schedule (which includes the CASTATE and CACITY tax details). So, let's look a the Sales Item Detail Entry again with these details:
- Shipping Method: Delivery
- Ship to Tax Schedule: CATAX
- Item Tax Option: Taxable
- Item Tax Schedule: VIRTUAL
Which taxes would be calculated in this scenario? None, because the CATAX schedule does not have any details in common with VIRTUAL. This is correct, since we said that our item was only taxable by Missouri (MOSTATE), Kansas (KSSTATE), and Colorado (COSTATE) not by California.
So, the Taxable option for items creates the most flexibility when you have items that are taxed in some states and other items taxed in all states (or different states). I have found this comes in to play quite often with technology products, including software downloads, where some states are more aggressive in taxing these items than others.
Clear as mud? Share you questions, hints, etc and I am happy to update the post--from Alaska, where I am this week teaching :)