Hi SIr,
Here is code ...
// <summary>Auto Numbering Plugin</summary>
namespace PCL.AutoNumberingPlugin
{
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Xml.Linq;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
/// <summary>
/// AutoNumberingPlugin Class
/// </summary>
public class AutoNumberingPlugin : IPlugin
{
/// <summary>
/// lock object
/// </summary>
private static object lockobject = new object();
/// <summary>
///Constant string for Unsecure Exception Message
/// </summary>
public const string unsecureExceptionMsg = "Unsecure configuration Missing or Error.";
/// <summary>
///Constant string for Unsecure Exception Message
/// </summary>
public const string invalidExceptionMsg = "Plugin registration not valid for {0} message.";
/// <summary>
/// string to store configuration data
/// </summary>
private string configurationData;
/// <summary>
/// Initializes a new instance of the <see cref="AutoNumberingPlugin" /> class.
/// </summary>
/// <param name="unsecure">un secured string parameter</param>
/// <param name="secure">secured string parameter</param>
public AutoNumberingPlugin(string unsecure, string secure)
{
this.configurationData = unsecure;
}
/// <summary>
/// IncrementalNumberingPlugin Method Execute
/// </summary>
/// <param name="serviceProvider">service Provider</param>
public void Execute(IServiceProvider serviceProvider)
{
ITracingService tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = factory.CreateOrganizationService(context.UserId);
string accountNumber = string.Empty;
string employeeCode = string.Empty;
string region = string.Empty;
string oppNumber = string.Empty;
string groupCode = string.Empty;
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
if (context.MessageName.ToLower() != "create")
{
throw new InvalidPluginExecutionException(String.Format(AutoNumberingPlugin.invalidExceptionMsg, context.MessageName));
}
lock (lockobject)
{
try
{
Entity targetEntity = (Entity)context.InputParameters["Target"];
//Dictionary to store configuration
Dictionary<string, string> globalConfig = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(this.configurationData))
{
globalConfig = ReadUnSecuredConfig(this.configurationData);
}
else
{
throw new InvalidPluginExecutionException(AutoNumberingPlugin.unsecureExceptionMsg);
}
//variable to Store autonumbering record guid
Guid numberingSchemeGuid = new Guid(globalConfig["autonumrecordguid"]);
this.LockProgramExecution(service, numberingSchemeGuid);
IncrementalNumbering setting = IncrementalNumbering.GetSettings(service, numberingSchemeGuid);
if (setting.EntityName != null)
{
int next = setting.CurrentPosition + setting.incrementby;
int autonumlength = setting.Autonumberlength;
string prefix = string.Empty;
string suffix = string.Empty;
if (setting.PrefixType == 0)
{
prefix = string.Empty;
}
else if (setting.PrefixType == 1)
{
prefix = setting.Prefix;
}
else if (setting.PrefixType == 2)
{
prefix = DateTime.Now.ToString(setting.Prefix, CultureInfo.CurrentCulture);
}
if (setting.SuffixType == 0)
{
suffix = string.Empty;
}
else if (setting.SuffixType == 1)
{
suffix = setting.Suffix;
}
else if (setting.SuffixType == 2)
{
suffix = DateTime.Now.ToString(setting.Suffix, CultureInfo.CurrentCulture);
}
//daily Reset
if (setting.ResetOn == 1)
{
if (((setting.LastUpdateOn).ToUniversalTime().Date) != DateTime.UtcNow.Date)
{
next = 1;
}
}
else if (setting.ResetOn == 2) //monthly Reset
{
if (((setting.LastUpdateOn).ToUniversalTime().Month) != DateTime.UtcNow.Month)
{
next = 1;
}
}
else if (setting.ResetOn == 3) //yearly Reset
{
if (((setting.LastUpdateOn).ToUniversalTime().Year) != DateTime.UtcNow.Year)
{
next = 1;
}
}
string nextnum = string.Empty;
if (targetEntity.LogicalName == "pcl_territorytargetsheet")
{
if (targetEntity.Contains("pcl_employeecode") && targetEntity.Attributes.Contains("pcl_employeecode"))
{
employeeCode = targetEntity.Attributes["pcl_employeecode"].ToString();
}
if (targetEntity.Contains("pcl_region") && targetEntity.Attributes.Contains("pcl_region"))
{
region = targetEntity.Attributes["pcl_region"].ToString();
}
nextnum = next.ToString(CultureInfo.CurrentCulture);
nextnum = nextnum.PadLeft(autonumlength, setting.lengthpad);
targetEntity.Attributes["pcl_financialyear"] = setting.FixPrefix;
nextnum = region + prefix + employeeCode + prefix + setting.FixPrefix + prefix + nextnum + suffix + setting.FixSuffix;
}
if (targetEntity.LogicalName == "opportunity")
{
if (targetEntity.Contains("parentaccountid") && targetEntity.Attributes.Contains("parentaccountid"))
{
EntityReference accountLookup = (EntityReference)targetEntity.Attributes["parentaccountid"];
Entity account = service.Retrieve(accountLookup.LogicalName, accountLookup.Id, new ColumnSet("accountnumber"));
if (account.Contains("accountnumber") && account.Attributes.Contains("accountnumber"))
{
accountNumber = account.Attributes["accountnumber"].ToString();
}
}
if (targetEntity.Contains("pcl_product") && targetEntity.Attributes.Contains("pcl_product"))
{
Guid productId = ((EntityReference)targetEntity.Attributes["pcl_product"]).Id;
// ConditionExpression conditionStatus = new ConditionExpression("statecode", ConditionOperator.Equal, 0); //Active
QueryExpression queryMaster = new QueryExpression("pcl_productgroup");
queryMaster.ColumnSet = new ColumnSet("pcl_groupcode", "pcl_productgroupid");
LinkEntity linkDetail = queryMaster.AddLink("product", "pcl_productgroupid", "pcl_productgroup", JoinOperator.Inner);
ConditionExpression conditionProduct = new ConditionExpression("productid", ConditionOperator.Equal, productId);
linkDetail.LinkCriteria.AddCondition(conditionProduct);
// linkDetail.LinkCriteria.AddCondition(conditionStatus);
EntityCollection Collection = service.RetrieveMultiple(queryMaster);
if (Collection.Entities.Count > 0)
{
groupCode = Collection.Entities[0].Attributes["pcl_groupcode"].ToString();
}
//tracing.Trace("Count = "+Collection.Entities.Count);
//tracing.Trace("Record Code = "+ Collection.Entities[0].Attributes["pcl_groupcode"]);
}
nextnum = next.ToString(CultureInfo.CurrentCulture);
nextnum = nextnum.PadLeft(autonumlength, setting.lengthpad);
targetEntity.Attributes["pcl_financialyear"] = setting.FixPrefix;
nextnum = groupCode + prefix + accountNumber + prefix + setting.FixPrefix + prefix + nextnum + suffix + setting.FixSuffix;
//tracing.Trace("nextnum" + nextnum);
}
if (targetEntity.LogicalName == "pcl_customerrequest")
{
tracing.Trace("Step1");
if (targetEntity.Contains("pcl_opportunity") && targetEntity.Attributes.Contains("pcl_opportunity"))
{
EntityReference oppLookup = (EntityReference)targetEntity.Attributes["pcl_opportunity"];
Entity oppourtunity = service.Retrieve(oppLookup.LogicalName,oppLookup.Id, new ColumnSet("pcl_opportunitynumber"));
if (oppourtunity.Contains("pcl_opportunitynumber") && oppourtunity.Attributes.Contains("pcl_opportunitynumber"))
{
oppNumber = oppourtunity.Attributes["pcl_opportunitynumber"].ToString();
}
var Count = getCustomerRequest(service,oppLookup.Id);
nextnum = next.ToString(CultureInfo.CurrentCulture);
nextnum = nextnum.PadLeft(autonumlength, setting.lengthpad);
nextnum =setting.FixPrefix + prefix + oppNumber + prefix + Count;
}
}
// nextnum = setting.FixPrefix + prefix + nextnum + suffix + setting.FixSuffix;
//nextnum = setting.FixPrefix + prefix + accountNumber + nextnum + suffix + setting.FixSuffix;
//Increment Number
if (setting.Increment(service, next))
{
targetEntity[setting.PropertyName] = nextnum;
}
}
}
catch (Exception ex)
{
throw new InvalidPluginExecutionException(ex.Message, ex);
}
}
}
}
public static int getCustomerRequest(IOrganizationService service,Guid oppId)
{
int count=0;
QueryExpression CR = new QueryExpression("pcl_customerrequest");
CR.ColumnSet = new ColumnSet("pcl_opportunity");
CR.Criteria.AddCondition("pcl_opportunity", ConditionOperator.Equal, oppId);
EntityCollection result = service.RetrieveMultiple(CR);
count = result.Entities.Count + 1;
return count;
}
/// <summary>
/// Creates Key pair dictionary from unsecured configuration text
/// </summary>
/// <param name="localConfig">unsecured configuration text</param>
private Dictionary<string, string> ReadUnSecuredConfig(string configData)
{
Dictionary<string, string> globalConfig = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(configData))
{
XDocument xmlConfigData = XDocument.Parse(configData);
foreach (XElement element in xmlConfigData.Descendants("appSettings"))
{
foreach (XElement childEllement in element.Descendants())
{
globalConfig.Add(childEllement.FirstAttribute.Value, childEllement.LastAttribute.Value);
}
}
}
return globalConfig;
}
/// <summary>
/// lock execution program
/// </summary>
/// <param name="service">Organization Service</param>
/// <param name="traceservice">Tracing Service</param>
/// <param name="numberingSchemeGuid">numbering Scheme </param>
private void LockProgramExecution(IOrganizationService service, Guid numberingSchemeGuid)
{
try
{
Random randNo = new Random();
int newRandomNo = randNo.Next(1, 1000);
Entity numSchemeRecordEntity = new Entity("pcl_numberingscheme");
numSchemeRecordEntity.Id = numberingSchemeGuid;
numSchemeRecordEntity.Attributes["pcl_randomnumber"] = newRandomNo.ToString();
service.Update(numSchemeRecordEntity);
}
catch (Exception ex)
{
throw new Exception("Exception in LockProgramExecution", ex);
}
}
}
}
This is my complete
Can someone explain me steps ..what value is taking from where?