using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using System.ServiceModel;
namespace autonumber
{
public class Autono : IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{
IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService _service = serviceFactory.CreateOrganizationService(context.UserId);
string seq = "";
int lastnumber;
if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
{
Entity entity = context.InputParameters["Target"] as Entity;
string records = @"
<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
<entity name='new_autonumber'>
<attribute name='new_lastnumber1'/>
</entity>
</fetch> ";
EntityCollection result = _service.RetrieveMultiple(new FetchExpression(records));
foreach (var c in result.Entities)
{
string count = (string)c.Attributes["new_lastnumber1"];
lastnumber = Convert.ToInt16(count);
lastnumber = lastnumber + 1;
seq = lastnumber.ToString();
c["new_lastnumber1"] = seq;
_service.Update(c);
}
Entity e = context.InputParameters["Target"] as Entity;
string zoneoptionSetValue = e.FormattedValues["new_zone"].ToString();
string zone = (zoneoptionSetValue.Substring(0, 2)).ToUpper();
string wsceoptionSetValue = e.FormattedValues["new_wsccategory"].ToString();
string wsc = (wsceoptionSetValue.Substring(0, 2)).ToUpper();
int len = seq.Length;
if (len == 1)
{
seq = zone + wsc + 0 + 0 + 0 + 0 + seq;
e["new_accountnumber"] = seq;
_service.Update(e);
}
if (len == 2)
{
seq = zone + wsc + 0 + 0 + 0 + seq;
e["new_accountnumber"] = seq;
_service.Update(e);
}
if (len == 3)
{
seq = zone + wsc + 0 + 0 + seq;
e["new_accountnumber"] = seq;
_service.Update(e);
}
if (len == 4)
{
seq = zone + wsc + 0 + seq;
e["new_accountnumber"] = seq;
_service.Update(e);
}
if (len == 5)
{
seq = zone + wsc + seq;
e["new_accountnumber"] = seq;
_service.Update(e);
}
}
}
}
}