Create Select Order on Server

The code below demonstrates how to create an order on a Select Server. The primary difference between clients and servers is that clients are created by a login process that provides a user and profile. Servers do not have profiles by default. Any order created by a Server will show up as created by “System”.

I must make it clear that this is not the preferred way to create orders. Orders should be created by clients.

class CreateOrder
{
    /// <summary>
    /// Private copy of service provider from server class.
    /// </summary>
    private IServiceProvider _sp;

    /// <summary>
    /// Constructor. Cache service provider.
    /// </summary>
    /// <param name="sp"></param>
    public CreateOrder(IServiceProvider sp)
    {
        _sp = sp;
    }

    /// <summary>
    /// Create example order after setting active profile.
    /// </summary>
    public void CreateOrder()
    {
        using (RuntimeContext.Impersonate(RuntimeContext.CurrentSessionToken, true))
        {
            // Set default profile.
            IProfileManager pm = GetService<IProfileManager>();
            IProfileInfo pi = pm.Profiles.Where(t => t.Name == "Default").FirstOrDefault();
            IProfile profile = pm.GetProfile(pi);
            pm.ActiveProfile = profile;

            // Create new order.
            IOrderStore os = GetService<IOrderStore>();
            var spec = new OrderCreationSpec();
            spec.SettlementType = SettlementType.CDF;
            IOrder order = os.NewOrder(spec);

            // Update new order as necessary...

            // Save the order in the database.
            os.ApplyChanges(order);
        }
    }

    /// <summary>
    /// Gets the specified service from the service provider.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns>Service</returns>
    public T GetService<T>()
    {
        return (T)_sp.GetService(typeof(T));
    }
}