public string UpdateChanges(EntityRecord entityRecord, IDictionary<string, object> existingRecord) { var updateProperties = entityRecord.Values .WhereIsNotSkipped() .Where(x => x.Raw is ValueBehavior == false) .Where(value => value.Property.IsKey == false) .ToList(); if (updateProperties.Any() == false) return "No changes"; var changeBuilder = new StringBuilder(); foreach (var propertyValue in updateProperties) { var columnName = propertyValue.Property.Column.Undecorate(); if (existingRecord.ContainsKey(columnName)) { var oldValue = existingRecord[columnName]; changeBuilder.AppendFormat( "{0} ({1} => {2})", propertyValue.Property.Name, oldValue.ToStringSafe(), propertyValue.AsString); changeBuilder.AppendLine(); } } return changeBuilder.ToString(); }
public bool Validate(EntityRecord entityRecord) { var instance = entityRecord.CreateInstance(); var context = new ValidationContext(instance); var isValid = true; foreach (var propertyValue in entityRecord.Values.WhereIsNotSkipped()) { if (propertyValue.Property.TypeInfo.IsFile) { var result = _fileValidator.Validate(propertyValue); if (result == false) isValid = false; } context.DisplayName = propertyValue.Property.Display; foreach (var validator in propertyValue.Property.Validators) { try { validator.Validate(propertyValue.Raw, context); } catch (ValidationException ex) { isValid = false; _notificator.AddModelError(propertyValue.Property.Name, ex.Message); } catch (Exception ex) { _log.Error(ex); } } } return isValid; }
private DbCommand CreateCommand(EntityRecord entityRecord) { var cmd = CreateBaseCommand(entityRecord); AddForeignsUpdate(cmd, entityRecord); AddManyToManyForeignsUpdate(cmd, entityRecord); return cmd; }
private DbCommand CreateCommand(EntityRecord entityRecord) { var cmd = CreateBaseCommand(entityRecord); if (entityRecord.Key.Count() == 1) AddForeignsUpdate(cmd, entityRecord); return cmd; }
public bool UpdateUserLastLoginTime(Guid userId) { RecordManager recMan = new RecordManager(service); var record = new EntityRecord(); record["id"] = userId; record["last_logged_in"] = DateTime.UtcNow; var response = recMan.UpdateRecord("user", record); return response.Success; }
private static IEnumerable<PropertyValue> GetPropertiesValuesToFill( EntityRecord entityRecord) { return entityRecord.Values .Where(value => value.Raw != null && (value.Raw is ValueBehavior) == false && !value.Property.IsForeignKey || (value.Property.IsForeignKey && value.Property.TypeInfo.IsSystemType)); }
private DbCommand CreateCommand( EntityRecord entityRecord, IDictionary<string, PropertyDeleteOption> options) { var cmd = CreateBaseCommand(entityRecord); if (entityRecord.Entity.SoftDeleteEnabled == false) AddForeignsSql(cmd, entityRecord, options); return cmd; }
public string DeleteChanges(EntityRecord entityRecord, IDictionary<string, object> existingRecord) { var display = entityRecord.ToString(); var joinedKeyValue = "#" + entityRecord.JoinedKeysValues; if (display != joinedKeyValue) { display += " ({0})".Fill(joinedKeyValue); } return "Deleted " + display; }
public string CreateChanges(EntityRecord entityRecord) { var display = entityRecord.ToString(); var joinedKeyValue = "#" + entityRecord.JoinedKeysValues; if (display != joinedKeyValue) { display += " ({0})".Fill(joinedKeyValue); } return "Created " + display; }
private DbCommand CreateCommand( EntityRecord entityRecord, object concurrencyCheckValue = null) { var cmd = CreateBaseCommand(entityRecord); AddConcurrencyCheck(cmd, entityRecord, concurrencyCheckValue); AddForeignsUpdate(cmd, entityRecord); AddManyToManyForeignsUpdate(cmd, entityRecord); return cmd; }
public static EntityRecord ConvertToEntityRecord(object inputRecord) { EntityRecord record = new EntityRecord(); foreach (var prop in inputRecord.GetType().GetProperties()) { record[prop.Name] = prop.GetValue(inputRecord); } return record; }
public IActionResult CreateEntityRecord(string entityName, [FromBody]EntityRecord postObj) { if (postObj == null) postObj = new EntityRecord(); if (!postObj.GetProperties().Any(x => x.Key == "id")) postObj["id"] = Guid.NewGuid(); else if (string.IsNullOrEmpty(postObj["id"] as string)) postObj["id"] = Guid.NewGuid(); QueryResponse result = recMan.CreateRecord(entityName, postObj); return DoResponse(result); }
public IEnumerable<BaseFilter> BuildFilters(EntityRecord entityRecord) { var filters = GetAllFilters(); foreach (var propertyValue in entityRecord.Values) { var filterType = GetMatchingFilter(propertyValue.Property, filters); if (filterType == null) continue; yield return CreateInstance(filterType, propertyValue); } }
private static void FillPropertiesValues(object instance, EntityRecord entityRecord) { foreach (var propertyValue in GetPropertiesValuesToFill(entityRecord)) { var value = propertyValue.AsObject; if (IsFile(propertyValue)) { value = (value as HttpPostedFileWrapper).FileName; } var propertyInfo = entityRecord.Entity.Type .GetProperty(propertyValue.Property.Name); propertyInfo.SetValue(instance, value); } }
public static List<EntityRecord> AsRecordList(this DataTable table) { List<EntityRecord> result = new List<EntityRecord>(); foreach (DataRow row in table.Rows) { EntityRecord record = new EntityRecord(); foreach (DataColumn column in table.Columns) { record[column.ColumnName] = row[column.ColumnName]; } result.Add(record); } return result; }
private DbCommand CreateBaseCommand(EntityRecord entityRecord) { var cmd = DB.CreateCommand(_admin.ConnectionStringName); var whereParts = new List<string>(); var counter = 0; foreach (var key in entityRecord.Keys) { key.SqlParameterName = (counter++).ToString(); whereParts.Add("{0} = @{1}".Fill(key.Property.Column, key.SqlParameterName)); cmd.AddParam(key.Raw); } var constraintsSeparator = Environment.NewLine + " AND "; var constraints = string.Join(constraintsSeparator, whereParts); cmd.AddParam(entityRecord.JoinedKeysValues); var joinedKeySqlParamName = (counter++).ToString(); var table = entityRecord.Entity.Table; if (entityRecord.Entity.SoftDeleteEnabled) { var setsList = new List<string>(); foreach (var property in entityRecord.Entity.Properties. Where(x => x.OnDeleteDefaultValue != null)) { AddParam(cmd, property); var column = property.Column; var parameterName = (counter++).ToString(); setsList.Add($"{column} = @{parameterName}"); } var setSeparator = "," + Environment.NewLine + " "; var sets = string.Join(setSeparator, setsList); cmd.CommandText = $@"UPDATE {table} SET {sets} WHERE {constraints}; SELECT @{joinedKeySqlParamName};"; } else { cmd.CommandText = $@"DELETE {table} WHERE {constraints}; SELECT @{joinedKeySqlParamName};"; } return cmd; }
protected virtual DbCommand CreateBaseCommand(EntityRecord entityRecord) { var cmd = DB.CreateCommand(_admin.ConnectionStringName); var counter = 0; var updateProperties = entityRecord.Values .WhereIsNotSkipped() .WhereIsNotOneToMany() .Where(value => value.Property.IsKey == false) .ToList(); if (updateProperties.Any()) { var setsList = new List<string>(); foreach (var propertyValue in updateProperties) { AddParam(cmd, propertyValue); var column = propertyValue.Property.Column; var parameterName = (counter++).ToString(); setsList.Add($"{column} = @{parameterName}"); } cmd.AddParams(entityRecord.Key.Select(value => value.Raw).ToArray()); var setsSeparator = "," + Environment.NewLine + " "; var sets = string.Join(setsSeparator, setsList); var whereParts = new List<string>(); foreach (var key in entityRecord.Key) { var column = key.Property.Column; var parameterName = (counter++).ToString(); whereParts.Add($"{key.Property.Column} = @{parameterName}"); } var constraintSeparator = Environment.NewLine + " AND "; var constraints = string.Join(constraintSeparator, whereParts); var table = entityRecord.Entity.Table; cmd.CommandText = $@"-- update record UPDATE {table} SET {sets} WHERE {constraints}; "; } cmd.AddParam(entityRecord.JoinedKeyValue); var joinedKeyValueParameterName = counter.ToString(); cmd.CommandText += $@"-- return record id SELECT @{joinedKeyValueParameterName}; -- update foreign entities records"; return cmd; }
public object ExecuteWithChanges( DbCommand cmd, EntityRecord entityRecord, EntityChangeType changeType, Func<string> changeDescriber = null) { _log.DebugFormat("Executing command: \r\n {0}", cmd.CommandText); object result; using (var conn = DB.OpenConnection(_admin.ConnectionStringName)) using (var tx = conn.BeginTransaction()) { try { cmd.Connection = conn; cmd.Transaction = tx; result = cmd.ExecuteScalar(); if (result != null) { if (_admin.IsChangesEnabled) { var changeCmd = CreateChangeCommand(entityRecord, changeType, result.ToString(), changeDescriber); _log.DebugFormat("Executing change command: \r\n {0}", changeCmd.CommandText); changeCmd.Connection = conn; changeCmd.Transaction = tx; changeCmd.ExecuteNonQuery(); } _log.Debug("Commit transaction"); tx.Commit(); } else { Rollback(tx); } } catch (Exception ex) { _log.Error(ex); Rollback(tx); throw; } } return result; }
public void SkipNotChangedProperties( EntityRecord entityRecord, IDictionary<string, object> existingRecord) { foreach (var property in entityRecord.Values .WhereIsNotSkipped() .Where(value => value.Property.IsKey == false)) { if (existingRecord.ContainsKey(property.Property.Column.Undecorate())) { var oldValue = existingRecord[property.Property.Column.Undecorate()]; var equals = Equals(property.Raw, oldValue); if (equals) property.DataBehavior = DataBehavior.Skip; } } }
public EntityRecord GetEntityRecord(Entity entity, params string[] key) { var keys = new object[key.Length]; for (int i = 0; i < key.Length; i++) { keys[i] = new PropertyValue(entity.Key[i]).ToObject(key[i]); } var item = GetRecord(entity, keys); if (item == null) { _notificator.Error(IlaroAdminResources.EntityNotExist); return null; } var entityRecord = new EntityRecord(entity); entityRecord.Fill(item); return entityRecord; }
public RecordHierarchy GetRecordHierarchy( EntityRecord entityRecord, IList<PropertyDeleteOption> deleteOptions = null) { _log.InfoFormat( "Getting record hierarchy for entity record ({0}#{1})", entityRecord.Entity.Name, entityRecord.JoinedKeyWithValue); var hierarchy = GetEntityHierarchy(entityRecord.Entity, deleteOptions); var sql = GenerateHierarchySql(hierarchy); _log.Debug($"Sql hierarchy: \r\n {sql}"); var model = new DynamicModel(_admin.ConnectionStringName); var records = model.Query(sql, entityRecord.Key.Select(x => x.Raw).ToArray()).ToList(); var recordHierarchy = GetHierarchyRecords(records, hierarchy); return recordHierarchy; }
public string Create(EntityRecord entityRecord, Func<string> changeDescriber = null) { try { var cmd = CreateCommand(entityRecord); var result = _executor.ExecuteWithChanges( cmd, entityRecord, EntityChangeType.Insert, changeDescriber); return result.ToStringSafe(); } catch (Exception ex) { _log.Error(ex); throw; } }
private DbCommand CreateBaseCommand(EntityRecord entityRecord) { var sbColumns = new StringBuilder(); var sbValues = new StringBuilder(); var cmd = DB.CreateCommand(_admin.ConnectionStringName); var counter = 0; foreach (var propertyValue in entityRecord.Values .WhereIsNotSkipped() .WhereIsNotOneToMany() .DistinctBy(x => x.Property.Column) .Where(x => x.Property.IsAutoKey == false)) { sbColumns.AppendFormat("{0},", propertyValue.Property.Column); sbValues.AppendFormat("@{0},", counter); AddParam(cmd, propertyValue); counter++; } var columns = sbColumns.ToString().Substring(0, sbColumns.Length - 1); var values = sbValues.ToString().Substring(0, sbValues.Length - 1); var idType = "int"; var insertedId = "SCOPE_IDENTITY()"; if (entityRecord.Keys.Count > 1 || entityRecord.Keys.FirstOrDefault().Property.TypeInfo.IsString) { idType = "nvarchar(max)"; insertedId = "@" + counter; cmd.AddParam(entityRecord.JoinedKeysValues); } var table = entityRecord.Entity.Table; cmd.CommandText = $@"-- insert record INSERT INTO {table} ({columns}) VALUES ({values}); -- return record id DECLARE @newID {idType} = {insertedId}; SELECT @newID; -- update foreign entities records"; return cmd; }
private DbCommand CreateChangeCommand( EntityRecord entityRecord, EntityChangeType changeType, string keyValue, Func<string> changeDescriber = null) { if(changeType == EntityChangeType.Insert) { entityRecord.SetKeyValue(keyValue); } var cmd = DB.CreateCommand(_admin.ConnectionStringName); var changeEntity = _admin.ChangeEntity; var table = changeEntity.Table; var entityNameColumn = changeEntity["EntityName"].Column; var entityKeyColumn = changeEntity["EntityKey"].Column; var changeTypeColumn = changeEntity["ChangeType"].Column; var recordDisplayColumn = changeEntity["RecordDisplayName"].Column; var descriptionColumn = changeEntity["Description"].Column; var changedOnColumn = changeEntity["ChangedOn"].Column; var changedByColumn = changeEntity["ChangedBy"].Column; var sql = $@"INSERT INTO {table} ({entityNameColumn}, {entityKeyColumn}, {changeTypeColumn}, {recordDisplayColumn}, {descriptionColumn}, {changedOnColumn}, {changedByColumn}) VALUES (@0,@1,@2,@3,@4,@5,@6);"; cmd.AddParam(entityRecord.Entity.Name); cmd.AddParam(keyValue); cmd.AddParam(changeType); cmd.AddParam(entityRecord.ToString()); cmd.AddParam(changeDescriber == null ? null : changeDescriber()); cmd.AddParam(DateTime.UtcNow); cmd.AddParam(_user.CurrentUserName()); cmd.CommandText = sql; return cmd; }
public bool Delete( EntityRecord entityRecord, IDictionary<string, PropertyDeleteOption> options, Func<string> changeDescriber = null) { try { var cmd = CreateCommand(entityRecord, options); var result = _executor.ExecuteWithChanges( cmd, entityRecord, EntityChangeType.Delete, changeDescriber); return result != null; } catch (Exception ex) { _log.Error(ex); throw; } }
protected virtual void VerifyModifiedValues(EntityRecord record) { var rights = record.UserPermissions; if (rights == null) { return; } var members = record.EntityInfo.Members; for (int i = 0; i < members.Count; i++) { var member = members[i]; if (member.Kind != MemberKind.Column) { continue; } if (record.Modified(member) && !rights.UpdateStrict.Allowed(member)) { //value was modified but update is not allowed for this member AccessDenied(AccessType.UpdateStrict, record, member); } } }
private EntityRecord ConvertJObjectToEntityRecord(JObject jObj, List <EqlFieldMeta> fieldMeta) { EntityRecord record = new EntityRecord(); foreach (EqlFieldMeta meta in fieldMeta) { if (meta.Field != null) { record[meta.Field.Name] = DbRecordRepository.ExtractFieldValue(jObj[meta.Field.Name], meta.Field); } else if (meta.Relation != null) { List <EntityRecord> relRecords = new List <EntityRecord>(); JArray relatedJsonRecords = jObj[meta.Name].Value <JArray>(); foreach (JObject relatedObj in relatedJsonRecords) { relRecords.Add(ConvertJObjectToEntityRecord(relatedObj, meta.Children)); } record[meta.Name] = relRecords; } } return(record); }
// identity/output parameters handling =========================================================================== // called only non-batch mode public bool CheckReferencesNewIdentity(EntityRecord rec, SqlColumnValuePlaceHolder cph, out string idParamName) { idParamName = null; if (!ReferencesNewIdentity(rec, cph.Column, out EntityRecord targetRec)) { return(false); } var targetCmdData = targetRec.DbCommandData; Util.Check(targetCmdData != null, "Fatal error: the target record of FK column {0} does not have {1} field set. " + "Fault in record sequencing.", cph.Column.ColumnName, nameof(EntityRecord.DbCommandData)); var idPrmInfo = targetCmdData.OutputParameters.First(op => op.Column.Flags.IsSet(DbColumnFlags.Identity)); Util.Check(idPrmInfo != null, "Fatal error: the identity parameter is not found in referenced target record. " + "Fault in record sequencing."); // Batch mode: check if identity parameter belongs to the same data command - the case for very large batches that contaim multiple // DbCommands (each containing mltiple update SQLs). It may happen that parameter returning identity is in different (prior) // DbCommand. Note: parameters cannot be reused accross DB commands if (targetRec.DbCommandData.DbCommand == this._dbCommand) { // use the same parameter idParamName = idPrmInfo.Parameter.ParameterName; return(true); } // different batch command. Create new parameter and copy action var newPrm = AddParameter(cph, 0, rec); idParamName = newPrm.ParameterName; _paramCopyList = _paramCopyList ?? new List <BatchParamCopy>(); _paramCopyList.Add(new BatchParamCopy() { From = idPrmInfo.Parameter, To = newPrm }); return(true); }
public string FormatColumnValuePlaceHolder(SqlColumnValuePlaceHolder cph, EntityRecord rec) { object memberValue = null; object colValue = null; // If it is output, it must be parameters if (cph.ParamDirection != ParameterDirection.Input) { if (cph.ParamDirection == ParameterDirection.InputOutput) //do we need initial value { memberValue = rec.GetValueDirect(cph.Column.Member); } else { memberValue = cph.Column.Member.DefaultValue; //this is important to setup prm.DbType for output parameter } colValue = cph.Column.Converter.PropertyToColumn(memberValue); return(AddParameter(cph, colValue, rec).ParameterName); } // special case: column references new identity value for record inserted in the same transaction if (_batchMode && CheckReferencesNewIdentity(rec, cph, out string prmName)) { return(prmName); } // get value and check if we can use literal memberValue = rec.GetValueDirect(cph.Column.Member); colValue = cph.Column.Converter.PropertyToColumn(memberValue); if (ShouldUseLiteral(memberValue, cph.Column)) { return(FormatAsLiteral(cph, colValue)); } else { return(AddParameter(cph, colValue, rec).ParameterName); } }
public override object RecordGetMemberValue(EntityRecord record, EntityMemberInfo member) { if (record.Status == EntityStatus.Loading || ReadUnrestricted || !record.AccessCheckEnabled) { return(base.RecordGetMemberValue(record, member)); } //Not elevated if (!CheckRecordAccess(record, _demandReadAccessType)) { return(member.DeniedValue); } var rights = record.UserPermissions; var allowed = _demandReadAccessLevel == ReadAccessLevel.Peek ? rights.Peek.Allowed(member) : rights.Peek.Allowed(member); if (allowed) { return(base.RecordGetMemberValue(record, member)); } //Access denied AccessDenied(_demandReadAccessType, record, member); // if AccessDenied did not throw, return default value return(member.DeniedValue); }
}//method //Copies PK values into corresponding FK public static void CopyPrimaryKeyToForeign(EntityRecord record, EntityMemberInfo entityRefMember, EntityRecord refTarget) { var refInfo = entityRefMember.ReferenceInfo; var fkMembers = refInfo.FromKey.ExpandedKeyMembers; //If target is null, set all to DbNull if (refTarget == null) { for (int i = 0; i < fkMembers.Count; i++) { record.SetValueDirect(fkMembers[i].Member, DBNull.Value); } return; } //refTarget is not null var pkMembers = refInfo.ToKey.ExpandedKeyMembers; for (int i = 0; i < pkMembers.Count; i++) { //copy value from PK to FK member var value = refTarget.GetValueDirect(pkMembers[i].Member); record.SetValueDirect(fkMembers[i].Member, value); } }//method
public bool Update( EntityRecord entityRecord, object concurrencyCheckValue = null, Func<string> changeDescriber = null) { try { var cmd = CreateCommand(entityRecord, concurrencyCheckValue); var previewSql = cmd.PreviewCommandText(); _log.Debug(previewSql); var result = _executor.ExecuteWithChanges( cmd, entityRecord, EntityChangeType.Update, changeDescriber); if (result == null) return false; if (result.Is(Const.ConcurrencyCheckError_ReturnValue)) throw new ConcurrencyCheckException(IlaroAdminResources.ConcurrencyCheckError); return true; } catch (ConcurrencyCheckException ex) { _log.Warn(ex); throw; } catch (Exception ex) { _log.Error(ex); throw; } }
public void SetSidebarSize(Guid userId, string size) { var currentUser = new SecurityManager().GetUser(userId); if (currentUser == null) { throw new Exception("Unknown user"); } var currentPref = currentUser.Preferences; currentPref.SidebarSize = size; var updateRecord = new EntityRecord(); updateRecord["id"] = currentUser.Id; updateRecord["preferences"] = JsonConvert.SerializeObject(currentPref); var updateResponse = new RecordManager().UpdateRecord("user", updateRecord); if (!updateResponse.Success) { throw new Exception(updateResponse.Message); } }
private static Email EntityRecordToEmailConvert(EntityRecord rec) { if (rec == null) { return(null); } Email model = new Email(); model.Id = (Guid)rec["id"]; model.ServiceId = (Guid)rec["service_id"]; model.Sender = JsonConvert.DeserializeObject <EmailAddress>((string)rec["sender"]); model.Recipients = JsonConvert.DeserializeObject <List <EmailAddress> >((string)rec["recipients"]); model.ReplyToEmail = (string)rec["reply_to_email"]; model.Subject = (string)rec["subject"]; model.ContentText = (string)rec["content_text"]; model.ContentHtml = (string)rec["content_html"]; model.CreatedOn = (DateTime)rec["created_on"]; model.SentOn = (DateTime?)rec["sent_on"]; model.Status = (EmailStatus)(int.Parse((string)rec["status"])); model.Priority = (EmailPriority)(int.Parse((string)rec["priority"])); model.ServerError = (string)rec["server_error"]; model.ScheduledOn = (DateTime?)rec["scheduled_on"]; model.RetriesCount = (int)((decimal)rec["retries_count"]); model.XSearch = (string)rec["x_search"]; if (!string.IsNullOrWhiteSpace((string)rec["attachments"])) { model.Attachments = JsonConvert.DeserializeObject <List <string> >((string)rec["attachments"]); } else { model.Attachments = new List <string>(); } return(model); }
private void CreateContact( IEnumerable <ContactRecord> contacts, EntityRecord entity, ContactType type, string title, string value) { if (!contacts.Any(cont => cont.Type == (int)type && cont.Title == title && cont.Contact == value)) { var contact = new ContactRecord { EntityRecord = entity, Type = (byte)type, Title = title.TrimIt(), Contact = value.TrimIt() }; _contactRepository.Create(contact); _contactRepository.Flush(); _log.Add(string.Format("{0} contact created", contact.Contact)); } }
public EntityRecord GetComponentData(Guid userId, string componentFullName) { var currentUser = new SecurityManager().GetUser(userId); if (currentUser == null) { throw new Exception("Unknown user"); } var currentPref = currentUser.Preferences; var componentFullNameLowerCase = componentFullName.ToLowerInvariant(); var componentDataDictionary = currentPref.ComponentDataDictionary; if (!componentDataDictionary.Properties.ContainsKey(componentFullNameLowerCase)) { return(null); } EntityRecord record = ((JObject)componentDataDictionary[componentFullNameLowerCase]).ToObject <EntityRecord>(); return(record); }
private static EntityRecord ErpPageToEntityRecordConvert(ErpPage data) { if (data == null) { return(null); } EntityRecord model = new EntityRecord(); model["id"] = data.Id; model["name"] = data.Name; model["label"] = data.Label; model["system"] = data.System; model["type"] = data.Type; model["icon_class"] = data.IconClass; model["weight"] = data.Weight; model["app_id"] = data.AppId; model["entity_id"] = data.EntityId; model["node_id"] = data.NodeId; model["area_id"] = data.AreaId; model["is_razor_body"] = data.IsRazorBody; model["layout"] = data.Layout; return(model); }
private static IReference[] GetEntityReferences(EntityRecord record, IEnumerable <string> storages) { var result = new[] { new Reference { Id = record.Id, Storage = StorageKeys.SmartWalk } }.Union( storages != null ? record.EntityMappingRecords .Where(emr => storages.ContainsIgnoreCase(emr.StorageRecord.StorageKey)) .Select(emr => new Reference { Id = emr.ExternalEntityId, Storage = emr.StorageRecord.StorageKey, Type = emr.Type }) : Enumerable.Empty <IReference>()) .ToArray(); return(result); }
//this overload saves us some cycles when we know already entity type access and there's no record-level access private bool CheckRecordAccess(EntityRecord record, AccessType accessType, UserEntityTypePermission typePermissions) { if (this.ReadUnrestricted) { return(true); } if (Context.User.Kind == UserKind.System) { record.UserPermissions = UserRecordPermission.AllowAll; return(true); } if (typePermissions.HasFilter) { return(CheckRecordAccess(record, accessType)); } //Otherwise, assume record rights are the same as type access record.UserPermissions = typePermissions; if (typePermissions.AccessTypes.IsSet(accessType)) { return(true); } AccessDenied(accessType, record); return(false); }
private void SetRecordServiceInformation(EntityRecord record, bool newRecord = true) { if (record == null) { return; } if (newRecord) { record["created_on"] = DateTime.UtcNow; record["last_modified_on"] = DateTime.UtcNow; if (SecurityContext.CurrentUser != null) { record["created_by"] = SecurityContext.CurrentUser.Id; record["last_modified_by"] = SecurityContext.CurrentUser.Id; } else { record["created_by"] = null; record["last_modified_by"] = null; } } else { record["last_modified_on"] = DateTime.UtcNow; if (SecurityContext.CurrentUser != null) { record["last_modified_by"] = SecurityContext.CurrentUser.Id; } else { record["last_modified_by"] = null; } } }
public ActionResult DeleteTimelog([FromBody] EntityRecord record) { var response = new ResponseModel(); #region << Init >> Guid recordId = Guid.Empty; if (!record.Properties.ContainsKey("id") || record["id"] == null) { throw new Exception("id is required"); } if (Guid.TryParse((string)record["id"], out Guid outGuid)) { recordId = outGuid; } else { throw new Exception("id is invalid Guid"); } #endregion try { new TimeLogService().Delete(recordId); } catch (Exception) { throw; } response.Success = true; response.Message = "Comment successfully deleted"; return(Json(response)); }
private static EntityRecord SmtpServiceToEntityRecordConvert(SmtpService model) { if (model == null) { return(null); } EntityRecord rec = new EntityRecord(); rec["id"] = model.Id; rec["name"] = model.Name; rec["server"] = model.Server; rec["port"] = model.Port; rec["username"] = model.Username; rec["password"] = model.Password; rec["default_from_email"] = model.DefaultFromEmail; rec["default_from_name"] = model.DefaultFromName; rec["default_reply_to_email"] = model.DefaultReplyToEmail; rec["max_retries_count"] = (decimal)((int)model.MaxRetriesCount); rec["retry_wait_minutes"] = (decimal)((int)model.RetryWaitMinutes); rec["is_default"] = model.IsDefault; rec["connection_security"] = ((int)model.ConnectionSecurity).ToString(); return(rec); }
public string Create( Entity entity, FormCollection collection, HttpFileCollectionBase files) { var entityRecord = new EntityRecord(entity); entityRecord.Fill(collection, files, x => x.OnCreateDefaultValue); if (_validator.Validate(entityRecord) == false) { _notificator.Error(IlaroAdminResources.RecordNotValid); return null; } var existingRecord = _source.GetRecord( entity, entityRecord.Key.Select(value => value.AsObject).ToArray()); if (existingRecord != null) { _notificator.Error(IlaroAdminResources.EntityAlreadyExist); return null; } var propertiesWithUploadedFiles = _filesHandler.Upload( entityRecord, x => x.OnCreateDefaultValue); var id = _creator.Create( entityRecord, () => _changeDescriber.CreateChanges(entityRecord)); if (id.IsNullOrWhiteSpace() == false) _filesHandler.ProcessUploaded(propertiesWithUploadedFiles); else _filesHandler.DeleteUploaded(propertiesWithUploadedFiles); return id; }
private static SmtpService EntityRecordToSmtpServiceConvert(EntityRecord rec) { if (rec == null) { return(null); } SmtpService model = new SmtpService(); model.Id = (Guid)rec["id"]; model.Name = (string)rec["name"]; model.Server = (string)rec["server"]; model.Port = (int)((decimal)rec["port"]); model.Username = (string)rec["username"]; model.Password = (string)rec["password"]; model.DefaultFromEmail = (string)rec["default_from_email"]; model.DefaultFromName = (string)rec["default_from_name"]; model.DefaultReplyToEmail = (string)rec["default_reply_to_email"]; model.MaxRetriesCount = (int)((decimal)rec["max_retries_count"]); model.RetryWaitMinutes = (int)((decimal)rec["retry_wait_minutes"]); model.IsDefault = (bool)rec["is_default"]; model.ConnectionSecurity = (SecureSocketOptions)(int.Parse((string)rec["connection_security"])); return(model); }
public IActionResult OnGet(BaseErpPageModel pageModel) { var page = (ErpPage)pageModel.DataModel.GetProperty("Page"); if (page != null && page.Id == CREATE_TASK_PAGE_ID) { EntityRecord record = (EntityRecord)pageModel.DataModel.GetProperty("Record"); #region << Init fields >> if (record == null) { record = new EntityRecord(); } //Preselect owner ErpUser currentUser = (ErpUser)pageModel.DataModel.GetProperty("CurrentUser"); if (currentUser != null) { record["owner_id"] = currentUser.Id; } //Preselect project if (pageModel.HttpContext.Request.Query.ContainsKey("projectId")) { var projectQueryId = pageModel.HttpContext.Request.Query["projectId"].ToString(); if (Guid.TryParse(projectQueryId, out Guid outGuid)) { record["project_id"] = outGuid; } } #endregion pageModel.DataModel.SetRecord(record); } return(null); }
public void PostCreateApiHookLogic(string entityName, EntityRecord record) { //Update key and search fields Guid projectId = Guid.Empty; Guid? projectOwnerId = null; string taskSubject = ""; var patchRecord = new TaskService().SetCalculationFields((Guid)record["id"], subject: out taskSubject, projectId: out projectId, projectOwnerId: out projectOwnerId); var updateResponse = new RecordManager(executeHooks: false).UpdateRecord("task", patchRecord); if (!updateResponse.Success) { throw new Exception(updateResponse.Message); } //Set the initial watchers list - project lead, creator, owner var watchers = new List <Guid>(); { var fieldName = "owner_id"; if (record.Properties.ContainsKey(fieldName) && record[fieldName] != null) { var userId = (Guid)record[fieldName]; if (!watchers.Contains(userId)) { watchers.Add(userId); } } } { var fieldName = "created_by"; if (record.Properties.ContainsKey(fieldName) && record[fieldName] != null) { var userId = (Guid)record[fieldName]; if (!watchers.Contains(userId)) { watchers.Add(userId); } } } if (projectOwnerId != null) { if (!watchers.Contains(projectOwnerId.Value)) { watchers.Add(projectOwnerId.Value); } } //Create relations var watchRelation = new EntityRelationManager().Read("user_nn_task_watchers").Object; if (watchRelation == null) { throw new Exception("Watch relation not found"); } foreach (var userId in watchers) { var createRelResponse = new RecordManager().CreateRelationManyToManyRecord(watchRelation.Id, userId, (Guid)record["id"]); if (!createRelResponse.Success) { throw new Exception(createRelResponse.Message); } } //Add activity log var subject = $"created <a href=\"/projects/tasks/tasks/r/{patchRecord["id"]}/details\">[{patchRecord["key"]}] {taskSubject}</a>"; var relatedRecords = new List <string>() { patchRecord["id"].ToString(), projectId.ToString() }; var scope = new List <string>() { "projects" }; //Add watchers as scope foreach (var userId in watchers) { relatedRecords.Add(userId.ToString()); } var taskSnippet = new Web.Services.RenderService().GetSnippetFromHtml((string)record["body"]); new FeedItemService().Create(id: Guid.NewGuid(), createdBy: SecurityContext.CurrentUser.Id, subject: subject, body: taskSnippet, relatedRecords: relatedRecords, scope: scope, type: "task"); }
public void PostPreUpdateApiHookLogic(string entityName, EntityRecord record, List <ErrorModel> errors) { var eqlResult = new EqlCommand("SELECT id,number, $project_nn_task.id, $project_nn_task.abbr, $user_nn_task_watchers.id FROM task WHERE id = @taskId", new EqlParameter("taskId", (Guid)record["id"])).Execute(); if (eqlResult.Count > 0) { var oldRecord = eqlResult[0]; Guid?oldProjectId = null; Guid?newProjectId = null; var taskWatcherIdList = new List <Guid>(); var projectAbbr = ""; if (oldRecord.Properties.ContainsKey("$project_nn_task") && oldRecord["$project_nn_task"] is List <EntityRecord> ) { var projectRecords = (List <EntityRecord>)oldRecord["$project_nn_task"]; if (projectRecords.Any()) { if (projectRecords[0].Properties.ContainsKey("id")) { oldProjectId = (Guid)projectRecords[0]["id"]; } if (projectRecords[0].Properties.ContainsKey("abbr")) { projectAbbr = (string)projectRecords[0]["abbr"]; } } } if (record.Properties.ContainsKey("$project_nn_task.id") && record["$project_nn_task.id"] != null) { if (record["$project_nn_task.id"] is Guid) { newProjectId = (Guid)record["$project_nn_task.id"]; } if (record["$project_nn_task.id"] is string) { newProjectId = new Guid(record["$project_nn_task.id"].ToString()); } } if (oldRecord.Properties.ContainsKey("$user_nn_task_watchers") && oldRecord["$user_nn_task_watchers"] is List <EntityRecord> ) { var watcherRecords = (List <EntityRecord>)oldRecord["$user_nn_task_watchers"]; foreach (var watcherRecord in watcherRecords) { taskWatcherIdList.Add((Guid)watcherRecord["id"]); } } if (oldProjectId != null && newProjectId != null && oldProjectId != newProjectId) { var recMan = new RecordManager(); var relations = new EntityRelationManager().Read().Object; var projectTaskRel = relations.First(x => x.Name == "project_nn_task"); if (projectTaskRel == null) { throw new Exception("project_nn_task relation not found"); } //Remove all NN relation var removeRelResponse = recMan.RemoveRelationManyToManyRecord(projectTaskRel.Id, oldProjectId, (Guid)record["id"]); if (!removeRelResponse.Success) { throw new Exception(removeRelResponse.Message); } //Create new NN relation var addRelResponse = recMan.RemoveRelationManyToManyRecord(projectTaskRel.Id, newProjectId, (Guid)record["id"]); if (!addRelResponse.Success) { throw new Exception(addRelResponse.Message); } //change key record["key"] = projectAbbr + "-" + ((decimal)oldRecord["number"]).ToString("N0"); var projectEqlResult = new EqlCommand("SELECT id,owner_id FROM project WHERE id = @projectId", new EqlParameter("projectId", newProjectId)).Execute(); Guid?projectOwnerId = null; if (projectEqlResult != null && ((List <EntityRecord>)projectEqlResult).Any()) { var newProjectRecord = ((List <EntityRecord>)projectEqlResult).First(); if (newProjectRecord.Properties.ContainsKey("owner_id") && newProjectRecord["owner_id"] != null) { if (newProjectRecord["owner_id"] is Guid) { projectOwnerId = (Guid)newProjectRecord["owner_id"]; } if (newProjectRecord["owner_id"] is string) { projectOwnerId = new Guid(newProjectRecord["owner_id"].ToString()); } } } //check if the new project owner is in the watcher list and add it if not if (projectOwnerId != null && !taskWatcherIdList.Contains(projectOwnerId.Value)) { var watcherTaskRel = relations.First(x => x.Name == "user_nn_task_watchers"); if (watcherTaskRel == null) { throw new Exception("user_nn_task_watchers relation not found"); } //Create new NN relation var addWatcherRelResponse = recMan.RemoveRelationManyToManyRecord(watcherTaskRel.Id, projectOwnerId, (Guid)record["id"]); if (!addWatcherRelResponse.Success) { throw new Exception(addWatcherRelResponse.Message); } } } } }
private static EntityRecord create_filter_record( Entity entity, NameValueCollection request) { var filterRecord = new EntityRecord(entity); if (request != null) filterRecord.Fill(request); return filterRecord; }
/// <summary> /// Calculates the key and x_search contents and updates the task /// </summary> /// <param name="data"></param> public EntityRecord SetCalculationFields(Guid taskId, out string subject, out Guid projectId, out Guid?projectOwnerId) { subject = ""; projectId = Guid.Empty; projectOwnerId = null; EntityRecord patchRecord = new EntityRecord(); var getTaskResponse = new RecordManager().Find(new EntityQuery("task", "*,$task_type_1n_task.label,$task_status_1n_task.label,$project_nn_task.abbr,$project_nn_task.id, $project_nn_task.owner_id", EntityQuery.QueryEQ("id", taskId))); if (!getTaskResponse.Success) { throw new Exception(getTaskResponse.Message); } if (!getTaskResponse.Object.Data.Any()) { throw new Exception("Task with this Id was not found"); } var taskRecord = getTaskResponse.Object.Data.First(); subject = (string)taskRecord["subject"]; var projectAbbr = ""; var status = ""; var type = ""; if (((List <EntityRecord>)taskRecord["$project_nn_task"]).Any()) { var projectRecord = ((List <EntityRecord>)taskRecord["$project_nn_task"]).First(); if (projectRecord != null && projectRecord.Properties.ContainsKey("abbr")) { projectAbbr = (string)projectRecord["abbr"]; } if (projectRecord != null) { projectId = (Guid)projectRecord["id"]; projectOwnerId = (Guid?)projectRecord["owner_id"]; } } if (((List <EntityRecord>)taskRecord["$task_status_1n_task"]).Any()) { var statusRecord = ((List <EntityRecord>)taskRecord["$task_status_1n_task"]).First(); if (statusRecord != null && statusRecord.Properties.ContainsKey("label")) { status = (string)statusRecord["label"]; } } if (((List <EntityRecord>)taskRecord["$task_type_1n_task"]).Any()) { var typeRecord = ((List <EntityRecord>)taskRecord["$task_type_1n_task"]).First(); if (typeRecord != null && typeRecord.Properties.ContainsKey("label")) { type = (string)typeRecord["label"]; } } patchRecord["id"] = taskId; patchRecord["key"] = projectAbbr + "-" + ((decimal)taskRecord["number"]).ToString("N0");; return(patchRecord); }
public IActionResult CreateTask([FromBody] JObject submitObj, Guid?projectId = null) { var response = new ResponseModel(); var task = new EntityRecord(); task["id"] = Guid.NewGuid(); if (projectId != null) { task["project_id"] = projectId; } #region << ConvertObject >> try { foreach (var prop in submitObj.Properties()) { switch (prop.Name.ToLower()) { case "subject": task["subject"] = (string)prop.Value; break; case "description": task["description"] = (string)prop.Value; break; case "$project_1_n_task.id": task["project_id"] = (Guid)prop.Value; break; case "start_date": task["start_date"] = ((DateTime)prop.Value).ToUniversalTime(); break; case "end_date": task["end_date"] = ((DateTime)prop.Value).ToUniversalTime(); break; case "priority": task["priority"] = (string)prop.Value; break; case "status": task["status"] = (string)prop.Value; break; case "owner_id": //will be init in the below break; } } } catch (Exception ex) { response.Success = false; response.Errors = new List <ErrorModel>(); response.Timestamp = DateTime.UtcNow; response.Message = "Validation error : " + ex.Message; response.Object = null; return(Json(response)); } #endregion #region << Validation >> var validationErrors = new List <ErrorModel>(); var validationError = new ErrorModel(); if (!task.Properties.ContainsKey("subject") || string.IsNullOrWhiteSpace((string)task["subject"])) { validationError = new ErrorModel(); validationError.Key = "subject"; validationError.Message = "subject is required"; validationError.Value = ""; validationErrors.Add(validationError); } if (!task.Properties.ContainsKey("project_id") || string.IsNullOrWhiteSpace((string)task["project_id"])) { validationError = new ErrorModel(); validationError.Key = "project_id"; validationError.Message = "project_id is required"; validationError.Value = ""; validationErrors.Add(validationError); } if (!task.Properties.ContainsKey("status") || string.IsNullOrWhiteSpace((string)task["status"])) { validationError = new ErrorModel(); validationError.Key = "status"; validationError.Message = "status is required"; validationError.Value = ""; validationErrors.Add(validationError); } if (!task.Properties.ContainsKey("priority") || string.IsNullOrWhiteSpace((string)task["priority"])) { validationError = new ErrorModel(); validationError.Key = "priority"; validationError.Message = "priority is required"; validationError.Value = ""; validationErrors.Add(validationError); } if (validationErrors.Count > 0) { response.Success = false; response.Timestamp = DateTime.UtcNow; response.Errors = validationErrors; response.Message = "Validation error occurred!"; response.Object = null; return(Json(response)); } #endregion #region << Get project owner and set as ticket owner >> EntityRecord projectObject = null; { var filterObj = EntityQuery.QueryEQ("id", (Guid)task["project_id"]); var query = new EntityQuery("wv_project", "*", filterObj, null, null, null); var result = recMan.Find(query); if (!result.Success) { response.Success = false; response.Timestamp = DateTime.UtcNow; response.Message = "Error getting the project: " + result.Message; response.Object = null; return(Json(response)); } else if (result.Object == null || result.Object.Data == null || !result.Object.Data.Any()) { response.Success = false; response.Timestamp = DateTime.UtcNow; response.Message = "Project not found"; response.Object = null; return(Json(response)); } projectObject = result.Object.Data[0]; task["owner_id"] = (Guid)result.Object.Data[0]["owner_id"]; } #endregion //Create transaction using (var connection = DbContext.Current.CreateConnection()) { try { connection.BeginTransaction(); //Update project tasks counters { var patchObject = new EntityRecord(); patchObject["id"] = (Guid)projectObject["id"]; switch ((string)task["status"]) { case "not started": patchObject["x_tasks_not_started"] = (decimal)projectObject["x_tasks_not_started"] + 1; break; case "in progress": patchObject["x_tasks_in_progress"] = (decimal)projectObject["x_tasks_in_progress"] + 1; break; case "completed": patchObject["x_tasks_completed"] = (decimal)projectObject["x_tasks_completed"] + 1; break; } var updateResponse = recMan.UpdateRecord("wv_project", patchObject); if (!updateResponse.Success) { throw new Exception(updateResponse.Message); } } //Create task { var createResponse = recMan.CreateRecord("wv_task", task); if (!createResponse.Success) { throw new Exception(createResponse.Message); } } connection.CommitTransaction(); } catch (Exception ex) { connection.RollbackTransaction(); response.Success = false; response.Timestamp = DateTime.UtcNow; response.Message = "Error saving the task: " + ex.Message; response.Object = null; return(Json(response)); } } response.Success = true; response.Timestamp = DateTime.UtcNow; response.Message = "My projects successfully read"; response.Object = null; return(Json(response)); }
public void OnPostUpdateRecord(string entityName, EntityRecord record) { new SearchService().RegenSearchField(entityName, record, Configuration.CaseSearchIndexFields); }
public IActionResult ProjectMilestones(string listName = null, string entityName = null, int page = 0) { var response = new ResponseModel(); #region << Can user read projects >> //Get current user ErpUser user = SecurityContext.CurrentUser; //Get entity meta var entity = entityManager.ReadEntity(entityName).Object; //Get list meta var list = entityManager.ReadRecordList(entity.Name, listName).Object; //check if user role has permissions var canRead = user.Roles.Any(x => entity.RecordPermissions.CanRead.Any(z => z == x.Id)); var canCreate = user.Roles.Any(x => entity.RecordPermissions.CanCreate.Any(z => z == x.Id)); var canUpdate = user.Roles.Any(x => entity.RecordPermissions.CanUpdate.Any(z => z == x.Id)); var canDelete = user.Roles.Any(x => entity.RecordPermissions.CanDelete.Any(z => z == x.Id)); if (!canRead) { response.Success = false; response.Message = "You do not have permission to read the projects in this system"; response.Timestamp = DateTime.UtcNow; return(Json(response)); //return empty object } #endregion #region << Get the project id >> var queryString = HttpContext.Request.QueryString.ToString(); var queryKeyValue = QueryHelpers.ParseQuery(queryString); var projectId = new Guid(); if (queryKeyValue.ContainsKey("recordId") && Guid.TryParse(queryKeyValue["recordId"], out projectId)) { } else { response.Success = false; response.Timestamp = DateTime.UtcNow; response.Message = "Project Id either not found or not a GUID"; response.Object = null; } #endregion #region << Get milestone data >> var requestedFields = "id,name,start_date,end_date,x_tasks_not_started,x_tasks_in_progress,x_tasks_completed,x_bugs_opened,x_bugs_reopened,x_bugs_closed"; QueryObject filterObj = EntityQuery.QueryEQ("project_id", projectId); var sortList = new List <QuerySortObject>(); sortList.Add(new QuerySortObject("end_date", QuerySortType.Descending)); EntityQuery resultQuery = new EntityQuery("wv_milestone", requestedFields, filterObj, sortList.ToArray(), null, null, null); QueryResponse result = recMan.Find(resultQuery); if (!result.Success) { response.Success = false; response.Timestamp = DateTime.UtcNow; response.Message = result.Message; response.Object = null; return(Json(response)); } #endregion var resultRecordsList = new List <EntityRecord>(); foreach (var record in result.Object.Data) { var recordObj = new EntityRecord(); recordObj["id"] = record["id"]; recordObj["name"] = record["name"]; recordObj["start_date"] = record["start_date"]; recordObj["end_date"] = record["end_date"]; #region << tasks Count "not started" vs "in progress" vs "completed" >> var tasksNotStarted = (decimal)record["x_tasks_not_started"]; var tasksInProgress = (decimal)record["x_tasks_in_progress"]; var tasksCompleted = (decimal)record["x_tasks_completed"]; recordObj["tasks_not_started_count"] = tasksNotStarted; recordObj["tasks_in_progress_count"] = tasksInProgress; recordObj["tasks_completed_count"] = tasksCompleted; if (tasksNotStarted + tasksInProgress + tasksCompleted > 0) { recordObj["tasks_not_started_percentage"] = Math.Round((decimal)(tasksNotStarted * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted)); recordObj["tasks_in_progress_percentage"] = Math.Round((decimal)(tasksInProgress * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted)); recordObj["tasks_completed_percentage"] = 100 - Math.Round((decimal)(tasksNotStarted * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted)) - Math.Round((decimal)(tasksInProgress * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted)); } else { recordObj["tasks_not_started_percentage"] = 0; recordObj["tasks_in_progress_percentage"] = 0; recordObj["tasks_completed_percentage"] = 0; } #endregion #region << bugs Count "opened" & "reopened" vs "closed" >> var bugsOpened = (decimal)record["x_bugs_opened"]; var bugsReOpened = (decimal)record["x_bugs_reopened"]; var bugsClosed = (decimal)record["x_bugs_closed"]; recordObj["bugs_opened_count"] = bugsOpened; recordObj["bugs_reopened_count"] = bugsReOpened; recordObj["bugs_closed_count"] = bugsClosed; if (bugsOpened + bugsReOpened + bugsClosed > 0) { recordObj["bugs_opened_percentage"] = Math.Round((decimal)(bugsOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed)); recordObj["bugs_reopened_percentage"] = Math.Round((decimal)(bugsReOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed)); recordObj["bugs_closed_percentage"] = 100 - Math.Round((decimal)(bugsOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed)) - Math.Round((decimal)(bugsReOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed)); } else { recordObj["bugs_opened_percentage"] = 0; recordObj["bugs_reopened_percentage"] = 0; recordObj["bugs_closed_percentage"] = 0; } #endregion resultRecordsList.Add(recordObj); } response.Success = true; response.Timestamp = DateTime.UtcNow; response.Message = "My projects successfully read"; response.Object = resultRecordsList; return(Json(response)); }
public IActionResult MyProjects(string listName = null, string entityName = null, int page = 0) { var response = new ResponseModel(); //var queryString = HttpContext.Request.QueryString; #region << Can user read projects >> //Get current user ErpUser user = SecurityContext.CurrentUser; //Get entity meta var entity = entityManager.ReadEntity(entityName).Object; //Get list meta var list = entityManager.ReadRecordList(entity.Name, listName).Object; //check if user role has permissions var canRead = user.Roles.Any(x => entity.RecordPermissions.CanRead.Any(z => z == x.Id)); var canCreate = user.Roles.Any(x => entity.RecordPermissions.CanCreate.Any(z => z == x.Id)); var canUpdate = user.Roles.Any(x => entity.RecordPermissions.CanUpdate.Any(z => z == x.Id)); var canDelete = user.Roles.Any(x => entity.RecordPermissions.CanDelete.Any(z => z == x.Id)); if (!canRead) { response.Success = false; response.Message = "You do not have permission to read the projects in this system"; response.Timestamp = DateTime.UtcNow; return(Json(response)); //return empty object } #endregion #region << Init fields >> var requestedFields = "id,name,start_date,end_date," + "x_milestones_opened,x_milestones_completed,x_tasks_not_started,x_tasks_in_progress,x_tasks_completed,x_bugs_opened,x_bugs_reopened,x_bugs_closed," + "$user_1_n_project_owner.id,$user_1_n_project_owner.image,$user_1_n_project_owner.username," + "$role_n_n_project_team.id,$role_n_n_project_customer.id"; #endregion #region << Query builder >> //QueryObject filterObj = EntityQuery.QueryEQ("id", recordId); QueryObject filterObj = null; EntityQuery resultQuery = new EntityQuery("wv_project", requestedFields, filterObj, null, null, null, null); #endregion #region << Sort >> #endregion #region << Execute >> QueryResponse result = recMan.Find(resultQuery); var resultRecordsList = new List <EntityRecord>(); if (!result.Success) { response.Success = false; response.Timestamp = DateTime.UtcNow; response.Message = result.Message; response.Object = null; return(Json(response)); } foreach (var record in result.Object.Data) { //Check if user can view the object var userIsPM = false; var userIsStaff = false; var userIsCustomer = false; #region << Check user roles >> foreach (var userRole in user.Roles) { userIsPM = ((List <EntityRecord>)record["$user_1_n_project_owner"]).Any(z => (Guid)z["id"] == user.Id); userIsStaff = ((List <EntityRecord>)record["$role_n_n_project_team"]).Any(z => (Guid)z["id"] == userRole.Id); userIsCustomer = ((List <EntityRecord>)record["$role_n_n_project_customer"]).Any(z => (Guid)z["id"] == userRole.Id); } #endregion if (userIsPM || userIsStaff || userIsCustomer) { var recordObj = new EntityRecord(); recordObj["id"] = record["id"]; recordObj["name"] = record["name"]; recordObj["start_date"] = record["start_date"]; recordObj["end_date"] = record["end_date"]; recordObj["owner_image"] = ((List <EntityRecord>)record["$user_1_n_project_owner"])[0]["image"]; recordObj["owner_username"] = ((List <EntityRecord>)record["$user_1_n_project_owner"])[0]["username"]; #region << milestones Count "opened" vs "completed" >> var milestonesOpened = (decimal)record["x_milestones_opened"]; var milestonesCompleted = (decimal)record["x_milestones_completed"]; recordObj["milestones_opened_count"] = milestonesOpened; recordObj["milestones_completed_count"] = milestonesCompleted; if (milestonesOpened + milestonesCompleted > 0) { recordObj["milestones_opened_percentage"] = Math.Round((decimal)(milestonesOpened * 100) / (milestonesOpened + milestonesCompleted)); recordObj["milestones_completed_percentage"] = 100 - Math.Round((decimal)(milestonesOpened * 100) / (milestonesOpened + milestonesCompleted)); } else { recordObj["milestones_opened_percentage"] = 0; recordObj["milestones_completed_percentage"] = 0; } #endregion #region << tasks Count "not started" vs "in progress" vs "completed" >> var tasksNotStarted = (decimal)record["x_tasks_not_started"]; var tasksInProgress = (decimal)record["x_tasks_in_progress"]; var tasksCompleted = (decimal)record["x_tasks_completed"]; recordObj["tasks_not_started_count"] = tasksNotStarted; recordObj["tasks_in_progress_count"] = tasksInProgress; recordObj["tasks_completed_count"] = tasksCompleted; if (tasksNotStarted + tasksInProgress + tasksCompleted > 0) { recordObj["tasks_not_started_percentage"] = Math.Round((decimal)(tasksNotStarted * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted)); recordObj["tasks_in_progress_percentage"] = Math.Round((decimal)(tasksInProgress * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted)); recordObj["tasks_completed_percentage"] = 100 - Math.Round((decimal)(tasksNotStarted * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted)) - Math.Round((decimal)(tasksInProgress * 100) / (tasksNotStarted + tasksInProgress + tasksCompleted)); } else { recordObj["tasks_not_started_percentage"] = 0; recordObj["tasks_in_progress_percentage"] = 0; recordObj["tasks_completed_percentage"] = 0; } #endregion #region << bugs Count "opened" & "reopened" vs "closed" >> var bugsOpened = (decimal)record["x_bugs_opened"]; var bugsReOpened = (decimal)record["x_bugs_reopened"]; var bugsClosed = (decimal)record["x_bugs_closed"]; recordObj["bugs_opened_count"] = bugsOpened; recordObj["bugs_reopened_count"] = bugsReOpened; recordObj["bugs_closed_count"] = bugsClosed; if (bugsOpened + bugsReOpened + bugsClosed > 0) { recordObj["bugs_opened_percentage"] = Math.Round((decimal)(bugsOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed)); recordObj["bugs_reopened_percentage"] = Math.Round((decimal)(bugsReOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed)); recordObj["bugs_closed_percentage"] = 100 - Math.Round((decimal)(bugsOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed)) - Math.Round((decimal)(bugsReOpened * 100) / (bugsOpened + bugsReOpened + bugsClosed)); } else { recordObj["bugs_opened_percentage"] = 0; recordObj["bugs_reopened_percentage"] = 0; recordObj["bugs_closed_percentage"] = 0; } resultRecordsList.Add(recordObj); #endregion } } #endregion var skipRecords = list.PageSize * (page - 1); if (page != 0) { resultRecordsList = resultRecordsList.Skip(skipRecords).Take(page).ToList(); } response.Success = true; response.Timestamp = DateTime.UtcNow; response.Message = "My projects successfully read"; response.Object = resultRecordsList; return(Json(response)); }
public IActionResult UpdateSitemapNode([FromBody] SitemapNodeSubmit node, [FromQuery] Guid?appId = null, [FromQuery] Guid?areaId = null) { var response = new ResponseModel(); response.Message = "Success"; response.Success = true; if (node == null) { response.Message = "Wrong object model submitted. Could not restore!"; response.Success = false; return(Json(response)); } if (appId == null) { response.Message = "Application Id needs to be submitted as 'appId' query string"; response.Success = false; return(Json(response)); } if (areaId == null) { response.Message = "Area Id needs to be submitted as 'areaId' query string"; response.Success = false; return(Json(response)); } if (node.Id == null || node.Id == Guid.Empty) { response.Message = "Node Id needs to be submitted"; response.Success = false; return(Json(response)); } var appSrv = new AppService(); var pageSrv = new PageService(); try { appSrv.UpdateAreaNode(node.Id, areaId ?? Guid.Empty, node.Name, node.Label, node.LabelTranslations, node.IconClass, node.Url, (int)node.Type, node.EntityId, node.Weight, node.Access, node.EntityListPages, node.EntityCreatePages, node.EntityDetailsPages, node.EntityManagePages); var allAppPages = pageSrv.GetAppControlledPages(appId ?? Guid.Empty); var currentAttachedNodePages = allAppPages.FindAll(x => x.NodeId == node.Id).Select(x => x.Id).ToList(); var currentAttachedPagesHashSet = new HashSet <Guid>(); foreach (var pageId in currentAttachedNodePages) { currentAttachedPagesHashSet.Add(pageId); } //Process submitted page Ids if (node.Pages == null) { node.Pages = new List <Guid>(); } foreach (var pageId in node.Pages) { var page = pageSrv.GetPage(pageId); if (page == null) { throw new Exception("Page not found"); } if (page.NodeId == null) { pageSrv.UpdatePage(page.Id, page.Name, page.Label, page.LabelTranslations, page.IconClass, page.System, page.Weight, page.Type, page.AppId, page.EntityId, node.Id, areaId, page.IsRazorBody, page.RazorBody, page.Layout); } else if (page.NodeId == node.Id) { currentAttachedPagesHashSet.Remove(page.Id); } } //Detach pages that were not submitted foreach (var pageId in currentAttachedPagesHashSet) { var page = pageSrv.GetPage(pageId); if (page == null) { throw new Exception("Page not found"); } pageSrv.UpdatePage(page.Id, page.Name, page.Label, page.LabelTranslations, page.IconClass, page.System, page.Weight, page.Type, page.AppId, page.EntityId, null, null, page.IsRazorBody, page.RazorBody, page.Layout); } } catch (Exception ex) { response.Message = ex.Message; response.Success = false; return(Json(response)); } var newSitemap = appSrv.GetApplication(appId ?? Guid.Empty).Sitemap; var initData = new EntityRecord(); initData["sitemap"] = appSrv.OrderSitemap(newSitemap); initData["node_page_dict"] = PageUtils.GetNodePageDictionary(appId); response.Object = initData; return(Json(response)); }
public IActionResult GetNodeAuxData([FromQuery] Guid?appId = null) { var response = new ResponseModel(); response.Message = "Success"; response.Success = true; if (appId == null) { response.Message = "Application Id needs to be submitted as 'appId' query string"; response.Success = false; return(Json(response)); } try { var responseObject = new EntityRecord(); var entitiesSelectOptions = new List <SelectOption>(); var appPageRecords = new List <EntityRecord>(); var allEntityPageRecords = new List <EntityRecord>(); var typesSelectOptions = new List <SelectOption>(); var entities = new EntityManager().ReadEntities().Object; foreach (var entity in entities) { var selectOption = new SelectOption() { Value = entity.Id.ToString(), Label = entity.Name }; entitiesSelectOptions.Add(selectOption); } entitiesSelectOptions = entitiesSelectOptions.OrderBy(x => x.Label).ToList(); entitiesSelectOptions.Insert(0, new SelectOption() { Value = "", Label = "not attached" }); responseObject["all_entities"] = entitiesSelectOptions; foreach (var typeEnum in Enum.GetValues(typeof(SitemapNodeType)).Cast <SitemapNodeType>()) { var selectOption = new SelectOption() { Value = ((int)typeEnum).ToString(), Label = typeEnum.GetLabel() }; typesSelectOptions.Add(selectOption); } responseObject["node_types"] = typesSelectOptions.OrderBy(x => x.Label).ToList(); var pageService = new PageService(); //Get App pages var appPages = pageService.GetAppControlledPages(appId.Value); var allAppPagesWithoutNodes = appPages.FindAll(x => x.NodeId == null && x.Type == PageType.Application).OrderBy(x => x.Name).ToList(); foreach (var page in allAppPagesWithoutNodes) { var selectOption = new EntityRecord(); selectOption["page_id"] = page.Id.ToString(); selectOption["page_name"] = page.Name; selectOption["node_id"] = page.NodeId != null ? (page.NodeId ?? Guid.Empty).ToString() : ""; appPageRecords.Add(selectOption); } responseObject["app_pages"] = appPageRecords.OrderBy(x => (string)x["page_name"]).ToList(); //Get EntityPages var allEntityPages = pageService.GetAll(); foreach (var page in allEntityPages) { if (page.EntityId != null && page.AppId == appId.Value) { var selectOption = new EntityRecord(); selectOption["page_id"] = page.Id.ToString(); selectOption["page_name"] = page.Name; selectOption["entity_id"] = page.EntityId; selectOption["type"] = ((int)page.Type).ToString(); selectOption["node_id"] = page.NodeId != null ? (page.NodeId ?? Guid.Empty).ToString() : ""; allEntityPageRecords.Add(selectOption); } } responseObject["all_entity_pages"] = allEntityPageRecords.OrderBy(x => (string)x["page_name"]).ToList(); response.Object = responseObject; } catch (Exception ex) { response.Message = ex.Message; response.Success = false; return(Json(response)); } return(Json(response)); }
public IActionResult CreateSitemapNode([FromBody] SitemapNodeSubmit node, [FromQuery] Guid?appId = null, [FromQuery] Guid?areaId = null) { var response = new ResponseModel(); response.Message = "Success"; response.Success = true; if (node == null) { response.Message = "Wrong object model submitted. Could not restore!"; response.Success = false; return(Json(response)); } if (appId == null) { response.Message = "Application Id needs to be submitted as 'appId' query string"; response.Success = false; return(Json(response)); } if (areaId == null) { response.Message = "Area Id needs to be submitted as 'areaId' query string"; response.Success = false; return(Json(response)); } if (node.Id == Guid.Empty) { node.Id = Guid.NewGuid(); } var appSrv = new AppService(); var pageSrv = new PageService(); try { appSrv.CreateAreaNode(node.Id, areaId ?? Guid.Empty, node.Name, node.Label, node.LabelTranslations, node.IconClass, node.Url, (int)node.Type, node.EntityId, node.Weight, node.Access, node.EntityListPages, node.EntityCreatePages, node.EntityDetailsPages, node.EntityManagePages); if (node.Pages == null) { node.Pages = new List <Guid>(); } foreach (var pageId in node.Pages) { var page = pageSrv.GetPage(pageId); if (page == null) { throw new Exception("Page not found"); } pageSrv.UpdatePage(page.Id, page.Name, page.Label, page.LabelTranslations, page.IconClass, page.System, page.Weight, page.Type, page.AppId, page.EntityId, node.Id, areaId, page.IsRazorBody, page.RazorBody, page.Layout); } } catch (Exception ex) { response.Message = ex.Message; response.Success = false; return(Json(response)); } var newSitemap = appSrv.GetApplication(appId ?? Guid.Empty).Sitemap; var initData = new EntityRecord(); initData["sitemap"] = appSrv.OrderSitemap(newSitemap); initData["node_page_dict"] = PageUtils.GetNodePageDictionary(appId); response.Object = initData; return(Json(response)); }
public void Start(PluginStartArguments pluginStartArgs) { //initialize static context StaticContext.Initialize(pluginStartArgs.Plugin, pluginStartArgs.ServiceProvider); var entMan = new EntityManager(); var relMan = new EntityRelationManager(); var recMan = new RecordManager(); var storeSystemSettings = DbContext.Current.SettingsRepository.Read(); var systemSettings = new SystemSettings(storeSystemSettings); using (SecurityContext.OpenSystemScope()) { //Create transaction using (var connection = DbContext.Current.CreateConnection()) { try { connection.BeginTransaction(); //Here we need to initialize or update the environment based on the plugin requirements. //The default place for the plugin data is the "plugin_data" entity -> the "data" text field, which is used to store stringified JSON //containing the plugin settings or version #region << 1.Get the current ERP database version and checks for other plugin dependencies >> if (systemSettings.Version > 0) { //Do something if database version is not what you expect } //This plugin needs the webvella-crm plugin to be installed, so we will check this here var installedPlugins = new PluginService().Plugins; var crmPluginFound = false; foreach (var plugin in installedPlugins) { switch (plugin.Name) { case "webvella-crm": crmPluginFound = true; break; default: break; } } if (!crmPluginFound) { throw new Exception("'webvella-crm' plugin is required for the 'webvella-project' to operate"); } #endregion #region << 2.Get the current plugin settings from the database >> var currentPluginSettings = new PluginSettings(); QueryObject pluginDataQueryObject = EntityQuery.QueryEQ("name", WEBVELLA_PROJECT_PLUGIN_NAME); var pluginDataQuery = new EntityQuery("plugin_data", "*", pluginDataQueryObject); var pluginDataQueryResponse = recMan.Find(pluginDataQuery); if (!pluginDataQueryResponse.Success) { throw new Exception("plugin 'webvella-project' failed to get its settings due to: " + pluginDataQueryResponse.Message); } if (pluginDataQueryResponse.Object == null || !pluginDataQueryResponse.Object.Data.Any() || pluginDataQueryResponse.Object.Data[0]["data"] == DBNull.Value) { //plugin was not installed currentPluginSettings.Version = 20160429; { string json = JsonConvert.SerializeObject(currentPluginSettings); var settingsEntityRecord = new EntityRecord(); settingsEntityRecord["id"] = WEBVELLA_PROJECT_PLUGIN_ID; settingsEntityRecord["name"] = WEBVELLA_PROJECT_PLUGIN_NAME; settingsEntityRecord["data"] = json; var settingsSaveReponse = recMan.CreateRecord("plugin_data", settingsEntityRecord); if (!settingsSaveReponse.Success) { throw new Exception("plugin 'webvella-project' failed to save its settings in the database due to: " + pluginDataQueryResponse.Message); } } } else { string json = (string)((List <EntityRecord>)pluginDataQueryResponse.Object.Data)[0]["data"]; currentPluginSettings = JsonConvert.DeserializeObject <PluginSettings>(json); } #endregion #region << 3. Run methods based on the current installed version of the plugin >> if (currentPluginSettings.Version < 20160430) { try { currentPluginSettings.Version = 20160430; Patch160430(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { var exception = ex; throw ex; } } if (currentPluginSettings.Version < 20160610) { try { currentPluginSettings.Version = 20160610; Patch160610(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { var exception = ex; throw ex; } } if (currentPluginSettings.Version < 20160613) { try { currentPluginSettings.Version = 20160613; Patch160613(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { var exception = ex; throw ex; } } if (currentPluginSettings.Version < 20160627) { try { currentPluginSettings.Version = 20160627; Patch160627(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { var exception = ex; throw ex; } } if (currentPluginSettings.Version < 20160707) { try { currentPluginSettings.Version = 20160707; Patch160707(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { var exception = ex; throw ex; } } if (currentPluginSettings.Version < 20161118) { try { currentPluginSettings.Version = 20161118; Patch161118(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { var exception = ex; throw ex; } } if (currentPluginSettings.Version < 20161119) { try { currentPluginSettings.Version = 20161119; Patch161119(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { var exception = ex; throw ex; } } if (currentPluginSettings.Version < 20170119) { try { currentPluginSettings.Version = 20170119; Patch170119(entMan, relMan, recMan, createSampleRecords); } catch (Exception ex) { var exception = ex; throw ex; } } #endregion #region << 4. Save needed changes to the plugin setting data >> { string json = JsonConvert.SerializeObject(currentPluginSettings); var settingsEntityRecord = new EntityRecord(); settingsEntityRecord["id"] = WEBVELLA_PROJECT_PLUGIN_ID; settingsEntityRecord["name"] = WEBVELLA_PROJECT_PLUGIN_NAME; settingsEntityRecord["data"] = json; var settingsUpdateReponse = recMan.UpdateRecord("plugin_data", settingsEntityRecord); if (!settingsUpdateReponse.Success) { throw new Exception("plugin 'webvella-project' failed to update its settings in the database due to: " + pluginDataQueryResponse.Message); } } #endregion connection.CommitTransaction(); } catch (Exception ex) { connection.RollbackTransaction(); throw ex; } } } }
string getValue(int i, string VALUE_FIELD_NAME, string DATASOURCE_NAME, PageDataModel pageModel, EntityRecord record) { string value = ""; if (VALUE_FIELD_NAME.Contains("$")) { value = pageModel.GetProperty(DATASOURCE_NAME + "[" + i + "]." + VALUE_FIELD_NAME).ToString(); } else { value = record[VALUE_FIELD_NAME].ToString(); } return(value); }
public void InitializeSystemEntities() { EntityResponse response = null; FieldResponse fieldResponse = null; EntityManager entMan = new EntityManager(); EntityRelationManager rm = new EntityRelationManager(); RecordManager recMan = new RecordManager(true); using (var connection = DbContext.Current.CreateConnection()) { //setup necessary extensions DbRepository.CreatePostgresqlExtensions(); try { connection.BeginTransaction(); CheckCreateSystemTables(); DbSystemSettings storeSystemSettings = DbContext.Current.SettingsRepository.Read(); Guid systemSettingsId = new Guid("F3223177-B2FF-43F5-9A4B-FF16FC67D186"); SystemSettings systemSettings = new SystemSettings(); systemSettings.Id = systemSettingsId; int currentVersion = 0; if (storeSystemSettings != null) { systemSettings = new SystemSettings(storeSystemSettings); currentVersion = systemSettings.Version; } //tmp code - during debug only //entityManager.DeleteEntity(SystemIds.UserEntityId); //entityManager.DeleteEntity(SystemIds.RoleEntityId); //rm.Delete(SystemIds.UserRoleRelationId); //currentVersion = 0; if (currentVersion < 150508) { systemSettings.Version = 150508; List<Guid> allowedRoles = new List<Guid>(); allowedRoles.Add(SystemIds.AdministratorRoleId); #region << create user entity >> { InputEntity userEntity = new InputEntity(); userEntity.Id = SystemIds.UserEntityId; userEntity.Name = "user"; userEntity.Label = "User"; userEntity.LabelPlural = "Users"; userEntity.System = true; userEntity.RecordPermissions = new RecordPermissions(); userEntity.RecordPermissions.CanCreate = new List<Guid>(); userEntity.RecordPermissions.CanRead = new List<Guid>(); userEntity.RecordPermissions.CanUpdate = new List<Guid>(); userEntity.RecordPermissions.CanDelete = new List<Guid>(); userEntity.RecordPermissions.CanCreate.Add(SystemIds.GuestRoleId); userEntity.RecordPermissions.CanCreate.Add(SystemIds.AdministratorRoleId); userEntity.RecordPermissions.CanRead.Add(SystemIds.GuestRoleId); userEntity.RecordPermissions.CanRead.Add(SystemIds.RegularRoleId); userEntity.RecordPermissions.CanRead.Add(SystemIds.AdministratorRoleId); userEntity.RecordPermissions.CanUpdate.Add(SystemIds.AdministratorRoleId); userEntity.RecordPermissions.CanDelete.Add(SystemIds.AdministratorRoleId); var systemItemIdDictionary = new Dictionary<string, Guid>(); systemItemIdDictionary["id"] = new Guid("8e438549-fd30-4766-95a9-061008cee48e"); systemItemIdDictionary["created_on"] = new Guid("6fda5e6b-80e6-4d8a-9e2a-d983c3694e96"); systemItemIdDictionary["created_by"] = new Guid("825e8367-3be1-4022-ba66-6494859d70d9"); systemItemIdDictionary["last_modified_on"] = new Guid("5a975d33-47c6-4ba6-83c8-c24034206879"); systemItemIdDictionary["last_modified_by"] = new Guid("cafc8cda-1a1d-43e4-9406-6acf8ba8fa8d"); response = entMan.CreateEntity(userEntity, false, false, systemItemIdDictionary); InputTextField firstName = new InputTextField(); firstName.Id = new Guid("DF211549-41CC-4D11-BB43-DACA4C164411"); firstName.Name = "first_name"; firstName.Label = "First Name"; firstName.PlaceholderText = ""; firstName.Description = "First name of the user"; firstName.HelpText = ""; firstName.Required = false; firstName.Unique = false; firstName.Searchable = false; firstName.Auditable = false; firstName.System = true; firstName.DefaultValue = ""; firstName.MaxLength = 200; fieldResponse = entMan.CreateField(userEntity.Id.Value, firstName, false); InputTextField lastName = new InputTextField(); lastName.Id = new Guid("63E685B1-B2C6-4961-B393-2B6723EBD1BF"); lastName.Name = "last_name"; lastName.Label = "Last Name"; lastName.PlaceholderText = ""; lastName.Description = "Last name of the user"; lastName.HelpText = ""; lastName.Required = false; lastName.Unique = false; lastName.Searchable = false; lastName.Auditable = false; lastName.System = true; lastName.DefaultValue = ""; lastName.MaxLength = 200; fieldResponse = entMan.CreateField(userEntity.Id.Value, lastName, false); InputTextField userName = new InputTextField(); userName.Id = new Guid("263c0b21-88c1-4c2b-80b4-db7402b0d2e2"); userName.Name = "username"; userName.Label = "User Name"; userName.PlaceholderText = ""; userName.Description = "screen name for the user"; userName.HelpText = ""; userName.Required = true; userName.Unique = true; userName.Searchable = true; userName.Auditable = false; userName.System = true; userName.DefaultValue = string.Empty; userName.MaxLength = 200; fieldResponse = entMan.CreateField(userEntity.Id.Value, userName, false); InputEmailField email = new InputEmailField(); email.Id = new Guid("9FC75C8F-CE80-4A64-81D7-E2BEFA5E4815"); email.Name = "email"; email.Label = "Email"; email.PlaceholderText = ""; email.Description = "Email address of the user"; email.HelpText = ""; email.Required = true; email.Unique = true; email.Searchable = true; email.Auditable = false; email.System = true; email.DefaultValue = string.Empty; email.MaxLength = 255; fieldResponse = entMan.CreateField(userEntity.Id.Value, email, false); InputPasswordField password = new InputPasswordField(); password.Id = new Guid("4EDE88D9-217A-4462-9300-EA0D6AFCDCEA"); password.Name = "password"; password.Label = "Password"; password.PlaceholderText = ""; password.Description = "Password for the user account"; password.HelpText = ""; password.Required = true; password.Unique = false; password.Searchable = false; password.Auditable = false; password.System = true; password.MinLength = 6; password.MaxLength = 24; password.Encrypted = true; fieldResponse = entMan.CreateField(userEntity.Id.Value, password, false); InputDateTimeField lastLoggedIn = new InputDateTimeField(); lastLoggedIn.Id = new Guid("3C85CCEC-D526-4E47-887F-EE169D1F508D"); lastLoggedIn.Name = "last_logged_in"; lastLoggedIn.Label = "Last Logged In"; lastLoggedIn.PlaceholderText = ""; lastLoggedIn.Description = ""; lastLoggedIn.HelpText = ""; lastLoggedIn.Required = false; lastLoggedIn.Unique = false; lastLoggedIn.Searchable = false; lastLoggedIn.Auditable = true; lastLoggedIn.System = true; lastLoggedIn.DefaultValue = null; lastLoggedIn.Format = "dd MMM yyyy HH:mm:ss"; lastLoggedIn.UseCurrentTimeAsDefaultValue = true; fieldResponse = entMan.CreateField(userEntity.Id.Value, lastLoggedIn, false); InputCheckboxField enabledField = new InputCheckboxField(); enabledField.Id = new Guid("C0C63650-7572-4252-8E4B-4E25C94897A6"); enabledField.Name = "enabled"; enabledField.Label = "Enabled"; enabledField.PlaceholderText = ""; enabledField.Description = "Shows if the user account is enabled"; enabledField.HelpText = ""; enabledField.Required = true; enabledField.Unique = false; enabledField.Searchable = false; enabledField.Auditable = false; enabledField.System = true; enabledField.DefaultValue = false; fieldResponse = entMan.CreateField(userEntity.Id.Value, enabledField, false); InputCheckboxField verifiedUserField = new InputCheckboxField(); verifiedUserField.Id = new Guid("F1BA5069-8CC9-4E66-BCC3-60E33C79C265"); verifiedUserField.Name = "verified"; verifiedUserField.Label = "Verified"; verifiedUserField.PlaceholderText = ""; verifiedUserField.Description = "Shows if the user email is verified"; verifiedUserField.HelpText = ""; verifiedUserField.Required = true; verifiedUserField.Unique = false; verifiedUserField.Searchable = false; verifiedUserField.Auditable = false; verifiedUserField.System = true; verifiedUserField.DefaultValue = false; fieldResponse = entMan.CreateField(userEntity.Id.Value, verifiedUserField, false); #region << image >> { InputImageField imageField = new InputImageField(); imageField.Id = new Guid("bf199b74-4448-4f58-93f5-6b86d888843b"); imageField.Name = "image"; imageField.Label = "Image"; imageField.PlaceholderText = ""; imageField.Description = ""; imageField.HelpText = ""; imageField.Required = false; imageField.Unique = false; imageField.Searchable = false; imageField.Auditable = false; imageField.System = true; imageField.DefaultValue = string.Empty; imageField.EnableSecurity = false; { var createResponse = entMan.CreateField(SystemIds.UserEntityId, imageField, false); if (!createResponse.Success) throw new Exception("System error 10060. Entity: user. Field: image" + " Message:" + createResponse.Message); } } #endregion } #endregion #region << create role entity >> { InputEntity roleEntity = new InputEntity(); roleEntity.Id = SystemIds.RoleEntityId; roleEntity.Name = "role"; roleEntity.Label = "Role"; roleEntity.LabelPlural = "Roles"; roleEntity.System = true; roleEntity.RecordPermissions = new RecordPermissions(); roleEntity.RecordPermissions.CanCreate = new List<Guid>(); roleEntity.RecordPermissions.CanRead = new List<Guid>(); roleEntity.RecordPermissions.CanUpdate = new List<Guid>(); roleEntity.RecordPermissions.CanDelete = new List<Guid>(); roleEntity.RecordPermissions.CanCreate.Add(SystemIds.GuestRoleId); roleEntity.RecordPermissions.CanCreate.Add(SystemIds.AdministratorRoleId); roleEntity.RecordPermissions.CanRead.Add(SystemIds.RegularRoleId); roleEntity.RecordPermissions.CanRead.Add(SystemIds.GuestRoleId); roleEntity.RecordPermissions.CanRead.Add(SystemIds.AdministratorRoleId); roleEntity.RecordPermissions.CanUpdate.Add(SystemIds.AdministratorRoleId); roleEntity.RecordPermissions.CanDelete.Add(SystemIds.AdministratorRoleId); var systemItemIdDictionary = new Dictionary<string, Guid>(); systemItemIdDictionary["id"] = new Guid("37fd9c4f-5413-4f3a-aa2f-d831cc106d03"); systemItemIdDictionary["created_on"] = new Guid("64047bab-dc73-4175-a744-e5d565e8adbb"); systemItemIdDictionary["created_by"] = new Guid("0ccd806b-715c-42d4-a580-f3f11f55d937"); systemItemIdDictionary["last_modified_on"] = new Guid("c4522433-1c67-44f9-b461-e85d4d363b70"); systemItemIdDictionary["last_modified_by"] = new Guid("a4489db4-9d76-4d5a-8940-6ef2da562c25"); systemItemIdDictionary["user_role_created_by"] = new Guid("c6151e80-9dce-4c0b-ae5f-4798e14cff4c"); systemItemIdDictionary["user_role_modified_by"] = new Guid("f3efaefe-32d2-4840-ac06-bc5723e323d0"); response = entMan.CreateEntity(roleEntity, false, false, systemItemIdDictionary); InputTextField nameRoleField = new InputTextField(); nameRoleField.Id = new Guid("36F91EBD-5A02-4032-8498-B7F716F6A349"); nameRoleField.Name = "name"; nameRoleField.Label = "Name"; nameRoleField.PlaceholderText = ""; nameRoleField.Description = "The name of the role"; nameRoleField.HelpText = ""; nameRoleField.Required = true; nameRoleField.Unique = false; nameRoleField.Searchable = false; nameRoleField.Auditable = false; nameRoleField.System = true; nameRoleField.DefaultValue = ""; nameRoleField.MaxLength = 200; nameRoleField.EnableSecurity = true; nameRoleField.Permissions = new FieldPermissions(); nameRoleField.Permissions.CanRead = new List<Guid>(); nameRoleField.Permissions.CanUpdate = new List<Guid>(); //READ nameRoleField.Permissions.CanRead.Add(SystemIds.AdministratorRoleId); nameRoleField.Permissions.CanRead.Add(SystemIds.RegularRoleId); //UPDATE nameRoleField.Permissions.CanUpdate.Add(SystemIds.AdministratorRoleId); fieldResponse = entMan.CreateField(roleEntity.Id.Value, nameRoleField, false); InputTextField descriptionRoleField = new InputTextField(); descriptionRoleField.Id = new Guid("4A8B9E0A-1C36-40C6-972B-B19E2B5D265B"); descriptionRoleField.Name = "description"; descriptionRoleField.Label = "Description"; descriptionRoleField.PlaceholderText = ""; descriptionRoleField.Description = ""; descriptionRoleField.HelpText = ""; descriptionRoleField.Required = true; descriptionRoleField.Unique = false; descriptionRoleField.Searchable = false; descriptionRoleField.Auditable = false; descriptionRoleField.System = true; descriptionRoleField.DefaultValue = ""; descriptionRoleField.MaxLength = 200; fieldResponse = entMan.CreateField(roleEntity.Id.Value, descriptionRoleField, false); } #endregion #region << create user - role relation >> { var userEntity = entMan.ReadEntity(SystemIds.UserEntityId).Object; var roleEntity = entMan.ReadEntity(SystemIds.RoleEntityId).Object; EntityRelation userRoleRelation = new EntityRelation(); userRoleRelation.Id = SystemIds.UserRoleRelationId; userRoleRelation.Name = "user_role"; userRoleRelation.Label = "User-Role"; userRoleRelation.System = true; userRoleRelation.RelationType = EntityRelationType.ManyToMany; userRoleRelation.TargetEntityId = userEntity.Id; userRoleRelation.TargetFieldId = userEntity.Fields.Single(x => x.Name == "id").Id; userRoleRelation.OriginEntityId = roleEntity.Id; userRoleRelation.OriginFieldId = roleEntity.Fields.Single(x => x.Name == "id").Id; { var result = rm.Create(userRoleRelation); if (!result.Success) throw new Exception("CREATE USER-ROLE RELATION:" + result.Message); } } #endregion #region << create system records >> { EntityRecord user = new EntityRecord(); user["id"] = SystemIds.SystemUserId; user["first_name"] = "Local"; user["last_name"] = "System"; user["password"] = Guid.NewGuid().ToString(); user["email"] = "*****@*****.**"; user["username"] = "******"; user["created_by"] = SystemIds.SystemUserId; user["last_modified_by"] = SystemIds.SystemUserId; user["created_on"] = DateTime.UtcNow; user["enabled"] = true; QueryResponse result = recMan.CreateRecord("user", user); if (!result.Success) throw new Exception("CREATE SYSTEM USER RECORD:" + result.Message); } { EntityRecord user = new EntityRecord(); user["id"] = SystemIds.FirstUserId; user["first_name"] = "WebVella"; user["last_name"] = "Erp"; user["password"] = "******"; user["email"] = "*****@*****.**"; user["username"] = "******"; user["created_by"] = SystemIds.SystemUserId; user["last_modified_by"] = SystemIds.SystemUserId; user["created_on"] = DateTime.UtcNow; user["enabled"] = true; QueryResponse result = recMan.CreateRecord("user", user); if (!result.Success) throw new Exception("CREATE FIRST USER RECORD:" + result.Message); } { EntityRecord adminRole = new EntityRecord(); adminRole["id"] = SystemIds.AdministratorRoleId; adminRole["name"] = "administrator"; adminRole["description"] = ""; adminRole["created_by"] = SystemIds.SystemUserId; adminRole["last_modified_by"] = SystemIds.SystemUserId; adminRole["created_on"] = DateTime.UtcNow; QueryResponse result = recMan.CreateRecord("role", adminRole); if (!result.Success) throw new Exception("CREATE ADMINITRATOR ROLE RECORD:" + result.Message); } { EntityRecord regularRole = new EntityRecord(); regularRole["id"] = SystemIds.RegularRoleId; regularRole["name"] = "regular"; regularRole["description"] = ""; regularRole["created_by"] = SystemIds.SystemUserId; regularRole["last_modified_by"] = SystemIds.SystemUserId; regularRole["created_on"] = DateTime.UtcNow; QueryResponse result = recMan.CreateRecord("role", regularRole); if (!result.Success) throw new Exception("CREATE REGULAR ROLE RECORD:" + result.Message); } { EntityRecord guestRole = new EntityRecord(); guestRole["id"] = SystemIds.GuestRoleId; guestRole["name"] = "guest"; guestRole["description"] = ""; guestRole["created_by"] = SystemIds.SystemUserId; guestRole["last_modified_by"] = SystemIds.SystemUserId; guestRole["created_on"] = DateTime.UtcNow; QueryResponse result = recMan.CreateRecord("role", guestRole); if (!result.Success) throw new Exception("CREATE GUEST ROLE RECORD:" + result.Message); } { QueryResponse result = recMan.CreateRelationManyToManyRecord(SystemIds.UserRoleRelationId, SystemIds.AdministratorRoleId, SystemIds.SystemUserId); if (!result.Success) throw new Exception("CREATE SYSTEM-USER <-> ADMINISTRATOR ROLE RELATION RECORD:" + result.Message); } { QueryResponse result = recMan.CreateRelationManyToManyRecord(SystemIds.UserRoleRelationId, SystemIds.AdministratorRoleId, SystemIds.FirstUserId); if (!result.Success) throw new Exception("CREATE FIRST-USER <-> ADMINISTRATOR ROLE RELATION RECORD:" + result.Message); result = recMan.CreateRelationManyToManyRecord(SystemIds.UserRoleRelationId, SystemIds.RegularRoleId, SystemIds.FirstUserId); if (!result.Success) throw new Exception("CREATE FIRST-USER <-> REGULAR ROLE RELATION RECORD:" + result.Message); } #endregion #region << create Area entity >> { InputEntity areaEntity = new InputEntity(); areaEntity.Id = SystemIds.AreaEntityId; areaEntity.Name = "area"; areaEntity.Label = "Area"; areaEntity.LabelPlural = "areas"; areaEntity.System = true; areaEntity.IconName = "folder"; areaEntity.Weight = 10; areaEntity.RecordPermissions = new RecordPermissions(); areaEntity.RecordPermissions.CanCreate = new List<Guid>(); areaEntity.RecordPermissions.CanRead = new List<Guid>(); areaEntity.RecordPermissions.CanUpdate = new List<Guid>(); areaEntity.RecordPermissions.CanDelete = new List<Guid>(); areaEntity.RecordPermissions.CanCreate.Add(SystemIds.AdministratorRoleId); areaEntity.RecordPermissions.CanRead.Add(SystemIds.RegularRoleId); areaEntity.RecordPermissions.CanRead.Add(SystemIds.AdministratorRoleId); areaEntity.RecordPermissions.CanUpdate.Add(SystemIds.AdministratorRoleId); areaEntity.RecordPermissions.CanDelete.Add(SystemIds.AdministratorRoleId); var systemItemIdDictionary = new Dictionary<string, Guid>(); systemItemIdDictionary["id"] = new Guid("19f16bdb-56e6-46bf-8310-2b42fd78be2a"); systemItemIdDictionary["created_on"] = new Guid("3e6be69e-8f25-40e4-9f21-86b0d1404230"); systemItemIdDictionary["created_by"] = new Guid("16fbba6c-6282-4828-9873-86b8fef745d4"); systemItemIdDictionary["last_modified_on"] = new Guid("5f076d8b-e587-4201-9481-67e19789ff6c"); systemItemIdDictionary["last_modified_by"] = new Guid("721b27b3-741d-4414-8783-a0245a4eec58"); systemItemIdDictionary["user_area_created_by"] = new Guid("5fe5fdc4-ee10-4661-93e7-25ea2a61e710"); systemItemIdDictionary["user_area_modified_by"] = new Guid("bb52122c-a354-4668-9423-71dfdc3d9f36"); { var createResponse = entMan.CreateEntity(areaEntity, false, false, systemItemIdDictionary); if (!createResponse.Success) throw new Exception("System error 10330. Message:" + createResponse.Message); } InputTextField color = new InputTextField(); color.Id = new Guid("2B4AACD9-3C34-4C44-B3A3-8AFF1520CFF6"); color.Name = "color"; color.Label = "Color"; color.PlaceholderText = ""; color.Description = ""; color.HelpText = ""; color.Required = true; color.Unique = false; color.Searchable = false; color.Auditable = false; color.System = true; color.DefaultValue = "teal"; color.MaxLength = null; { var createResponse = entMan.CreateField(SystemIds.AreaEntityId, color, false); if (!createResponse.Success) throw new Exception("System error 10340. Message:" + createResponse.Message); } InputTextField label = new InputTextField(); label.Id = new Guid("F050E7A1-AFB7-4346-B57B-1F12B2BD5AE5"); label.Name = "label"; label.Label = "Label"; label.PlaceholderText = ""; label.Description = ""; label.HelpText = ""; label.Required = true; label.Unique = false; label.Searchable = false; label.Auditable = false; label.System = true; label.DefaultValue = "Default"; label.MaxLength = null; { var createResponse = entMan.CreateField(SystemIds.AreaEntityId, label, false); if (!createResponse.Success) throw new Exception("System error 10340. Message:" + createResponse.Message); } InputTextField iconName = new InputTextField(); iconName.Id = new Guid("5EA0C872-D219-4D94-9EFA-C5DA978D316B"); iconName.Name = "icon_name"; iconName.Label = "Icon Name"; iconName.PlaceholderText = ""; iconName.Description = ""; iconName.HelpText = ""; iconName.Required = true; iconName.Unique = false; iconName.Searchable = false; iconName.Auditable = false; iconName.System = true; iconName.DefaultValue = "database"; iconName.MaxLength = null; { var createResponse = entMan.CreateField(SystemIds.AreaEntityId, iconName, false); if (!createResponse.Success) throw new Exception("System error 10340. Message:" + createResponse.Message); } InputNumberField weight = new InputNumberField(); weight.Id = new Guid("9B169431-6C31-4141-80EB-5844B8333E63"); weight.Name = "weight"; weight.Label = "Weight"; weight.PlaceholderText = ""; weight.Description = ""; weight.HelpText = ""; weight.Required = true; weight.Unique = false; weight.Searchable = false; weight.Auditable = false; weight.System = true; weight.DefaultValue = 10; weight.MinValue = 0; weight.DecimalPlaces = 2; { var createResponse = entMan.CreateField(SystemIds.AreaEntityId, weight, false); if (!createResponse.Success) throw new Exception("System error 10340. Message:" + createResponse.Message); } InputTextField attachments = new InputTextField(); attachments.Id = new Guid("288EA657-C12C-4AC1-B701-81D6F9F39363"); attachments.Name = "attachments"; attachments.Label = "Attachments JSON String"; attachments.PlaceholderText = ""; attachments.Description = "Stringified Array of attached objects"; attachments.HelpText = ""; attachments.Required = false; attachments.Unique = false; attachments.Searchable = false; attachments.Auditable = false; attachments.System = true; attachments.DefaultValue = null; attachments.MaxLength = null; { var createResponse = entMan.CreateField(SystemIds.AreaEntityId, attachments, false); if (!createResponse.Success) throw new Exception("System error 10340. Message:" + createResponse.Message); } InputTextField name = new InputTextField(); name.Id = new Guid("F297577B-073E-4D18-81F3-675C1AFB466D"); name.Name = "name"; name.Label = "Name"; name.PlaceholderText = ""; name.Description = ""; name.HelpText = ""; name.Required = true; name.Unique = false; name.Searchable = false; name.Auditable = false; name.System = true; name.DefaultValue = "default"; name.MaxLength = null; { var createResponse = entMan.CreateField(SystemIds.AreaEntityId, name, false); if (!createResponse.Success) throw new Exception("System error 10340. Message:" + createResponse.Message); } InputTextField roles = new InputTextField(); roles.Id = new Guid("8E486F76-D0C1-4D0E-8617-9EF868BF1C55"); roles.Name = "roles"; roles.Label = "Roles JSON String"; roles.PlaceholderText = ""; roles.Description = "Stringified Array of roles that have access to this area"; roles.HelpText = ""; roles.Required = false; roles.Unique = false; roles.Searchable = false; roles.Auditable = false; roles.System = true; roles.DefaultValue = null; roles.MaxLength = null; { var createResponse = entMan.CreateField(SystemIds.AreaEntityId, roles, false); if (!createResponse.Success) throw new Exception("System error 10340. Message:" + createResponse.Message); } #region << folder >> { InputTextField textboxField = new InputTextField(); textboxField.Id = new Guid("6a0fdf14-2d2b-4c6c-b2f1-4d846c7d5ab8"); textboxField.Name = "folder"; textboxField.Label = "folder"; textboxField.PlaceholderText = ""; textboxField.Description = ""; textboxField.HelpText = ""; textboxField.Required = false; textboxField.Unique = false; textboxField.Searchable = false; textboxField.Auditable = false; textboxField.System = true; textboxField.DefaultValue = string.Empty; textboxField.MaxLength = null; textboxField.EnableSecurity = true; textboxField.Permissions = new FieldPermissions(); textboxField.Permissions.CanRead = new List<Guid>(); textboxField.Permissions.CanUpdate = new List<Guid>(); //READ textboxField.Permissions.CanRead.Add(SystemIds.AdministratorRoleId); //UPDATE textboxField.Permissions.CanUpdate.Add(SystemIds.AdministratorRoleId); { var createResponse = entMan.CreateField(SystemIds.AreaEntityId, textboxField, false); if (!createResponse.Success) throw new Exception("System error 10060. Entity: area Field: folder" + " Message:" + response.Message); } } #endregion } #endregion } if (currentVersion < 20160430) { systemSettings.Version = 20160430; #region << plugin_data >> var PLUGIN_DATA_ID = new Guid("d928d031-c8b1-4359-be3e-39bceb58f268"); var PLUGIN_DATA_NAME = "plugin_data"; { #region << entity >> { InputEntity entity = new InputEntity(); entity.Id = PLUGIN_DATA_ID; entity.Name = PLUGIN_DATA_NAME; entity.Label = "Plugin Data"; entity.LabelPlural = "Plugin Data"; entity.System = true; entity.IconName = "database"; entity.Weight = 99; entity.RecordPermissions = new RecordPermissions(); entity.RecordPermissions.CanCreate = new List<Guid>(); entity.RecordPermissions.CanRead = new List<Guid>(); entity.RecordPermissions.CanUpdate = new List<Guid>(); entity.RecordPermissions.CanDelete = new List<Guid>(); //Create entity.RecordPermissions.CanCreate.Add(SystemIds.AdministratorRoleId); //READ entity.RecordPermissions.CanRead.Add(SystemIds.AdministratorRoleId); //UPDATE entity.RecordPermissions.CanUpdate.Add(SystemIds.AdministratorRoleId); //DELETE entity.RecordPermissions.CanDelete.Add(SystemIds.AdministratorRoleId); var systemItemIdDictionary = new Dictionary<string, Guid>(); systemItemIdDictionary["id"] = new Guid("bdb47d11-b8ee-42e9-8cd1-56e43246656b"); systemItemIdDictionary["created_on"] = new Guid("00f172b1-393b-4674-b6cd-32669dfb0924"); systemItemIdDictionary["created_by"] = new Guid("89379dbe-98ea-40b0-a794-a7cbf36201af"); systemItemIdDictionary["last_modified_on"] = new Guid("aaee0db8-d131-4273-b06a-a788757e24c3"); systemItemIdDictionary["last_modified_by"] = new Guid("eb0d2a71-4172-4293-87d7-d238a2153abf"); systemItemIdDictionary["user_plugin_data_created_by"] = new Guid("00e3f673-9dbc-4b57-b6d8-38d75e7d165a"); systemItemIdDictionary["user_plugin_data_modified_by"] = new Guid("c228125d-066c-415b-8c2a-a43ba2774411"); { var createResponse = entMan.CreateEntity(entity, false, false, systemItemIdDictionary); if (!createResponse.Success) throw new Exception("System error 10050. Entity: " + PLUGIN_DATA_NAME + " Field: entity creation" + " Message:" + response.Message); } } #endregion #region << name >> { InputTextField textboxField = new InputTextField(); textboxField.Id = new Guid("ab81aec7-da90-4ba8-8ac7-378faa01763f"); textboxField.Name = "name"; textboxField.Label = "Name"; textboxField.PlaceholderText = ""; textboxField.Description = ""; textboxField.HelpText = ""; textboxField.Required = true; textboxField.Unique = true; textboxField.Searchable = false; textboxField.Auditable = false; textboxField.System = true; textboxField.DefaultValue = string.Empty; textboxField.MaxLength = null; textboxField.EnableSecurity = true; textboxField.Permissions = new FieldPermissions(); textboxField.Permissions.CanRead = new List<Guid>(); textboxField.Permissions.CanUpdate = new List<Guid>(); //READ textboxField.Permissions.CanRead.Add(SystemIds.AdministratorRoleId); //UPDATE textboxField.Permissions.CanUpdate.Add(SystemIds.AdministratorRoleId); { var createResponse = entMan.CreateField(PLUGIN_DATA_ID, textboxField, false); if (!createResponse.Success) throw new Exception("System error 10060. Entity: " + PLUGIN_DATA_NAME + " Field: field_name" + " Message:" + response.Message); } } #endregion #region << data >> { InputTextField textboxField = new InputTextField(); textboxField.Id = new Guid("52a799ad-80a3-404b-99b5-1f58ce437982"); textboxField.Name = "data"; textboxField.Label = "Data"; textboxField.PlaceholderText = ""; textboxField.Description = ""; textboxField.HelpText = ""; textboxField.Required = false; textboxField.Unique = false; textboxField.Searchable = false; textboxField.Auditable = false; textboxField.System = true; textboxField.DefaultValue = string.Empty; textboxField.MaxLength = null; textboxField.EnableSecurity = true; textboxField.Permissions = new FieldPermissions(); textboxField.Permissions.CanRead = new List<Guid>(); textboxField.Permissions.CanUpdate = new List<Guid>(); //READ textboxField.Permissions.CanRead.Add(SystemIds.AdministratorRoleId); //UPDATE textboxField.Permissions.CanUpdate.Add(SystemIds.AdministratorRoleId); { var createResponse = entMan.CreateField(PLUGIN_DATA_ID, textboxField, false); if (!createResponse.Success) throw new Exception("System error 10060. Entity: " + PLUGIN_DATA_NAME + " Field: field_name" + " Message:" + response.Message); } } #endregion } #endregion } new DbSystemSettingsRepository().Save(new DbSystemSettings { Id = systemSettings.Id, Version = systemSettings.Version }); connection.CommitTransaction(); } catch (Exception ex) { var exception = ex; connection.RollbackTransaction(); throw; } } //recMan.ConvertNtoNRelations(); }
private void AddForeignsUpdate(DbCommand cmd, EntityRecord entityRecord) { var sbUpdates = new StringBuilder(); var paramIndex = cmd.Parameters.Count; foreach (var propertyValue in entityRecord.Values .WhereOneToMany() .Where(value => value.Values.IsNullOrEmpty() == false)) { var values = propertyValue.Values.Select( x => x.ToStringSafe().Split(Const.KeyColSeparator).Select(y => y.Trim()).ToList()).ToList(); var whereParts = new List<string>(); for (int i = 0; i < propertyValue.Property.ForeignEntity.Key.Count; i++) { var key = propertyValue.Property.ForeignEntity.Key[i]; var joinedValues = string.Join(",", values.Select(x => "@" + paramIndex++)); whereParts.Add("{0} In ({1})".Fill(key.Column, joinedValues)); cmd.AddParams(values.Select(x => x[i]).OfType<object>().ToArray()); } var constraintSeparator = Environment.NewLine + " AND "; var constraints = string.Join(constraintSeparator, whereParts); sbUpdates.AppendLine(); var table = propertyValue.Property.ForeignEntity.Table; var foreignKey = entityRecord.Entity.Key.FirstOrDefault().Column; sbUpdates.Append($@"UPDATE {table} SET {foreignKey} = @newID WHERE {constraints};"); } cmd.CommandText += sbUpdates.ToString(); }