public SearchNewDevicesResponse SearchNewDevices(SearchNewDevicesRequest request) { return(PersistenceOperation.Process(request, () => { var op = new DeviceOp(); var newDeviceIds = op.SearchNewDevices(); return new SearchNewDevicesResponse() { ResultType = ResultTypes.Ok, NewDeviceCodes = newDeviceIds }; })); }
public QueryDeviceUsersResponse QueryDeviceUsers(QueryDeviceUsersRequest request) { return(PersistenceOperation.Process(request, () => { if (WebSocketClientManager.GetInstance().GetClientById(request.Device.Code.ToInt32()) == null) { var msg = string.Format("设备:[{0}]未连接", string.Join(",", request.Device.Name)); return new QueryDeviceUsersResponse() { ResultType = ResultTypes.DeviceNotConnected, Messages = new[] { msg } }; } var userDtos = new List <DeviceUserDto>(); var deviceUsers = new List <UserInfo>(); var op = new DeviceUserOp(); if (!string.IsNullOrWhiteSpace(request.UserCode)) { var userRepo = RepositoryManager.GetRepository <IUserRepository>(); var userInfo = userRepo.QueryUsersForSummaryData(new Hashtable() { { "UserCode", request.UserCode } }).FirstOrDefault(); if (userInfo != null) { var deviceUser = op.TryGetUesrInfo(userInfo, request.Device); if (deviceUser != null) { deviceUsers.Add(deviceUser); } } } else { deviceUsers = op.QueryUsersByDevice(request.Device); } if (deviceUsers != null) { deviceUsers.ForEach(x => userDtos.Add(new DeviceUserDto() { UserCode = x.UserId, UserName = string.IsNullOrWhiteSpace(x.UserName) ? "未命名人员" : x.UserName, })); } return new QueryDeviceUsersResponse() { ResultType = ResultTypes.Ok, Users = userDtos }; })); }
private bool InitializeProvider() { // We finally have the lock and are passed the guard. Let's update our operation if // this is an Unload. if (this.operation == PersistenceOperation.Unload && this.instance.Controller.State == WorkflowInstanceState.Complete) { this.operation = PersistenceOperation.Complete; } if (this.instance.HasPersistenceProvider && !this.instance.persistenceManager.IsInitialized) { var result = this.instance.persistenceManager.BeginInitialize(this.instance.DefinitionIdentity, this.timeoutHelper.RemainingTime(), this.PrepareAsyncCompletion(UnloadOrPersistAsyncResult.initializedCallback), this); return(this.SyncContinue(result)); } else { return(this.EnsureProviderReadyness()); } }
public SyncDevicesResponse SyncDevices(SyncDevicesRequest request) { return(PersistenceOperation.Process(request, () => { var newDeviceControllers = new List <DeviceController>(); var op = new DeviceOp(); var newDeviceIds = op.SearchNewDevices(); newDeviceIds.ForEach(x => { Log.InfoFormat("sync device id={0} to system", x); newDeviceControllers.Add(op.SyncDeviceToSystem(x)); Log.Info("sync device to system successfully"); }); return new SyncDevicesResponse() { ResultType = ResultTypes.Ok, NewDeviceControllers = newDeviceControllers }; })); }
public static void ProcessDeviceTrafficEvent(string message) { var ev = DataContractSerializationHelper.Deserialize <DeviceTrafficEvent>(message); PersistenceOperation.Process("", () => { var deviceControllerRepo = RepositoryManager.GetRepository <IDeviceControllerRepository>(); var deviceTrafficLogRepo = RepositoryManager.GetRepository <IDeviceTrafficLogRepository>(); var logInfo = new Rld.Acs.Model.DeviceTrafficLog(); logInfo.DeviceID = -1; logInfo.DeviceCode = ev.DeviceTrafficLog.DeviceId.ToString(); logInfo.DeviceUserID = ev.DeviceTrafficLog.UserId; logInfo.RecordType = ev.DeviceTrafficLog.AccessLogType.ToString(); logInfo.RecordTime = ev.DeviceTrafficLog.CreateTime; logInfo.RecordUploadTime = DateTime.Now; logInfo.Remark = ev.DeviceTrafficLog.Message; if (ev.DeviceTrafficLog.CheckInOptions.Any()) { logInfo.AuthenticationType = 0; ev.DeviceTrafficLog.CheckInOptions.ForEach(option => logInfo.AuthenticationType += (int)option); } var deviceInfo = deviceControllerRepo.Query(new Hashtable() { { "Code", ev.DeviceTrafficLog.DeviceId } }).FirstOrDefault(); if (deviceInfo != null) { logInfo.DeviceID = deviceInfo.DeviceID; logInfo.DeviceType = deviceInfo.Model; logInfo.DeviceSN = deviceInfo.SN; } deviceTrafficLogRepo.Insert(logInfo); return(new Message.ResponseBase()); }); }
bool OpenProvider() { if (this.operation == PersistenceOperation.Unload) { if (this.instance.state != State.Suspended && !this.instance.IsIdle) { if (this.isTry) { this.tryResult = false; return true; } // Force unload } // Release the last referenceCount if (!this.instance.TryReleaseLastReference()) { if (this.isTry) { this.tryResult = false; return true; } // Force unload } } // We finally have the lock and are passed the guard. Let's update our operation if this is an Unload. if (this.operation == PersistenceOperation.Unload && this.instance.Controller.State == WorkflowInstanceState.Complete) { this.operation = PersistenceOperation.Delete; } bool completedSync = false; if (this.instance.persistenceContext != null && this.instance.persistenceContext.State == CommunicationState.Created) { IAsyncResult result = this.instance.persistenceContext.BeginOpen(timeoutHelper.RemainingTime(), PrepareInnerAsyncCompletion(providerOpenedCallback), this); if (result.CompletedSynchronously) { completedSync = OnProviderOpened(result); } } else { completedSync = Track(); } return completedSync; }
public UnloadOrPersistAsyncResult(WorkflowServiceInstance instance, PersistenceOperation operation, bool isWorkflowThread, bool isTry, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { // The isTry flag is only true when this is an idle policy initiated persist/unload. Fx.Assert((isWorkflowThread && !isTry) || !isWorkflowThread, "Either we're the workflow thread and NOT a try or we're not a workflow thread."); this.instance = instance; this.timeoutHelper = new TimeoutHelper(timeout); this.operation = operation; this.isWorkflowThread = isWorkflowThread; this.isTry = isTry; this.tryResult = true; this.isUnloaded = (operation == PersistenceOperation.Unload || operation == PersistenceOperation.Delete); this.saveStatus = SaveStatus.Locked; this.isCompletionTransactionRequired = this.isUnloaded && instance.Controller.State == WorkflowInstanceState.Complete && instance.creationContext != null && instance.creationContext.IsCompletionTransactionRequired; this.isIdlePolicyPersist = isTry && operation == PersistenceOperation.Save; if (operation == PersistenceOperation.Unload) { this.saveStatus = SaveStatus.Unlocked; } else if (operation == PersistenceOperation.Delete) { this.saveStatus = SaveStatus.Completed; } else if (operation == PersistenceOperation.Save) { SetStartTime(); } // Save off the current transaction in case we have an async operation before we end up creating // the WorkflowPersistenceContext and create it on another thread. Do a simple clone here to prevent // the object referenced by Transaction.Current from disposing before we get around to referencing it // when we create the WorkflowPersistenceContext. // // This will throw TransactionAbortedException by design, if the transaction is already rolled back. Transaction currentTransaction = Transaction.Current; if (currentTransaction != null) { OnCompleting = UnloadOrPersistAsyncResult.completeCallback; this.dependentTransaction = currentTransaction.DependentClone(DependentCloneOption.BlockCommitUntilComplete); } bool completeSelf = true; bool success = false; try { if (this.isWorkflowThread) { Fx.Assert(this.instance.Controller.IsPersistable, "The runtime won't schedule this work item unless we've passed the guard"); // We're an internal persistence on the workflow thread which means // that we are passed the guard already, we have the lock, and we know // we aren't detached. completeSelf = OpenProvider(); } else { try { completeSelf = LockAndPassGuard(); } finally { if (completeSelf) { Fx.Assert(!this.isWorkflowThread, "We should never be calling ReleaseLock if this is the workflow thread."); this.instance.ReleaseLock(ref this.ownsLock, this.isIdlePolicyPersist && this.tryResult); } } } success = true; } finally { if (!success) { if (this.dependentTransaction != null) { this.dependentTransaction.Complete(); } } } if (completeSelf) { Complete(true); } }
void TrackPersistence(PersistenceOperation operation) { if (this.Controller.TrackingEnabled) { if (operation == PersistenceOperation.Delete) { this.Controller.Track(new WorkflowInstanceRecord(this.Id, this.WorkflowDefinition.DisplayName, WorkflowInstanceStates.Deleted, this.DefinitionIdentity)); } else if (operation == PersistenceOperation.Unload) { this.serviceHost.WorkflowServiceHostPerformanceCounters.WorkflowUnloaded(); this.Controller.Track(new WorkflowInstanceRecord(this.Id, this.WorkflowDefinition.DisplayName, WorkflowInstanceStates.Unloaded, this.DefinitionIdentity)); } else { this.serviceHost.WorkflowServiceHostPerformanceCounters.WorkflowPersisted(); this.Controller.Track(new WorkflowInstanceRecord(this.Id, this.WorkflowDefinition.DisplayName, WorkflowInstanceStates.Persisted, this.DefinitionIdentity)); } } }
public UnloadOrPersistAsyncResult(WorkflowApplication instance, TimeSpan timeout, PersistenceOperation operation, bool isWorkflowThread, bool isInternalPersist, AsyncCallback callback, object state) : base(callback, state) { this.instance = instance; this.timeoutHelper = new TimeoutHelper(timeout); this.operation = operation; this.isInternalPersist = isInternalPersist; this.isUnloaded = (operation == PersistenceOperation.Unload || operation == PersistenceOperation.Complete); this.OnCompleting = UnloadOrPersistAsyncResult.completeCallback; bool completeSelf; var success = false; // Save off the current transaction in case we have an async operation before we end // up creating the WorkflowPersistenceContext and create it on another thread. Do a // blocking dependent clone that we will complete when we are completed. // // This will throw TransactionAbortedException by design, if the transaction is // already rolled back. var currentTransaction = Transaction.Current; if (currentTransaction != null) { this.dependentTransaction = currentTransaction.DependentClone(DependentCloneOption.BlockCommitUntilComplete); } try { if (isWorkflowThread) { Fx.Assert(this.instance.Controller.IsPersistable, "The runtime won't schedule this work item unless we've passed the guard"); // We're an internal persistence on the workflow thread which means that we // are passed the guard already, we have the lock, and we know we aren't detached. completeSelf = this.InitializeProvider(); success = true; } else { this.instanceOperation = new RequiresPersistenceOperation(); try { if (this.instance.WaitForTurnAsync(this.instanceOperation, this.timeoutHelper.RemainingTime(), waitCompleteCallback, this)) { completeSelf = this.ValidateState(); } else { completeSelf = false; } success = true; } finally { if (!success) { this.NotifyOperationComplete(); } } } } finally { // If we had an exception, we need to complete the dependent transaction. if (!success) { if (this.dependentTransaction != null) { this.dependentTransaction.Complete(); } } } if (completeSelf) { this.Complete(true); } }
public SyncDeviceUsersResponse SyncDeviceUsers(SyncDeviceUsersRequest request) { return(PersistenceOperation.Process(request, () => { try { var userRepo = RepositoryManager.GetRepository <IUserRepository>(); var deviceRepo = RepositoryManager.GetRepository <IDeviceControllerRepository>(); Log.Info("Check offline devices"); var allDevices = deviceRepo.QuerySummaryData(new Hashtable() { { "Status", (int)GeneralStatus.Enabled } }); var offlineDevices = allDevices.FindAll(d => WebSocketClientManager.GetInstance().GetClientById(d.Code.ToInt32()) == null); var onlineDevices = allDevices.Except(offlineDevices); var requestOfflineDevice = offlineDevices.FindAll(x => request.Devices.Select(xx => xx.DeviceID).Contains(x.DeviceID)); if (requestOfflineDevice.Any()) { var msg = string.Format("设备:[{0}]未连接", string.Join(",", requestOfflineDevice.Select(x => x.Name))); return new SyncDeviceUsersResponse() { ResultType = ResultTypes.DeviceNotConnected, Messages = new[] { msg } }; } //if (offlineDevices.Any()) //{ // var msg = string.Format("设备:[{0}]未连接", string.Join(",", offlineDevices.Select(x => x.Name))); // return new SyncDBUsersResponse() { ResultType = ResultTypes.DeviceNotConnected, Messages = new[] { msg } }; //} Log.Info("Load data for request devices..."); var requestDevices = new List <DeviceController>(); request.Devices.ForEach(x => { var d = onlineDevices.FirstOrDefault(e => e.DeviceID == x.DeviceID); if (d != null) { requestDevices.Add(d); } }); request.Devices = requestDevices; Log.Info("Load data for request users..."); var requestUsers = new List <User>(); request.Users.ForEach(x => { if (x.UserID != 0) { x = userRepo.GetByKey(x.UserID); } requestUsers.Add(x); }); request.Users = requestUsers; Log.Info("Process business..."); request.Users.ForEach(user => request.Devices.ForEach(device => { new DeviceUserOp().SyncUser(request.Option, user, device); })); return new SyncDeviceUsersResponse() { ResultType = ResultTypes.Ok }; } catch (Exception ex) { return new SyncDeviceUsersResponse() { ResultType = ResultTypes.UnknownError, Messages = new[] { ex.Message } }; } })); }
private static SaveWorkflowCommand CreateSaveCommand(IDictionary <XName, InstanceValue> instance, IDictionary <XName, InstanceValue> instanceMetadata, PersistenceOperation operation) { var saveCommand = new SaveWorkflowCommand() { CompleteInstance = operation == PersistenceOperation.Complete, UnlockInstance = operation != PersistenceOperation.Save, }; if (instance != null) { foreach (var value in instance) { saveCommand.InstanceData.Add(value); } } if (instanceMetadata != null) { foreach (var value in instanceMetadata) { saveCommand.InstanceMetadataChanges.Add(value); } } return(saveCommand); }
public void Save(IDictionary <XName, InstanceValue> instance, PersistenceOperation operation, TimeSpan timeout) { this.store.Execute(this.handle, CreateSaveCommand(instance, (this.isLocked ? this.mutableMetadata : this.instanceMetadata), operation), timeout); this.isLocked = true; }
public IAsyncResult BeginSave(IDictionary <XName, InstanceValue> instance, PersistenceOperation operation, TimeSpan timeout, AsyncCallback callback, object state) => this.store.BeginExecute(this.handle, CreateSaveCommand(instance, (this.isLocked ? this.mutableMetadata : this.instanceMetadata), operation), timeout, callback, state);
private void TrackPersistence(PersistenceOperation operation) { if (base.Controller.TrackingEnabled) { if (operation == PersistenceOperation.Delete) { base.Controller.Track(new WorkflowInstanceRecord(this.Id, base.WorkflowDefinition.DisplayName, "Deleted")); } else if (operation == PersistenceOperation.Unload) { base.Controller.Track(new WorkflowInstanceRecord(this.Id, base.WorkflowDefinition.DisplayName, "Unloaded")); } else { base.Controller.Track(new WorkflowInstanceRecord(this.Id, base.WorkflowDefinition.DisplayName, "Persisted")); } } }