using System.Collections;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Globalization;
namespace gm_PAT_Lock_After_Specs_Complete_class
class gm_PAT_Lock_After_Specs_Complete_class : Item
public gm_PAT_Lock_After_Specs_Complete_class() : base(null) { }
public Item gm_PAT_Lock_After_Specs_Complete()
Aras.Server.Core.CallContext CCO = ((Aras.Server.Core.IOMConnection)serverConnection).CCO;
Aras.Server.Core.IContextState RequestState = CCO.RequestState;
#region gm_PAT_Lock_After_Specs_Complete
string MethodName = "gm_PAT_Lock_After_Specs_Complete";
grantIdentityPrivileges("Aras PLM");
IDataAccessLayer dataAccessLayer = new DataAccessLayer(innovator);
BusinessLogic businessLogic = new BusinessLogic(dataAccessLayer);
businessLogic.LockPAT(this);
catch (System.ArgumentException argex)
result = innovator.newError("<style>#toggleInfo {display: none;} #copyBuffer {display: none;}</style>" + argex.Message);
catch (System.ApplicationException appex)
result = innovator.newError(string.Format("<b>ERROR in method {0}</b><br>{1}", MethodName, appex.Message));
catch (Aras.Server.Core.ItemIsLockedException ex)
result = innovator.newError(ex.Message);
result.setErrorDetail(ex.InnerException.Message);
catch (System.Exception ex)
if (ex.Message == "Aras.Server.Core.ItemIsLockedBySomeoneElseException")
result = innovator.newError("The ECR is locked by someone else. Unlock the ECR to proceed further.");
result = innovator.newError(string.Format("<b>SYSTEM EXCEPTION in method {0}</b><br>{1}", MethodName, ex.Message));
revokeIdentityPrivileges();
private Innovator _innovator;
public Innovator innovator
_innovator = this.getInnovator();
public class BusinessLogic
private static class Constants
internal static class ItemTypeNames
internal const string WorkflowTask = "Workflow Task";
internal const string WorkOrder = "gm_Work Order";
internal const string WorkOrderPAT = "gm_Work Order gm_PATSrc";
internal const string WorkOrderPPAT = "gm_Work Order PPPAT";
internal static class PropertyNames
internal const string AssignmentId = "AssignmentId";
internal const string State = "state";
internal const string Item = "item";
internal const string IsAuto = "is_auto";
internal const string LockedById = "locked_by_id";
internal const string KeyedName = "keyed_name";
internal const string Type = "_type";
internal static class PropertyCondition
internal const string NotNull = "is not null";
internal static class Actions
internal const string Get = "get";
internal const string PromoteItem = "promoteItem";
internal static class Attributes
internal const string Select = "select";
internal const string IdList = "idlist";
internal static class WorkOrderStates
internal const string Investigate = "Investigate";
internal static class PatStates
internal const string Locked = "Locked";
internal static class EcrTypes
internal const string BCR = "BOM Change Request Type";
internal const string BSD = "Build Site Direction Type";
private readonly IDataAccessLayer dataAccessLayer;
private Item workOrder = null;
private readonly Innovator inn = null;
public BusinessLogic(IDataAccessLayer dataAccessLayer)
this.dataAccessLayer = dataAccessLayer;
this.inn = dataAccessLayer.getInnovator();
public void LockPAT(Item activity)
workOrder = GetWorkOrder(activity);
if (workOrder != null && workOrder.getProperty(Constants.PropertyNames.State).Equals(Constants.WorkOrderStates.Investigate, StringComparison.OrdinalIgnoreCase))
Item effPtVal = inn.newItem("Method", "gm_PIC EffectivePointValidation");
effPtVal.setProperty("source_id", workOrder.getID());
effPtVal = effPtVal.apply();
if (effPtVal.isError()) throw new ApplicationException(effPtVal.getErrorString());
Item effPtValStk = inn.newItem("Method", "gm_EffecPt_StockDisp_Validation");
effPtValStk.setProperty("id", workOrder.getID());
effPtValStk = effPtValStk.apply();
if (effPtValStk.isError()) throw new ApplicationException(effPtValStk.getErrorString());
string type = workOrder.getProperty(Constants.PropertyNames.Type, "");
if (type.Equals(Constants.EcrTypes.BCR, StringComparison.OrdinalIgnoreCase) || type.Equals(Constants.EcrTypes.BSD, StringComparison.OrdinalIgnoreCase))
PromoteRelationship(Constants.ItemTypeNames.WorkOrderPPAT, Constants.PatStates.Locked);
PromoteRelationship(Constants.ItemTypeNames.WorkOrderPAT, Constants.PatStates.Locked);
private Item GetWorkOrder(Item activity)
var workflowTask = dataAccessLayer.getItemById(Constants.ItemTypeNames.WorkflowTask, activity.getProperty(Constants.PropertyNames.AssignmentId));
if (!workflowTask.isError() && !workflowTask.isEmpty())
return dataAccessLayer.getItemById(Constants.ItemTypeNames.WorkOrder, workflowTask.getProperty(Constants.PropertyNames.Item));
private List<string> GetRelationshipTypeIds(string relationshipTypeName, string newState)
workOrder.fetchRelationships(relationshipTypeName, "id,state");
var ecrRelationships = workOrder.getRelationships(relationshipTypeName);
int count = ecrRelationships.getItemCount();
List<string> relationshipIds = new List<string>(count);
for (int i = 0; i < count; i++)
var currentState = ecrRelationships.getItemByIndex(i).getProperty(Constants.PropertyNames.State, "");
if (!currentState.Equals(newState, StringComparison.OrdinalIgnoreCase))
relationshipIds.Add(ecrRelationships.getItemByIndex(i).getID());
private void PromoteRelationship(string relationship, string newState)
var idsToPromote = GetRelationshipTypeIds(relationship, newState);
Item itemsToPromote = dataAccessLayer.newItem(relationship, Constants.Actions.Get);
itemsToPromote.setAttribute(Constants.Attributes.IdList, string.Join(",", idsToPromote));
itemsToPromote.setProperty(Constants.PropertyNames.State, newState);
var results = itemsToPromote.apply(Constants.Actions.PromoteItem);
throw new Aras.Server.Core.InnovatorServerException(results.getErrorDetail());
catch (Aras.Server.Core.ItemIsLockedException)
GetAllKeyedNames(relationship, idsToPromote);
private void GetAllKeyedNames(string relationship, List<string> idsToPromote)
Item itemsFailedToPromote = dataAccessLayer.newItem(relationship, Constants.Actions.Get);
itemsFailedToPromote.setAttribute(Constants.Attributes.IdList, string.Join(",", idsToPromote));
itemsFailedToPromote.setPropertyCondition(Constants.PropertyNames.LockedById, Constants.PropertyCondition.NotNull);
itemsFailedToPromote.setAttribute(Constants.Attributes.Select, "id, keyed_name,locked_by_id");
itemsFailedToPromote = itemsFailedToPromote.apply();
if (itemsFailedToPromote.isError())
throw new Aras.Server.Core.InnovatorServerException(
"Failed trying to Promote locked items. " + itemsFailedToPromote.getErrorDetail());
List<string> lockedItems = new List<string>();
for (var i = 0; i < itemsFailedToPromote.getItemCount(); i++)
var itm = itemsFailedToPromote.getItemByIndex(i);
if (itm.getProperty("locked_by_id") == null) continue;
var lockedItem = itm.getProperty(Constants.PropertyNames.KeyedName, "");
if (!string.IsNullOrWhiteSpace(lockedItem))
lockedItems.Add("\"" + lockedItem + "\"");
string itemOrItems = lockedItems.Count != 1 ? " items" : " item";
string isOrAre = lockedItems.Count != 1 ? " are" : " is";
new Exception("Locked Item Type: " + relationship + ". Locked Ids: " + string.Join(", ", idsToPromote) + ".");
throw new Aras.Server.Core.ItemIsLockedException(
"<b>" + string.Join("</b>, <b>", lockedItems) + "</b>" + itemOrItems + isOrAre +
" locked. Your vote cannot be completed while the" + itemOrItems + isOrAre + " locked. Unlock the" +
itemOrItems + " to continue voting.", detailException);
public interface IDataAccessLayer
Innovator getInnovator();
Item newItem(string itemTypeName, string action);
Item getItemById(string itemTypeName, string id);
Item fetchRelationships(Item item, string relationshipTypeName);
public class DataAccessLayer : IDataAccessLayer
private readonly Innovator innovator = null;
public DataAccessLayer(Innovator innovator)
this.innovator = innovator;
public Innovator getInnovator()
public Item newItem(string itemTypeName, string action)
return innovator.newItem(itemTypeName, action);
public Item getItemById(string itemTypeName, string id)
return innovator.getItemById(itemTypeName, id);
public Item apply(Item item)
public Item fetchRelationships(Item item, string relationshipTypeName)
return item.fetchRelationships(relationshipTypeName);
#region "Identity Privileges"
private string AssignedIdentity;
public void grantIdentityPrivileges(string assignedIdent)
if (!string.IsNullOrEmpty(AssignedIdentity))
revokeIdentityPrivileges();
Aras.Server.Security.Identity secIdentity = Aras.Server.Security.Identity.GetByName(assignedIdent);
if (Aras.Server.Security.Permissions.GrantIdentity(secIdentity))
AssignedIdentity = assignedIdent;
public void revokeIdentityPrivileges()
if (AssignedIdentity != null)
Aras.Server.Security.Permissions.RevokeIdentity(Aras.Server.Security.Identity.GetByName(AssignedIdentity));
public void EndOfMethod()
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.SessionState;
using System.Globalization;
using System.Web.ModelBinding;
namespace gm_Query_PPAT_onSearch_class
class gm_Query_PPAT_onSearch_class : Item
public gm_Query_PPAT_onSearch_class() : base(null) { }
public Item gm_Query_PPAT_onSearch()
Aras.Server.Core.CallContext CCO = ((Aras.Server.Core.IOMConnection)serverConnection).CCO;
Aras.Server.Core.IContextState RequestState = CCO.RequestState;
#region gm_Query_PPAT_onSearch
if(System.Diagnostics.Debugger.Launch())
System.Diagnostics.Debugger.Break();
const string methodName = "gm_Query_PPAT_onSearch";
IDataAccessLayer dataAccessLayer = new DataAccessLayer(innovator);
BusinessLogic businessLogic = new BusinessLogic(dataAccessLayer);
result = businessLogic.Search(result);
catch (Aras.Server.Core.InnovatorServerException ex)
result = innovator.newError(string.Format("<b>SYSTEM EXCEPTION in method {0}</b><br>{1}", methodName, ex.Message));
catch (System.ArgumentException argex)
result = innovator.newError("<style>#toggleInfo {display: none;} #copyBuffer {display: none;}</style>" + argex.Message);
private Innovator _innovator;
public Innovator innovator
_innovator = this.getInnovator();
public class BusinessLogic
private readonly IDataAccessLayer _dataAccessLayer;
public BusinessLogic(IDataAccessLayer dataAccessLayer)
_dataAccessLayer = dataAccessLayer;
public Item Search(Item searchItem)
var queryPpat = new QueryPpatPoco(searchItem);
queryPpat.PreProdProgramCode = GetProgramCode(queryPpat.PreProdProgramName);
var sqlParameters = new List<System.Data.SqlClient.SqlParameter>();
var query = queryPpat.GenerateQuery(sqlParameters);
var result = _dataAccessLayer.GetResult(query, sqlParameters, queryPpat.PreProdProgramName, queryPpat.HardwareStage);
throw new ArgumentException(result.getErrorDetail());
public string GetProgramCode(string programName)
var query = "select _PREPROD_PROD_PGM_CD from GM_PREPROD_PROD_PGM_CD where _PREPROD_PROD_PGM_NM = '" +
var result = _dataAccessLayer.ApplySql(query);
throw new ArgumentException("\"Pre - Production Program\" is not valid.");
return result.getItemByIndex(0).getProperty("_preprod_prod_pgm_cd");
public class QueryPpatPoco
internal static class PropertyNames
internal const string VehicleBuildQuery = "_vehicle_build_query";
internal const string GpsBuildQuery = "_gps_build_query";
internal const string PreProdProgramName = "_pre_prod_program_name";
internal const string HardwareStage = "_hardware_stage";
internal const string UpcPrefix = "_upc_prefix";
internal const string Upc = "_upc";
internal const string Fna = "_fna";
internal const string FnaDescription = "_fna_desc";
internal const string PartNumber = "_part_numbers";
internal const string Pls = "_pls";
internal const string Dls = "_dls";
internal const string EngineerCodes = "_engr_codes";
internal const string EngineerLastNames = "_engr_last_name";
private const string Keyedname = "keyed_name";
public bool VehicleBuildQuery { get; set; }
public bool GpsBuildQuery { get; set; }
public string PreProdProgramName { get; set; }
public string PreProdProgramCode { get; set; }
public string HardwareStage { get; set; }
public string UpcPrefix { get; set; }
public string Upc { get; set; }
public string Fna { get; set; }
public string FnaDescription { get; set; }
public string PartNumber { get; set; }
public string Pls { get; set; }
public string Dls { get; set; }
public List<string> EngineerCodes { get; set; }
public List<string> EngineerLastNames { get; set; }
public QueryPpatPoco(Item queryItem)
VehicleBuildQuery = Trim(queryItem.getProperty(PropertyNames.VehicleBuildQuery, "0")).Equals("1", StringComparison.OrdinalIgnoreCase);
GpsBuildQuery = Trim(queryItem.getProperty(PropertyNames.GpsBuildQuery, "0")).Equals("1", StringComparison.OrdinalIgnoreCase);
PreProdProgramName = Trim(queryItem.getProperty(PropertyNames.PreProdProgramName));
HardwareStage = Trim(queryItem.getProperty(PropertyNames.HardwareStage));
UpcPrefix = Trim(queryItem.getPropertyAttribute(PropertyNames.UpcPrefix, Keyedname));
Upc = Trim(queryItem.getPropertyAttribute(PropertyNames.Upc, Keyedname));
Fna = Trim(queryItem.getPropertyAttribute(PropertyNames.Fna, Keyedname));
FnaDescription = Trim(queryItem.getProperty(PropertyNames.FnaDescription));
PartNumber = Trim(queryItem.getPropertyAttribute(PropertyNames.PartNumber, Keyedname));
Pls = Trim(queryItem.getProperty(PropertyNames.Pls));
Dls = Trim(queryItem.getProperty(PropertyNames.Dls));
EngineerCodes = Trim(queryItem.getProperty(PropertyNames.EngineerCodes, "")).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
EngineerLastNames = Trim(queryItem.getProperty(PropertyNames.EngineerLastNames, "")).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
private void SanityCheck()
if (!VehicleBuildQuery && !GpsBuildQuery)
throw new ArgumentException("Either \"Vehicle Build Query\" or \"GPS Build Query\" must be selected.");
if (string.IsNullOrWhiteSpace(PreProdProgramName) || string.IsNullOrWhiteSpace(HardwareStage))
throw new ArgumentException(" \"Pre - Production Program\" and \"Hardware Stage\" must be selected.");
if (string.IsNullOrWhiteSpace(PartNumber) && string.IsNullOrWhiteSpace(UpcPrefix) && string.IsNullOrWhiteSpace(Upc) && string.IsNullOrWhiteSpace(Fna)
&& string.IsNullOrWhiteSpace(FnaDescription) && (EngineerCodes == null || !EngineerCodes.Any()) && (EngineerLastNames == null || !EngineerLastNames.Any()))
throw new ArgumentException("You must select a \"Pre-Production Program and Hardware Stage\" and a minimum of one other criteria in order to perform a search.");
if (EngineerCodes != null && (EngineerCodes.Count > 6 || EngineerCodes.Any(s => s.Length != 4)))
throw new ArgumentException("Engineer Code(s) must be 4 characters each separated by commas; maximum of 6 Engineer Codes allowed.");
if (EngineerLastNames != null && EngineerLastNames.Any() && EngineerLastNames.Select(s => s.Length).Sum() > 30)
throw new ArgumentException("Engineer Last Name(s) must be 30 or fewer characters.");
public string Trim(string input)
return input != null ? input.Trim() : null;
public string GenerateQuery(List<System.Data.SqlClient.SqlParameter> sqlParameters)
var searchQuery = string.Empty;
searchQuery = new VehicleSearchQuery(this).GetQuery(sqlParameters);
if (!GpsBuildQuery) return searchQuery;
searchQuery += " union ";
searchQuery += new GpsSearchQuery(this).GetQuery(sqlParameters);
public abstract class BaseSearchQuery
protected string PartNumberColName;
protected string DlsColName;
protected string PlsColName;
protected string UpcPrefixColName;
protected string UpcColName;
protected string FnaColName;
protected string FnaDescriptionColName;
protected string EngineerCodesColName;
protected string EngineerLastNamesColName;
protected QueryPpatPoco SearchItem;
protected static class ParameterNames
internal const string PreProdProgam = "@preprodpgram";
internal const string HardwareStage = "@hardwarestage";
internal const string PartNumber = "@partnumber";
internal const string Dls = "@dls";
internal const string Pls = "@pls";
internal const string UpcPrefix = "@upcprefix";
internal const string Upc = "@upc";
internal const string Fna = "@fna";
internal const string FnaDescription = "@fnadesc";
internal const string EngineerCodes = "@engineercodes";
internal const string EngineerLastNames = "@engineerlastname";
protected bool IsVehicle = false;
protected BaseSearchQuery(QueryPpatPoco ppatSearch)
public abstract void SetColumnNames();
public abstract string BaseQuery();
private static void AddToSqlParameter(List<System.Data.SqlClient.SqlParameter> sqlParameters, string parameterName, string value)
var sqlParameter = new System.Data.SqlClient.SqlParameter(parameterName, value);
if (string.IsNullOrWhiteSpace(value))
sqlParameter.Value = DBNull.Value;
sqlParameters.Add(sqlParameter);
public string GetQuery(List<System.Data.SqlClient.SqlParameter> sqlParameters)
var query = new StringBuilder();
var parameterPrefix = IsVehicle ? "Vehicle" : "Gps";
query.Append(BaseQuery());
AddToSqlParameter(sqlParameters, ParameterNames.PreProdProgam + parameterPrefix, SearchItem.PreProdProgramCode);
AddToSqlParameter(sqlParameters, ParameterNames.HardwareStage + parameterPrefix, SearchItem.HardwareStage);
AddToSqlParameter(sqlParameters, ParameterNames.PartNumber + parameterPrefix, SearchItem.PartNumber);
AddToSqlParameter(sqlParameters, ParameterNames.Dls + parameterPrefix, SearchItem.Dls);
AddToSqlParameter(sqlParameters, ParameterNames.Pls + parameterPrefix, SearchItem.Pls);
AddToSqlParameter(sqlParameters, ParameterNames.Upc + parameterPrefix, SearchItem.Upc);
AddToSqlParameter(sqlParameters, ParameterNames.Fna + parameterPrefix, SearchItem.Fna);
AddToSqlParameter(sqlParameters, ParameterNames.FnaDescription + parameterPrefix, SearchItem.FnaDescription);
AddToSqlParameter(sqlParameters, ParameterNames.UpcPrefix + parameterPrefix, SearchItem.UpcPrefix);
AddToSqlParameter(sqlParameters, ParameterNames.EngineerCodes + parameterPrefix, string.Join(",", SearchItem.EngineerCodes));
AddToSqlParameter(sqlParameters, ParameterNames.EngineerLastNames + parameterPrefix, string.Join(",", SearchItem.EngineerLastNames));
public class GpsSearchQuery : BaseSearchQuery
public GpsSearchQuery(QueryPpatPoco ppatSearch) : base(ppatSearch)
public sealed override void SetColumnNames()
PartNumberColName = "a01.CPNT_part_no";
DlsColName = "a01.CPNT_part_dls";
PlsColName = "a01.CPNT_part_pls";
UpcColName = "a01.CPNT_upc_cde";
FnaColName = "a01.CPNT_fna_Cde";
FnaDescriptionColName = "a01.fna_desc";
EngineerCodesColName = "a01.ENGR_CD_LIST";
EngineerLastNamesColName = "a01.ENGR_NM_LIST";
public override string BaseQuery()
return string.Format(@"select * from Fn_ECM_PreProd_COMP_VW ( {0}Gps, {1}Gps, {2}Gps, {3}Gps, {4}Gps, {5}Gps, {6}Gps, {7}Gps, {8}Gps, {9}Gps, {10}Gps)",
ParameterNames.PreProdProgam,
ParameterNames.HardwareStage,
ParameterNames.PartNumber,
ParameterNames.FnaDescription,
ParameterNames.UpcPrefix,
ParameterNames.EngineerCodes,
ParameterNames.EngineerLastNames);
public class VehicleSearchQuery : BaseSearchQuery
public VehicleSearchQuery(QueryPpatPoco ppatSearch) : base(ppatSearch)
public sealed override void SetColumnNames()
PartNumberColName = "a01.part_no";
DlsColName = "a01.part_dls";
PlsColName = "a01.part_pls";
UpcPrefixColName = "a01.upc_Prefx";
UpcColName = "a01.upc_cde";
FnaColName = "a01.fna_Cde";
FnaDescriptionColName = "a01.fna_desc";
EngineerCodesColName = "a01.ENGR_CD_LIST";
EngineerLastNamesColName = "a01.ENGR_NM_LIST";
public override string BaseQuery()
return string.Format(@"select * from fn_ECM_PreProd_BOM_VW ( {0}Vehicle, {1}Vehicle, {2}Vehicle, {3}Vehicle, {4}Vehicle, {5}Vehicle, {6}Vehicle, {7}Vehicle, {8}Vehicle, {9}Vehicle, {10}Vehicle)",
ParameterNames.PreProdProgam,
ParameterNames.HardwareStage,
ParameterNames.PartNumber,
ParameterNames.FnaDescription,
ParameterNames.UpcPrefix,
ParameterNames.EngineerCodes,
ParameterNames.EngineerLastNames);
public interface IDataAccessLayer
Item NewItem(string itemTypeName, string action);
Item GetResult(string sql, List<System.Data.SqlClient.SqlParameter> sqlParameters, string preprodProgramName, string hardwareStage);
Item ApplySql(string sql);
public class DataAccessLayer : IDataAccessLayer
private readonly Innovator _innovator;
private const string QueryPpatResult = "gm_Query PPAT Result";
private const string QueryPpatSearch = "gm_Query PPAT";
private readonly Dictionary<string, string> _propertyMap = new Dictionary<string, string>()
{"_current_part_number","PART_Number"},
{"_current_part_number_dls","DLS"},
{"_current_part_number_pls","PLS"},
{"_upc_prefix","UPC_Prefix"},
{"_fna_desc","fna_desc"},
{"_part_usage_qty","QTY"},
{"_indent_level","Indent_Level"},
{"_sequence_number","SEQ_Number"},
{"_engineer_code","Engr_Code_LIST"},
{"_prod_yr","ModelYear"},
{"_prod_line_cde","Product"},
{"_dynamic_torque_code","Torque_D"},
{"_static_torque_cde","Torque_S"},
{"_permanent_notes","PermNotes"},
{"_part_fstnr_ind_cde","FastenerInd"},
{"_bld_blk_phase","BlockPhase"},
{"_control_number","ControlNumber"},
{"_hand_cde","HandCode"},
{"_sys_bom_item_no","item"},
{"_less_finish_indicator","lessFinish"},
{"_usage_st_cde","Status"},
{"_mdl_cde","ModelCode"},
{"_no_of_units_qty","NOU"},
{"_unit_msre_cde","UOM"},
{"_div_cde","EngrRelDiv"},
public DataAccessLayer(Innovator innovator)
public Item NewItem(string itemTypeName, string action)
return _innovator.newItem(itemTypeName, action);
public Item GetResult(string sql, List<System.Data.SqlClient.SqlParameter> sqlParameters, string preprodProgramName, string hardwareStage)
var querySearch = _innovator.newItem(QueryPpatSearch);
using (var conn = new System.Data.SqlClient.SqlConnection())
conn.ConnectionString = GetConnectionString();
using (var command = new System.Data.SqlClient.SqlCommand())
command.Connection = conn;
command.Parameters.AddRange(sqlParameters.ToArray());
command.CommandText = sql;
command.CommandTimeout = 0;
foreach (System.Data.SqlClient.SqlParameter commandParameter in command.Parameters)
query = query.Replace(commandParameter.ParameterName, "'" + commandParameter.Value + "'");
if(System.Diagnostics.Debugger.Launch())
System.Diagnostics.Debugger.Break();
using (var reader = command.ExecuteReader())
querySearch.addRelationship(GetItem(reader, preprodProgramName, hardwareStage));
public Item ApplySql(string sql)
return _innovator.applySQL(sql);
private List<string> GetPermanentAndTorqueNotes(string permNotes)
var result = new List<string>();
if (string.IsNullOrWhiteSpace(permNotes)) return result;
List<string> splitedString = permNotes.Split(new string[] { ";;" }, StringSplitOptions.RemoveEmptyEntries).ToList();
result.Add(string.Join("\n", splitedString.Where(s => s.Trim().StartsWith("TORQ:")).Select(s => s.Trim())));
result.Add(string.Join("\n", splitedString.Where(s => !s.Trim().StartsWith("TORQ:")).Select(s => s.Trim())));
private Item GetItem(System.Data.SqlClient.SqlDataReader reader, string preprodProgramName, string hardwareStage)
var item = _innovator.newItem(QueryPpatResult);
item.setID(_innovator.getNewID());
foreach (var map in _propertyMap)
if (map.Key == "_permanent_notes")
var notes = GetPermanentAndTorqueNotes(GetDataString(reader, map.Value));
if (!notes.Any()) continue;
item.setProperty(map.Key, notes.Last());
item.setProperty("_torque_notes", notes.First());
else if (map.Key == "_control_number")
var controlNumber = GetDataString(reader, map.Value);
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(controlNumber))
item.setProperty(map.Key, controlNumber);
item.setProperty(map.Key, GetDataString(reader, map.Value));
item.setProperty("_pre_prod_program_name", preprodProgramName);
item.setProperty("_hardware_stage", hardwareStage);
private static string GetDataString(System.Data.SqlClient.SqlDataReader reader, string columnName)
var colIndex = reader.GetOrdinal(columnName);
if (colIndex < 0) return string.Empty;
if (!reader.IsDBNull(colIndex))
return reader.GetValue(colIndex).ToString().Trim();
private static string GetConnectionString()
var cofigNode = GetConfigFilePath();
var node = GetNodeForFileName(cofigNode, "Hub2Edge", "gpd_connection");
if (node.Attributes == null || node.Attributes["server"] == null || node.Attributes["database"] == null || node.Attributes["uid"] == null || node.Attributes["pwd"] == null)
throw new Aras.Server.Core.InnovatorServerException("Config not setup right.");
return "Data Source=" + node.Attributes["server"].Value +
";Initial Catalog=" + node.Attributes["database"].Value +
";User id=" + node.Attributes["uid"].Value +
";Password=" + node.Attributes["pwd"].Value;
private static XmlNode GetNodeForFileName(string filePath, string nodeName, string id)
var doc = new XmlDocument();
var nodes = doc.GetElementsByTagName(nodeName);
throw new Aras.Server.Core.InnovatorServerException("Configuration not setup right.");
for (var i = 0; i < nodes.Count; i++)
var idAttribute = nodes[i].Attributes["id"];
if (idAttribute != null && id.Equals(idAttribute.Value))
private static string GetConfigFilePath()
var innovatorConfig = Aras.Server.Core.InnovatorServerConfig.GetServerConfig();
var configFilePath = innovatorConfig.GetBasicConfigFilePath();
if (string.IsNullOrWhiteSpace(configFilePath))
throw new Aras.Server.Core.InnovatorServerException("Connection information to read data not found. Please, contact the administrator.");
var configNode = GetNodeForFileName(configFilePath, "ConfigFilePath", "");
throw new Aras.Server.Core.InnovatorServerException("Config not setup right.");
var configValue = configNode.Attributes != null ? configNode.Attributes["value"] : null;
throw new Aras.Server.Core.InnovatorServerException("Config not setup right.");
return configValue.Value;
public void EndOfMethod()
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.SessionState;
using System.Globalization;
using System.Web.ModelBinding;
namespace gm_Query_PPAT_onSearch_class
class gm_Query_PPAT_onSearch_class : Item
public gm_Query_PPAT_onSearch_class() : base(null) { }
public Item gm_Query_PPAT_onSearch()
Aras.Server.Core.CallContext CCO = ((Aras.Server.Core.IOMConnection)serverConnection).CCO;
Aras.Server.Core.IContextState RequestState = CCO.RequestState;
#region gm_Query_PPAT_onSearch
if(System.Diagnostics.Debugger.Launch())
System.Diagnostics.Debugger.Break();
const string methodName = "gm_Query_PPAT_onSearch";
IDataAccessLayer dataAccessLayer = new DataAccessLayer(innovator);
BusinessLogic businessLogic = new BusinessLogic(dataAccessLayer);
result = businessLogic.Search(result);
catch (Aras.Server.Core.InnovatorServerException ex)
result = innovator.newError(string.Format("<b>SYSTEM EXCEPTION in method {0}</b><br>{1}", methodName, ex.Message));
catch (System.ArgumentException argex)
result = innovator.newError("<style>#toggleInfo {display: none;} #copyBuffer {display: none;}</style>" + argex.Message);
private Innovator _innovator;
public Innovator innovator
_innovator = this.getInnovator();
public class BusinessLogic
private readonly IDataAccessLayer _dataAccessLayer;
public BusinessLogic(IDataAccessLayer dataAccessLayer)
_dataAccessLayer = dataAccessLayer;
public Item Search(Item searchItem)
var queryPpat = new QueryPpatPoco(searchItem);
queryPpat.PreProdProgramCode = GetProgramCode(queryPpat.PreProdProgramName);
var sqlParameters = new List<System.Data.SqlClient.SqlParameter>();
var query = queryPpat.GenerateQuery(sqlParameters);
var result = _dataAccessLayer.GetResult(query, sqlParameters, queryPpat.PreProdProgramName, queryPpat.HardwareStage);
throw new ArgumentException(result.getErrorDetail());
public string GetProgramCode(string programName)
var query = "select _PREPROD_PROD_PGM_CD from GM_PREPROD_PROD_PGM_CD where _PREPROD_PROD_PGM_NM = '" +
var result = _dataAccessLayer.ApplySql(query);
throw new ArgumentException("\"Pre - Production Program\" is not valid.");
return result.getItemByIndex(0).getProperty("_preprod_prod_pgm_cd");
public class QueryPpatPoco
internal static class PropertyNames
internal const string VehicleBuildQuery = "_vehicle_build_query";
internal const string GpsBuildQuery = "_gps_build_query";
internal const string PreProdProgramName = "_pre_prod_program_name";
internal const string HardwareStage = "_hardware_stage";
internal const string UpcPrefix = "_upc_prefix";
internal const string Upc = "_upc";
internal const string Fna = "_fna";
internal const string FnaDescription = "_fna_desc";
internal const string PartNumber = "_part_numbers";
internal const string Pls = "_pls";
internal const string Dls = "_dls";
internal const string EngineerCodes = "_engr_codes";
internal const string EngineerLastNames = "_engr_last_name";
private const string Keyedname = "keyed_name";
public bool VehicleBuildQuery { get; set; }
public bool GpsBuildQuery { get; set; }
public string PreProdProgramName { get; set; }
public string PreProdProgramCode { get; set; }
public string HardwareStage { get; set; }
public string UpcPrefix { get; set; }
public string Upc { get; set; }
public string Fna { get; set; }
public string FnaDescription { get; set; }
public string PartNumber { get; set; }
public string Pls { get; set; }
public string Dls { get; set; }
public List<string> EngineerCodes { get; set; }
public List<string> EngineerLastNames { get; set; }
public QueryPpatPoco(Item queryItem)
VehicleBuildQuery = Trim(queryItem.getProperty(PropertyNames.VehicleBuildQuery, "0")).Equals("1", StringComparison.OrdinalIgnoreCase);
GpsBuildQuery = Trim(queryItem.getProperty(PropertyNames.GpsBuildQuery, "0")).Equals("1", StringComparison.OrdinalIgnoreCase);
PreProdProgramName = Trim(queryItem.getProperty(PropertyNames.PreProdProgramName));
HardwareStage = Trim(queryItem.getProperty(PropertyNames.HardwareStage));
UpcPrefix = Trim(queryItem.getPropertyAttribute(PropertyNames.UpcPrefix, Keyedname));
Upc = Trim(queryItem.getPropertyAttribute(PropertyNames.Upc, Keyedname));
Fna = Trim(queryItem.getPropertyAttribute(PropertyNames.Fna, Keyedname));
FnaDescription = Trim(queryItem.getProperty(PropertyNames.FnaDescription));
PartNumber = Trim(queryItem.getPropertyAttribute(PropertyNames.PartNumber, Keyedname));
Pls = Trim(queryItem.getProperty(PropertyNames.Pls));
Dls = Trim(queryItem.getProperty(PropertyNames.Dls));
EngineerCodes = Trim(queryItem.getProperty(PropertyNames.EngineerCodes, "")).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
EngineerLastNames = Trim(queryItem.getProperty(PropertyNames.EngineerLastNames, "")).Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).ToList();
private void SanityCheck()
if (!VehicleBuildQuery && !GpsBuildQuery)
throw new ArgumentException("Either \"Vehicle Build Query\" or \"GPS Build Query\" must be selected.");
if (string.IsNullOrWhiteSpace(PreProdProgramName) || string.IsNullOrWhiteSpace(HardwareStage))
throw new ArgumentException(" \"Pre - Production Program\" and \"Hardware Stage\" must be selected.");
if (string.IsNullOrWhiteSpace(PartNumber) && string.IsNullOrWhiteSpace(UpcPrefix) && string.IsNullOrWhiteSpace(Upc) && string.IsNullOrWhiteSpace(Fna)
&& string.IsNullOrWhiteSpace(FnaDescription) && (EngineerCodes == null || !EngineerCodes.Any()) && (EngineerLastNames == null || !EngineerLastNames.Any()))
throw new ArgumentException("You must select a \"Pre-Production Program and Hardware Stage\" and a minimum of one other criteria in order to perform a search.");
if (EngineerCodes != null && (EngineerCodes.Count > 6 || EngineerCodes.Any(s => s.Length != 4)))
throw new ArgumentException("Engineer Code(s) must be 4 characters each separated by commas; maximum of 6 Engineer Codes allowed.");
if (EngineerLastNames != null && EngineerLastNames.Any() && EngineerLastNames.Select(s => s.Length).Sum() > 30)
throw new ArgumentException("Engineer Last Name(s) must be 30 or fewer characters.");
public string Trim(string input)
return input != null ? input.Trim() : null;
public string GenerateQuery(List<System.Data.SqlClient.SqlParameter> sqlParameters)
var searchQuery = string.Empty;
searchQuery = new VehicleSearchQuery(this).GetQuery(sqlParameters);
if (!GpsBuildQuery) return searchQuery;
searchQuery += " union ";
searchQuery += new GpsSearchQuery(this).GetQuery(sqlParameters);
public abstract class BaseSearchQuery
protected string PartNumberColName;
protected string DlsColName;
protected string PlsColName;
protected string UpcPrefixColName;
protected string UpcColName;
protected string FnaColName;
protected string FnaDescriptionColName;
protected string EngineerCodesColName;
protected string EngineerLastNamesColName;
protected QueryPpatPoco SearchItem;
protected static class ParameterNames
internal const string PreProdProgam = "@preprodpgram";
internal const string HardwareStage = "@hardwarestage";
internal const string PartNumber = "@partnumber";
internal const string Dls = "@dls";
internal const string Pls = "@pls";
internal const string UpcPrefix = "@upcprefix";
internal const string Upc = "@upc";
internal const string Fna = "@fna";
internal const string FnaDescription = "@fnadesc";
internal const string EngineerCodes = "@engineercodes";
internal const string EngineerLastNames = "@engineerlastname";
protected bool IsVehicle = false;
protected BaseSearchQuery(QueryPpatPoco ppatSearch)
public abstract void SetColumnNames();
public abstract string BaseQuery();
private static void AddToSqlParameter(List<System.Data.SqlClient.SqlParameter> sqlParameters, string parameterName, string value)
var sqlParameter = new System.Data.SqlClient.SqlParameter(parameterName, value);
if (string.IsNullOrWhiteSpace(value))
sqlParameter.Value = DBNull.Value;
sqlParameters.Add(sqlParameter);
public string GetQuery(List<System.Data.SqlClient.SqlParameter> sqlParameters)
var query = new StringBuilder();
var parameterPrefix = IsVehicle ? "Vehicle" : "Gps";
query.Append(BaseQuery());
AddToSqlParameter(sqlParameters, ParameterNames.PreProdProgam + parameterPrefix, SearchItem.PreProdProgramCode);
AddToSqlParameter(sqlParameters, ParameterNames.HardwareStage + parameterPrefix, SearchItem.HardwareStage);
AddToSqlParameter(sqlParameters, ParameterNames.PartNumber + parameterPrefix, SearchItem.PartNumber);
AddToSqlParameter(sqlParameters, ParameterNames.Dls + parameterPrefix, SearchItem.Dls);
AddToSqlParameter(sqlParameters, ParameterNames.Pls + parameterPrefix, SearchItem.Pls);
AddToSqlParameter(sqlParameters, ParameterNames.Upc + parameterPrefix, SearchItem.Upc);
AddToSqlParameter(sqlParameters, ParameterNames.Fna + parameterPrefix, SearchItem.Fna);
AddToSqlParameter(sqlParameters, ParameterNames.FnaDescription + parameterPrefix, SearchItem.FnaDescription);
AddToSqlParameter(sqlParameters, ParameterNames.UpcPrefix + parameterPrefix, SearchItem.UpcPrefix);
AddToSqlParameter(sqlParameters, ParameterNames.EngineerCodes + parameterPrefix, string.Join(",", SearchItem.EngineerCodes));
AddToSqlParameter(sqlParameters, ParameterNames.EngineerLastNames + parameterPrefix, string.Join(",", SearchItem.EngineerLastNames));
public class GpsSearchQuery : BaseSearchQuery
public GpsSearchQuery(QueryPpatPoco ppatSearch) : base(ppatSearch)
public sealed override void SetColumnNames()
PartNumberColName = "a01.CPNT_part_no";
DlsColName = "a01.CPNT_part_dls";
PlsColName = "a01.CPNT_part_pls";
UpcColName = "a01.CPNT_upc_cde";
FnaColName = "a01.CPNT_fna_Cde";
FnaDescriptionColName = "a01.fna_desc";
EngineerCodesColName = "a01.ENGR_CD_LIST";
EngineerLastNamesColName = "a01.ENGR_NM_LIST";
public override string BaseQuery()
return string.Format(@"select * from Fn_ECM_PreProd_COMP_VW ( {0}Gps, {1}Gps, {2}Gps, {3}Gps, {4}Gps, {5}Gps, {6}Gps, {7}Gps, {8}Gps, {9}Gps, {10}Gps)",
ParameterNames.PreProdProgam,
ParameterNames.HardwareStage,
ParameterNames.PartNumber,
ParameterNames.FnaDescription,
ParameterNames.UpcPrefix,
ParameterNames.EngineerCodes,
ParameterNames.EngineerLastNames);
public class VehicleSearchQuery : BaseSearchQuery
public VehicleSearchQuery(QueryPpatPoco ppatSearch) : base(ppatSearch)
public sealed override void SetColumnNames()
PartNumberColName = "a01.part_no";
DlsColName = "a01.part_dls";
PlsColName = "a01.part_pls";
UpcPrefixColName = "a01.upc_Prefx";
UpcColName = "a01.upc_cde";
FnaColName = "a01.fna_Cde";
FnaDescriptionColName = "a01.fna_desc";
EngineerCodesColName = "a01.ENGR_CD_LIST";
EngineerLastNamesColName = "a01.ENGR_NM_LIST";
public override string BaseQuery()
return string.Format(@"select * from fn_ECM_PreProd_BOM_VW ( {0}Vehicle, {1}Vehicle, {2}Vehicle, {3}Vehicle, {4}Vehicle, {5}Vehicle, {6}Vehicle, {7}Vehicle, {8}Vehicle, {9}Vehicle, {10}Vehicle)",
ParameterNames.PreProdProgam,
ParameterNames.HardwareStage,
ParameterNames.PartNumber,
ParameterNames.FnaDescription,
ParameterNames.UpcPrefix,
ParameterNames.EngineerCodes,
ParameterNames.EngineerLastNames);
public interface IDataAccessLayer
Item NewItem(string itemTypeName, string action);
Item GetResult(string sql, List<System.Data.SqlClient.SqlParameter> sqlParameters, string preprodProgramName, string hardwareStage);
Item ApplySql(string sql);
public class DataAccessLayer : IDataAccessLayer
private readonly Innovator _innovator;
private const string QueryPpatResult = "gm_Query PPAT Result";
private const string QueryPpatSearch = "gm_Query PPAT";
private readonly Dictionary<string, string> _propertyMap = new Dictionary<string, string>()
{"_current_part_number","PART_Number"},
{"_current_part_number_dls","DLS"},
{"_current_part_number_pls","PLS"},
{"_upc_prefix","UPC_Prefix"},
{"_fna_desc","fna_desc"},
{"_part_usage_qty","QTY"},
{"_indent_level","Indent_Level"},
{"_sequence_number","SEQ_Number"},
{"_engineer_code","Engr_Code_LIST"},
{"_prod_yr","ModelYear"},
{"_prod_line_cde","Product"},
{"_dynamic_torque_code","Torque_D"},
{"_static_torque_cde","Torque_S"},
{"_permanent_notes","PermNotes"},
{"_part_fstnr_ind_cde","FastenerInd"},
{"_bld_blk_phase","BlockPhase"},
{"_control_number","ControlNumber"},
{"_hand_cde","HandCode"},
{"_sys_bom_item_no","item"},
{"_less_finish_indicator","lessFinish"},
{"_usage_st_cde","Status"},
{"_mdl_cde","ModelCode"},
{"_no_of_units_qty","NOU"},
{"_unit_msre_cde","UOM"},
{"_div_cde","EngrRelDiv"},
public DataAccessLayer(Innovator innovator)
public Item NewItem(string itemTypeName, string action)
return _innovator.newItem(itemTypeName, action);
public Item GetResult(string sql, List<System.Data.SqlClient.SqlParameter> sqlParameters, string preprodProgramName, string hardwareStage)
var querySearch = _innovator.newItem(QueryPpatSearch);
using (var conn = new System.Data.SqlClient.SqlConnection())
conn.ConnectionString = GetConnectionString();
using (var command = new System.Data.SqlClient.SqlCommand())
command.Connection = conn;
command.Parameters.AddRange(sqlParameters.ToArray());
command.CommandText = sql;
command.CommandTimeout = 0;
foreach (System.Data.SqlClient.SqlParameter commandParameter in command.Parameters)
query = query.Replace(commandParameter.ParameterName, "'" + commandParameter.Value + "'");
if(System.Diagnostics.Debugger.Launch())
System.Diagnostics.Debugger.Break();
using (var reader = command.ExecuteReader())
querySearch.addRelationship(GetItem(reader, preprodProgramName, hardwareStage));
public Item ApplySql(string sql)
return _innovator.applySQL(sql);
private List<string> GetPermanentAndTorqueNotes(string permNotes)
var result = new List<string>();
if (string.IsNullOrWhiteSpace(permNotes)) return result;
List<string> splitedString = permNotes.Split(new string[] { ";;" }, StringSplitOptions.RemoveEmptyEntries).ToList();
result.Add(string.Join("\n", splitedString.Where(s => s.Trim().StartsWith("TORQ:")).Select(s => s.Trim())));
result.Add(string.Join("\n", splitedString.Where(s => !s.Trim().StartsWith("TORQ:")).Select(s => s.Trim())));
private Item GetItem(System.Data.SqlClient.SqlDataReader reader, string preprodProgramName, string hardwareStage)
var item = _innovator.newItem(QueryPpatResult);
item.setID(_innovator.getNewID());
foreach (var map in _propertyMap)
if (map.Key == "_permanent_notes")
var notes = GetPermanentAndTorqueNotes(GetDataString(reader, map.Value));
if (!notes.Any()) continue;
item.setProperty(map.Key, notes.Last());
item.setProperty("_torque_notes", notes.First());
else if (map.Key == "_control_number")
var controlNumber = GetDataString(reader, map.Value);
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(controlNumber))
item.setProperty(map.Key, controlNumber);
item.setProperty(map.Key, GetDataString(reader, map.Value));
item.setProperty("_pre_prod_program_name", preprodProgramName);
item.setProperty("_hardware_stage", hardwareStage);
private static string GetDataString(System.Data.SqlClient.SqlDataReader reader, string columnName)
var colIndex = reader.GetOrdinal(columnName);
if (colIndex < 0) return string.Empty;
if (!reader.IsDBNull(colIndex))
return reader.GetValue(colIndex).ToString().Trim();
private static string GetConnectionString()
var cofigNode = GetConfigFilePath();
var node = GetNodeForFileName(cofigNode, "Hub2Edge", "gpd_connection");
if (node.Attributes == null || node.Attributes["server"] == null || node.Attributes["database"] == null || node.Attributes["uid"] == null || node.Attributes["pwd"] == null)
throw new Aras.Server.Core.InnovatorServerException("Config not setup right.");
return "Data Source=" + node.Attributes["server"].Value +
";Initial Catalog=" + node.Attributes["database"].Value +
";User id=" + node.Attributes["uid"].Value +
";Password=" + node.Attributes["pwd"].Value;
private static XmlNode GetNodeForFileName(string filePath, string nodeName, string id)
var doc = new XmlDocument();
var nodes = doc.GetElementsByTagName(nodeName);
throw new Aras.Server.Core.InnovatorServerException("Configuration not setup right.");
for (var i = 0; i < nodes.Count; i++)
var idAttribute = nodes[i].Attributes["id"];
if (idAttribute != null && id.Equals(idAttribute.Value))
private static string GetConfigFilePath()
var innovatorConfig = Aras.Server.Core.InnovatorServerConfig.GetServerConfig();
var configFilePath = innovatorConfig.GetBasicConfigFilePath();
if (string.IsNullOrWhiteSpace(configFilePath))
throw new Aras.Server.Core.InnovatorServerException("Connection information to read data not found. Please, contact the administrator.");
var configNode = GetNodeForFileName(configFilePath, "ConfigFilePath", "");
throw new Aras.Server.Core.InnovatorServerException("Config not setup right.");
var configValue = configNode.Attributes != null ? configNode.Attributes["value"] : null;
throw new Aras.Server.Core.InnovatorServerException("Config not setup right.");
return configValue.Value;
public void EndOfMethod()
using System.Collections;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Globalization;
namespace gm_Query_PPAT_Parse_class
class gm_Query_PPAT_Parse_class : Item
public gm_Query_PPAT_Parse_class() : base(null) { }
public Item gm_Query_PPAT_Parse()
Aras.Server.Core.CallContext CCO = ((Aras.Server.Core.IOMConnection)serverConnection).CCO;
Aras.Server.Core.IContextState RequestState = CCO.RequestState;
#region gm_Query_PPAT_Parse
const string methodName = "gm_Query_PPAT_Parse";
IDataAccessLayer dataAccessLayer = new DataAccessLayer(innovator);
BusinessLogic businessLogic = new BusinessLogic(dataAccessLayer);
result = businessLogic.Parse(result);
catch (Aras.Server.Core.InnovatorServerException ex)
result = innovator.newError(string.Format("<b>SYSTEM EXCEPTION in method {0}</b><br>{1}", methodName, ex.Message));
catch (System.ArgumentException argex)
result = innovator.newError("<style>#toggleInfo {display: none;} #copyBuffer {display: none;}</style>" + argex.Message);
private Innovator _innovator;
public Innovator innovator
get { return _innovator ?? (_innovator = this.getInnovator()); }
public class BusinessLogic
private readonly IDataAccessLayer _dataAccessLayer;
private static readonly Dictionary<string, Item> ReferencedItems = new Dictionary<string, Item>();
internal abstract class ReferenceItem
public string ItemTypeName;
public string ItemProperty;
public bool ShouldBeActive;
public string SelectList;
public string QueryResultProperty;
public string OrderByList;
public string ValidItemQuery;
public string PpatProperty;
public Item GetValidItemByQuery(Dictionary<string, Item> referenceItems)
if (referenceItems == null || !referenceItems.ContainsKey(ItemTypeName) || string.IsNullOrWhiteSpace(ValidItemQuery)) return null;
var allItems = referenceItems[ItemTypeName];
if (allItems == null) return null;
var validItem = allItems.getItemsByXPath(ValidItemQuery);
if (validItem == null || (validItem.nodeList != null && validItem.nodeList.Count == 0))
return (validItem.nodeList != null && validItem.nodeList.Count > 1) ? validItem.getItemByIndex(0) : validItem;
public Item GetValidItem(Dictionary<string, Item> referenceItems, string itemPropertyValue)
ValidItemQuery = "//Item[" + ItemProperty + "[normalize-space(text())='" + itemPropertyValue + "']]";
return GetValidItemByQuery(referenceItems);
public virtual void SetValidItem(Item newPat, Item queryResultRow)
var propertyValue = queryResultRow.getProperty(QueryResultProperty, "");
if (string.IsNullOrWhiteSpace(propertyValue)) return;
var validItem = GetValidItem(ReferencedItems, propertyValue);
newPat.setPropertyItem(PpatProperty, validItem);
internal class AssemblyStation : ReferenceItem
internal AssemblyStation()
ItemTypeName = "gm_Bld Div Assy Sta";
ItemProperty = "_mod_assy_sta";
SelectList = "id,keyed_name,_mod_assy_sta";
QueryResultProperty = QueryResult.AsmStn;
PpatProperty = Ppat.AsmStn;
internal class EngRelDiv : ReferenceItem
ItemTypeName = "gm_Eng Div Cd";
ItemProperty = "_eng_div_cd";
SelectList = "id,keyed_name,_eng_div_cd";
QueryResultProperty = QueryResult.EngRelDivCode;
PpatProperty = Ppat.EngRelDivCode;
internal class StatusCode : ReferenceItem
ItemTypeName = "gm_Louwp Stat Cd";
ItemProperty = "_louwp_stat_cd";
SelectList = "id,keyed_name,_louwp_stat_cd";
QueryResultProperty = QueryResult.Status;
PpatProperty = Ppat.Status;
internal class Part : ReferenceItem
ItemTypeName = "gm_Part";
ItemProperty = "_part_nbr";
SelectList = "id,_part_nbr,_part_dls,_part_pls,_part_fstnr_ind_cd,_preferred_part,_non_pref_ind_cd";
QueryResultProperty = QueryResult.CurrentPart;
PpatProperty = Ppat.CurrentPart;
OrderByList = "_part_nbr,_part_dls desc,_part_pls desc";
public Item GetValidItem(Dictionary<string, Item> referenceItems, string partNumber, string dls, string pls)
if (referenceItems == null || !referenceItems.ContainsKey(ItemTypeName)) return null;
var allParts = referenceItems[ItemTypeName];
if (allParts == null) return null;
var query = "//Item[_part_nbr[normalize-space(text())='" + partNumber + "']";
if (!string.IsNullOrWhiteSpace(dls))
query += " and _part_dls[normalize-space(text())='" + dls + "']";
query += " and (_part_dls='' or _part_dls=' ') ";
if (!string.IsNullOrWhiteSpace(pls))
query += " and _part_pls[normalize-space(text())='" + pls + "']";
query += " and (_part_pls='' or _part_pls=' ') ";
var validItem = allParts.getItemsByXPath(query);
if (validItem == null || (validItem.nodeList != null && validItem.nodeList.Count == 0))
return (validItem.nodeList != null && validItem.nodeList.Count > 1) ? validItem.getItemByIndex(0) : validItem;
public override void SetValidItem(Item newPat, Item queryResultRow)
var currentPartNumber = queryResultRow.getProperty(QueryResult.CurrentPart, "");
if (string.IsNullOrWhiteSpace(currentPartNumber)) return;
var dls = queryResultRow.getProperty(QueryResult.CurrentDls, "");
var pls = queryResultRow.getProperty(QueryResult.CurrentPls, "");
var validPart = GetValidItem(ReferencedItems, currentPartNumber, dls, pls);
if (validPart == null) return;
newPat.setPropertyItem(Ppat.CurrentPart, validPart);
newPat.setProperty(Ppat.CurrentDls, dls);
newPat.setProperty(Ppat.CurrentPls, pls);
internal class Uom : ReferenceItem
ItemTypeName = "gm_Uom Cd";
ItemProperty = "_uom_cd";
SelectList = "id,keyed_name,_uom_cd";
QueryResultProperty = QueryResult.UomCode;
PpatProperty = Ppat.UomCode;
public override void SetValidItem(Item newPat, Item queryResultRow)
var quantity = queryResultRow.getProperty(QueryResult.Qty, "");
newPat.setProperty(Ppat.Qty, quantity);
if (string.IsNullOrWhiteSpace(quantity) || !decimal.TryParse(quantity, out qty) || qty < 0 || qty > 99999) return;
newPat.setProperty(Ppat.Qty, ((int)qty).ToString());
var nou = queryResultRow.getProperty(QueryResult.Nou, "");
if (!string.IsNullOrWhiteSpace(nou) && decimal.TryParse(nou, out intNou) && intNou > 0)
newPat.setProperty(Ppat.Nou, nou);
var uom = queryResultRow.getProperty(QueryResult.UomCode, "");
if (string.IsNullOrWhiteSpace(uom)) return;
var validItem = GetValidItem(ReferencedItems, uom);
newPat.setPropertyItem(Ppat.UomCode, validItem);
internal class UpcFna : ReferenceItem
public readonly string ItemFnaCode = "_fna_cd";
public readonly string ItemFnaDescriptoin = "_fna_desc";
public readonly string ItemVppsCode = "_xpand_cd";
ItemTypeName = "gm_Upc Fna";
ItemProperty = "_upc_cd";
SelectList = "id,_upc_cd,_fna_cd,_fna_desc,_xpand_cd";
QueryResultProperty = QueryResult.Upc;
public Item GetValidItem(Dictionary<string, Item> referenceItems, string upcCode, string fna, string fnaDescription, string vpps)
if (referenceItems == null || !referenceItems.ContainsKey(ItemTypeName)) return null;
var allItems = referenceItems[ItemTypeName];
if (allItems == null) return null;
var query = "//Item[_upc_cd[normalize-space(text())='" + upcCode + "']";
if (!string.IsNullOrWhiteSpace(fna))
query += " and _fna_cd[normalize-space(text())='" + fna + "']";
query += " and (_fna_cd='' or _fna_cd=' ') ";
if (!string.IsNullOrWhiteSpace(fnaDescription))
query += " and _fna_desc[normalize-space(text())='" + fnaDescription + "']";
query += " and (_fna_desc='' or _fna_desc=' ') ";
if (!string.IsNullOrWhiteSpace(vpps))
query += " and _xpand_cd[normalize-space(text())='" + vpps + "']";
query += " and (_xpand_cd='' or _xpand_cd=' ') ";
var validItem = allItems.getItemsByXPath(query);
if (validItem == null || (validItem.nodeList != null && validItem.nodeList.Count == 0))
return (validItem.nodeList != null && validItem.nodeList.Count > 1) ? validItem.getItemByIndex(0) : validItem;
public override void SetValidItem(Item newPat, Item queryResultRow)
var upc = queryResultRow.getProperty(QueryResult.Upc, "");
if (string.IsNullOrWhiteSpace(upc)) return;
var fna = queryResultRow.getProperty(QueryResult.Fna, "");
var fnaDesc = queryResultRow.getProperty(QueryResult.FnaDescription, "");
var vpps = queryResultRow.getProperty(QueryResult.Vpps, "");
var validItem = GetValidItem(ReferencedItems, upc, fna, fnaDesc, vpps);
if (validItem == null) return;
newPat.setPropertyItem(Ppat.Upc, validItem);
newPat.setProperty(Ppat.Fna, fna);
newPat.setProperty(Ppat.FnaDescription, fnaDesc);
newPat.setProperty(Ppat.Vpps, vpps);
internal class UpcPrefix : ReferenceItem
ItemTypeName = "gm_Upc Prefix";
ItemProperty = "_upc_prefix";
SelectList = "id,keyed_name,_upc_prefix";
QueryResultProperty = QueryResult.UpcPrefixCode;
PpatProperty = Ppat.UpcPrefixCode;
internal static class QueryResult
internal const string ItemTypeName = "gm_Query PPAT Result";
internal const string RowNumber = "_row_number";
internal const string ModelYear = "_prod_yr";
internal const string Product = "_prod_line_cde";
internal const string CurrentPart = "_current_part_number";
internal const string CurrentDls = "_current_part_number_dls";
internal const string CurrentPls = "_current_part_number_pls";
internal const string UpcPrefixCode = "_upc_prefix";
internal const string Upc = "_upc_cde";
internal const string Fna = "_fna_cde";
internal const string FnaDescription = "_fna_desc";
internal const string IndentLevel = "_indent_level";
internal const string SequenceNumber = "_sequence_number";
internal const string AsmStn = "_asm_stn";
internal const string ModelCode = "_mdl_cde";
internal const string HandCode = "_hand_cde";
internal const string Status = "_usage_st_cde";
internal const string Qty = "_part_usage_qty";
internal const string Nou = "_no_of_units_qty";
internal const string UomCode = "_unit_msre_cde";
internal const string PreProdStockDisp = "_pre_prod_stock_disposition";
internal const string EngineerCode = "_engineer_code";
internal const string ControlNumber = "_control_number";
internal const string DynamicTorque = "_dynamic_torque_code";
internal const string StaticTorque = "_static_torque_cde";
internal const string TorqueNotes = "_torque_notes";
internal const string PermanentNotes = "_permanent_notes";
internal const string BldBlkPhase = "_bld_blk_phase";
internal const string Item = "_sys_bom_item_no";
internal const string Calc = "_calc";
internal const string FastenerIndicator = "_part_fstnr_ind_cde";
internal const string PreProdProgramName = "_pre_prod_program_name";
internal const string HardwareStage = "_hardware_stage";
internal const string EngRelDivCode = "_div_cde";
internal const string Vpps = "_vpps_cde";
internal const string Fnm = "_fna_mdf_desc";
internal const string LessFinish = "_less_finish_indicator";
internal static class Ppat
internal const string ItemTypeName = "gm_Work Order PPPAT";
internal const string RowNumber = "_row_number";
internal const string ChangeAction = "_change_action";
internal const string ModelYear = "_prod_yr";
internal const string Product = "_prod_line_cde";
internal const string CurrentPart = "_current_part_number";
internal const string CurrentDls = "_current_part_number_dls";
internal const string CurrentPls = "_current_part_number_pls";
internal const string UpcPrefixCode = "_upc_prefix";
internal const string Upc = "_upc_cde";
internal const string Fna = "_fna_cde";
internal const string FnaDescription = "_fna_desc";
internal const string IndentLevel = "_indent_level";
internal const string SequenceNumber = "_sequence_number";
internal const string Fnm = "_fna_mdf_desc";
internal const string AsmStn = "_asm_stn";
internal const string ModelCode = "_mdl_cde";
internal const string HandCode = "_hand_cde";
internal const string Status = "_usage_st_cde";
internal const string Qty = "_part_usage_qty";
internal const string Nou = "_no_of_units_qty";
internal const string UomCode = "_unit_msre_cde";
internal const string PreProdStockDisp = "_pre_prod_stock_disposition";
internal const string EngineerCode = "_engineer_code";
internal const string ControlNumber = "_control_number";
internal const string DynamicTorque = "_dynamic_torque_code";
internal const string StaticTorque = "_static_torque_cde";
internal const string TorqueNotes = "_torque_notes";
internal const string PermanentNotes = "_permanent_notes";
internal const string BldBlkPhase = "_bld_blk_phase";
internal const string Item = "_sys_bom_item_no";
internal const string Calc = "_calc";
internal const string FastenerIndicator = "_part_fstnr_ind_cde";
internal const string PreProdProgramName = "_pre_prod_program_name";
internal const string HardwareStage = "_hardware_stage";
internal const string EngRelDivCode = "_div_cde";
internal const string Vpps = "_vpps_cde";
internal const string CreatedByQuery = "_created_by_query";
internal const string TypeId = "typeId";
internal const string LessFinish = "_less_finish_indicator";
private static class Constants
internal static class ItemTypeNames
internal const string PpatInstance = "gm_PPAT Instance";
internal static class PropertyNames
internal const string Active = "_active";
internal static class Actions
internal const string Add = "add";
internal const string Get = "get";
internal static class Attributes
internal const string OrderBy = "orderby";
internal const string Select = "select";
public BusinessLogic(IDataAccessLayer dataAccessLayer)
_dataAccessLayer = dataAccessLayer;
public Item Parse(Item ppatQuery)
var resultsRel = _ppatQuery.getRelationships(QueryResult.ItemTypeName);
var resultCount = resultsRel.getItemCount();
var resultItem = _dataAccessLayer.NewItem("Result", Constants.Actions.Get);
var rowNumber = _ppatQuery.getProperty(QueryResult.RowNumber, "0");
int.TryParse(rowNumber, out currentRowNumber);
for (var i = 0; i < resultCount; i++)
resultItem.addRelationship(GetValidPpat(resultsRel.getItemByIndex(i), currentRowNumber + i + 1));
public Item GetValidPpat(Item queryResultRow, int rowNum)
var newPat = _dataAccessLayer.NewItem(Ppat.ItemTypeName, Constants.Actions.Add);
newPat.setAttribute(Ppat.TypeId, "7497E4C7DDA24FC1859030780C223D94");
newPat.setProperty(Ppat.CreatedByQuery, "1");
newPat.setProperty(Ppat.RowNumber, rowNum.ToString());
SetItemTypes(newPat, queryResultRow);
SetStringProperties(newPat, queryResultRow);
var ppatInstance = _dataAccessLayer.NewItem(Constants.ItemTypeNames.PpatInstance, Constants.Actions.Add);
ppatInstance.node.InnerXml = newPat.node.InnerXml;
newPat.addRelationship(ppatInstance);
private void LoadItemtypes()
GetItem(new AssemblyStation());
GetItem(new EngRelDiv());
GetItem(new StatusCode());
GetItem(new UpcPrefix());
private void GetUpcfna(ReferenceItem referenceItem)
var upcReferenceItem = referenceItem as UpcFna;
if (upcReferenceItem == null) return;
var rels = _ppatQuery.getRelationships(QueryResult.ItemTypeName);
var itemCount = rels.getItemCount();
if (itemCount < 1) return;
var uniqueCombination = new List<string>();
var upcFna = _dataAccessLayer.NewItem(upcReferenceItem.ItemTypeName, Constants.Actions.Get);
var orCondition = upcFna.newOR();
for (var i = 0; i < itemCount; i++)
var item = rels.getItemByIndex(i);
var upc = item.getProperty(QueryResult.Upc, "");
var fna = item.getProperty(QueryResult.Fna, "");
var fnaDesc = item.getProperty(QueryResult.FnaDescription, "");
var vppsCode = item.getProperty(QueryResult.Vpps, "");
if (string.IsNullOrWhiteSpace(upc) || string.IsNullOrWhiteSpace(fna) || uniqueCombination.Contains(upc + fna + fnaDesc + vppsCode)) continue;
uniqueCombination.Add(upc + fna + fnaDesc + vppsCode);
var andCondition = orCondition.newAND();
andCondition.setProperty(upcReferenceItem.ItemProperty, upc);
andCondition.setProperty(upcReferenceItem.ItemFnaCode, fna);
if (!string.IsNullOrWhiteSpace(fnaDesc))
andCondition.setProperty(upcReferenceItem.ItemFnaDescriptoin, fnaDesc);
if (!string.IsNullOrWhiteSpace(vppsCode))
andCondition.setProperty(upcReferenceItem.ItemVppsCode, vppsCode);
upcFna.setAttribute(Constants.Attributes.Select, upcReferenceItem.SelectList);
ReferencedItems.Add(upcReferenceItem.ItemTypeName, upcFna);
private void GetItem(ReferenceItem referenceItem)
var valuesInQuery = GetProperty(referenceItem.QueryResultProperty);
if (string.IsNullOrWhiteSpace(valuesInQuery)) return;
var item = _dataAccessLayer.NewItem(referenceItem.ItemTypeName, Constants.Actions.Get);
item.setProperty(referenceItem.ItemProperty, valuesInQuery);
item.setPropertyCondition(referenceItem.ItemProperty, "in");
item.setAttribute(Constants.Attributes.Select, referenceItem.SelectList);
if (referenceItem.ShouldBeActive)
item.setProperty(Constants.PropertyNames.Active, "1");
if (!string.IsNullOrWhiteSpace(referenceItem.OrderByList))
item.setProperty(Constants.Attributes.OrderBy, referenceItem.OrderByList);
ReferencedItems.Add(referenceItem.ItemTypeName, item);
private string GetProperty(string propertyName)
var rels = _ppatQuery.getRelationships(QueryResult.ItemTypeName);
var itemCount = rels.getItemCount();
var values = new List<string>(itemCount);
for (var i = 0; i < itemCount; i++)
var item = rels.getItemByIndex(i);
var value = item.getProperty(propertyName, "");
if (!string.IsNullOrWhiteSpace(value))
return "'" + string.Join("','", values.Distinct()) + "'";
private static void SetItemTypes(Item newPat, Item queryResultRow)
new Part().SetValidItem(newPat, queryResultRow);
new UpcPrefix().SetValidItem(newPat, queryResultRow);
new AssemblyStation().SetValidItem(newPat, queryResultRow);
new Uom().SetValidItem(newPat, queryResultRow);
new StatusCode().SetValidItem(newPat, queryResultRow);
new EngRelDiv().SetValidItem(newPat, queryResultRow);
new UpcFna().SetValidItem(newPat, queryResultRow);
private static void SetStringProperties(Item newPat, Item queryResultRow)
newPat.setProperty(Ppat.HandCode, queryResultRow.getProperty(QueryResult.HandCode, ""));
newPat.setProperty(Ppat.PreProdStockDisp, queryResultRow.getProperty(QueryResult.PreProdStockDisp, ""));
newPat.setProperty(Ppat.ModelYear, queryResultRow.getProperty(QueryResult.ModelYear, ""));
newPat.setProperty(Ppat.Product, queryResultRow.getProperty(QueryResult.Product, ""));
newPat.setProperty(Ppat.ModelCode, queryResultRow.getProperty(QueryResult.ModelCode, ""));
newPat.setProperty(Ppat.SequenceNumber, queryResultRow.getProperty(QueryResult.SequenceNumber, ""));
newPat.setProperty(Ppat.Fnm, queryResultRow.getProperty(QueryResult.Fnm, ""));
newPat.setProperty(Ppat.EngineerCode, queryResultRow.getProperty(QueryResult.EngineerCode, ""));
newPat.setProperty(Ppat.ControlNumber, queryResultRow.getProperty(QueryResult.ControlNumber, ""));
newPat.setProperty(Ppat.DynamicTorque, queryResultRow.getProperty(QueryResult.DynamicTorque, ""));
newPat.setProperty(Ppat.StaticTorque, queryResultRow.getProperty(QueryResult.StaticTorque, ""));
newPat.setProperty(Ppat.TorqueNotes, queryResultRow.getProperty(QueryResult.TorqueNotes, ""));
newPat.setProperty(Ppat.PermanentNotes, queryResultRow.getProperty(QueryResult.PermanentNotes, ""));
newPat.setProperty(Ppat.BldBlkPhase, queryResultRow.getProperty(QueryResult.BldBlkPhase, ""));
newPat.setProperty(Ppat.Item, queryResultRow.getProperty(QueryResult.Item, ""));
newPat.setProperty(Ppat.Calc, queryResultRow.getProperty(QueryResult.Calc, ""));
newPat.setProperty(Ppat.FastenerIndicator, queryResultRow.getProperty(QueryResult.FastenerIndicator, ""));
newPat.setProperty(Ppat.PreProdProgramName, queryResultRow.getProperty(QueryResult.PreProdProgramName, ""));
newPat.setProperty(Ppat.HardwareStage, queryResultRow.getProperty(QueryResult.HardwareStage, ""));
newPat.setProperty(Ppat.IndentLevel, queryResultRow.getProperty(QueryResult.IndentLevel, ""));
newPat.setProperty(Ppat.LessFinish, queryResultRow.getProperty(QueryResult.LessFinish, ""));
public interface IDataAccessLayer
Item NewItem(string itemTypeName);
Item NewItem(string itemTypeName, string action);
Item ApplyAml(string aml);
Item GetItemById(string itemTypeName, string id);
Item FetchRelationships(Item item, string relationshipTypeName);
public class DataAccessLayer : IDataAccessLayer
private readonly Innovator _innovator;
public DataAccessLayer(Innovator innovator)
public Item NewItem(string itemTypeName)
return _innovator.newItem(itemTypeName);
public Item NewItem(string itemTypeName, string action)
return _innovator.newItem(itemTypeName, action);
public Item GetItemById(string itemTypeName, string id)
return _innovator.getItemById(itemTypeName, id);
public Item Apply(Item item)
public Item FetchRelationships(Item item, string relationshipTypeName)
return item.fetchRelationships(relationshipTypeName);
public Item ApplyAml(string aml)
return _innovator.applyAML(aml);
public void EndOfMethod()
using System.Collections;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Globalization;
namespace gm_Promote_class
class gm_Promote_class : Item
public gm_Promote_class() : base(null) { }
Aras.Server.Core.CallContext CCO = ((Aras.Server.Core.IOMConnection)serverConnection).CCO;
Aras.Server.Core.IContextState RequestState = CCO.RequestState;
string ecrId = this.getProperty("ecrId");
string state = this.getProperty("state");
Innovator inn = this.getInnovator();
var plmIden = Aras.Server.Security.Identity.GetByName("Aras PLM");
Aras.Server.Security.Permissions.GrantIdentity(plmIden);
Item workOrder = inn.getItemById("gm_Work Order", ecrId);
if (!string.IsNullOrEmpty(workOrder.getProperty("locked_by_id", "")))
throw new ArgumentException("ECR is locked by someone else. Unlock the ECR to continue.");
if ("New".Equals(state, StringComparison.OrdinalIgnoreCase))
var workOrderToUpdate = inn.newItem("gm_Work Order", "edit");
workOrderToUpdate.setID(ecrId);
workOrderToUpdate.setProperty("_finaliseddistributionlist", "0");
workOrderToUpdate = workOrderToUpdate.apply();
if (workOrderToUpdate.isError())
return workOrderToUpdate;
result = workOrder.promote(state, "");
catch (ArgumentException argex)
result = inn.newError(argex.Message);
catch (ApplicationException appex)
result = inn.newError(appex.Message);
result = inn.newError(ex.Message);
Aras.Server.Security.Permissions.RevokeIdentity(plmIden);
using System.Collections;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Globalization;
namespace gm_Update_ECR_Rel_Lifecycle_class
class gm_Update_ECR_Rel_Lifecycle_class : Item
public gm_Update_ECR_Rel_Lifecycle_class() : base(null) { }
public Item gm_Update_ECR_Rel_Lifecycle()
Aras.Server.Core.CallContext CCO = ((Aras.Server.Core.IOMConnection)serverConnection).CCO;
Aras.Server.Core.IContextState RequestState = CCO.RequestState;
#region gm_Update_ECR_Lifecycle
if (System.Diagnostics.Debugger.Launch())
System.Diagnostics.Debugger.Break();
string MethodName = "gm_Update_ECR_Rel_Lifecycle";
IDataAccessLayer dataAccessLayer = new DataAccessLayer(innovator);
BusinessLogic businessLogic = new BusinessLogic(dataAccessLayer, this);
businessLogic.UpdateRelationshipLifecycle();
catch (System.ArgumentException argex)
result = innovator.newError(argex.Message);
catch (Aras.Server.Core.ItemIsLockedException ex)
result = innovator.newError(ex.Message);
if (ex.InnerException != null)
result.setErrorDetail(ex.InnerException.Message);
throw new Aras.Server.Core.ItemIsLockedException(ex.Message);
catch (Aras.Server.Core.InnovatorServerException appex)
result = innovator.newError(string.Format("<b>ERROR in method {0}</b><br>{1}", MethodName, appex.Message));
catch (System.Exception ex)
result = innovator.newError(string.Format("<b>SYSTEM EXCEPTION in method {0}</b><br>{1}", MethodName, ex.Message));
result.setErrorDetail(ex.StackTrace);
private Innovator _innovator;
public Innovator innovator
_innovator = this.getInnovator();
public class BusinessLogic
private static class Constants
internal static class ItemTypeNames
internal const string EcrLifecycelConfiguration = "gm_WO Lifecycle Configuration";
internal const string ListValue = "value";
internal static class PropertyNames
internal const string State = "state";
internal const string SourceId = "source_id";
internal const string Classification = "classification";
internal const string TransmitDateTime = "_transmit_dte_time";
internal const string ListValue = "value";
internal const string ToState = "to_state";
internal const string FromState = "from_state";
internal const string Transition = "transition";
internal const string LockedById = "locked_by_id";
internal const string KeyedName = "keyed_name";
internal static class PropertyCondition
internal const string NotNull = "is not null";
internal static class Actions
internal const string Get = "get";
internal const string PromoteItem = "promoteItem";
internal static class Attributes
internal const string Select = "select";
internal const string IdList = "idlist";
internal static class RelationshipLifeCycleStates
internal const string Edit = "Edit";
internal const string Locked = "Locked";
internal const string Append = "Append";
internal const string Closed = "Closed";
internal static class WorkOrderLifeCycleStates
internal const string New = "New";
internal const string Investigate = "Investigate";
internal const string Closed = "Closed";
internal const string Cancelled = "Cancelled";
internal const string Draft = "Draft";
internal const string Execute = "Execute";
internal const string Approved = "Approved";
internal const string Complete = "Complete";
internal static class Ids
internal const string WorkOrderRelationshipsList = "E218BA855EF14FCFB7DE0E0DE8908EEA";
internal const string WorkOrderLifecycleConfigurationItem = "18F84106BED24A9FBC663A7AFC1943F8";
internal static class EcrClassification
internal const string Mmo = "Misc Material Order Type/MMO - Misc Material Order";
internal const string PptInitial = "Pre-Prod Tooling Type/PPT - Initial Tool Kickoff";
private readonly IDataAccessLayer dataAccessLayer;
private readonly Item workOrder;
private Item Configuration;
private readonly Innovator inn;
public BusinessLogic(IDataAccessLayer dataAccessLayer, Item workOrder)
this.dataAccessLayer = dataAccessLayer;
this.workOrder = workOrder;
this.inn = dataAccessLayer.getInnovator();
public void UpdateRelationshipLifecycle()
var transition = workOrder.getPropertyItem(Constants.PropertyNames.Transition);
var nextState = transition.getPropertyAttribute(Constants.PropertyNames.ToState, "keyed_name");
var presentState = transition.getPropertyAttribute(Constants.PropertyNames.FromState, "keyed_name");
if (workOrder.getProperty(Constants.PropertyNames.State, "")
.Equals(nextState, StringComparison.OrdinalIgnoreCase)) return;
var allRelationships = GetRelationshipTypes();
List<string> relationshipsToEdit = allRelationships;
if (workOrder.getProperty(Constants.PropertyNames.Classification, string.Empty)
.Equals(Constants.EcrClassification.Mmo, StringComparison.OrdinalIgnoreCase)
|| workOrder.getProperty(Constants.PropertyNames.Classification, string.Empty)
.Equals(Constants.EcrClassification.PptInitial, StringComparison.OrdinalIgnoreCase))
UpdateEmsTransmitDate(nextState);
if (nextState.Equals(Constants.WorkOrderLifeCycleStates.Closed, StringComparison.OrdinalIgnoreCase) ||
nextState.Equals(Constants.WorkOrderLifeCycleStates.Cancelled, StringComparison.OrdinalIgnoreCase))
PromoteRelationship(relationshipsToEdit, Constants.RelationshipLifeCycleStates.Closed);
if (!nextState.Equals(Constants.WorkOrderLifeCycleStates.New, StringComparison.OrdinalIgnoreCase))
List<string> lockedRelationships = GetLockedRelationships(nextState);
PromoteRelationship(lockedRelationships, Constants.RelationshipLifeCycleStates.Locked);
List<string> appendedRelationships = GetAppendedRelationships(nextState);
PromoteRelationship(appendedRelationships, Constants.RelationshipLifeCycleStates.Append);
relationshipsToEdit = allRelationships.Except(lockedRelationships.Union(appendedRelationships)).ToList();
PromoteRelationship(relationshipsToEdit, Constants.RelationshipLifeCycleStates.Edit);
private void UpdateEmsTransmitDate(string nextState)
if (Constants.WorkOrderLifeCycleStates.Execute.Equals(nextState, StringComparison.OrdinalIgnoreCase)
|| Constants.WorkOrderLifeCycleStates.Approved.Equals(nextState, StringComparison.OrdinalIgnoreCase)
|| Constants.WorkOrderLifeCycleStates.Complete.Equals(nextState, StringComparison.OrdinalIgnoreCase)
|| Constants.WorkOrderLifeCycleStates.Closed.Equals(nextState, StringComparison.OrdinalIgnoreCase)
|| Constants.WorkOrderLifeCycleStates.Cancelled.Equals(nextState, StringComparison.OrdinalIgnoreCase))
var transmitDate = workOrder.getProperty(Constants.PropertyNames.TransmitDateTime, string.Empty);
if (string.IsNullOrWhiteSpace(transmitDate))
dataAccessLayer.applySQL("update gm_work_order set _transmit_dte_time ='" + DateTime.UtcNow.ToString("s") +
"' where id='" + workOrder.getID() + "'");
private List<string> GetRelationshipTypes()
var list = dataAccessLayer.newItem(Constants.ItemTypeNames.ListValue, Constants.Actions.Get);
list.setProperty(Constants.PropertyNames.SourceId, Constants.Ids.WorkOrderRelationshipsList);
list.setAttribute(Constants.Attributes.Select, Constants.PropertyNames.ListValue);
throw new Aras.Server.Core.InnovatorServerException(list.getErrorDetail());
int count = list.getItemCount();
List<string> listValues = new List<string>(count);
for (var i = 0; i < count; i++)
listValues.Add(list.getItemByIndex(i).getProperty(Constants.PropertyNames.ListValue));
private void PromoteRelationship(List<string> relationshipsTypes, string newState)
foreach (var relationship in relationshipsTypes)
var idsToPromote = GetRelationshipTypeIds(relationship, newState);
if (!idsToPromote.Any()) continue;
Item itemsToPromote = dataAccessLayer.newItem(relationship, Constants.Actions.Get);
itemsToPromote.setAttribute(Constants.Attributes.IdList, string.Join(",", idsToPromote));
itemsToPromote.setProperty(Constants.PropertyNames.State, newState);
var results = itemsToPromote.apply(Constants.Actions.PromoteItem);
throw new Aras.Server.Core.InnovatorServerException(results.getErrorDetail());
catch (Aras.Server.Core.ItemIsLockedException ex)
ThrowAppropriateException(relationship, idsToPromote, ex);
private void ThrowAppropriateException(string relationship, List<string> idsToPromote,
Aras.Server.Core.ItemIsLockedException ex)
Item itemsFailedToPromote = dataAccessLayer.newItem(relationship, Constants.Actions.Get);
itemsFailedToPromote.setAttribute(Constants.Attributes.IdList, string.Join(",", idsToPromote));
itemsFailedToPromote.setPropertyCondition(Constants.PropertyNames.LockedById, Constants.PropertyCondition.NotNull);
itemsFailedToPromote.setAttribute(Constants.Attributes.Select, "id, keyed_name,locked_by_id");
itemsFailedToPromote = itemsFailedToPromote.apply();
if (itemsFailedToPromote.isError())
string message = "Failed trying to Promote locked items. " + itemsFailedToPromote.getErrorDetail();
throw new Aras.Server.Core.InnovatorServerException(message);
List<string> lockedItems = new List<string>();
for (var i = 0; i < itemsFailedToPromote.getItemCount(); i++)
var itm = itemsFailedToPromote.getItemByIndex(i);
if (itm.getProperty("locked_by_id") == null) continue;
var lockedItem = itm.getProperty(Constants.PropertyNames.KeyedName, "");
if (!string.IsNullOrWhiteSpace(lockedItem))
lockedItems.Add(string.Format("\"{0}\"", lockedItem));
string itemOrItems = lockedItems.Count != 1 ? " items" : " item";
string isOrAre = lockedItems.Count != 1 ? " are" : " is";
string developerMessage = string.Format("Locked Item Type: {0}. Locked Ids: {1}.",
relationship, string.Join(", ", idsToPromote));
var detailException = new Exception(developerMessage, ex);
"<b>{0}</b>{1}{2} locked. Your vote cannot be completed while the{3}{4} locked. Unlock the{5} to continue voting.",
string.Join("</b>, <b>", lockedItems),
itemOrItems, isOrAre, itemOrItems, isOrAre, itemOrItems);
throw new Aras.Server.Core.ItemIsLockedException(lockedMessage, detailException);
private List<string> GetRelationshipTypeIds(string relationshipTypeName, string newState)
workOrder.fetchRelationships(relationshipTypeName, "id,state");
catch (Aras.Server.Core.ItemTypeNotFoundException)
return new List<string>();
var ecrRelationships = workOrder.getRelationships(relationshipTypeName);
int count = ecrRelationships.getItemCount();
List<string> relationshipIds = new List<string>(count);
for (int i = 0; i < count; i++)
var currentState = ecrRelationships.getItemByIndex(i).getProperty(Constants.PropertyNames.State, "");
if (!currentState.Equals(newState, StringComparison.OrdinalIgnoreCase))
relationshipIds.Add(ecrRelationships.getItemByIndex(i).getID());
private List<string> GetLockedRelationships(string workOrderState)
var configurationItem = GetECRRelationshipsLifecycleConfiguration(workOrderState);
string configurationString = null;
configurationString = configurationItem.getProperty("_locked_in_" + workOrderState.ToLower());
return configurationString == null ? new List<string>() : configurationString.Split(',').ToList();
private List<string> GetAppendedRelationships(string workOrderState)
var configurationItem = GetECRRelationshipsLifecycleConfiguration(workOrderState);
string configurationString = null;
configurationString = configurationItem.getProperty("_appended_in_" + workOrderState.ToLower());
return configurationString == null ? new List<string>() : configurationString.Split(',').ToList();
private Item GetECRRelationshipsLifecycleConfiguration(string workOrderState)
if (Configuration == null)
Configuration = dataAccessLayer.newItem(Constants.ItemTypeNames.EcrLifecycelConfiguration, Constants.Actions.Get);
Configuration.setID(Constants.Ids.WorkOrderLifecycleConfigurationItem);
Configuration.setAttribute(Constants.Attributes.Select, "_locked_in_" + workOrderState.ToLower() + ",_appended_in_" + workOrderState.ToLower());
Configuration = dataAccessLayer.apply(Configuration);
if (Configuration.isError())
throw new Aras.Server.Core.InnovatorServerException(Configuration.getErrorDetail());
public interface IDataAccessLayer
Innovator getInnovator();
Item newItem(string itemTypeName, string action);
Item getItemById(string itemTypeName, string id);
Item getItemByKeyedName(string itemTypeName, string keyedName);
Item fetchRelationships(Item item, string relationshipTypeName);
Item applySQL(string sql);
public class DataAccessLayer : IDataAccessLayer
private readonly Innovator innovator;
public Innovator getInnovator()
public DataAccessLayer(Innovator innovator)
this.innovator = innovator;
public Item newItem(string itemTypeName, string action)
return innovator.newItem(itemTypeName, action);
public Item getItemById(string itemTypeName, string id)
return innovator.getItemById(itemTypeName, id);
public Item apply(Item item)
public Item fetchRelationships(Item item, string relationshipTypeName)
return item.fetchRelationships(relationshipTypeName);
public Item getItemByKeyedName(string itemTypeName, string keyedName)
return innovator.getItemByKeyedName(itemTypeName, keyedName);
public Item applySQL(string sql)
return innovator.applySQL(sql);
public void EndOfMethod()
using System.Collections;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Globalization;
namespace gm_Validate_Can_Add_class
class gm_Validate_Can_Add_class : Item
public gm_Validate_Can_Add_class() : base(null) { }
public Item gm_Validate_Can_Add()
Aras.Server.Core.CallContext CCO = ((Aras.Server.Core.IOMConnection)serverConnection).CCO;
Aras.Server.Core.IContextState RequestState = CCO.RequestState;
#region gm_Validate_Can_Add
if (System.Diagnostics.Debugger.Launch()) System.Diagnostics.Debugger.Break();
var sourceId = this.getProperty("source_id");
if (!string.IsNullOrWhiteSpace(sourceId))
string type = "is_bulk_" + this.getType().ToLower().Replace(' ', '_');
string state = getPropertyByECRId(sourceId, "state", RequestState);
string isFromECR = getPropertyByECRId(sourceId, type, RequestState, true);
if (!"true".Equals(isFromECR, StringComparison.OrdinalIgnoreCase))
var methodBody = "<relationshipTypeName>" + this.getType() + "</relationshipTypeName><workOrderState>" + state + "</workOrderState><workOrderId>" + sourceId + "</workOrderId>";
var validationResult = innovator.applyMethod("gm_WO Validate Can Add Rel", methodBody);
setPropertyByECRId(sourceId, type, RequestState, "true");
private string getPropertyByECRId(string id, string property, Aras.Server.Core.IContextState contextState, bool isNotECRProperty = false)
string key = "ECR_" + id;
Dictionary<string, string> dict = null;
if (contextState.Contains(key))
dict = (Dictionary<string, string>)contextState[key];
if (dict.ContainsKey(property))
if (string.IsNullOrEmpty(result) && !string.IsNullOrEmpty(id) && !isNotECRProperty)
Item workOrder = innovator.newItem("gm_Work Order", "get");
workOrder.setAttribute("select", property);
workOrder = workOrder.apply();
if (!workOrder.isError())
result = workOrder.getProperty(property, "");
if (!string.IsNullOrEmpty(result) && dict != null)
dict.Add(property, result);
private void setPropertyByECRId(string id, string property, Aras.Server.Core.IContextState contextState, string value)
string key = "ECR_" + id;
Dictionary<string, string> dict = null;
if (contextState.Contains(key))
dict = (Dictionary<string, string>)contextState[key];
if (dict.ContainsKey(property))
dict.Add(property, value);
private Innovator _innovator;
public Innovator innovator
_innovator = this.getInnovator();
public void EndOfMethod()