Skip to content

Instantly share code, notes, and snippets.

@smiler
Created December 7, 2011 10:39
Show Gist options
  • Select an option

  • Save smiler/1442339 to your computer and use it in GitHub Desktop.

Select an option

Save smiler/1442339 to your computer and use it in GitHub Desktop.
DuplicateContractCommand = new RelayCommand<ContractListItem>(c =>
{
if (CheckLocked()) return;
SaveBeforeContinue();
var copy = c.Contract.Copy();
// Append (n) to the copys name.
// The algorithm will find the highest n in use for the common prefix of the property identifier.
var regex = new Regex(@"\((?<index>\d+)\)$");
var match = regex.Match(copy.PropertyIdentifier);
var max = 0;
if (match.Success)
{
max = int.Parse(match.Groups["index"].Captures[0].Value);
}
foreach (var contractListItem in ContractListItems)
{
// Strip any copy suffix and compare to make sure that we have a real collision
var cleanName = regex.Replace(copy.PropertyIdentifier, "").ToLower().Trim();
var currentItemCleanName = regex.Replace(contractListItem.Contract.PropertyIdentifier, "").ToLower().Trim();
if (currentItemCleanName != cleanName)
continue;
// Get "copy number" of this item and store it as max if it's higher than before
var innerMatch = regex.Match(contractListItem.Contract.PropertyIdentifier);
if (innerMatch.Success)
{
var num = int.Parse(innerMatch.Groups["index"].Captures[0].Value);
if (num > max)
max = num;
}
}
// Set new name to one above max
if (match.Success)
copy.PropertyIdentifier = regex.Replace(copy.PropertyIdentifier, "(" + ++max + ")");
else
copy.PropertyIdentifier = copy.PropertyIdentifier + " (" + ++max + ")";
// Save to db
_dataService.SaveContract(copy);
// Create new list item
var newContractListItem = new ContractListItem() { Contract = copy, TransactionId = copy.Id };
ContractListItems.Add(newContractListItem);
CurrentContractListItem = newContractListItem;
RaisePropertyChanged(() => CurrentContractListItem);
}, c => c != null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment