Posted on 09/11/2012 09:16:49
Hi Martjn,
I see your point. It would be nice if GenerateVouchers returned an IEnumerable so you knew which codes were generated. That would make it easy to generate a single voucher in an existing list and retrieve its code. For now you can work around that though by checking if the voucher is used. Something like this should work:
VoucherList voucherList = VoucherList.GetListByID(8);
if (voucherList != null)
{
Voucher.GenerateVouchers(1, voucherList.ID);
Voucher voucher = Voucher.GetAllVouchersForList(voucherList.ID).OrderBy(x => x.ID).Last(x => x.DateUsed == null);
string code = voucher.Code;
}
This code gets a VoucherList based on a known ID. It then generates a new voucher and then queries the last available voucher.
Note that this could lead to issues on high volume websites as you may end up with someone else's voucher code. You could make it more bullet proof by first checking the number of vouchers (or the highest ID) before you do the insert and then check if you got what you expected.
Also note: this isn't very efficient code; the GetAll methods retrieves all vouchers and only one is used. This would be more efficient if GenerateVouchers returned the generated Vouchers. Then you could do this:
VoucherList voucherList = VoucherList.GetListByID(8);
if (voucherList != null)
{
Voucher voucher = Voucher.GenerateVouchers(1, voucherList.ID).First();
string code = voucher.Code;
}
Hope this helps,
Imar