// The persistence engine will send a variety of commands to the configured InstanceStore, // such as CreateWorkflowOwnerCommand, SaveWorkflowCommand, and LoadWorkflowCommand. // This method is where we will handle those commands. protected override IAsyncResult BeginTryCommand(InstancePersistenceContext context, InstancePersistenceCommand command, TimeSpan timeout, AsyncCallback callback, object state) { IDictionary <XName, InstanceValue> instanceStateData = null; //The CreateWorkflowOwner command instructs the instance store to create a new instance owner bound to the instanace handle if (command is CreateWorkflowOwnerCommand) { context.BindInstanceOwner(_storeId, Guid.NewGuid()); } //The SaveWorkflow command instructs the instance store to modify the instance bound to the instance handle or an instance key else if (command is SaveWorkflowCommand) { SaveWorkflowCommand saveCommand = (SaveWorkflowCommand)command; instanceStateData = saveCommand.InstanceData; var instanceStateXml = DictionaryToXml(instanceStateData); Save(context.InstanceView.InstanceId, this._storeId, instanceStateXml); } //The LoadWorkflow command instructs the instance store to lock and load the instance bound to the identifier in the instance handle else if (command is LoadWorkflowCommand) { var xml = Load(context.InstanceView.InstanceId, this._storeId); instanceStateData = XmlToDictionary(xml); //load the data into the persistence Context context.LoadedInstance(InstanceState.Initialized, instanceStateData, null, null, null); } return(new CompletedAsyncResult <bool>(true, callback, state)); }
private static DateTime?GetPendingTimerExpiration(SaveWorkflowCommand saveWorkflowCommand) { if (saveWorkflowCommand.InstanceData.TryGetValue(PendingTimerExpirationPropertyName, out var instanceValue)) { return(((DateTime)instanceValue.Value).ToUniversalTime()); } return(default);
public Boolean SaveAllInstanceData(Guid instanceId, SaveWorkflowCommand command) { Boolean isExistingInstance = false; try { String fileName = String.Format("{0}.xml", instanceId); String fullPath = Path.Combine(_dataDirectory, fileName); isExistingInstance = File.Exists(fullPath); XElement root = new XElement("Instance"); root.Add(new XAttribute("InstanceId", instanceId)); XDocument xml = new XDocument(root); NetDataContractSerializer serializer = new NetDataContractSerializer(); XElement section = new XElement("InstanceData"); root.Add(section); foreach (var entry in command.InstanceData) { SaveSingleEntry(serializer, section, entry); } SaveInstanceDocument(fullPath, xml); } catch (IOException exception) { Console.WriteLine( "SaveAllInstanceData Exception: {0}", exception.Message); throw exception; } return(isExistingInstance); }
/// <summary> /// Saves all instance meta data. /// </summary> /// <param name="instanceId">The instance id.</param> /// <param name="command">The command.</param> /// <exception cref="System.Runtime.DurableInstancing.InstancePersistenceException"></exception> public void SaveAllInstanceMetaData(Guid instanceId, SaveWorkflowCommand command) { try { String fileName = String.Format("{0}.meta.xml", instanceId); String fullPath = Path.Combine(_dataDirectory, fileName); XElement root = new XElement("Instance"); root.Add(new XAttribute("WorkflowInstanceId", instanceId)); XDocument xml = new XDocument(root); NetDataContractSerializer serializer = new NetDataContractSerializer(); XElement section = new XElement("InstanceMetadata"); root.Add(section); foreach (var entry in command.InstanceMetadataChanges) { SaveSingleEntry(serializer, section, entry); } SaveInstanceDocument(fullPath, xml); } catch (Exception exception) { Dev2Logger.Error(exception); throw new InstancePersistenceException(exception.Message, exception); } }
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 Unlock(TimeSpan timeout) { var saveCmd = new SaveWorkflowCommand() { UnlockInstance = true, }; this.store.Execute(this.handle, saveCmd, timeout); }
public IAsyncResult BeginUnlock(TimeSpan timeout, AsyncCallback callback, object state) { var saveCmd = new SaveWorkflowCommand() { UnlockInstance = true, }; return(this.store.BeginExecute(this.handle, saveCmd, timeout, callback, state)); }
private bool SaveWorkflow(InstancePersistenceContext context, SaveWorkflowCommand command) { if (context.InstanceVersion == -1) { context.BindAcquiredLock(0); } if (command.CompleteInstance) { context.CompletedInstance(); if (!KeepInstanceDataAfterCompletion && ToDelete != null) { //DeleteFiles(context.InstanceView.InstanceId); ToDelete(); } } else { Dictionary <string, InstanceValue> instanceData = SerializeablePropertyBagConvertXNameInstanceValue(command.InstanceData); Dictionary <string, InstanceValue> instanceMetadata = SerializeInstanceMetadataConvertXNameInstanceValue(context, command); try { //serialize_dc(instanceData, instanceMetadata); //string serializedCorrelation = WorkflowSerialization.Serialize<WorkflowCorrelation>(this.Correlation); string serializedInstanceData = WorkflowSerialization.Serialize <Dictionary <string, InstanceValue> >(instanceData); string serializedInstanceMetadata = WorkflowSerialization.Serialize <Dictionary <string, InstanceValue> >(instanceMetadata); if (ToPersist != null) { ToPersist(new Serialized() { SerializedInstanceData = WorkflowSerialization.Serialize <Dictionary <string, InstanceValue> >(instanceData), SerializedInstanceMetadata = WorkflowSerialization.Serialize <Dictionary <string, InstanceValue> >(instanceMetadata) }); } } catch (Exception exc) { throw exc; } context.PersistedInstance(command.InstanceData); if (command.CompleteInstance) { context.CompletedInstance(); } if (command.UnlockInstance || command.CompleteInstance) { context.InstanceHandle.Free(); } } return(true); }
private void PopulateActivationMetadata(SaveWorkflowCommand saveCommand) { if (!this.IsInitialized) { foreach (KeyValuePair <XName, InstanceValue> pair in this.directory.InstanceMetadataChanges) { saveCommand.InstanceMetadataChanges.Add(pair.Key, pair.Value); } } }
private bool SaveWorkflow(InstancePersistenceContext context, SaveWorkflowCommand command) { if (context.InstanceVersion == -1) { context.BindAcquiredLock(0); } if (command.CompleteInstance) { context.CompletedInstance(); if (!KeepInstanceDataAfterCompletion) { DeleteFiles(context.InstanceView.InstanceId); } } else { Dictionary <string, InstanceValue> instanceData = SerializeablePropertyBagConvertXNameInstanceValue(command.InstanceData); Dictionary <string, InstanceValue> instanceMetadata = SerializeInstanceMetadataConvertXNameInstanceValue(context, command); try { var serializedInstanceData = JsonConvert.SerializeObject(instanceData, Formatting.Indented, _jsonSerializerSettings); File.WriteAllText(_storeDirectoryPath + "\\" + context.InstanceView.InstanceId + "-InstanceData", serializedInstanceData); var serializedInstanceMetadata = JsonConvert.SerializeObject(instanceMetadata, Formatting.Indented, _jsonSerializerSettings); File.WriteAllText(_storeDirectoryPath + "\\" + context.InstanceView.InstanceId + "-InstanceMetadata", serializedInstanceMetadata); } catch (Exception) { throw; } foreach (KeyValuePair <XName, InstanceValue> property in command.InstanceMetadataChanges) { context.WroteInstanceMetadataValue(property.Key, property.Value); } context.PersistedInstance(command.InstanceData); if (command.CompleteInstance) { context.CompletedInstance(); } if (command.UnlockInstance || command.CompleteInstance) { context.InstanceHandle.Free(); } } return(true); }
// The persistence engine will send a variety of commands to the configured InstanceStore, // such as CreateWorkflowOwnerCommand, SaveWorkflowCommand, and LoadWorkflowCommand. // This method is where we will handle those commands. protected override IAsyncResult BeginTryCommand(InstancePersistenceContext context, InstancePersistenceCommand command, TimeSpan timeout, AsyncCallback callback, object state) { IDictionary <XName, InstanceValue> instanceStateData = null; WorkflowInstance instance = null; Guid InstanceId = Guid.Empty; if (context != null && context.InstanceView != null) { InstanceId = context.InstanceView.InstanceId; instance = WorkflowInstance.Instances.Where(x => x.InstanceId == InstanceId.ToString()).FirstOrDefault(); } //The CreateWorkflowOwner command instructs the instance store to create a new instance owner bound to the instanace handle if (command is CreateWorkflowOwnerCommand) { context.BindInstanceOwner(_storeId, Guid.NewGuid()); } //The SaveWorkflow command instructs the instance store to modify the instance bound to the instance handle or an instance key else if (command is SaveWorkflowCommand) { if (instance != null && instance.Workflow != null && instance.Workflow.Serializable == true) { SaveWorkflowCommand saveCommand = (SaveWorkflowCommand)command; try { instanceStateData = saveCommand.InstanceData; var instanceStateXml = DictionaryToXml(instanceStateData); Save(context.InstanceView.InstanceId, this._storeId, instanceStateXml); } catch (Exception) { instance.Workflow.Serializable = false; } } } //The LoadWorkflow command instructs the instance store to lock and load the instance bound to the identifier in the instance handle else if (command is LoadWorkflowCommand) { var xml = Load(InstanceId, _storeId); // if (xml == null) throw new ArgumentNullException("Failed locating instance data for " + context.InstanceView.InstanceId.ToString()); // if (xml == null) return new CompletedAsyncResult<bool>(false, callback, state); if (xml == null) { return(new CompletedAsyncResult <bool>(true, callback, state)); } instanceStateData = XmlToDictionary(xml); //load the data into the persistence Context context.LoadedInstance(InstanceState.Initialized, instanceStateData, null, null, null); } return(new CompletedAsyncResult <bool>(true, callback, state)); }
private bool SaveWorkflow(InstancePersistenceContext context, SaveWorkflowCommand command) { if (context.InstanceVersion == -1) { context.BindAcquiredLock(0); } if (command.CompleteInstance) { context.CompletedInstance(); } else { string instanceType = ""; const string InstanceTypeXName = "{urn:schemas-microsoft-com:System.Runtime.DurableInstancing/4.0/metadata}InstanceType"; InstanceValue instanceTypeInstanceValue; if (command.InstanceMetadataChanges.TryGetValue(InstanceTypeXName, out instanceTypeInstanceValue)) { instanceType = instanceTypeInstanceValue.Value.ToString(); } Dictionary <string, object> fullInstanceData = new Dictionary <string, object>(); fullInstanceData.Add("instanceId", context.InstanceView.InstanceId); fullInstanceData.Add("instanceOwnerId", context.InstanceView.InstanceOwner.InstanceOwnerId); fullInstanceData.Add("instanceData", SerializeablePropertyBag(command.InstanceData)); fullInstanceData.Add("instanceMetadata", SerializeInstanceMetadata(context, command)); foreach (KeyValuePair <XName, InstanceValue> property in command.InstanceMetadataChanges) { context.WroteInstanceMetadataValue(property.Key, property.Value); } context.PersistedInstance(command.InstanceData); _stores.Save(WorkflowStoreComponents.Definition | WorkflowStoreComponents.Metadata | WorkflowStoreComponents.Streams | WorkflowStoreComponents.TerminatingError | WorkflowStoreComponents.Timer | WorkflowStoreComponents.ActivityState | WorkflowStoreComponents.JobState, fullInstanceData); } return(true); }
private Exception ProcessSaveWorkflow( InstancePersistenceContext context, SaveWorkflowCommand command) { try { if (command.CompleteInstance) { _dataStore.DeleteInstance( context.InstanceView.InstanceId); _dataStore.DeleteInstanceAssociation( context.InstanceView.InstanceId); return(null); } if (command.InstanceData.Count > 0 || command.InstanceMetadataChanges.Count > 0) { if (!_dataStore.SaveAllInstanceData( context.InstanceView.InstanceId, command)) { _dataStore.SaveAllInstanceMetaData( context.InstanceView.InstanceId, command); } } if (command.InstanceKeysToAssociate.Count > 0) { foreach (var entry in command.InstanceKeysToAssociate) { _dataStore.SaveInstanceAssociation( context.InstanceView.InstanceId, entry.Key, false); } } return(null); } catch (InstancePersistenceException exception) { Console.WriteLine( // ReSharper disable LocalizableElement "ProcessSaveWorkflow exception: {0}", exception.Message); // ReSharper restore LocalizableElement return(exception); } }
private static bool HandleEndEnlist(IAsyncResult result) { PersistenceContext.AssociateKeysAsyncResult asyncState = (PersistenceContext.AssociateKeysAsyncResult)result.AsyncState; bool flag = false; if (!asyncState.persistenceContext.directory.TryAddAssociations(asyncState.persistenceContext, asyncState.keysToAssociate, asyncState.persistenceContext.keysToAssociate, asyncState.applicationKeys ? asyncState.persistenceContext.keysToDisassociate : null)) { lock (asyncState.persistenceContext.ThisLock) { asyncState.persistenceContext.ThrowIfDisposedOrNotOpen(); } throw Fx.AssertAndThrow("Should only fail to add keys in a race with abort."); } if (asyncState.persistenceContext.directory.ConsistencyScope == DurableConsistencyScope.Global) { if ((asyncState.persistenceContext.keysToAssociate.Count == 0) && ((asyncState.persistenceContext.keysToDisassociate.Count == 0) || !asyncState.applicationKeys)) { return(asyncState.AfterUpdate()); } if (asyncState.persistenceContext.store == null) { return(flag); } SaveWorkflowCommand command = new SaveWorkflowCommand(); foreach (InstanceKey key in asyncState.persistenceContext.keysToAssociate) { command.InstanceKeysToAssociate.Add(key.Value, key.Metadata); } if (asyncState.applicationKeys) { foreach (InstanceKey key2 in asyncState.persistenceContext.keysToDisassociate) { command.InstanceKeysToFree.Add(key2.Value); } } IAsyncResult result3 = null; using (asyncState.PrepareTransactionalCall(asyncState.transaction)) { result3 = asyncState.persistenceContext.store.BeginExecute(asyncState.persistenceContext.handle, command, asyncState.timeoutHelper.RemainingTime(), asyncState.PrepareAsyncCompletion(handleEndExecute), asyncState); } return(asyncState.SyncContinue(result3)); } return(asyncState.AfterUpdate()); }
//The persistence engine will send a variety of commands to the configured InstanceStore, //such as CreateWorkflowOwnerCommand, SaveWorkflowCommand, and LoadWorkflowCommand. //This method is where we will handle those commands protected override IAsyncResult BeginTryCommand(InstancePersistenceContext context, InstancePersistenceCommand command, TimeSpan timeout, AsyncCallback callback, object state) { IDictionary <XName, InstanceValue> data = null; //The CreateWorkflowOwner command instructs the instance store to create a new instance owner bound to the instanace handle if (command is CreateWorkflowOwnerCommand || command is CreateWorkflowOwnerWithIdentityCommand) //Arghya test { context.BindInstanceOwner(ownerInstanceID, Guid.NewGuid()); //TODO?? } //The SaveWorkflow command instructs the instance store to modify the instance bound to the instance handle or an instance key else if (command is SaveWorkflowCommand) { SaveWorkflowCommand saveCommand = (SaveWorkflowCommand)command; data = saveCommand.InstanceData; Save(data, context.InstanceView.InstanceId.ToString()); //arghya } //The LoadWorkflow command instructs the instance store to lock and load the instance bound to the identifier in the instance handle else if (command is LoadWorkflowCommand) { //string fileName = Path.Combine(Directory.GetCurrentDirectory(), string.Format(CultureInfo.InvariantCulture, InstanceFormatString, this.ownerInstanceID)); string fileName = Path.Combine( Directory.GetCurrentDirectory(), string.Format(CultureInfo.InvariantCulture, InstanceFormatString, context.InstanceView.InstanceId.ToString())); //this.ownerInstanceID //arghya try { using (FileStream inputStream = new FileStream(fileName, FileMode.Open)) { data = LoadInstanceDataFromFile(inputStream); //load the data into the persistence Context context.LoadedInstance(InstanceState.Initialized, data, null, null, null); } } catch (Exception exception) { throw new FileLoadException(exception.Message); //PersistenceException //using System.ServiceModel.Persistence; } } return(new CompletedAsyncResult <bool>(true, callback, state)); }
/// <summary> /// Handles a <see cref="SaveWorkflowCommand"/>. /// </summary> /// <param name="context"></param> /// <param name="command"></param> Task <bool> SaveWorkflowCommand(InstancePersistenceContext context, SaveWorkflowCommand command) { // save the instance data state.InstanceState = InstanceState.Initialized; SaveInstanceData(context.InstanceView.InstanceId, command.InstanceData); SaveInstanceMetadata(context.InstanceView.InstanceId, command.InstanceMetadataChanges); state.OnPersisted(); // clear instance data when complete if (command.CompleteInstance) { state.InstanceState = InstanceState.Completed; state.ClearInstanceData(); state.ClearInstanceMetadata(); state.OnCompleted(); } return(Task.FromResult(true)); }
private bool SaveWorkflow(InstancePersistenceContext context, SaveWorkflowCommand command) { if (context.InstanceVersion == -1) { context.BindAcquiredLock(0); } if (command.CompleteInstance) { context.CompletedInstance(); if (!KeepInstanceDataAfterCompletion) { _repository.Delete(context.InstanceView.InstanceId); } } else { var data = SerializeData(command.InstanceData); var metadata = SerializeMetadata(context.InstanceView.InstanceMetadata, command.InstanceMetadataChanges); _repository.Save(context.InstanceView.InstanceId, new InstanceDataPackage(metadata, data)); foreach (var property in command.InstanceMetadataChanges) { context.WroteInstanceMetadataValue(property.Key, property.Value); } context.PersistedInstance(command.InstanceData); if (command.CompleteInstance) { context.CompletedInstance(); } if (command.UnlockInstance || command.CompleteInstance) { context.InstanceHandle.Free(); } } return(true); }
//The persistence engine will send a variety of commands to the configured InstanceStore, //such as CreateWorkflowOwnerCommand, SaveWorkflowCommand, and LoadWorkflowCommand. //This method is where we will handle those commands protected override IAsyncResult BeginTryCommand(InstancePersistenceContext context, InstancePersistenceCommand command, TimeSpan timeout, AsyncCallback callback, object state) { IDictionary <XName, InstanceValue> data = null; //The CreateWorkflowOwner command instructs the instance store to create a new instance owner bound to the instanace handle if (command is CreateWorkflowOwnerCommand) { context.BindInstanceOwner(ownerInstanceID, Guid.NewGuid()); } //The SaveWorkflow command instructs the instance store to modify the instance bound to the instance handle or an instance key else if (command is SaveWorkflowCommand) { SaveWorkflowCommand saveCommand = (SaveWorkflowCommand)command; data = saveCommand.InstanceData; Save(data); } //The LoadWorkflow command instructs the instance store to lock and load the instance bound to the identifier in the instance handle else if (command is LoadWorkflowCommand) { string fileName = this.ownerInstanceID.ToString(); try { using (FileStream inputStream = new FileStream(fileName, FileMode.Open)) { data = LoadInstanceDataFromFile(inputStream); //load the data into the persistence Context context.LoadedInstance(InstanceState.Initialized, data, null, null, null); } } catch (Exception exception) { throw new Exception(exception.Message); } } return(new CompletedAsyncResult <bool>(true, callback, state)); }
//The persistence engine will send a variety of commands to the configured InstanceStore, //such as CreateWorkflowOwnerCommand, SaveWorkflowCommand, and LoadWorkflowCommand. //This method is where we will handle those commands protected override IAsyncResult BeginTryCommand(InstancePersistenceContext context, InstancePersistenceCommand command, TimeSpan timeout, AsyncCallback callback, object state) { IDictionary <XName, InstanceValue> data = null; //The CreateWorkflowOwner command instructs the instance store to create a new instance owner bound to the instanace handle if (command is CreateWorkflowOwnerCommand) { context.BindInstanceOwner(ownerInstanceID, ownerInstanceID); } //The SaveWorkflow command instructs the instance store to modify the instance bound to the instance handle or an instance key else if (command is SaveWorkflowCommand) { SaveWorkflowCommand saveCommand = (SaveWorkflowCommand)command; data = saveCommand.InstanceData; Save(data); //_saveWaitHandler.WaitOne(new TimeSpan(0, 0, 1)); } //The LoadWorkflow command instructs the instance store to lock and load the instance bound to the identifier in the instance handle else if (command is LoadWorkflowCommand) { string fileName = GetFileName(this.ownerInstanceID); data = LoadInstanceDataFromFile(fileName); var nonWriteOnly = data.Where(kvp => (kvp.Value.Options & InstanceValueOptions.WriteOnly) != InstanceValueOptions.WriteOnly).ToDictionary(k => k.Key, v => v.Value); //load the data into the persistence Context context.LoadedInstance(InstanceState.Initialized, nonWriteOnly, null, null, null); } else if (command.Name.LocalName == "CreateWorkflowOwner") { //do nothing } var result = new CompletedAsyncResult <bool>(true, callback, state); return(result); }
private long ProcessSaveCommand(InstancePersistenceContext context, SaveWorkflowCommand command) { Owner owner = CheckOwner(context, command.Name); Instance instance = PersistenceItemManager.Load <Instance>(context.InstanceView.InstanceId); if (instance == null) { // Checking instance.Owner is like an InstanceLockQueryResult. context.QueriedInstanceStore(new InstanceLockQueryResult(context.InstanceView.InstanceId, Guid.Empty)); if (context.InstanceView.IsBoundToLock) { context.InstanceHandle.Free(); throw new InstanceLockLostException(command.Name, context.InstanceView.InstanceId); } instance = new Instance() { Version = 1, Id = context.InstanceView.InstanceId, Owner = context.InstanceView.InstanceOwner.InstanceOwnerId, Metadata = new PropertyBag() }; PersistenceItemManager.SaveToFile <Instance>(instance); context.BindAcquiredLock(1); } else { // Checking instance.Owner is like an InstanceLockQueryResult. context.QueriedInstanceStore(new InstanceLockQueryResult(context.InstanceView.InstanceId, instance.Owner)); if (instance.State == InstanceState.Completed) { throw new InstanceCompleteException(command.Name, context.InstanceView.InstanceId); } if (instance.Owner == Guid.Empty) { if (context.InstanceView.IsBoundToLock) { context.InstanceHandle.Free(); throw new InstanceLockLostException(command.Name, context.InstanceView.InstanceId); } instance.Version++; instance.Owner = context.InstanceView.InstanceOwner.InstanceOwnerId; PersistenceItemManager.SaveToFile <Instance>(instance); context.BindAcquiredLock(instance.Version); } else { if (instance.Owner != context.InstanceView.InstanceOwner.InstanceOwnerId) { if (context.InstanceView.IsBoundToLock) { context.InstanceHandle.Free(); throw new InstanceLockLostException(command.Name, context.InstanceView.InstanceId); } throw new InstanceLockedException(command.Name, instance.Owner); } if (context.InstanceView.IsBoundToLock) { if (context.InstanceVersion != instance.Version) { if (context.InstanceVersion > instance.Version) { throw new InvalidProgramException("This is a bug, the context should never be bound higher than the lock."); } context.InstanceHandle.Free(); throw new InstanceLockLostException(command.Name, context.InstanceView.InstanceId); } } else { // This is the very interesting parallel-convoy conflicting handle race resolution case. Two handles // can get bound to the same lock, which is necessary to allow parallel convoy to succeed without preventing // zombied locked instances from being reclaimed. return(instance.Version); } } } foreach (KeyValuePair <Guid, IDictionary <XName, InstanceValue> > keyEntry in command.InstanceKeysToAssociate) { Key key = PersistenceItemManager.Load <Key>(keyEntry.Key); if (key != null) { if (key.TargetInstanceId != Guid.Empty && key.TargetInstanceId != context.InstanceView.InstanceId) { throw new InstanceKeyCollisionException(command.Name, context.InstanceView.InstanceId, new InstanceKey(keyEntry.Key), key.TargetInstanceId); } // The SaveWorkflowCommand treats this as a no-op, whether completed or not. } else { key = new Key() { Id = keyEntry.Key, State = InstanceKeyState.Associated, TargetInstanceId = context.InstanceView.InstanceId, Metadata = new PropertyBag(keyEntry.Value) }; PersistenceItemManager.SaveToFile <Key>(key); context.AssociatedInstanceKey(keyEntry.Key); if (keyEntry.Value != null) { foreach (KeyValuePair <XName, InstanceValue> property in keyEntry.Value) { context.WroteInstanceKeyMetadataValue(keyEntry.Key, property.Key, property.Value); } } } } foreach (Guid keyGuid in command.InstanceKeysToComplete) { Key key = PersistenceItemManager.Load <Key>(keyGuid); if (key != null && key.TargetInstanceId == context.InstanceView.InstanceId) { if (key.State == InstanceKeyState.Associated) //if (key.State != InstanceKeyState.Completed) { key.State = InstanceKeyState.Completed; PersistenceItemManager.SaveToFile <Key>(key); context.CompletedInstanceKey(keyGuid); } } else { // The SaveWorkflowCommand does not allow this. (Should it validate against it?) throw new InvalidOperationException("Attempting to complete a key which is not associated."); } } foreach (Guid keyGuid in command.InstanceKeysToFree) { Key key = PersistenceItemManager.Load <Key>(keyGuid); if (key != null && key.TargetInstanceId == context.InstanceView.InstanceId) { if (key.State != InstanceKeyState.Completed) { context.CompletedInstanceKey(keyGuid); } key.State = InstanceKeyState.Unknown; key.TargetInstanceId = Guid.Empty; key.Metadata = null; PersistenceItemManager.SaveToFile <Key>(key); context.UnassociatedInstanceKey(keyGuid); } else { // The SaveWorkflowCommand does not allow this. (Should it validate against it?) throw new InvalidOperationException("Attempting to complete a key which is not associated."); } } foreach (KeyValuePair <Guid, IDictionary <XName, InstanceValue> > keyEntry in command.InstanceKeyMetadataChanges) { Key key = PersistenceItemManager.Load <Key>(keyEntry.Key); if (key != null && key.TargetInstanceId == context.InstanceView.InstanceId && key.State == InstanceKeyState.Associated) { if (keyEntry.Value != null) { foreach (KeyValuePair <XName, InstanceValue> property in keyEntry.Value) { if (property.Value.IsDeletedValue) { key.Metadata.Remove(property.Key); } else { key.Metadata[property.Key] = new InstanceValue(property.Value); } context.WroteInstanceKeyMetadataValue(keyEntry.Key, property.Key, property.Value); } PersistenceItemManager.SaveToFile <Key>(key); } } else { // The SaveWorkflowCommand does not allow this. (Should it validate against it?) throw new InvalidOperationException("Attempting to complete a key which is not associated."); } } foreach (KeyValuePair <XName, InstanceValue> property in command.InstanceMetadataChanges) { if (property.Value.IsDeletedValue) { instance.Metadata.Remove(property.Key); } else { instance.Metadata[property.Key] = new InstanceValue(property.Value); } context.WroteInstanceMetadataValue(property.Key, property.Value); } if (command.InstanceData.Count > 0) { instance.Data = new PropertyBag(command.InstanceData); context.PersistedInstance(command.InstanceData); } PersistenceItemManager.SaveToFile <Instance>(instance); // The command does the implicit advancement of everything into safe completed states. if (command.CompleteInstance) { if (instance.Data == null) { instance.Data = new PropertyBag(); PersistenceItemManager.SaveToFile <Instance>(instance); context.PersistedInstance(new Dictionary <XName, InstanceValue>()); } Queue <Guid> keysToComplete = new Queue <Guid>(); foreach (KeyValuePair <Guid, InstanceKeyView> keyEntry in context.InstanceView.InstanceKeys) { if (keyEntry.Value.InstanceKeyState == InstanceKeyState.Associated) { keysToComplete.Enqueue(keyEntry.Key); } } foreach (Guid keyToComplete in keysToComplete) { Key key = PersistenceItemManager.Load <Key>(keyToComplete); key.State = InstanceKeyState.Completed; PersistenceItemManager.SaveToFile <Key>(key); context.CompletedInstanceKey(keyToComplete); } instance.State = InstanceState.Completed; instance.Owner = Guid.Empty; PersistenceItemManager.SaveToFile <Instance>(instance); context.CompletedInstance(); context.InstanceHandle.Free(); } if (command.UnlockInstance) { instance.Owner = Guid.Empty; PersistenceItemManager.SaveToFile <Instance>(instance); context.InstanceHandle.Free(); } return(0); }
protected override IAsyncResult BeginTryCommand(InstancePersistenceContext context, InstancePersistenceCommand command, TimeSpan timeout, AsyncCallback callback, object state) { SaveWorkflowCommand save = command as SaveWorkflowCommand; if (save != null) { lock (FileStore.s_thisLock) { ProcessSaveCommand(context, save); } } LoadWorkflowCommand load = command as LoadWorkflowCommand; if (load != null) { lock (FileStore.s_thisLock) { ProcessLoadCommand(context, load); } } LoadWorkflowByInstanceKeyCommand loadByKey = command as LoadWorkflowByInstanceKeyCommand; if (loadByKey != null) { lock (FileStore.s_thisLock) { ProcessLoadByKeyCommand(context, loadByKey); } } if (save != null || load != null || loadByKey != null) { return(new CompletedAsyncResult(callback, state)); } if (command is CreateWorkflowOwnerCommand createOwner) { Guid ownerId = Guid.NewGuid(); Owner owner = new Owner(); lock (s_thisLock) { owner.Id = ownerId; owner.LockToken = Guid.NewGuid(); owner.Metadata = new PropertyBag(createOwner.InstanceOwnerMetadata); PersistenceItemManager.SaveToFile <Owner>(owner); } context.BindInstanceOwner(ownerId, owner.LockToken); context.BindEvent(HasRunnableWorkflowEvent.Value); return(new CompletedAsyncResult(callback, state)); } if (command is DeleteWorkflowOwnerCommand deleteOwner) { Guid ownerId = context.InstanceView.InstanceOwner.InstanceOwnerId; lock (FileStore.s_thisLock) { Owner owner = PersistenceItemManager.Load <Owner>(ownerId); if (owner != null && owner.LockToken == context.LockToken) { PersistenceItemManager.Remove <Owner>(ownerId); } } context.InstanceHandle.Free(); return(new CompletedAsyncResult(callback, state)); } return(base.BeginTryCommand(context, command, timeout, callback, state)); }
private bool SaveWorkflow(InstancePersistenceContext context, SaveWorkflowCommand command) { if (context.InstanceVersion == -1) { context.BindAcquiredLock(0); } if (command.CompleteInstance) { context.CompletedInstance(); if (!KeepInstanceDataAfterCompletion) { DeleteFiles(context.InstanceView.InstanceId); } } else { Dictionary <string, InstanceValue> instanceData = SerializeablePropertyBagConvertXNameInstanceValue(command.InstanceData); Dictionary <string, InstanceValue> instanceMetadata = SerializeInstanceMetadataConvertXNameInstanceValue(context, command); try { //var serializedInstanceData = JsonConvert.SerializeObject(instanceData, Formatting.Indented, _jsonSerializerSettings); ////File.WriteAllText(_storeDirectoryPath + "\\" + context.InstanceView.InstanceId + "-InstanceData", serializedInstanceData); //File.WriteAllText(_storePathInstanceData, serializedInstanceData); //var test_deserializ = JsonConvert.DeserializeObject<Dictionary<string, InstanceValue>>(serializedInstanceData, _jsonSerializerSettings); //var serializedInstanceMetadata = JsonConvert.SerializeObject(instanceMetadata, Formatting.Indented, _jsonSerializerSettings); ////File.WriteAllText(_storeDirectoryPath + "\\" + context.InstanceView.InstanceId + "-InstanceMetadata", serializedInstanceMetadata); //File.WriteAllText(_storePathInstanceMetadata, serializedInstanceMetadata); serialize_dc(instanceData, instanceMetadata); } catch (Exception exc) { System.Runtime.Serialization.DataContractSerializerSettings settings = new System.Runtime.Serialization.DataContractSerializerSettings { PreserveObjectReferences = true, KnownTypes = _knownTypes }; string s1 = null; System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(instanceData.GetType(), settings); using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, instanceData); s1 = System.Text.Encoding.UTF8.GetString(ms.ToArray()); } Dictionary <string, InstanceValue> obj = null; System.Runtime.Serialization.DataContractSerializer deserializer = new System.Runtime.Serialization.DataContractSerializer(instanceData.GetType(), settings); using (MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(s1))) { obj = (Dictionary <string, InstanceValue>)deserializer.ReadObject(ms); } throw; } foreach (KeyValuePair <XName, InstanceValue> property in command.InstanceMetadataChanges) { context.WroteInstanceMetadataValue(property.Key, property.Value); } context.PersistedInstance(command.InstanceData); if (command.CompleteInstance) { context.CompletedInstance(); } if (command.UnlockInstance || command.CompleteInstance) { context.InstanceHandle.Free(); } } return(true); }
private Dictionary <string, InstanceValue> SerializeInstanceMetadataConvertXNameInstanceValue(InstancePersistenceContext context, SaveWorkflowCommand command) { Dictionary <string, InstanceValue> metadata = null; foreach (var property in command.InstanceMetadataChanges) { if (!property.Value.Options.HasFlag(InstanceValueOptions.WriteOnly)) { if (metadata == null) { metadata = new Dictionary <string, InstanceValue>(); // copy current metadata. note that we must get rid of InstanceValue as it is not properly serializeable foreach (var m in context.InstanceView.InstanceMetadata) { metadata.Add(m.Key.ToString(), m.Value); } } if (metadata.ContainsKey(property.Key.ToString())) { if (property.Value.IsDeletedValue) { metadata.Remove(property.Key.ToString()); } else { metadata[property.Key.ToString()] = property.Value; } } else { if (!property.Value.IsDeletedValue) { metadata.Add(property.Key.ToString(), property.Value); } } } } if (metadata == null) { metadata = new Dictionary <string, InstanceValue>(); } return(metadata); }
public UpdateSuspendMetadataAsyncResult(PersistenceContext persistenceContext, Exception reason, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.persistenceContext = persistenceContext; base.OnCompleting = new Action <AsyncResult, Exception>(this.OnFinishOperation); bool flag = false; try { this.persistenceContext.StartOperation(); this.timeoutHelper = new TimeoutHelper(timeout); Transaction current = Transaction.Current; if (current != null) { this.transaction = current.DependentClone(DependentCloneOption.BlockCommitUntilComplete); } if (this.persistenceContext.store != null) { SaveWorkflowCommand saveCommand = new SaveWorkflowCommand(); this.persistenceContext.PopulateActivationMetadata(saveCommand); saveCommand.InstanceMetadataChanges[WorkflowServiceNamespace.SuspendReason] = new InstanceValue(reason.Message); saveCommand.InstanceMetadataChanges[WorkflowServiceNamespace.SuspendException] = new InstanceValue(reason, InstanceValueOptions.WriteOnly | InstanceValueOptions.Optional); saveCommand.UnlockInstance = true; IAsyncResult result = this.persistenceContext.store.BeginExecute(this.persistenceContext.handle, saveCommand, this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleEndExecute), this); if (base.SyncContinue(result)) { base.Complete(true); } } else { base.Complete(true); } flag = true; } catch (OperationCanceledException exception) { throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new CommunicationObjectAbortedException(System.ServiceModel.Activities.SR.HandleFreedInDirectory, exception)); } catch (TimeoutException) { this.persistenceContext.Fault(); throw; } finally { if (!flag) { try { if (this.transaction != null) { this.transaction.Complete(); } } finally { this.persistenceContext.FinishOperation(); } } } }
private bool SaveWorkflow(InstancePersistenceContext context, SaveWorkflowCommand command) { if (context.InstanceVersion == -1) { context.BindAcquiredLock(0); } if (command.CompleteInstance) { context.CompletedInstance(); if (!KeepInstanceDataAfterCompletion) { DeleteFiles(context.InstanceView.InstanceId); } } else { Dictionary <string, InstanceValue> instanceData = SerializeablePropertyBagConvertXNameInstanceValue(command.InstanceData); Dictionary <string, InstanceValue> instanceMetadata = SerializeInstanceMetadataConvertXNameInstanceValue(context, command); FileStream instanceDataStream; FileStream instanceMetadataStream; GetFileStreams(context.InstanceView.InstanceId, out instanceDataStream, out instanceMetadataStream, FileMode.OpenOrCreate); DataContractSerializer instanceDataSerializer; DataContractSerializer instanceMetadataSerializer; GetDataContractSerializers(out instanceDataSerializer, out instanceMetadataSerializer); try { instanceDataSerializer.WriteObject(instanceDataStream, instanceData); instanceMetadataSerializer.WriteObject(instanceMetadataStream, instanceMetadata); } catch (Exception) { throw; } finally { instanceDataStream.Flush(); instanceDataStream.Dispose(); instanceMetadataStream.Flush(); instanceMetadataStream.Dispose(); } foreach (KeyValuePair <XName, InstanceValue> property in command.InstanceMetadataChanges) { context.WroteInstanceMetadataValue(property.Key, property.Value); } context.PersistedInstance(command.InstanceData); if (command.CompleteInstance) { context.CompletedInstance(); } if (command.UnlockInstance || command.CompleteInstance) { context.InstanceHandle.Free(); } } return(true); }
public SaveAsyncResult(PersistenceContext persistenceContext, IDictionary <XName, InstanceValue> instance, SaveStatus saveStatus, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.persistenceContext = persistenceContext; base.OnCompleting = new Action <AsyncResult, Exception>(this.OnFinishOperation); this.saveStatus = saveStatus; bool flag = false; try { this.persistenceContext.StartOperation(); this.persistenceContext.ThrowIfCompleted(); this.persistenceContext.ThrowIfNotVisible(); this.timeoutHelper = new TimeoutHelper(timeout); Transaction current = Transaction.Current; if (current != null) { this.transaction = current.DependentClone(DependentCloneOption.BlockCommitUntilComplete); } if (this.persistenceContext.store != null) { SaveWorkflowCommand saveCommand = new SaveWorkflowCommand(); foreach (KeyValuePair <XName, InstanceValue> pair in instance) { saveCommand.InstanceData.Add(pair); } this.persistenceContext.PopulateActivationMetadata(saveCommand); if (this.persistenceContext.IsSuspended) { saveCommand.InstanceMetadataChanges.Add(WorkflowServiceNamespace.SuspendReason, new InstanceValue(this.persistenceContext.SuspendedReason)); } else { saveCommand.InstanceMetadataChanges.Add(WorkflowServiceNamespace.SuspendReason, InstanceValue.DeletedValue); saveCommand.InstanceMetadataChanges.Add(WorkflowServiceNamespace.SuspendException, InstanceValue.DeletedValue); } foreach (InstanceKey key in this.persistenceContext.keysToAssociate) { saveCommand.InstanceKeysToAssociate.Add(key.Value, key.Metadata); } foreach (InstanceKey key2 in this.persistenceContext.keysToDisassociate) { saveCommand.InstanceKeysToFree.Add(key2.Value); } if (this.saveStatus == SaveStatus.Completed) { saveCommand.CompleteInstance = true; saveCommand.UnlockInstance = true; } else { saveCommand.UnlockInstance = this.saveStatus == SaveStatus.Unlocked; } IAsyncResult result = this.persistenceContext.store.BeginExecute(this.persistenceContext.handle, saveCommand, this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleEndExecute), this); if (base.SyncContinue(result)) { base.Complete(true); } } else { if (this.saveStatus == SaveStatus.Completed) { this.persistenceContext.IsCompleted = true; this.persistenceContext.IsLocked = false; } else { this.persistenceContext.IsLocked = this.saveStatus != SaveStatus.Unlocked; } if (this.AfterSave()) { base.Complete(true); } } flag = true; } catch (OperationCanceledException exception) { throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new CommunicationObjectAbortedException(System.ServiceModel.Activities.SR.HandleFreedInDirectory, exception)); } catch (TimeoutException) { this.persistenceContext.Fault(); throw; } finally { if (!flag) { try { if (this.transaction != null) { this.transaction.Complete(); } } finally { this.persistenceContext.FinishOperation(); } } } }
public ReleaseAsyncResult(PersistenceContext persistenceContext, TimeSpan timeout, AsyncCallback callback, object state) : base(callback, state) { this.persistenceContext = persistenceContext; base.OnCompleting = new Action <AsyncResult, Exception>(this.OnFinishOperation); bool flag = false; try { this.persistenceContext.StartOperation(); this.timeoutHelper = new TimeoutHelper(timeout); Transaction current = Transaction.Current; if (current != null) { this.transaction = current.DependentClone(DependentCloneOption.BlockCommitUntilComplete); } if (this.persistenceContext.IsVisible) { if ((this.persistenceContext.store != null) && this.persistenceContext.IsLocked) { SaveWorkflowCommand saveCommand = new SaveWorkflowCommand { UnlockInstance = true }; this.persistenceContext.PopulateActivationMetadata(saveCommand); IAsyncResult result = this.persistenceContext.store.BeginExecute(this.persistenceContext.handle, saveCommand, this.timeoutHelper.RemainingTime(), base.PrepareAsyncCompletion(handleEndExecute), this); if (base.SyncContinue(result)) { base.Complete(true); } } else if (this.AfterUnlock()) { base.Complete(true); } } else { lock (this.persistenceContext.ThisLock) { this.persistenceContext.ThrowIfDisposedOrNotOpen(); } base.Complete(true); } flag = true; } catch (OperationCanceledException exception) { throw System.ServiceModel.Activities.FxTrace.Exception.AsError(new CommunicationObjectAbortedException(System.ServiceModel.Activities.SR.HandleFreedInDirectory, exception)); } catch (TimeoutException) { this.persistenceContext.Fault(); throw; } finally { if (!flag) { try { if (this.transaction != null) { this.transaction.Complete(); } } finally { this.persistenceContext.FinishOperation(); } } } }