(C#) Sample code for Creating Shipments via API


This is a C# code example for creating a Shipment

public static void CreateShipment(){

    AmeriCommerceDatabaseIO oWs = InitializeWebservice();

    // get an existing order
    OrderTrans oOrder = oWs.Order_GetByKey(100167);

    // fill its collection of existing shipments
    oOrder = oWs.Order_FillOrderShippingCollection(oOrder);

    // create a list out of the shipments collection array so we can manipulate it
    System.Collections.Generic.List<OrderShippingTrans> oShipmentCol;

    if (oOrder.OrderShippingColTrans != null)
        oShipmentCol = new System.Collections.Generic.List<OrderShippingTrans>(oOrder.OrderShippingColTrans);
    else
        oShipmentCol = new System.Collections.Generic.List<OrderShippingTrans>();

    // add a new shipment
    OrderShippingTrans oShipment = new OrderShippingTrans();
    oShipment.IsNew = true;
    oShipment.OrderID = oOrder.orderID;
    oShipment.TrackingNumbers = "1234567890";
    oShipment.ShippingDate = MakeDataDateTime(DateTime.Parse("09/1/09"));
    oShipment.ShippingMethod = "test";
    oShipment.TotalWeight = MakeDataMoney(1.0m);

    // optionally add items to shipment
    // this shipment will contain all items on the order, but it can be a partial shipment as well
    oOrder = oWs.Order_FillOrderItemCollection(oOrder);

    // this part is a bit strange - this is due to OrderShippingOrderItemsTrans being an associative entity
    // between the OrderItems and OrderShipping collections
    // since the shipment will contain all the items on the order, create an array that is the same length as the order's items array
    oShipment.OrderItemColTrans = new OrderItemTrans[oOrder.OrderItemColTrans.Length];

    // loop through and create the associative entity for each order item
    for (int i = 0; i < oOrder.OrderItemColTrans.Length; i++){
        OrderShippingOrderItemsTrans oItem = new OrderShippingOrderItemsTrans();
        oItem.IsNew = true;
        oItem.OrderItemsID = oOrder.OrderItemColTrans[i].orderItemsID;
        oItem.QuantityShipped = oOrder.OrderItemColTrans[i].quantity;

        oShipment.OrderItemColTrans[i] = oOrder.OrderItemColTrans[i];
        oShipment.OrderItemColTrans[i].OrderShippingOrderItemsTrans = oItem;
    }

    // add this shipment to the collection
    oShipmentCol.Add(oShipment);

    // convert the shipment col back to an array and assign it to the order
    oOrder.OrderShippingColTrans = oShipmentCol.ToArray();

    // saving the parent object (the order) will handle saving all of its children (shipments, etc)
    oWs.Order_Save(oOrder);
}

How helpful was this article?
Number of questions: 0