Commerce Server 2007: How to use a predefined tracking number for placing an Order?

An often asked question while working with the Order system in Commerce Server has been whether it is possible to use a predefined order number instead of having the Order system generate it for you. The answer is Yes and here is how you can do that.


Generally what is referred to as “order number” is just a friendly string by which the placed order can be uniquely identified (the unfriendly way is to just use the OrderGroupId). The actual property name on the OrderGroup class which corresponds to this is the TrackingNumber property. In the default processing of the order, when the Basket.SaveAsOrder() method is called the Basket is deleted and the PurchaseOrder created. This is also the time that the TrackingNumber property either gets populated with a system generated value (which is basically a sequential numbering based off the IdentityCounter table value – and yes it does take care of a web farm scenario and no – it is not guaranteed to use every number in the sequence, for e.g. an IISReset among other things can cause this numbering to jump) depending on whether the property has been set on the Basket or not. So if you wish to use a predefined value, simply set this property on the Basket before invoking SaveAsOrder() and your value will be carried forward to the PurchaseOrder. If you do not explicitly set this property on the Basket the Order system will populate it for you with a numeric value converted to string. One thing to keep in mind is that there is no SQL constraint for the uniqueness for this property, so the onus is on you to ensure this unique when you set it on the Basket. Otherwise you can potentially end up with 2 Orders having the same TrackingNumber “12345”.


Sample code:


              Guid uid = new Guid(CommerceContext.Current.UserID);

        Basket myCart = OrderContext.Current.GetBasket(uid, "myCart1");

        myCart.TrackingNumber = "12345";

        PurchaseOrder myOrder1 = myCart.SaveAsOrder();

        myCart = OrderContext.Current.GetBasket(uid, "myCart2");

        PurchaseOrder myOrder2 = myCart.SaveAsOrder();

        //Now myOrder1 has a user configured TrackingNumber of "12345"

        //and myOrder2 has a system configured TrackingNumber (something like "6001")