Exemple #1
0
        public static int?GetDocEntryFromDocNum(BoObjectTypes type, int docNum, int?seriesCode = null)
        {
            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var recordSet = factory.Create <Recordset>(BoObjectTypes.BoRecordset);
                if (!seriesCode.HasValue)
                {
                    seriesCode = GetDefaultSeries(type).Series;
                }

                var objectTypeDefinition = ObjectTypeDefinitions.FirstOrDefault((def) => { return(def.ObjectType.Equals(type)); });
                if (objectTypeDefinition != null)
                {
                    return(recordSet.DoQueryValue <int?>(string.Format("SELECT {0} FROM {1} WHERE {2} = '{3}' AND Series = '{4}'",
                                                                       objectTypeDefinition.DocEntryColumn,
                                                                       objectTypeDefinition.DataBaseTable,
                                                                       objectTypeDefinition.DocNumColumn,
                                                                       docNum,
                                                                       seriesCode)));
                }
                else
                {
                    throw new ArgumentOutOfRangeException("type");
                }
            }
        }
Exemple #2
0
        public static SboReportDocument FromDefaultReportFor(string reportCode, string cardCode, int?userSign = null)
        {
            Logger.Trace("Getting Crystal Report document from default for {0} - {1} - {2}", reportCode, cardCode, userSign);

            string layoutCode = null;

            var cacheKey = $"SboReportDocument.FromDefaultReportFor({reportCode},{cardCode},{userSign})";

            if (SboTemporaryCache.Contains(cacheKey))
            {
                layoutCode = SboTemporaryCache.Get <string>(cacheKey);
            }

            if (layoutCode == null)
            {
                using (var factory = new SboDisposableBusinessObjectFactory())
                {
                    var companyService      = factory.GetCompanyService();
                    var reportLayoutService = (ReportLayoutsService)companyService.GetBusinessService(ServiceTypes.ReportLayoutsService);

                    var reportParam =
                        (ReportParams)reportLayoutService.GetDataInterface(ReportLayoutsServiceDataInterfaces.rlsdiReportParams);
                    reportParam.UserID     = userSign ?? SboAddon.Instance.Company.UserSignature;
                    reportParam.ReportCode = reportCode;
                    reportParam.CardCode   = cardCode;

                    var reportLayout = reportLayoutService.GetDefaultReport(reportParam);
                    layoutCode = reportLayout.LayoutCode;

                    SboTemporaryCache.Set(cacheKey, layoutCode);
                }
            }

            return(FromLayoutCode(layoutCode));
        }
Exemple #3
0
 public static List <Dictionary <string, object> > QueryList(string query, params object[] args)
 {
     using (var factory = new SboDisposableBusinessObjectFactory())
     {
         return(factory.Create <Recordset>(BoObjectTypes.BoRecordset).DoQueryList(query, args));
     }
 }
Exemple #4
0
        public static void AddUserTable(String name, String description, BoUTBTableType type)
        {
            if (UserTableExists(name))
            {
                throw new Exception(string.Format("Table '{0}' already exists", name));
            }

            if (name.StartsWith("@"))
            {
                name = name.Substring(1);
            }

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var userTablesMd = factory.Create <UserTablesMD>(BoObjectTypes.oUserTables);

                userTablesMd.TableName        = name;
                userTablesMd.TableDescription = description;
                userTablesMd.TableType        = type;

                if (userTablesMd.Add() != 0)
                {
                    throw new Exception(SboAddon.Instance.Company.GetLastErrorDescription());
                }

                Logger.Info("Table '{0}' was added successfully", userTablesMd.TableName);
            }
        }
Exemple #5
0
        public static string GetNextTableCode(string tableName, int codeLength = 10)
        {
            if (!tableName.StartsWith("@"))
            {
                tableName = "@" + tableName;
            }

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var recordSet = factory.Create <Recordset>(BoObjectTypes.BoRecordset);
                recordSet.DoQuery(string.Format(SboAddon.Instance.Company.DbServerType.Equals(BoDataServerTypes.dst_HANADB) ?
                                                @"SELECT CAST(MAX(CAST(""Code"" AS BIGINT)) AS NVARCHAR(30)) AS Code FROM ""{0}""" :
                                                @"SELECT CONVERT(nvarchar(30), MAX(CONVERT(bigint, Code))) [Code] FROM [{0}] WHERE ISNUMERIC(Code) = 1", tableName));

                long?code = (recordSet.RecordCount == 0 ||
                             String.IsNullOrWhiteSpace((string)recordSet.Fields.Item("Code").Value))
                    ? 0
                    : Convert.ToInt64(recordSet.Fields.Item("Code").Value, CultureInfo.InvariantCulture);

                if (!code.HasValue)
                {
                    code = 0;
                }

                return((code.Value + 1).ToString(CultureInfo.InvariantCulture).PadLeft(codeLength, '0'));
            }
        }
Exemple #6
0
 public static bool UserFieldExists(string tableName, string name)
 {
     using (var factory = new SboDisposableBusinessObjectFactory())
     {
         var recordSet = factory.Create <Recordset>(BoObjectTypes.BoRecordset);
         recordSet.DoQuery(string.Format(@"SELECT * FROM CUFD WHERE (""TableID"" = '{0}' OR ""TableID"" = '@{0}') AND (""AliasID"" = '{1}' OR ""AliasID"" = 'U_{1}')", tableName, name));
         return(recordSet.RecordCount != 0);
     }
 }
Exemple #7
0
 public static T GetRecordByQuery <T>(string query, params object[] parameters) where T : SboUserDefinedTableDefinition, new()
 {
     using (var f = new SboDisposableBusinessObjectFactory())
     {
         var rs = f.Create <Recordset>(BoObjectTypes.BoRecordset);
         rs.DoQuery(String.Format(query, parameters));
         return(rs.RecordCount > 0 ? rs.GetRecord <T>((string)rs.Fields.Item("Code").Value) : null);
     }
 }
Exemple #8
0
 public static T QueryValue <T>(string query, params object[] args)
 {
     using (var factory = new SboDisposableBusinessObjectFactory())
     {
         var ast       = System.Threading.Thread.CurrentThread.GetApartmentState();
         var recordset = factory.Create <Recordset>(BoObjectTypes.BoRecordset);
         return(recordset.DoQueryValue <T>(query, args));
     }
 }
Exemple #9
0
        private void SetSettingValue(string key, string val)
        {
            var cacheKey = String.Format("{0}||||{1}||||{2}||||{3}", _tableName, _addonName, _userName, key);

            _cache.Remove(cacheKey);

            var nextTableCode = SboUserDefinedDataManager.GetNextTableCode(_tableName);

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var recordSet = factory.Create <Recordset>(BoObjectTypes.BoRecordset);

                try
                {
                    if (HasSetting(key))
                    {
                        Log.Debug("Updating setting key " + key);
                        recordSet.DoQuery(_userName == null
                                              ? string.Format(
                                              @"UPDATE ""@{0}"" SET ""U_BigValue"" = '{3}' WHERE ""U_Addon"" = '{1}' AND RTRIM(COALESCE(""U_User"", '')) = '' AND ""U_BigKey"" = '{2}'",
                                              _tableName, _addonName, key,
                                              val
                                              )
                                              : string.Format(
                                              @"UPDATE ""@{0}"" SET ""U_BigValue"" = '{4}' WHERE ""U_Addon"" = '{1}' AND ""U_User"" = '{2}' AND ""U_BigKey"" = '{3}'",
                                              _tableName, _addonName, _userName, key,
                                              val
                                              )
                                          );
                    }
                    else
                    {
                        Log.Debug("Inserting setting key " + key);
                        recordSet.DoQuery(_userName == null
                                              ? string.Format(
                                              @"INSERT INTO ""@{0}"" (""Code"", ""Name"", ""U_Addon"", ""U_BigKey"", ""U_BigValue"") VALUES ('{1}', '{1}', '{2}', '{3}', '{4}')",
                                              _tableName,
                                              nextTableCode,
                                              _addonName, key, val
                                              )
                                              : string.Format(
                                              @"INSERT INTO ""@{0}"" (""Code"", ""Name"", ""U_Addon"", ""U_User"", ""U_BigKey"", ""U_BigValue"") VALUES ('{1}', '{1}', '{2}', '{3}', '{4}', '{5}')",
                                              _tableName,
                                              nextTableCode,
                                              _addonName, _userName, key, val
                                              )
                                          );
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e, "Recordset error");
                }
            }
        }
Exemple #10
0
        public static bool UserObjectExists(string name)
        {
            if (name.StartsWith("@"))
            {
                name = name.Substring(1);
            }

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var userObjectsMd = factory.Create <UserObjectsMD>(BoObjectTypes.oUserObjectsMD);
                return(userObjectsMd.GetByKey(name));
            }
        }
Exemple #11
0
 public static void RemoveUserTable(string name)
 {
     using (var factory = new SboDisposableBusinessObjectFactory())
     {
         var userTable = factory.Create <UserTablesMD>(BoObjectTypes.oUserTables);
         userTable.GetByKey(name);
         if (userTable.Remove() != 0)
         {
             throw new Exception(string.Format("Error removing table {0}: {1}",
                                               name,
                                               SboAddon.Instance.Company.GetLastErrorDescription()));
         }
     }
 }
Exemple #12
0
        public static void AddDocumentAttachment(BoObjectTypes type, int docEntry, params string[] filenames)
        {
            if (docEntry <= 0)
            {
                return;
            }

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var sapDocument = factory.Create <Documents>(type);
                sapDocument.GetByKey(docEntry);

                var attachment = factory.Create <Attachments2>(BoObjectTypes.oAttachments2);
                if (sapDocument.AttachmentEntry > 0)
                {
                    attachment.GetByKey(sapDocument.AttachmentEntry);
                    attachment.Lines.Add();
                }
                foreach (var file in filenames)
                {
                    attachment.Lines.SourcePath    = Path.GetDirectoryName(file);
                    attachment.Lines.FileName      = Path.GetFileNameWithoutExtension(file);
                    attachment.Lines.FileExtension = Path.GetExtension(file).TrimStart('.');
                    attachment.Lines.Add();
                }
                if (sapDocument.AttachmentEntry > 0)
                {
                    if (attachment.Update() != 0)
                    {
                        throw new Exception(SboAddon.Instance.Company.GetLastErrorDescription());
                    }
                }
                else
                {
                    if (attachment.Add() != 0)
                    {
                        throw new Exception(SboAddon.Instance.Company.GetLastErrorDescription());
                    }

                    var attachmentId = SboAddon.Instance.Company.GetNewObjectKey();

                    sapDocument.AttachmentEntry = Convert.ToInt32(attachmentId);
                    if (sapDocument.Update() != 0)
                    {
                        throw new Exception(SboAddon.Instance.Company.GetLastErrorDescription());
                    }
                }
            }
        }
Exemple #13
0
        public static string GetLocalCurrency()
        {
            if (_getLocalCurrencyCache != null)
            {
                return(_getLocalCurrencyCache);
            }

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                CompanyService companyService = factory.GetCompanyService();
                AdminInfo      adminInfo      = companyService.GetAdminInfo();

                _getLocalCurrencyCache = adminInfo.LocalCurrency.ToUpperInvariant();
                return(_getLocalCurrencyCache);
            }
        }
Exemple #14
0
        public static int?GetDocNumFromDocEntry(BoObjectTypes type, int docEntry)
        {
            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var recordSet = factory.Create <Recordset>(BoObjectTypes.BoRecordset);

                var objectTypeDefinition = ObjectTypeDefinitions.FirstOrDefault(def => def.ObjectType.Equals(type));
                if (objectTypeDefinition != null)
                {
                    return(recordSet.DoQueryValue <int?>(
                               $@"SELECT ""{objectTypeDefinition.DocNumColumn}"" FROM {objectTypeDefinition.DataBaseTable} WHERE ""{objectTypeDefinition.DocEntryColumn}"" = '{docEntry}'"));
                }
                else
                {
                    throw new ArgumentOutOfRangeException("type");
                }
            }
        }
Exemple #15
0
        public static System.Data.DataTable getDataTable(string sql, string CallerRef)
        {
            System.Data.DataTable dtOut = new System.Data.DataTable();

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                SAPbobsCOM.Recordset rs = (SAPbobsCOM.Recordset)factory.Create <Recordset>(BoObjectTypes.BoRecordset);

                try
                {
                    rs.DoQuery(sql);
                    if (!rs.EoF)
                    {
                        for (int i = 0; i < rs.Fields.Count; i++)
                        {
                            dtOut.Columns.Add(rs.Fields.Item(i).Description);
                        }
                    }

                    while (!rs.EoF)
                    {
                        DataRow nr = dtOut.NewRow();
                        for (int i = 0; i < rs.Fields.Count; i++)
                        {
                            nr[i] = rs.Fields.Item(i).Value;
                        }
                        dtOut.Rows.Add(nr);
                        rs.MoveNext();
                    }
                }
                catch (Exception ex)
                {
                    dtOut = new DataTable();
                    dtOut.Columns.Add("Error");
                    dtOut.Rows.Add(ex.Message);
                }
                finally
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(rs);
                    rs = null;
                }
            }
            return(dtOut);
        }
Exemple #16
0
        public static List <T> GetRecordsByQuery <T>(string query, params object[] parameters) where T : SboUserDefinedTableDefinition, new()
        {
            using (var f = new SboDisposableBusinessObjectFactory())
            {
                var rs = f.Create <Recordset>(BoObjectTypes.BoRecordset);
                rs.DoQuery(String.Format(query, parameters));
                var list = new List <T>();

                if (rs.RecordCount > 0)
                {
                    rs.MoveFirst();
                    while (!rs.EoF)
                    {
                        list.Add(GetRecord <T>((string)rs.Fields.Item("Code").Value));
                        rs.MoveNext();
                    }
                }

                return(list);
            }
        }
Exemple #17
0
        private bool HasSetting(string key)
        {
            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var recordSet = factory.Create <Recordset>(BoObjectTypes.BoRecordset);

                recordSet.DoQuery(_userName == null
                                      ? string.Format(
                                      @"SELECT ""Code"" FROM ""@{0}"" WHERE ""U_Addon"" = '{1}' AND RTRIM(COALESCE(""U_User"", '')) = '' AND ""U_BigKey"" = '{2}'", _tableName,
                                      _addonName, key)
                                      : string.Format(
                                      @"SELECT ""Code"" FROM ""@{0}"" WHERE ""U_Addon"" = '{1}' AND ""U_User"" = '{2}' AND ""U_BigKey"" = '{3}'",
                                      _tableName, _addonName, _userName, key));

                if (recordSet.RecordCount > 0)
                {
                    return(true);
                }

                return(false);
            }
        }
Exemple #18
0
        public static SboReportDocument FromLayoutCode(string layoutCode)
        {
            Logger.Trace("Getting Crystal Report document from layoutCode {0}", layoutCode);

            string tempFilename = null;
            var    cacheKey     = $"SboReportDocument.FromLayoutCode({layoutCode})";

            if (SboTemporaryCache.Contains(cacheKey))
            {
                tempFilename = SboTemporaryCache.Get <string>(cacheKey);
            }

            if (tempFilename == null || !File.Exists(tempFilename))
            {
                using (var factory = new SboDisposableBusinessObjectFactory())
                {
                    var companyService = factory.GetCompanyService();
                    var blobParams     = (BlobParams)companyService.GetDataInterface(CompanyServiceDataInterfaces.csdiBlobParams);
                    blobParams.Table = "RDOC";
                    blobParams.Field = "Template";

                    BlobTableKeySegment keySegment = blobParams.BlobTableKeySegments.Add();
                    keySegment.Name  = "DocCode";
                    keySegment.Value = layoutCode;

                    var blob = (Blob)companyService.GetDataInterface(CompanyServiceDataInterfaces.csdiBlob);
                    blob = companyService.GetBlob(blobParams);

                    tempFilename = Path.GetTempFileName();
                    File.WriteAllBytes(tempFilename, Convert.FromBase64String(blob.Content));

                    SboTemporaryCache.Set(cacheKey, tempFilename);
                }
            }

            return(FromFile(tempFilename));
        }
Exemple #19
0
        private string GetSettingValue(string key)
        {
            var cacheKey = String.Format("{0}||||{1}||||{2}||||{3}", _tableName, _addonName, _userName, key);

            if (_cache.Contains(cacheKey))
            {
                return((string)_cache.Get(cacheKey));
            }

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var recordSet = factory.Create <Recordset>(BoObjectTypes.BoRecordset);
                recordSet.DoQuery(_userName == null
                                      ? string.Format(
                                      @"SELECT ""U_BigValue"" FROM ""@{0}"" WHERE ""U_Addon"" = '{1}' AND RTRIM(COALESCE(""U_User"", '')) = '' AND ""U_BigKey"" = '{2}'", _tableName,
                                      _addonName, key)
                                      : string.Format(
                                      @"SELECT ""U_BigValue"" FROM ""@{0}"" WHERE ""U_Addon"" = '{1}' AND ""U_User"" = '{2}' AND ""U_BigKey"" = '{3}'",
                                      _tableName, _addonName, _userName, key));
                if (recordSet.RecordCount == 0)
                {
                    return(null);
                }

                recordSet.MoveFirst();

                var parameterValue = (string)recordSet.Fields.Item("U_BigValue").Value;

                _cache.Set(cacheKey, parameterValue, new CacheItemPolicy()
                {
                    SlidingExpiration = TimeSpan.FromMinutes(5)
                });

                return(parameterValue);
            }
        }
Exemple #20
0
        public static UserObjectsMD AddUserObject(String name, String description, BoUDOObjType type)
        {
            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                if (name.StartsWith("@"))
                {
                    name = name.Substring(1);
                }

                var userObjectMd = factory.Create <UserObjectsMD>(BoObjectTypes.oUserObjectsMD);
                userObjectMd.Code       = name;
                userObjectMd.Name       = description;
                userObjectMd.ObjectType = type;
                userObjectMd.TableName  = name;

                if (userObjectMd.Add() != 0)
                {
                    throw new Exception(SboAddon.Instance.Company.GetLastErrorDescription());
                }

                Logger.Info("Object '{0}' was added successfully", userObjectMd.Name);
                return(userObjectMd);
            }
        }
Exemple #21
0
        public static void UpdateUserField(string tableName, string name, string description = null, int?editSize        = null,
                                           Dictionary <string, string> validValues           = null, string defaultValue = null, string linkedUdo = null, bool?mandatory = false)
        {
            if (!UserFieldExists(tableName, name))
            {
                throw new Exception(string.Format("Userfield {0} doesn't exists in table {1}", name, tableName));
            }

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var fieldId = SboDiUtils.QueryValue <int>(string.Format(@"SELECT ""FieldID"" FROM CUFD WHERE (""TableID"" = '{0}' OR ""TableID"" = '@{0}') AND (""AliasID"" = '{1}' OR ""AliasID"" = 'U_{1}')", tableName, name));

                var userFieldsMd = factory.Create <UserFieldsMD>(BoObjectTypes.oUserFields);
                if (!userFieldsMd.GetByKey(tableName, fieldId))
                {
                    throw new Exception(string.Format("Could not find userfield {0} in table {1}", name, tableName));
                }

                if (!String.IsNullOrWhiteSpace(description))
                {
                    userFieldsMd.Description = description;
                }
                if (editSize.HasValue)
                {
                    userFieldsMd.EditSize = editSize.Value;
                }

                /* TODO: Update validvalues
                 * if (validValues != null)
                 * {
                 *  int insertedValues = 0;
                 *  foreach (string key in validValues.Keys)
                 *  {
                 *      userFieldsMd.ValidValues.Value = key;
                 *      userFieldsMd.ValidValues.Description = validValues[key];
                 *
                 *      if (insertedValues < validValues.Count - 1)
                 *          userFieldsMd.ValidValues.Add();
                 *
                 *      insertedValues++;
                 *  }
                 * }*/
                if (!String.IsNullOrWhiteSpace(defaultValue))
                {
                    userFieldsMd.DefaultValue = defaultValue;
                }
                if (!String.IsNullOrWhiteSpace(linkedUdo))
                {
                    userFieldsMd.LinkedUDO = linkedUdo;
                }

                if (mandatory.HasValue)
                {
                    userFieldsMd.Mandatory = mandatory.GetValueOrDefault(false) ? BoYesNoEnum.tYES : BoYesNoEnum.tNO;
                }

                Logger.Debug("Updating field {0} in table {1}", name, tableName);
                if (userFieldsMd.Update() != 0)
                {
                    throw new Exception(SboAddon.Instance.Company.GetLastErrorDescription());
                }

                Logger.Info("Updated field {0} in table {1}", name, tableName);
            }
        }
Exemple #22
0
 public static T GetRecord <T>(string code) where T : SboUserDefinedTableDefinition, new()
 {
     using (var f = new SboDisposableBusinessObjectFactory())
         return(f.Create <Recordset>(BoObjectTypes.BoRecordset).GetRecord <T>(code));
 }
Exemple #23
0
 public static void ReplaceRecord(SboUserDefinedTableDefinition record)
 {
     using (var f = new SboDisposableBusinessObjectFactory())
         f.Create <Recordset>(BoObjectTypes.BoRecordset).Replace(record);
 }
Exemple #24
0
        private static void AddUserObjectIfNotExist(Type definition)
        {
            var tableName = definition.GetCustomAttributes(typeof(SboUserDefinedTableAttribute), true).Select(a => ((SboUserDefinedTableAttribute)a).Name).FirstOrDefault();

            var objectAttribute     = definition.GetCustomAttributes(typeof(SboUserDefinedObjectAttribute), true);
            var objectName          = objectAttribute.Select(a => ((SboUserDefinedObjectAttribute)a).Name).FirstOrDefault();
            var objectDescription   = objectAttribute.Select(a => ((SboUserDefinedObjectAttribute)a).Description).FirstOrDefault();
            var objectType          = objectAttribute.Select(a => ((SboUserDefinedObjectAttribute)a).Type).FirstOrDefault();
            var objectFormType      = objectAttribute.Select(a => ((SboUserDefinedObjectAttribute)a).FormType).FirstOrDefault();
            var menuFather          = objectAttribute.Select(a => ((SboUserDefinedObjectAttribute)a).FatherMenu).FirstOrDefault();
            var menuUid             = objectAttribute.Select(a => ((SboUserDefinedObjectAttribute)a).MenuUid).FirstOrDefault();
            var menuCaption         = objectAttribute.Select(a => ((SboUserDefinedObjectAttribute)a).MenuCaption).FirstOrDefault();
            var formXmlResourcePath = objectAttribute.Select(a => ((SboUserDefinedObjectAttribute)a).FormXmlResourcePath).FirstOrDefault();

            if (UserObjectExists(objectName))
            {
                return;
            }

            var properties = (from property in definition.GetProperties()
                              let udfAttribute =
                                  property.GetCustomAttributes(typeof(SboUserDefinedFieldAttribute), false).SingleOrDefault() as
                                  SboUserDefinedFieldAttribute
                                  where udfAttribute != null
                                  orderby udfAttribute.Order
                                  select new { Property = property, PropertyAttribute = udfAttribute }).ToList();

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var userObjectMd = factory.Create <UserObjectsMD>(BoObjectTypes.oUserObjectsMD);

                userObjectMd.Code       = objectName;
                userObjectMd.Name       = objectDescription;
                userObjectMd.ObjectType = objectType;
                userObjectMd.TableName  = tableName;
                if (objectFormType.Equals(SboUserDefinedObjectFormType.Matrix))
                {
                    userObjectMd.CanCreateDefaultForm              = BoYesNoEnum.tYES;
                    userObjectMd.EnableEnhancedForm                = BoYesNoEnum.tNO;
                    userObjectMd.UseUniqueFormType                 = BoYesNoEnum.tYES;
                    userObjectMd.FormColumns.FormColumnAlias       = "Code";
                    userObjectMd.FormColumns.FormColumnDescription = "Code";
                    userObjectMd.FormColumns.Add();
                    foreach (var p in properties.Where(p => p.PropertyAttribute.FormField))
                    {
                        userObjectMd.FormColumns.FormColumnAlias       = "U_" + (String.IsNullOrEmpty(p.PropertyAttribute.Name) ? p.Property.Name : p.PropertyAttribute.Name);
                        userObjectMd.FormColumns.FormColumnDescription = p.PropertyAttribute.Description;
                        userObjectMd.FormColumns.Editable = BoYesNoEnum.tYES;
                        userObjectMd.FormColumns.Add();
                    }
                }
                else if (objectFormType.Equals(SboUserDefinedObjectFormType.Enhanced))
                {
                    userObjectMd.CanCreateDefaultForm              = BoYesNoEnum.tYES;
                    userObjectMd.EnableEnhancedForm                = BoYesNoEnum.tYES;
                    userObjectMd.UseUniqueFormType                 = BoYesNoEnum.tYES;
                    userObjectMd.FormColumns.FormColumnAlias       = "Code";
                    userObjectMd.FormColumns.FormColumnDescription = "Code";
                    userObjectMd.FormColumns.Add();
                    foreach (var p in properties.Where(p => p.PropertyAttribute.FormField))
                    {
                        userObjectMd.FormColumns.FormColumnAlias       = "U_" + (String.IsNullOrEmpty(p.PropertyAttribute.Name) ? p.Property.Name : p.PropertyAttribute.Name);
                        userObjectMd.FormColumns.FormColumnDescription = p.PropertyAttribute.Description;
                        userObjectMd.FormColumns.Editable = BoYesNoEnum.tYES;
                        userObjectMd.FormColumns.Add();
                    }
                }
                if (properties.Any(p => p.PropertyAttribute.SearchField))
                {
                    userObjectMd.CanFind = BoYesNoEnum.tYES;
                    foreach (var p in properties.Where(p => p.PropertyAttribute.SearchField))
                    {
                        userObjectMd.FindColumns.ColumnAlias       = "U_" + (String.IsNullOrEmpty(p.PropertyAttribute.Name) ? p.Property.Name : p.PropertyAttribute.Name);
                        userObjectMd.FindColumns.ColumnDescription = p.PropertyAttribute.Description;
                        userObjectMd.FindColumns.Add();
                    }
                }

                if (menuFather > 0)
                {
                    userObjectMd.MenuItem     = BoYesNoEnum.tYES;
                    userObjectMd.FatherMenuID = menuFather;
                    userObjectMd.MenuUID      = menuUid ?? objectName;
                    userObjectMd.MenuCaption  = menuCaption ?? objectDescription;
                }

                if (userObjectMd.Add() != 0)
                {
                    throw new Exception(SboAddon.Instance.Company.GetLastErrorDescription());
                }

                Logger.Info("Object '{0}' was added successfully", userObjectMd.Name);
            }
        }
Exemple #25
0
        public static void AddUserField(string tableName, string name, string description, BoFieldTypes type = BoFieldTypes.db_Alpha, BoFldSubTypes subType = BoFldSubTypes.st_None, int?editSize = null,
                                        Dictionary <string, string> validValues = null, string defaultValue = null, string linkedUdo = null, bool?mandatory = false)
        {
            if (UserFieldExists(tableName, name))
            {
                throw new Exception(string.Format("Userfield {0} already exists in table {1}", name, tableName));
            }

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var userFieldsMd = factory.Create <UserFieldsMD>(BoObjectTypes.oUserFields);

                userFieldsMd.TableName   = tableName;
                userFieldsMd.Name        = name;
                userFieldsMd.Description = description;
                userFieldsMd.Type        = type;
                userFieldsMd.SubType     = subType;
                if (!editSize.HasValue)
                {
                    switch (type)
                    {
                    case BoFieldTypes.db_Alpha:
                        editSize = 254;
                        break;

                    case BoFieldTypes.db_Memo:
                        break;

                    case BoFieldTypes.db_Numeric:
                        break;

                    case BoFieldTypes.db_Date:
                        break;

                    case BoFieldTypes.db_Float:
                        break;

                    default:
                        throw new ArgumentOutOfRangeException(nameof(type), type, null);
                    }
                }

                if (!type.Equals(BoFieldTypes.db_Date) && editSize.HasValue)
                {
                    userFieldsMd.EditSize = editSize.Value;
                }
                if (validValues != null)
                {
                    int insertedValues = 0;
                    foreach (string key in validValues.Keys)
                    {
                        userFieldsMd.ValidValues.Value       = key;
                        userFieldsMd.ValidValues.Description = validValues[key];

                        if (insertedValues < validValues.Count - 1)
                        {
                            userFieldsMd.ValidValues.Add();
                        }

                        insertedValues++;
                    }
                }
                if (defaultValue != null)
                {
                    userFieldsMd.DefaultValue = defaultValue;
                }

                if (linkedUdo != null)
                {
                    userFieldsMd.LinkedUDO = linkedUdo;
                }

                userFieldsMd.Mandatory = mandatory.GetValueOrDefault(false) ? BoYesNoEnum.tYES : BoYesNoEnum.tNO;

                Logger.Debug("Adding field {0} to table {1}", name, tableName);
                if (userFieldsMd.Add() != 0)
                {
                    throw new Exception(SboAddon.Instance.Company.GetLastErrorDescription());
                }

                Logger.Info("Added field {0} to table {1}", name, tableName);
            }
        }
Exemple #26
0
        public static void RenameUserTable(String oldName, String newName, String description = null)
        {
            if (oldName.StartsWith("@"))
            {
                oldName = oldName.Substring(1);
            }
            if (newName.StartsWith("@"))
            {
                newName = newName.Substring(1);
            }
            if (!UserTableExists(oldName))
            {
                throw new Exception(String.Format("Cannot rename table {0} to {1}, table {0} doesn't exist", oldName, newName));
            }
            if (UserTableExists(newName))
            {
                throw new Exception(String.Format("Cannot rename table {0} to {1}, table {1} already exists", oldName, newName));
            }

            var newFields = new List <dynamic>();

            using (var factory = new SboDisposableBusinessObjectFactory())
            {
                var userTableOld = factory.Create <UserTablesMD>(BoObjectTypes.oUserTables);
                userTableOld.GetByKey(oldName);

                AddUserTable(newName, description ?? userTableOld.TableDescription, userTableOld.TableType);

                var userField = factory.Create <UserFieldsMD>(BoObjectTypes.oUserFields);
                var recordSet = factory.Create <Recordset>(BoObjectTypes.BoRecordset);
                recordSet.DoQuery(string.Format(@"SELECT * FROM CUFD WHERE (""TableID"" = '{0}' OR ""TableID"" = '@{0}')",
                                                oldName));

                while (!recordSet.EoF)
                {
                    userField.GetByKey((string)recordSet.Fields.Item("TableID").Value, (int)recordSet.Fields.Item("FieldID").Value);
                    newFields.Add(
                        new
                    {
                        TableName    = newName,
                        Name         = userField.Name,
                        Description  = userField.Description,
                        Type         = userField.Type,
                        SubType      = userField.SubType,
                        EditSize     = userField.EditSize,
                        ValidValues  = userField.ValidValues.ToDictionary(),
                        DefaultValue = userField.DefaultValue
                    });

                    recordSet.MoveNext();
                }
            }

            foreach (var f in newFields)
            {
                AddUserField(f.TableName, f.Name, f.Description, f.Type, f.SubType, f.EditSize, f.ValidValues, f.DefaultValue);
            }

            SboDiUtils.QueryValue <int>(string.Format(@"INSERT INTO ""@{0}"" SELECT * FROM ""@{1}""", newName, oldName));

            RemoveUserTable(oldName);

            Logger.Info("Renamed user table {0} to {1}", oldName, newName);
        }