public ApiController(IWebHookService hooksService) { recMan = new RecordManager(); secMan = new SecurityManager(); entMan = new EntityManager(); relMan = new EntityRelationManager(); this.hooksService = hooksService; }
public bool Run(SynchronizationContext syncCtx, SendOrPostCallback callback) { foreach (string deviceName in selectedDevices.Keys) { DeviceRunContext context = this.selectedDevices[deviceName]; context.SynchronizationContext = syncCtx; context.Callback = callback; this.RunDevice(context); } RecordManager.DoSystemEventRecord(Device.Main, "Devices are running now.", RecordType.Event); return(true); }
public void SetStatus(Guid taskId, Guid statusId) { var patchRecord = new EntityRecord(); patchRecord["id"] = taskId; patchRecord["status_id"] = statusId; var updateResponse = new RecordManager().UpdateRecord("task", patchRecord); if (!updateResponse.Success) { throw new Exception(updateResponse.Message); } }
public void StartTaskTimelog(Guid taskId) { var patchRecord = new EntityRecord(); patchRecord["id"] = taskId; patchRecord["timelog_started_on"] = DateTime.Now; var updateResponse = new RecordManager().UpdateRecord("task", patchRecord); if (!updateResponse.Success) { throw new Exception(updateResponse.Message); } }
public static void Init() { GameObject obj = new GameObject("[AudioManager]"); AudioPlayManager audioManager = obj.AddComponent <AudioPlayManager>(); DontDestroyOnLoad(obj); a2DPlayer = new Audio2DPlayer(audioManager); a3DPlayer = new Audio3DPlayer(audioManager); TotleVolume = RecordManager.GetFloatRecord("GameSettingData", "TotleVolume", 1f); MusicVolume = RecordManager.GetFloatRecord("GameSettingData", "MusicVolume", 1f); SFXVolume = RecordManager.GetFloatRecord("GameSettingData", "SFXVolume", 1f); }
static int CleanCache(IntPtr L) { try { ToLua.CheckArgsCount(L, 0); RecordManager.CleanCache(); return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public IActionResult OnPost() { var initResult = Init(); if (initResult != null) { return(initResult); } PageInit(); if (Record == null) { return(NotFound()); } try { Record = (EntityRecord) new PageService().ConvertFormPostToEntityRecord(PageContext.HttpContext, RecordId, ErpEntity); //clear empty password properties from record, only update if new password is set //this is because browsers don't render password inputs and don't submit any value, if no user input Fields.Where(x => x.GetFieldType() == FieldType.PasswordField && string.IsNullOrWhiteSpace((string)Record[x.Name])) .ToList() .ForEach(x => Record.Properties.Remove(x.Name)); var response = new RecordManager().UpdateRecord(ErpEntity, Record); if (!response.Success) { var exception = new ValidationException(response.Message); exception.Errors = response.Errors.MapTo <ValidationError>(); throw exception; } return(Redirect(ReturnUrl)); } catch (ValidationException ex) { Validation.Message = ex.Message; Validation.Errors = ex.Errors; } catch (Exception ex) { Validation.Message = ex.Message; Validation.Errors.Add(new ValidationError("", ex.Message, isSystem: true)); } ErpRequestContext.PageContext = PageContext; BeforeRender(); return(Page()); }
public string SelectMap(string digitMean) { quit = false; int numLabel = (edLine - stLine - 1) / (1 + l); if (numLabel == 0) { quit = true; return(""); } // 모든 label 알아내기 CryptoGrapher.ReadFile(ref buffer, FILENAME); string[] labels = new string[numLabel]; for (int i = 0; i < numLabel; ++i) { int labelLine = stLine + 1 + i * (1 + l); labels[i] = buffer[labelLine].Substring(2); } while (Console.KeyAvailable) { Console.ReadKey(true); } while (true) { ShowMap(labels[cur], 0, 0); ConsoleKeyInfo cki = Console.ReadKey(true); string s = cki.Key.ToString(); if (s == "Enter" || s == "Spacebar") { return(labels[cur]); } else if (s == "R") { RecordManager r = new RecordManager(game); r.ShowRecord(labels[cur], digitMean); MyFunction.WaitForExit(); } else if (s == "LeftArrow") { cur = (cur - 1 + numLabel) % numLabel; } else if (s == "RightArrow") { cur = (cur + 1) % numLabel; } else if (s == "Q") { quit = true; return(""); } } }
public void CreateRecordsWithoutRequiredParameterTest(int number) { var connection = PrivateApiConnection.GetConnectionForCurrentTest(); // the way to obtain a connection, created for test. Dictionary <string, int> fields = null; using (LogHelper.LoggerForCurrentTest.EnterReproStep("Reading required info")) { var fieldHandler = new FieldManager(connection); fields = fieldHandler.GetFieldGuid(new[] { "P_Name", "P_Owner" }, new[] { Porters.TestCoreFramework.Enums.ResourceType.Client }) .Result.Result.ToDictionary(x => $"{char.ToUpper(x.Resource[0]) + x.Resource.Substring(1)}.{x.Alias}", x => (int)UuidUtil.GetId(x.Id)); } PrAssume.That(fields, PrIs.Not.Null.And.Count.EqualTo(2)); //create var recordHandler = new RecordManager(connection); var response = recordHandler.WriteRecords(new RecordsCreateRequestItem // creating a request object manually { Data = new List <RecordsCreateRequestItem.RecordsCreateItem> { new RecordsCreateRequestItem.RecordsCreateItem { Resource = (int)Porters.TestCoreFramework.Enums.ResourceType.Client, Properties = new List <Dictionary <int, object> > { new Dictionary <int, object> { [-1] = "Client Test Name new ", [int.MinValue] = 1, [int.MaxValue] = "Test value in non existing field" } } }, new RecordsCreateRequestItem.RecordsCreateItem { Resource = (int)Porters.TestCoreFramework.Enums.ResourceType.Client, Properties = new List <Dictionary <int, object> > { new Dictionary <int, object> { [fields["Client.P_Name"]] = "Client Test Name new ", [0] = 1 } } } } }); // example of complex assert (it is preferable to use one complex, instead of several simple) PrAssert.That(response, PrIs.ErrorResponse().And.ErrorCode(106).And.HttpCode(400)); }
public RecordApi( UserManager <UserInfo> userManager, SignInManager <UserInfo> signInManager, IOptions <IdentityCookieOptions> identityCookieOptions, ILoggerFactory loggerFactory, IOptions <ConnectionInfo> config) { _userManager = userManager; _signInManager = signInManager; _externalCookieScheme = identityCookieOptions.Value.ExternalCookieAuthenticationScheme; _logger = loggerFactory.CreateLogger <AccountApiController>(); _userInfoManager = new UserInfoManager(config); _recordManager = new RecordManager(config); }
void Awake() { if (Instance == null) { DontDestroyOnLoad(gameObject); Instance = this; } else if (Instance != this) { Destroy(gameObject); } LoadRecords(); }
public void StopTaskTimelog(Guid taskId) { //Create transaction var patchRecord = new EntityRecord(); patchRecord["id"] = taskId; patchRecord["timelog_started_on"] = null; var updateResponse = new RecordManager().UpdateRecord("task", patchRecord); if (!updateResponse.Success) { throw new Exception(updateResponse.Message); } }
public static void Init() { if (!isInit) { isInit = true; s_favoritesList = new List<string>(); RecordTable data = RecordManager.GetData(c_recordName); foreach (var item in data) { s_favoritesList.Add(item.Key); } } }
private void OnGUI() { if (GUI.Button(new Rect(10, 10, 100, 20), "Test")) { AudioPlayManager.TotleVolume = 0.7f; AudioPlayManager.SaveVolume(); Debug.Log("保存成功"); } if (GUI.Button(new Rect(10, 40, 100, 20), "Result")) { Debug.Log("读取值:" + RecordManager.GetFloatRecord("GameSettingData", "TotleVolume", 1f)); } }
public ReportViewModel(IStatisticProvider frametimeStatisticProvider, IEventAggregator eventAggregator, IAppConfiguration appConfiguration, RecordManager recordManager) { _frametimeStatisticProvider = frametimeStatisticProvider; _eventAggregator = eventAggregator; _appConfiguration = appConfiguration; _recordManager = recordManager; CopyTableDataCommand = new DelegateCommand(OnCopyTableData); ReportInfoCollection.CollectionChanged += new NotifyCollectionChangedEventHandler ((sender, eventArg) => HasNoReportItems = !ReportInfoCollection.Any()); SubscribeToSelectRecord(); }
public static void TestsSetup() { if (ImageFileIds == null) { ImageFileIds = UploadImageFiles(); } AttachmentFileIds = new Dictionary <ResourceId, Dictionary <FileType, int> >(); var connection = PrivateApiConnection.GetConnectionForCurrentTest(); var fileManager = new LegacyFileManager(connection); var fieldManager = new FieldManager(connection); var recordManager = new RecordManager(connection); foreach (var resource in Enum.GetValues(typeof(ResourceId)).Cast <ResourceId>().Except(new[] { ResourceId.None })) { AttachmentFileIds.Add(resource, new Dictionary <FileType, int>()); var recordId = RecordsCreator.Data[$"{resource}"].Id; var requiredFields = ResourceMandatoryFields[resource](false).Keys.Concat(SearchConstants.SystemFieldsValues[resource].Values); var fieldIs = fieldManager.GetFieldGuid(requiredFields, new[] { (TestCoreFramework.Enums.ResourceType)((int)resource) }).Result.Result.ToDictionary(x => x.Alias, x => UuidUtil.GetId(x.Id)); var record = recordManager.ReadRecords(new RecordsHandlingComponent.DataContract.RecordsGetRequestItem { Fields = string.Join(",", requiredFields.Select(x => resource + "." + x)), Resource = (TestCoreFramework.Enums.ResourceType)((int)resource), IdList = new List <int> { Convert.ToInt32(recordId) } }).Result.Items.Single(); var files = ImageFileIds[resource].ToDictionary(x => FieldCreator.Data[$"{resource}_File_{x.Key}"].Id, x => x.Value); fileManager.AssociateFilesAndRecord(resource, Convert.ToInt32(recordId), fieldIs.ToDictionary(x => x.Value, x => (object)GetStringRepresentation(record[$"{resource}.{x.Key}"])), files.ToArray()); //apparently, Contract has no sublist to upload attachment to if (resource != ResourceId.Contract) { foreach (var fileType in FileTypesToTest) { var fileInfo = CommonConstants.Files[fileType]; var fileName = fileInfo.Location.Split('/').Last().Replace("file", "attachment_file"); fileName = OverrideExtensionFileTypes.Contains(fileType) ? fileName.Replace("." + fileInfo.Extension, ".txt") : fileName; AttachmentFileIds[resource][fileType] = fileManager.UploadFileAsAttachment(fileInfo.Location, ((int)resource).ToString(), recordId.ToString(), fileName); } } } }
static int CleanRecord(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); string arg0 = ToLua.CheckString(L, 1); RecordManager.CleanRecord(arg0); return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int SaveData(IntPtr L) { try { ToLua.CheckArgsCount(L, 2); string arg0 = ToLua.CheckString(L, 1); RecordTable arg1 = (RecordTable)ToLua.CheckObject(L, 2, typeof(RecordTable)); RecordManager.SaveData(arg0, arg1); return(0); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
static int GetData(IntPtr L) { try { ToLua.CheckArgsCount(L, 1); string arg0 = ToLua.CheckString(L, 1); RecordTable o = RecordManager.GetData(arg0); ToLua.PushObject(L, o); return(1); } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public CollectionEnumerator( Collection collection, Session session, RecordManager recordManager, IObjectSerializer <T> serializer, string indexName, bool IsDescending = false ) : base(session) { this.Collection = collection; this.RecordManager = recordManager; this.Serializer = serializer; this.IndexName = indexName; this.IsDescending = IsDescending; }
internal virtual void UnRegisterKey(object key, Int64 address, Session session, RecordManager recordManager, string indexName) { var index = new RecordIndex <ValueWithAddressIndexKey <TAttribute> >( this.Session, this.RecordManager, indexName, this.Session.SerializerResolver.SerializerFor <Node <ValueWithAddressIndexKey <TAttribute> > >() ); index.UnRegister((ValueWithAddressIndexKey <TAttribute>)key); }
void Start() { GetComponent <Button>().onClick.AddListener(() => { if (RecordManager.tempRecord.showedInstrument != null && RecordManager.tempRecord.showedInstrument.instrumentType != null) { Main.m_Entity.HideEntity(GameManager.Instance.CurrentInstrument); } CreateObject.HideCurrent(); CreateInstrument.HideCurrent(); RecordManager.ClearTempRecord(); GameManager.Instance.SwitchProcedure <AddValueProcedure>(); }); }
private void stopMenuItem_Click(object sender, EventArgs e) { this.quitByUser = true; this.deviceRunning = false; this.startToolBarButton.Enabled = true; // deviceListView.Enabled = true; this.UpdateDevicesWaitStatus(); this.cmdReceiver.Close(); Program.DeviceManager.CloseAllDevices(); RecordManager.DoSystemEventRecord(Device.Main, "User Stopped the devices"); Program.Exit(); // For quit Mutex; Program.DeviceManager.OpenMainProgram(); Application.Exit(); }
internal override void UnRegisterKey(object key, Int64 address, Session session, RecordManager recordManager, string indexName) { var index = new RecordIndex <TID>( this.Session, recordManager, indexName, this.Session.SerializerResolver.SerializerFor <Node <TID> >() ); index.UnRegister((TID)key); }
public void RenameMap(string label, string newLabel) // Map상의 label 수정 { bool res = ReadLabel(label, l); if (!res) { DeleteMap(label); return; } buffer[labelLine] = "//" + newLabel; CryptoGrapher.WriteFile(buffer, FILENAME); // Record상의 label 수정 RecordManager r = new RecordManager(game); r.ModifyRecord(label, newLabel); }
public void InsertInvalidPhaseDateRecordTest(TestCoreFramework.Enums.ResourceType resourceId, int ownerId, ResourceFields.ValidPhase phase, ResourceFields.InvalidDateTime time) { var fieldHandler = new FieldManager(); var fields = fieldHandler.GetFieldGuid(ResourceFields.RequireFields[resourceId], new[] { resourceId }) .Result.Result.ToDictionary(x => $"{char.ToUpper(x.Resource[0]) + x.Resource.Substring(1)}.{x.Alias}", x => (int)UuidUtil.GetId(x.Id)); var recordHandler = new RecordManager(); var request = RecordRequestComposer.ComposeCreateRequest() .Append(resourceId, CreateResourceRequiredFieldData(fields, resourceId, ownerId, phase, time)) .Result; var response = recordHandler.WriteRecords(request); PrAssert.That(response, PrIs.ErrorResponse()); }
public void CauseStrike(string reason) { StrikeSource strikeSource = new StrikeSource(); strikeSource.ComponentType = Assets.Scripts.Missions.ComponentTypeEnum.Mod; strikeSource.InteractionType = Assets.Scripts.Records.InteractionTypeEnum.Other; strikeSource.Time = CurrentTimerElapsed; strikeSource.ComponentName = reason; RecordManager recordManager = RecordManager.Instance; recordManager.RecordStrike(strikeSource); Bomb.OnStrike(null); }
public void SaveEmail(Email email) { PrepareEmailXSearch(email); RecordManager recMan = new RecordManager(); var response = recMan.Find(new EntityQuery("email", "*", EntityQuery.QueryEQ("id", email.Id))); if (response.Object != null && response.Object.Data != null && response.Object.Data.Count != 0) { recMan.UpdateRecord("email", email.MapTo <EntityRecord>()); } else { recMan.CreateRecord("email", email.MapTo <EntityRecord>()); } }
private void Awake() { sceneManager = FindObjectOfType <SceneManager>(); recordManager = new RecordManager(); if (sceneManager == null) { throw new Exception("No se encontro el SceneManager"); } OnStartGame += StartGame; OnExitGame += ExitGame; SetBestScore(); }
public Node <TNodeKey> CreateNode(int degree, bool allowRecordReuse = true) { var node = new Node <TNodeKey>(degree); var data = Serializer.Serialize(node); var allocationStrategy = this.Session.AllocationStrategyResolver.StrategyFor(node); var record = RecordManager.AppendRecord(data, allocationStrategy, allowRecordReuse); node.Address = record.Header.Address; this.MetaRecord.NumberOfNodes++; CacheNode(node); return(node); }
/// <summary> /// 根据bundleName获取加载路径 /// </summary> /// <param name="bundleName"></param> /// <returns></returns> static string GetBundlePath(ResourcesConfig config) { bool isLoadByPersistent = RecordManager.GetData(HotUpdateManager.c_HotUpdateRecordName).GetRecord(config.name, "null") == "null" ? false:true; ResLoadLocation loadType = ResLoadLocation.Streaming; //加载路径由 加载根目录 和 相对路径 合并而成 //加载根目录由配置决定 if (isLoadByPersistent) { loadType = ResLoadLocation.Persistent; } return(PathTool.GetAbsolutePath(loadType, config.path + "." + c_AssetsBundlesExpandName)); }
protected void FileSelectedCallback(string path) { m_fileBrowser = null; m_textPath = path; FileReadWriteManager fileManager = new FileReadWriteManager(); string content = fileManager.ReadTextFile (m_textPath); recordManager = new RecordManager(content); //Console.WriteLine("finish reading..."); //dispatch events if (RecordLoaded != null) { RecordLoaded(this, EventArgs.Empty); } Destroy(this); }
private void ViewRecord(object sender, EventArgs e) { RecordManager RecordManager = new RecordManager(this.Doctor, this.Patient, this.Record); RecordManager.Show(); }
private void SetupRecordManager() { this.recordManager = new RecordManager(); this.recordManager.Load(); }
void OnRecordLoaded(object sender, EventArgs e) { //test //Instantiate (obstacle,new Vector3(3,0,0),new Quaternion(-0.707f,0,0,0.707f)); recordManager = GameObject.Find("Canvas").GetComponent<TextFileFinder>().recordManager; //TODO: test if cancel InitBattleMap(); enable_update = true; }
// Use this for initialization void Start() { transitionDone = true; totalLevels = Constants.lastPlayableSceneIndex - Constants.introSceneIndex; recordManager = gameObject.GetComponent("RecordManager") as RecordManager; currentLevel = 1; last = currentLevel; display = last; if (spacing == 0) spacing = 0.5f; backButtonTextScript = backButton.GetComponent("TextScript") as TextScript; nextButtonTextScript = nextButton.GetComponent("TextScript") as TextScript; instantiateTexts(); initTextScripts(); initTransitionValues(); initIsDoneTransition(); }
void Awake() { _instance = this; }
public IActionResult UpdateEntityRelationRecordReverse([FromBody]InputEntityRelationRecordReverseUpdateModel model) { var recMan = new RecordManager(); var entMan = new EntityManager(); BaseResponseModel response = new BaseResponseModel { Timestamp = DateTime.UtcNow, Success = true, Errors = new List<ErrorModel>() }; if (model == null) { response.Errors.Add(new ErrorModel { Message = "Invalid model." }); response.Success = false; return DoResponse(response); } EntityRelation relation = null; if (string.IsNullOrWhiteSpace(model.RelationName)) { response.Errors.Add(new ErrorModel { Message = "Invalid relation name.", Key = "relationName" }); response.Success = false; return DoResponse(response); } else { relation = new EntityRelationManager().Read(model.RelationName).Object; if (relation == null) { response.Errors.Add(new ErrorModel { Message = "Invalid relation name. No relation with that name.", Key = "relationName" }); response.Success = false; return DoResponse(response); } } var originEntity = entMan.ReadEntity(relation.OriginEntityId).Object; var targetEntity = entMan.ReadEntity(relation.TargetEntityId).Object; var originField = originEntity.Fields.Single(x => x.Id == relation.OriginFieldId); var targetField = targetEntity.Fields.Single(x => x.Id == relation.TargetFieldId); if (model.DetachOriginFieldRecordIds != null && model.DetachOriginFieldRecordIds.Any() && originField.Required && relation.RelationType != EntityRelationType.ManyToMany) { response.Errors.Add(new ErrorModel { Message = "Cannot detach records, when origin field is required.", Key = "originFieldRecordId" }); response.Success = false; return DoResponse(response); } ////////////////////////////////////////////////////////////////////////////////////// //WEBHOOK FILTER << manage_relation_input_filter >> ////////////////////////////////////////////////////////////////////////////////////// try { //Hook for the origin entity dynamic hookFilterObj = new ExpandoObject(); hookFilterObj.record = model; hookFilterObj.direction = "target-origin"; hookFilterObj.relation = relation; hookFilterObj.originEntity = originEntity; hookFilterObj.targetEntity = targetEntity; hookFilterObj.controller = this; hookFilterObj = hooksService.ProcessFilters(SystemWebHookNames.ManageRelationInput, originEntity.Name, hookFilterObj); model = hookFilterObj.record; //Hook for the target entity hookFilterObj = new ExpandoObject(); hookFilterObj.record = model; hookFilterObj.direction = "target-origin"; hookFilterObj.relation = relation; hookFilterObj.originEntity = originEntity; hookFilterObj.targetEntity = targetEntity; hookFilterObj.controller = this; hookFilterObj = hooksService.ProcessFilters(SystemWebHookNames.ManageRelationInput, targetEntity.Name, hookFilterObj); model = hookFilterObj.record; } catch (Exception ex) { return Json(CreateErrorResponse("Plugin error in web hook manage_relation_input_filter: " + ex.Message)); }// <<< EntityQuery query = new EntityQuery(targetEntity.Name, "id," + targetField.Name, EntityQuery.QueryEQ("id", model.TargetFieldRecordId), null, null, null); QueryResponse result = recMan.Find(query); if (result.Object.Data.Count == 0) { response.Errors.Add(new ErrorModel { Message = "Target record was not found. Id=[" + model.TargetFieldRecordId + "]", Key = "targetFieldRecordId" }); response.Success = false; return DoResponse(response); } var targetRecord = result.Object.Data[0]; object targetValue = targetRecord[targetField.Name]; var attachOriginRecords = new List<EntityRecord>(); var detachOriginRecords = new List<EntityRecord>(); foreach (var originId in model.AttachOriginFieldRecordIds) { query = new EntityQuery(originEntity.Name, "id," + originField.Name, EntityQuery.QueryEQ("id", originId), null, null, null); result = recMan.Find(query); if (result.Object.Data.Count == 0) { response.Errors.Add(new ErrorModel { Message = "Attach origin record was not found. Id=[" + originEntity.Id + "]", Key = "originRecordId" }); response.Success = false; return DoResponse(response); } else if (attachOriginRecords.Any(x => (Guid)x["id"] == originId)) { response.Errors.Add(new ErrorModel { Message = "Attach origin id was duplicated. Id=[" + originEntity.Id + "]", Key = "originRecordId" }); response.Success = false; return DoResponse(response); } attachOriginRecords.Add(result.Object.Data[0]); } foreach (var originId in model.DetachOriginFieldRecordIds) { query = new EntityQuery(originEntity.Name, "id," + originField.Name, EntityQuery.QueryEQ("id", originId), null, null, null); result = recMan.Find(query); if (result.Object.Data.Count == 0) { response.Errors.Add(new ErrorModel { Message = "Detach origin record was not found. Id=[" + originEntity.Id + "]", Key = "originRecordId" }); response.Success = false; return DoResponse(response); } else if (detachOriginRecords.Any(x => (Guid)x["id"] == originId)) { response.Errors.Add(new ErrorModel { Message = "Detach origin id was duplicated. Id=[" + originEntity.Id + "]", Key = "originRecordId" }); response.Success = false; return DoResponse(response); } detachOriginRecords.Add(result.Object.Data[0]); } using (var connection = DbContext.Current.CreateConnection()) { connection.BeginTransaction(); ////////////////////////////////////////////////////////////////////////////////////// //WEBHOOK FILTER << manage_relation_pre_save_filter >> ////////////////////////////////////////////////////////////////////////////////////// try { //Hook for the origin entity dynamic hookFilterObj = new ExpandoObject(); hookFilterObj.direction = "target-origin"; hookFilterObj.attachOriginRecords = attachOriginRecords; hookFilterObj.detachOriginRecords = detachOriginRecords; hookFilterObj.targetRecord = targetRecord; hookFilterObj.originEntity = originEntity; hookFilterObj.targetEntity = targetEntity; hookFilterObj.relation = relation; hookFilterObj.controller = this; hookFilterObj = hooksService.ProcessFilters(SystemWebHookNames.ManageRelationPreSave, originEntity.Name, hookFilterObj); attachOriginRecords = hookFilterObj.attachOriginRecords; detachOriginRecords = hookFilterObj.detachOriginRecords; //Hook for the target entity hookFilterObj = new ExpandoObject(); hookFilterObj.direction = "target-origin"; hookFilterObj.attachOriginRecords = attachOriginRecords; hookFilterObj.detachOriginRecords = detachOriginRecords; hookFilterObj.targetRecord = targetRecord; hookFilterObj.originEntity = originEntity; hookFilterObj.targetEntity = targetEntity; hookFilterObj.relation = relation; hookFilterObj.controller = this; hookFilterObj = hooksService.ProcessFilters(SystemWebHookNames.ManageRelationPreSave, targetEntity.Name, hookFilterObj); attachOriginRecords = hookFilterObj.attachOriginRecords; detachOriginRecords = hookFilterObj.detachOriginRecords; } catch (Exception ex) { return Json(CreateErrorResponse("Plugin error in web hook manage_relation_pre_save_filter: " + ex.Message)); }// <<< try { switch (relation.RelationType) { case EntityRelationType.OneToOne: case EntityRelationType.OneToMany: { foreach (var record in detachOriginRecords) { record[originField.Name] = null; var updResult = recMan.UpdateRecord(originEntity, record); if (!updResult.Success) { connection.RollbackTransaction(); response.Errors = updResult.Errors; response.Message = "Origin record id=[" + record["id"] + "] detach operation failed."; response.Success = false; return DoResponse(response); } } foreach (var record in attachOriginRecords) { var patchObject = new EntityRecord(); patchObject["id"] = (Guid)record["id"]; patchObject[originField.Name] = targetValue; var updResult = recMan.UpdateRecord(originEntity, patchObject); if (!updResult.Success) { connection.RollbackTransaction(); response.Errors = updResult.Errors; response.Message = "Origin record id=[" + record["id"] + "] attach operation failed."; response.Success = false; return DoResponse(response); } } } break; case EntityRelationType.ManyToMany: { foreach (var record in detachOriginRecords) { QueryResponse updResult = recMan.RemoveRelationManyToManyRecord(relation.Id, (Guid)record[originField.Name], (Guid)targetValue ); if (!updResult.Success) { connection.RollbackTransaction(); response.Errors = updResult.Errors; response.Message = "Origin record id=[" + record["id"] + "] detach operation failed."; response.Success = false; return DoResponse(response); } } foreach (var record in attachOriginRecords) { QueryResponse updResult = recMan.CreateRelationManyToManyRecord(relation.Id, (Guid)record[originField.Name], (Guid)targetValue); if (!updResult.Success) { connection.RollbackTransaction(); response.Errors = updResult.Errors; response.Message = "Origin record id=[" + record["id"] + "] attach operation failed."; response.Success = false; return DoResponse(response); } } } break; default: { connection.RollbackTransaction(); throw new Exception("Not supported relation type"); } } connection.CommitTransaction(); } catch (Exception ex) { connection.RollbackTransaction(); response.Success = false; response.Message = ex.Message; return DoResponse(response); } } ////////////////////////////////////////////////////////////////////////////////////// //WEBHOOK ACTION << manage_relation_success_action >> ////////////////////////////////////////////////////////////////////////////////////// try { dynamic hookActionObj = new ExpandoObject(); hookActionObj.record = model; hookActionObj.result = result; hookActionObj.relation = relation; hookActionObj.controller = this; hooksService.ProcessActions(SystemWebHookNames.ManageRelationAction, originEntity.Name, hookActionObj); hookActionObj = new ExpandoObject(); hookActionObj.record = model; hookActionObj.result = result; hookActionObj.relation = relation; hookActionObj.controller = this; hooksService.ProcessActions(SystemWebHookNames.ManageRelationAction, targetEntity.Name, hookActionObj); } catch (Exception ex) { return Json(CreateErrorResponse("Plugin error in web hook create_record_success_action: " + ex.Message)); }// <<< return DoResponse(response); }
protected void SmartWrites(RecordManager RM, ref bool WriteHandled) { if (!HasID && HasChanges) { throw new EIDObjectWithoutIDException("Can't write object without ID"); // ID = Guid.NewGuid(); // ??? } if (this is ISmartActiveRecord) { bool HasRef = false; foreach (PropType pt in ChangedProperties) { object v = null; if (ValueExists<ITrackChanges>(pt, out v) && (v as ITrackChanges).HasChanges) { InTable table = RM.ActiveRecordInfo(v.GetType(), false); if (table != null) if (table.Write(v, false) > 0) HasRef = true; ClearChanges(pt); } } WriteHandled = !(HasChanges || (HasRef && IsNewObject)); } }