Hi
My suggestion would be to keep your autonumber method as is, just have an additional optional field called suffix that if populated is added to the end of the new number. This means that you can that use this method for anything, if you want to add a city, country, county etc to the end it doesn't matter. The method only know if there is a suffix add it otherwise return the number as is. heres is an example
internal static string getNextId(IOrganizationService service, Entity target, string idField, int numberOfDigits, string suffix ="")
{
string newId = "";
if (service != null && target != null)
{
try
{
//QueryByAttribute qe = new QueryByAttribute(target.LogicalName);
QueryExpression qe = new QueryExpression(target.LogicalName);
// Retrieve new_autonumber field
qe.ColumnSet = new ColumnSet();
qe.ColumnSet.Columns.Add(idField);
qe.Orders.Add(new OrderExpression(idField, OrderType.Descending));
qe.PageInfo.Count = 1;
qe.PageInfo.PageNumber = 1;
// Retrieve first page (one record) of records
EntityCollection ec = service.RetrieveMultiple(qe);
int nextnumber = 0; // default initial value
if (ec != null & ec.Entities.Count > 0)
{
Entity result = (Entity)ec[0];
// Calculate next supplier if value if existing value
if (result.Attributes.Contains(idField))
{
if (result[idField].GetType() == typeof(int))
{
nextnumber = result.GetAttributeValue<int>(idField);
}
else
{
string suppcode = result.GetAttributeValue<string>(idField);
if (!string.IsNullOrEmpty(suppcode))
{
nextnumber = int.Parse(suppcode);
}
}
}
}
//increment number;
nextnumber += 1;
//Update the target id field with the new number
if (target.Attributes.Contains(idField))
{
target[idField] = nextnumber;
}
else
{
target.Attributes.Add(idField, nextnumber);
}
string padding = "D" + numberOfDigits.ToString();
newId = nextnumber.ToString(padding);
if (!string.IsNullOrEmpty(suffix))
{
newId += suffix;
}
}
catch (System.Exception ex)
{
// do nothing
}
}
return newId;
}
I would also do this as a Prevalidation Create. Plugin.
regards
Imtiaz