Auto Numbering - Customer ID

I notice all of these solutions deal with Incrementing from the server. Here is a way to do it in the client using UserCodes:

using System.Linq;
//also use wizard to bring in UserCodesAdapter

long GetSeq(string WhichSeq, bool ReadOnly = false)
{
	bool error = false;
	long seq = 0;
	var codeAdapter = new UserCodesAdapter(oTrans);
	codeAdapter.BOConnect();
	error = !codeAdapter.GetByID("AutoInc");
	string errorMsg = string.Empty;;
	if(!error)
	{
	   var codes = codeAdapter.UserCodesData.UDCodes.AsEnumerable().Where(c => c.Field<string>("CodeID") == WhichSeq).FirstOrDefault();
		if(codes == null)
		{ //check for our inc code
			error = true;
			errorMsg = string.Format("Code {0} not found in AutoInc usercodes.",WhichSeq);	
		}
		if(!error)
		{
			try
			{
			  seq = (long)codes["Sequence_c"];
				if(!ReadOnly) //we're gonna inc it
				{
					codes["Sequence_c"] = seq+1;
 					codes["RowMod"] = "U";
				}
			}
			catch //return 0 and set to 1
			{
				if(!ReadOnly)
				{
				  codes["Sequence_c"] = 1;
				  codes["RowMod"] = "U";	
				}
			}

			if(codes["RowMod"].ToString() == "U")
			{
				codeAdapter.Update();			
			}
		}
	}
	codeAdapter.Dispose();
	if(error) throw new Exception(errorMsg);
	return seq;
}

To call it:

long seq;
seq = GetSeq("Elevator"); //by default it will inc after giving the seq#
MessageBox.Show("E "+seq.ToString());

seq = GetSeq("Elevator",true);  //if you pass a true, it will NOT inc, but only supply the current value
MessageBox.Show("E2 "+seq.ToString());

seq = GetSeq("BROKE",true); //passing a non-exisitng code will provide an error
MessageBox.Show("B "+seq.ToString());

Setup:
Create a UserCodeType of “AutoInc” and add the desired sequences (in this case Elevator and GrainNum)
Using UD Field maintenance - add a longint field of Sequence_c to the UserCodes table.

1 Like