/// <summary> /// Adds the UserFieldMD to the current company Database. /// </summary> /// <param name="company">SAPbobsCOM.Company we are connected to.</param> /// <returns>Return value from the SDK action UserFieldsMD.Add().</returns> public int Add(Company company) { UserFieldsMD userFields = null; int ret = -1; try { userFields = (UserFieldsMD)company.GetBusinessObject(BoObjectTypes.oUserFields); userFields.TableName = Table; userFields.Name = Name; userFields.Description = Description; userFields.Type = this.Type; userFields.SubType = this.SubType; if (Size != 0) { userFields.EditSize = Size; } userFields.Mandatory = IsNullable ? BoYesNoEnum.tNO : BoYesNoEnum.tYES; //// valid values foreach (B1DbValidValue vval in ValidValues) { userFields.ValidValues.Value = vval.Val; userFields.ValidValues.Description = vval.Description; userFields.ValidValues.Add(); } //// default value if (DefaultValue != -1) { userFields.DefaultValue = ValidValues[DefaultValue].Val; } ret = userFields.Add(); #if DEBUG if (ret != 0) { int errcode; string errmsg; company.GetLastError(out errcode, out errmsg); System.Console.Out.WriteLine("Field " + Name + " : " + errmsg); } #endif } catch (Exception ex) { throw ex; } finally { // clean DI object System.Runtime.InteropServices.Marshal.ReleaseComObject(userFields); userFields = null; //System.GC.Collect(); //System.GC.WaitForPendingFinalizers(); } return(ret); }
public static string CreateField(string tablename, string fieldname, string description, BoFieldTypes type, int size, bool isMandatory, bool isSapTable = false, string likedToTAble = "", string defaultValue = "", BoFldSubTypes subType = BoFldSubTypes.st_None) { // Get a new Recordset object Recordset oRecordSet = (Recordset)Company.GetBusinessObject(BoObjectTypes.BoRecordset); string sqlQuery = $"SELECT T0.TableID, T0.FieldID FROM CUFD T0 WHERE T0.TableID = '@{tablename}' AND T0.AliasID = '{fieldname}'"; oRecordSet.DoQuery(sqlQuery); var updateFlag = oRecordSet.RecordCount == 1; var fieldId = int.Parse(oRecordSet.Fields.Item("FieldID").Value.ToString()); System.Runtime.InteropServices.Marshal.ReleaseComObject(oRecordSet); UserFieldsMD oUfield = (UserFieldsMD)Company.GetBusinessObject(BoObjectTypes.oUserFields); if (updateFlag) { return(""); //oUfield.GetByKey(tablename, fieldId); } try { oUfield.TableName = tablename; oUfield.Name = fieldname; oUfield.Description = description; oUfield.Type = type; oUfield.Mandatory = isMandatory ? BoYesNoEnum.tYES : BoYesNoEnum.tNO; oUfield.DefaultValue = defaultValue; if (type == BoFieldTypes.db_Float) { oUfield.SubType = subType; } if (type == BoFieldTypes.db_Alpha || type == BoFieldTypes.db_Numeric) { oUfield.EditSize = size; } oUfield.LinkedTable = likedToTAble; int ret = updateFlag ? oUfield.Update() : oUfield.Add(); if (ret == 0) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oUfield); return(string.Empty); } else { System.Runtime.InteropServices.Marshal.ReleaseComObject(oUfield); return(Company.GetLastErrorDescription()); } } catch (Exception e) { return($"exeption : {e.Message}, Sap Error {Company.GetLastErrorDescription()}"); } finally { System.Runtime.InteropServices.Marshal.ReleaseComObject(oUfield); } }
/// <summary> /// Cria o campo dentro do company informado /// </summary> /// <param name="oCmp">Company para criar o campo</param> /// <param name="campo">Campo a ser criado</param> public static void CriarCampo(Company oCmp, Campo campo) { ValidarCampo(campo); UserFieldsMD oUser = (UserFieldsMD)oCmp.GetBusinessObject(BoObjectTypes.oUserFields); oUser.TableName = campo.TableName; oUser.Name = campo.Name; oUser.Description = campo.Description; oUser.Mandatory = campo.Obrigatorio; oUser.Type = campo.Tipo; if (!String.IsNullOrEmpty(campo.TabelaSAPLinked)) { oUser.LinkedTable = campo.TabelaSAPLinked; } if (campo.SubTipo != null) { oUser.SubType = (BoFldSubTypes)campo.SubTipo; } if (campo.Tamanho != null) { oUser.EditSize = (int)campo.Tamanho; } if (!String.IsNullOrWhiteSpace(campo.ValorPadrao)) { oUser.DefaultValue = campo.ValorPadrao; } if (campo.ValoresValidos != null) { int n = 0; foreach (ValoresValidos valorValido in campo.ValoresValidos) { n++; oUser.ValidValues.Description = valorValido.Descricao; oUser.ValidValues.Value = valorValido.Valor; if (n < campo.ValoresValidos.Count) { oUser.ValidValues.Add(); } } } int res = oUser.Add(); System.Runtime.InteropServices.Marshal.ReleaseComObject(oUser); oUser = null; GC.Collect(); if (res != 0) { throw new Exception(oCmp.GetLastErrorDescription()); } }
/// <summary> /// Create field on table /// </summary> /// <param name="tableName"></param> /// <param name="fieldName"></param> /// <param name="fieldDescription"></param> /// <param name="type"></param> /// <param name="size"></param> /// <param name="subType"></param> /// <param name="validValues">Dropdown values</param> /// <param name="defaultValue"></param> /// <returns></returns> public static void CreateField(string tableName, string fieldName, string fieldDescription, BoFieldTypes type = BoFieldTypes.db_Alpha, int size = 50, BoFldSubTypes subType = BoFldSubTypes.st_None, IDictionary <string, string> validValues = null, string defaultValue = null) { UserFieldsMD userFieldsMd = null; try { userFieldsMd = SboApp.Company.GetBusinessObject(BoObjectTypes.oUserFields) as UserFieldsMD; if (userFieldsMd == null) { throw new NullReferenceException("Failed to get UserFieldsMD object"); } var fieldId = GetFieldId(tableName, fieldName); if (fieldId != -1) { return; } userFieldsMd.TableName = tableName; userFieldsMd.Name = fieldName; userFieldsMd.Description = fieldDescription; userFieldsMd.Type = type; userFieldsMd.SubType = subType; userFieldsMd.Size = size; userFieldsMd.EditSize = size; userFieldsMd.DefaultValue = defaultValue; if (validValues != null) { foreach (var validValue in validValues) { userFieldsMd.ValidValues.Value = validValue.Key; userFieldsMd.ValidValues.Description = validValue.Value; userFieldsMd.ValidValues.Add(); } } ErrorHelper.HandleErrorWithException(userFieldsMd.Add(), "Could not create field"); } catch (Exception ex) { SboApp.Logger.Error($"Create Field {tableName}.{fieldName} Error: {ex.Message}", ex); throw; } finally { if (userFieldsMd != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(userFieldsMd); } } }
/// <summary> /// Initializes the field. /// </summary> /// <remarks> /// Ranaya, 26/05/2017. /// </remarks> /// <param name="pObjField"> /// The object field. /// </param> private void InitializeField(Models.Field pObjField) { UserFieldsMD lObjUserField = null; try { if (!ExistsField(pObjField.TableName, pObjField.GetAttributes().Name)) { lObjUserField = pObjField.GetUserField(); HandleException.Field(lObjUserField.Add()); } } finally { MemoryUtility.ReleaseComObject(lObjUserField); } }
/// <summary> /// Executes the update action and releases the object. /// </summary> public void Execute() { var result = field.Add(); if (result != 0) { var errorArgs = new UserFieldErrorEventArgs { TableName = field.TableName, FieldName = field.Name, ErrorCode = company.GetLastErrorCode(), ErrorDescription = company.GetLastErrorDescription() }; OnError(this, errorArgs); } Marshal.ReleaseComObject(field); }
private void AddUserField(Domain.UserTables.UserField userField) { UserFieldsMD userFieldMd = null; GC.Collect(); GC.WaitForPendingFinalizers(); var company = Company; userFieldMd = company.GetUserFieldMd(); try { userFieldMd.TableName = userField.TableName; userFieldMd.Name = userField.Name; userFieldMd.Description = userField.Description; userFieldMd.Type = userField.Type; if (userField.SubType != BoFldSubTypes.st_None) { userFieldMd.SubType = userField.SubType; } if (userField.Size != 0) { userFieldMd.EditSize = userField.Size; } if (userFieldMd.Add() != 0) { var message = $"$Criação de Campo de Usuário [{userField.TableName} - {userField.Name}]"; company.ThrowExceptionForLastError(message); } } finally { userFieldMd.ReleaseCom(); } }
//Cria campo de usuario public void CreateField(string tableName, string tableField, string fieldDescr, BoFieldTypes type, int size, BoFldSubTypes subType = SAPbobsCOM.BoFldSubTypes.st_None, string defaultValue = "", string[] validValues = null, BoYesNoEnum mandatory = BoYesNoEnum.tNO) { int err = 0; string errMsg = ""; UserFieldsMD oUserFieldsMD = null; try { bool exist = UserFieldsExist(tableName, tableField); oUserFieldsMD = ((UserFieldsMD)(oConnection.Company.GetBusinessObject(BoObjectTypes.oUserFields))); //se o campo nao existe, cria if (!exist) { if (tableField.Length >= 20) { throw new Exception("Nome de campo maior que 19 caracteres: " + tableField + " Len: " + tableField.Length); } if (fieldDescr.Length >= 30) { throw new Exception("Descrição de campo maior que 29 caracteres: " + fieldDescr + " Len: " + fieldDescr.Length); } //Adiciona o campo oUserFieldsMD.TableName = tableName;//.Length >= 20 ? tableName.Substring(0, 20) : tableName; oUserFieldsMD.Name = tableField; oUserFieldsMD.Description = fieldDescr; oUserFieldsMD.Type = type; oUserFieldsMD.Size = size; oUserFieldsMD.EditSize = size; oUserFieldsMD.SubType = subType; oUserFieldsMD.DefaultValue = defaultValue; oUserFieldsMD.Mandatory = mandatory; if (validValues != null) { IValidValuesMD vals = oUserFieldsMD.ValidValues; for (int i = 0; i < validValues.Length; i++) { string[] dv = validValues[i].Trim().Split(new char[] { ',', '|', '=' }); vals.SetCurrentLine(i); vals.Value = dv[0]; vals.Description = dv[1]; vals.Add(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(vals); vals = null; System.GC.Collect(); } if (oUserFieldsMD.Add() != 0) { oConnection.Company.GetLastError(out err, out errMsg); logMessage = "Erro ao criar Campo de Usuário: '" + tableField + "' em '" + tableName + "': " + errMsg + " : " + err; logger.log(logMessage, Logger.LogType.ERROR, null, false); } else { //mostra msg logMessage = "Criado campo de Usuário: '" + tableField + "' em '" + tableName; logger.log(logMessage, Logger.LogType.INFO); } System.Runtime.InteropServices.Marshal.ReleaseComObject(oUserFieldsMD); oUserFieldsMD = null; System.GC.Collect(); } } catch (Exception e) { oConnection.Company.GetLastError(out err, out errMsg); logMessage = "Erro ao criar Campo de Usuário: '" + tableField + "' em '" + tableName + "': " + errMsg + " : " + err; logger.log(logMessage, Logger.LogType.ERROR, e); //SB1ControlException.SB1ControlException.Save(e); if (oUserFieldsMD != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oUserFieldsMD); } oUserFieldsMD = null; System.GC.Collect(); if (oUserFieldsMD != null) { System.Runtime.InteropServices.Marshal.ReleaseComObject(oUserFieldsMD); } oUserFieldsMD = null; System.GC.Collect(); } }
public void CriaCampo(Company oCompany, string sTabela, string sCampo, string sDescricao, BoFieldTypes Tipo, BoFldSubTypes SubTipo, int iComprimento, BoYesNoEnum Obrigatorio, bool bValorPadrao, string sValorPadrao, bool bValoresValidos, string[,] sValoresValidos, out string sMensagem) { sMensagem = string.Empty; try { if (!VerificaExistenciaCampo(oCompany, sTabela, sCampo)) { int lErrCode; string lErrStr; int lRetVal; UserFieldsMD oUserFieldMD = null; //Limpa a memória oUserFieldMD = (UserFieldsMD)oCompany.GetBusinessObject(BoObjectTypes.oUserFields); System.Runtime.InteropServices.Marshal.ReleaseComObject(oUserFieldMD); oUserFieldMD = null; GC.Collect(); oUserFieldMD = (UserFieldsMD)oCompany.GetBusinessObject(BoObjectTypes.oUserFields); oUserFieldMD.TableName = sTabela; oUserFieldMD.Name = sCampo; oUserFieldMD.Description = sDescricao; oUserFieldMD.Type = Tipo; oUserFieldMD.SubType = SubTipo; oUserFieldMD.Mandatory = Obrigatorio; if (bValoresValidos) { for (int i = 0; i < sValoresValidos.GetLength(0); i++) { oUserFieldMD.ValidValues.Value = sValoresValidos[i, 0]; oUserFieldMD.ValidValues.Description = sValoresValidos[i, 1]; oUserFieldMD.ValidValues.Add(); } } if (bValorPadrao) { oUserFieldMD.DefaultValue = sValorPadrao; } if (iComprimento > 0) { oUserFieldMD.Size = iComprimento; } lRetVal = oUserFieldMD.Add(); if (lRetVal != 0) { oCompany.GetLastError(out lErrCode, out lErrStr); sMensagem = string.Format("Falha! Descricao B1: {0} - Codigo Erro B1: {1}", lErrStr, lErrCode.ToString()); } else { sMensagem = string.Format("Campo {0} - {1}, criado com sucesso..", sCampo, sDescricao); } //Limpa a Memória System.Runtime.InteropServices.Marshal.ReleaseComObject(oUserFieldMD); oUserFieldMD = null; GC.Collect(); } } catch (Exception ex) { sMensagem = string.Format("Erro ao criar Tabela/Campos SAP, Erro: {0}", ex.Message); } }