static SuspensionStateChange GetSuspensionReason(SaveWorkflowCommand saveWorkflowCommand, out string suspensionReason, out string suspensionExceptionName)
        {
            IDictionary <XName, InstanceValue> instanceMetadataChanges = saveWorkflowCommand.InstanceMetadataChanges;
            SuspensionStateChange suspensionStateChange = SuspensionStateChange.NoChange;
            InstanceValue         propertyValue;

            suspensionReason        = null;
            suspensionExceptionName = null;

            if (instanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SuspendReason, out propertyValue))
            {
                if (!propertyValue.IsDeletedValue)
                {
                    suspensionStateChange = SuspensionStateChange.SuspendInstance;
                    suspensionReason      = (string)propertyValue.Value;

                    if (instanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SuspendException, out propertyValue) && !propertyValue.IsDeletedValue)
                    {
                        suspensionExceptionName = ((Exception)propertyValue.Value).GetType().ToString();
                    }
                }
                else
                {
                    suspensionStateChange = SuspensionStateChange.UnsuspendInstance;
                }
            }

            return(suspensionStateChange);
        }
        /// <summary>
        /// Saves all instance data.
        /// </summary>
        /// <param name="instanceId">The instance id.</param>
        /// <param name="command">The command.</param>
        /// <returns></returns>
        /// <exception cref="System.Runtime.DurableInstancing.InstancePersistenceException"></exception>
        public Boolean SaveAllInstanceData(Guid instanceId, SaveWorkflowCommand command)
        {
            Boolean isExistingInstance;
            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("WorkflowInstanceId", 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(Exception exception)
            {
                Dev2Logger.Log.Error(exception);
                throw new InstancePersistenceException(exception.Message, exception);
            }
            return isExistingInstance;
        }
Пример #3
0
        private static void UpdateKeyData(InstancePersistenceContext context, SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceView instanceView = context.InstanceView;

            foreach (KeyValuePair <Guid, IDictionary <XName, InstanceValue> > pair in saveWorkflowCommand.InstanceKeysToAssociate)
            {
                if (!instanceView.InstanceKeys.ContainsKey(pair.Key))
                {
                    context.AssociatedInstanceKey(pair.Key);
                    if (pair.Value != null)
                    {
                        foreach (KeyValuePair <XName, InstanceValue> pair2 in pair.Value)
                        {
                            context.WroteInstanceKeyMetadataValue(pair.Key, pair2.Key, pair2.Value);
                        }
                    }
                }
            }
            foreach (Guid guid in saveWorkflowCommand.InstanceKeysToComplete)
            {
                InstanceKeyView view2;
                if (instanceView.InstanceKeys.TryGetValue(guid, out view2) && (view2.InstanceKeyState != InstanceKeyState.Completed))
                {
                    context.CompletedInstanceKey(guid);
                }
            }
            foreach (Guid guid2 in saveWorkflowCommand.InstanceKeysToFree)
            {
                InstanceKeyView view3;
                if (instanceView.InstanceKeys.TryGetValue(guid2, out view3))
                {
                    context.UnassociatedInstanceKey(guid2);
                }
            }
            foreach (KeyValuePair <Guid, IDictionary <XName, InstanceValue> > pair3 in saveWorkflowCommand.InstanceKeyMetadataChanges)
            {
                if (pair3.Value != null)
                {
                    foreach (KeyValuePair <XName, InstanceValue> pair4 in pair3.Value)
                    {
                        context.WroteInstanceKeyMetadataValue(pair3.Key, pair4.Key, pair4.Value);
                    }
                }
            }
            if (saveWorkflowCommand.CompleteInstance)
            {
                foreach (KeyValuePair <Guid, InstanceKeyView> pair5 in instanceView.InstanceKeys)
                {
                    if ((pair5.Value != null) && (pair5.Value.InstanceKeyState == InstanceKeyState.Associated))
                    {
                        context.CompletedInstanceKey(pair5.Key);
                    }
                }
            }
        }
        protected override Exception ProcessSqlResult(SqlDataReader reader)
        {
            Exception exception = StoreUtilities.GetNextResultSet(base.InstancePersistenceCommand.Name, reader);

            if (exception == null)
            {
                SaveWorkflowCommand  saveWorkflowCommand  = base.InstancePersistenceCommand as SaveWorkflowCommand;
                InstanceLockTracking instanceLockTracking = (InstanceLockTracking)(base.InstancePersistenceContext.UserContext);
                if ((this.serviceDeploymentHash != Guid.Empty) && (this.serviceDeploymentId == 0))
                {
                    this.serviceDeploymentId = reader.GetInt64(1);
                    PutServiceDeploymentId();
                    exception = StoreUtilities.GetNextResultSet(base.InstancePersistenceCommand.Name, reader);
                }

                if (exception == null)
                {
                    if (!base.InstancePersistenceContext.InstanceView.IsBoundToLock)
                    {
                        long instanceVersion = reader.GetInt64(1);
                        instanceLockTracking.TrackStoreLock(base.InstancePersistenceContext.InstanceView.InstanceId, instanceVersion, this.DependentTransaction);
                        base.InstancePersistenceContext.BindAcquiredLock(instanceVersion);
                    }

                    if (saveWorkflowCommand.InstanceData.Count > 0)
                    {
                        base.InstancePersistenceContext.PersistedInstance(saveWorkflowCommand.InstanceData);
                    }

                    SaveWorkflowAsyncResult.UpdateKeyData(base.InstancePersistenceContext, saveWorkflowCommand);

                    foreach (KeyValuePair <XName, InstanceValue> property in saveWorkflowCommand.InstanceMetadataChanges)
                    {
                        base.InstancePersistenceContext.WroteInstanceMetadataValue(property.Key, property.Value);
                    }

                    if (saveWorkflowCommand.CompleteInstance)
                    {
                        base.InstancePersistenceContext.CompletedInstance();
                    }

                    if (saveWorkflowCommand.UnlockInstance || saveWorkflowCommand.CompleteInstance)
                    {
                        instanceLockTracking.TrackStoreUnlock(this.DependentTransaction);
                        base.InstancePersistenceContext.InstanceHandle.Free();
                    }
                }
                else if (exception is InstanceLockLostException)
                {
                    base.InstancePersistenceContext.InstanceHandle.Free();
                }
            }

            return(exception);
        }
Пример #5
0
        private static string GetExecutionStatus(SaveWorkflowCommand saveWorkflowCommand)
        {
            string        str = null;
            InstanceValue value2;

            if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.StatusPropertyName, out value2))
            {
                str = (string)value2.Value;
            }
            return(str);
        }
        static string GetExecutionStatus(SaveWorkflowCommand saveWorkflowCommand)
        {
            string        executionStatus = null;
            InstanceValue executionStatusProperty;

            if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.StatusPropertyName, out executionStatusProperty))
            {
                executionStatus = (string)executionStatusProperty.Value;
            }

            return(executionStatus);
        }
        static bool IsReadyToRun(SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceValue statusPropertyValue;

            if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.StatusPropertyName, out statusPropertyValue) &&
                ((string)statusPropertyValue.Value) == SqlWorkflowInstanceStoreConstants.ExecutingStatusPropertyValue)
            {
                return(true);
            }

            return(false);
        }
Пример #8
0
        private static long?GetPendingTimerExpiration(SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceValue value2;

            if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.PendingTimerExpirationPropertyName, out value2))
            {
                DateTime time2 = (DateTime)value2.Value;
                TimeSpan span  = (TimeSpan)(time2.ToUniversalTime() - DateTime.UtcNow);
                return(new long?((long)span.TotalMilliseconds));
            }
            return(null);
        }
        static Int64?GetPendingTimerExpiration(SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceValue pendingTimerExpirationPropertyValue;

            if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.PendingTimerExpirationPropertyName, out pendingTimerExpirationPropertyValue))
            {
                DateTime pendingTimerExpiration = ((DateTime)pendingTimerExpirationPropertyValue.Value).ToUniversalTime();
                TimeSpan datetimeOffset         = pendingTimerExpiration - DateTime.UtcNow;

                return((Int64)datetimeOffset.TotalMilliseconds);
            }

            return(null);
        }
Пример #10
0
        protected override Exception ProcessSqlResult(SqlDataReader reader)
        {
            Exception nextResultSet = StoreUtilities.GetNextResultSet(base.InstancePersistenceCommand.Name, reader);

            if (nextResultSet == null)
            {
                SaveWorkflowCommand  instancePersistenceCommand = base.InstancePersistenceCommand as SaveWorkflowCommand;
                InstanceLockTracking userContext = (InstanceLockTracking)base.InstancePersistenceContext.UserContext;
                if ((this.serviceDeploymentHash != Guid.Empty) && (this.serviceDeploymentId == 0L))
                {
                    this.serviceDeploymentId = reader.GetInt64(1);
                    this.PutServiceDeploymentId();
                    nextResultSet = StoreUtilities.GetNextResultSet(base.InstancePersistenceCommand.Name, reader);
                }
                if (nextResultSet == null)
                {
                    if (!base.InstancePersistenceContext.InstanceView.IsBoundToLock)
                    {
                        long instanceVersion = reader.GetInt64(1);
                        userContext.TrackStoreLock(base.InstancePersistenceContext.InstanceView.InstanceId, instanceVersion, base.DependentTransaction);
                        base.InstancePersistenceContext.BindAcquiredLock(instanceVersion);
                    }
                    if (instancePersistenceCommand.InstanceData.Count > 0)
                    {
                        base.InstancePersistenceContext.PersistedInstance(instancePersistenceCommand.InstanceData);
                    }
                    UpdateKeyData(base.InstancePersistenceContext, instancePersistenceCommand);
                    foreach (KeyValuePair <XName, InstanceValue> pair in instancePersistenceCommand.InstanceMetadataChanges)
                    {
                        base.InstancePersistenceContext.WroteInstanceMetadataValue(pair.Key, pair.Value);
                    }
                    if (instancePersistenceCommand.CompleteInstance)
                    {
                        base.InstancePersistenceContext.CompletedInstance();
                    }
                    if (instancePersistenceCommand.UnlockInstance || instancePersistenceCommand.CompleteInstance)
                    {
                        userContext.TrackStoreUnlock(base.DependentTransaction);
                        base.InstancePersistenceContext.InstanceHandle.Free();
                    }
                    return(nextResultSet);
                }
                if (nextResultSet is InstanceLockLostException)
                {
                    base.InstancePersistenceContext.InstanceHandle.Free();
                }
            }
            return(nextResultSet);
        }
Пример #11
0
        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;
        }
Пример #12
0
        private static Guid?GetWorkflowHostType(SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceValue value2;

            if (!saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowNamespace.WorkflowHostType, out value2))
            {
                return(null);
            }
            XName name = value2.Value as XName;

            if (name == null)
            {
                throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(System.Activities.DurableInstancing.SR.InvalidWorkflowHostTypeValue(WorkflowNamespace.WorkflowHostType)));
            }
            return(new Guid(HashHelper.ComputeHash(Encoding.Unicode.GetBytes(((XName)value2.Value).ToString()))));
        }
        static Guid?GetWorkflowHostType(SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceValue instanceValue;

            if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowNamespace.WorkflowHostType, out instanceValue))
            {
                XName workflowHostType = instanceValue.Value as XName;

                if (workflowHostType == null)
                {
                    throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(SR.InvalidMetadataValue(WorkflowNamespace.WorkflowHostType, typeof(XName).Name)));
                }
                byte[] workflowHostTypeBuffer = Encoding.Unicode.GetBytes(((XName)instanceValue.Value).ToString());
                return(new Guid(HashHelper.ComputeHash(workflowHostTypeBuffer)));
            }
            return(null);
        }
Пример #14
0
        private static string GetBlockingBookmarks(SaveWorkflowCommand saveWorkflowCommand)
        {
            string        str = null;
            InstanceValue value2;

            if (!saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.BinaryBlockingBookmarksPropertyName, out value2))
            {
                return(str);
            }
            StringBuilder builder = new StringBuilder(0x200);
            IEnumerable <BookmarkInfo> enumerable = value2.Value as IEnumerable <BookmarkInfo>;

            foreach (BookmarkInfo info in enumerable)
            {
                builder.AppendFormat(CultureInfo.InvariantCulture, "[{0}: {1}]{2}", new object[] { info.BookmarkName, info.OwnerDisplayName, Environment.NewLine });
            }
            return(builder.ToString());
        }
        public static ArraySegment <byte> SerializeMetadataPropertyBag(SaveWorkflowCommand saveWorkflowCommand,
                                                                       InstancePersistenceContext context, InstanceEncodingOption instanceEncodingOption)
        {
            IObjectSerializer          serializer             = ObjectSerializerFactory.GetObjectSerializer(instanceEncodingOption);
            Dictionary <XName, object> propertyBagToSerialize = new Dictionary <XName, object>();

            if (context.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None)
            {
                foreach (KeyValuePair <XName, InstanceValue> metadataProperty in context.InstanceView.InstanceMetadata)
                {
                    if ((metadataProperty.Value.Options & InstanceValueOptions.WriteOnly) == 0)
                    {
                        propertyBagToSerialize.Add(metadataProperty.Key, metadataProperty.Value.Value);
                    }
                }
            }

            foreach (KeyValuePair <XName, InstanceValue> metadataChange in saveWorkflowCommand.InstanceMetadataChanges)
            {
                if (metadataChange.Value.IsDeletedValue)
                {
                    if (context.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None)
                    {
                        propertyBagToSerialize.Remove(metadataChange.Key);
                    }
                    else
                    {
                        propertyBagToSerialize[metadataChange.Key] = new DeletedMetadataValue();
                    }
                }
                else if ((metadataChange.Value.Options & InstanceValueOptions.WriteOnly) == 0)
                {
                    propertyBagToSerialize[metadataChange.Key] = metadataChange.Value.Value;
                }
            }

            if (propertyBagToSerialize.Count > 0)
            {
                return(serializer.SerializePropertyBag(propertyBagToSerialize));
            }

            return(new ArraySegment <byte>());
        }
        static string GetBlockingBookmarks(SaveWorkflowCommand saveWorkflowCommand)
        {
            string        blockingBookmarks = null;
            InstanceValue binaryBlockingBookmarks;

            if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.BinaryBlockingBookmarksPropertyName, out binaryBlockingBookmarks))
            {
                StringBuilder bookmarkListBuilder          = new StringBuilder(SqlWorkflowInstanceStoreConstants.DefaultStringBuilderCapacity);
                IEnumerable <BookmarkInfo> activeBookmarks = binaryBlockingBookmarks.Value as IEnumerable <BookmarkInfo>;

                foreach (BookmarkInfo bookmarkInfo in activeBookmarks)
                {
                    bookmarkListBuilder.AppendFormat(CultureInfo.InvariantCulture, "[{0}: {1}]{2}", bookmarkInfo.BookmarkName, bookmarkInfo.OwnerDisplayName, Environment.NewLine);
                }

                blockingBookmarks = bookmarkListBuilder.ToString();
            }

            return(blockingBookmarks);
        }
        public static ArraySegment <byte> SerializeMetadataPropertyBag(SaveWorkflowCommand saveWorkflowCommand, InstancePersistenceContext context, InstanceEncodingOption instanceEncodingOption)
        {
            IObjectSerializer          objectSerializer = ObjectSerializerFactory.GetObjectSerializer(instanceEncodingOption);
            Dictionary <XName, object> dictionary       = new Dictionary <XName, object>();

            if (context.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None)
            {
                foreach (KeyValuePair <XName, InstanceValue> pair in context.InstanceView.InstanceMetadata)
                {
                    if ((pair.Value.Options & InstanceValueOptions.WriteOnly) == InstanceValueOptions.None)
                    {
                        dictionary.Add(pair.Key, pair.Value.Value);
                    }
                }
            }
            foreach (KeyValuePair <XName, InstanceValue> pair2 in saveWorkflowCommand.InstanceMetadataChanges)
            {
                if (pair2.Value.IsDeletedValue)
                {
                    if (context.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None)
                    {
                        dictionary.Remove(pair2.Key);
                    }
                    else
                    {
                        DeletedMetadataValue value2 = new DeletedMetadataValue();
                        dictionary[pair2.Key] = value2;
                    }
                }
                else if ((pair2.Value.Options & InstanceValueOptions.WriteOnly) == InstanceValueOptions.None)
                {
                    dictionary[pair2.Key] = pair2.Value.Value;
                }
            }
            if (dictionary.Count > 0)
            {
                return(objectSerializer.SerializePropertyBag(dictionary));
            }
            return(new ArraySegment <byte>());
        }
Пример #18
0
        private static SuspensionStateChange GetSuspensionReason(SaveWorkflowCommand saveWorkflowCommand, out string suspensionReason, out string suspensionExceptionName)
        {
            InstanceValue value2;
            IDictionary <XName, InstanceValue> instanceMetadataChanges = saveWorkflowCommand.InstanceMetadataChanges;
            SuspensionStateChange noChange = SuspensionStateChange.NoChange;

            suspensionReason        = null;
            suspensionExceptionName = null;
            if (!instanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SuspendReason, out value2))
            {
                return(noChange);
            }
            if (!value2.IsDeletedValue)
            {
                noChange         = SuspensionStateChange.SuspendInstance;
                suspensionReason = (string)value2.Value;
                if (instanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SuspendException, out value2) && !value2.IsDeletedValue)
                {
                    suspensionExceptionName = ((Exception)value2.Value).GetType().ToString();
                }
                return(noChange);
            }
            return(SuspensionStateChange.UnsuspendInstance);
        }
        static void UpdateKeyData(InstancePersistenceContext context, SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceView instanceView = context.InstanceView;

            foreach (KeyValuePair <Guid, IDictionary <XName, InstanceValue> > keyEntry in saveWorkflowCommand.InstanceKeysToAssociate)
            {
                if (!instanceView.InstanceKeys.ContainsKey(keyEntry.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 key in saveWorkflowCommand.InstanceKeysToComplete)
            {
                InstanceKeyView existingKeyView;
                if (instanceView.InstanceKeys.TryGetValue(key, out existingKeyView))
                {
                    if (existingKeyView.InstanceKeyState != InstanceKeyState.Completed)
                    {
                        context.CompletedInstanceKey(key);
                    }
                }
            }

            foreach (Guid key in saveWorkflowCommand.InstanceKeysToFree)
            {
                InstanceKeyView existingKeyView;
                if (instanceView.InstanceKeys.TryGetValue(key, out existingKeyView))
                {
                    context.UnassociatedInstanceKey(key);
                }
            }

            foreach (KeyValuePair <Guid, IDictionary <XName, InstanceValue> > keyEntry in saveWorkflowCommand.InstanceKeyMetadataChanges)
            {
                if (keyEntry.Value != null)
                {
                    foreach (KeyValuePair <XName, InstanceValue> property in keyEntry.Value)
                    {
                        context.WroteInstanceKeyMetadataValue(keyEntry.Key, property.Key, property.Value);
                    }
                }
            }

            if (saveWorkflowCommand.CompleteInstance)
            {
                foreach (KeyValuePair <Guid, InstanceKeyView> instanceKeys in instanceView.InstanceKeys)
                {
                    if (instanceKeys.Value != null)
                    {
                        if (instanceKeys.Value.InstanceKeyState == InstanceKeyState.Associated)
                        {
                            context.CompletedInstanceKey(instanceKeys.Key);
                        }
                    }
                }
            }
        }
        static SuspensionStateChange GetSuspensionReason(SaveWorkflowCommand saveWorkflowCommand, out string suspensionReason, out string suspensionExceptionName)
        {
            IDictionary<XName, InstanceValue> instanceMetadataChanges = saveWorkflowCommand.InstanceMetadataChanges;
            SuspensionStateChange suspensionStateChange = SuspensionStateChange.NoChange;
            InstanceValue propertyValue;
            suspensionReason = null;
            suspensionExceptionName = null;

            if (instanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SuspendReason, out propertyValue))
            {
                if (!propertyValue.IsDeletedValue)
                {
                    suspensionStateChange = SuspensionStateChange.SuspendInstance;
                    suspensionReason = (string)propertyValue.Value;

                    if (instanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SuspendException, out propertyValue) && !propertyValue.IsDeletedValue)
                    {
                        suspensionExceptionName = ((Exception)propertyValue.Value).GetType().ToString();
                    }
                }
                else
                {
                    suspensionStateChange = SuspensionStateChange.UnsuspendInstance;
                }
            }

            return suspensionStateChange;
        }
        static string GetExecutionStatus(SaveWorkflowCommand saveWorkflowCommand)
        {
            string executionStatus = null;
            InstanceValue executionStatusProperty;

            if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.StatusPropertyName, out executionStatusProperty))
            {
                executionStatus = (string)executionStatusProperty.Value;
            }

            return executionStatus;
        }
        public static ArraySegment<byte> SerializeMetadataPropertyBag(SaveWorkflowCommand saveWorkflowCommand,
            InstancePersistenceContext context, InstanceEncodingOption instanceEncodingOption)
        {
            IObjectSerializer serializer = ObjectSerializerFactory.GetObjectSerializer(instanceEncodingOption);
            Dictionary<XName, object> propertyBagToSerialize = new Dictionary<XName, object>();

            if (context.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None)
            {
                foreach (KeyValuePair<XName, InstanceValue> metadataProperty in context.InstanceView.InstanceMetadata)
                {
                    if ((metadataProperty.Value.Options & InstanceValueOptions.WriteOnly) == 0)
                    {
                        propertyBagToSerialize.Add(metadataProperty.Key, metadataProperty.Value.Value);
                    }
                }
            }

            foreach (KeyValuePair<XName, InstanceValue> metadataChange in saveWorkflowCommand.InstanceMetadataChanges)
            {
                if (metadataChange.Value.IsDeletedValue)
                {
                    if (context.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None)
                    {
                        propertyBagToSerialize.Remove(metadataChange.Key);
                    }
                    else
                    {
                        propertyBagToSerialize[metadataChange.Key] = new DeletedMetadataValue();
                    }
                }
                else if ((metadataChange.Value.Options & InstanceValueOptions.WriteOnly) == 0)
                {
                    propertyBagToSerialize[metadataChange.Key] = metadataChange.Value.Value;
                }
            }

            if (propertyBagToSerialize.Count > 0)
            {
                return serializer.SerializePropertyBag(propertyBagToSerialize);
            }

            return new ArraySegment<byte>();
        }
 private void SerializePromotedProperties(SqlParameterCollection parameters, StringBuilder commandTextBuilder, SaveWorkflowCommand saveWorkflowCommand)
 {
     int num = 0;
     foreach (KeyValuePair<string, Tuple<List<XName>, List<XName>>> pair in base.Store.Promotions)
     {
         StringBuilder builder = new StringBuilder(0x200);
         int num2 = 1;
         bool flag = false;
         string str = string.Format(CultureInfo.InvariantCulture, "@promotionName{0}", new object[] { num });
         string str2 = string.Format(CultureInfo.InvariantCulture, "@instanceId{0}", new object[] { num });
         builder.Append(string.Format(CultureInfo.InvariantCulture, "exec {0}.[InsertPromotedProperties] ", new object[] { "[System.Activities.DurableInstancing]" }));
         builder.Append("@promotionName=");
         builder.Append(str);
         builder.Append(",");
         builder.Append("@instanceId=");
         builder.Append(str2);
         foreach (XName name in pair.Value.Item1)
         {
             InstanceValue value2;
             if (saveWorkflowCommand.InstanceData.TryGetValue(name, out value2))
             {
                 if (!SerializationUtilities.IsPropertyTypeSqlVariantCompatible(value2))
                 {
                     throw FxTrace.Exception.AsError(new InstancePersistenceException(System.Activities.DurableInstancing.SR.CannotPromoteAsSqlVariant(value2.Value.GetType().ToString(), name.ToString())));
                 }
                 string str3 = string.Format(CultureInfo.InvariantCulture, "@value{0}=", new object[] { num2 });
                 string str4 = string.Format(CultureInfo.InvariantCulture, "@value{0}_promotion{1}", new object[] { num2, num });
                 SqlParameter parameter = new SqlParameter {
                     SqlDbType = SqlDbType.Variant,
                     ParameterName = str4,
                     Value = value2.Value ?? DBNull.Value
                 };
                 parameters.Add(parameter);
                 builder.Append(", ");
                 builder.Append(str3);
                 builder.Append(str4);
                 flag = true;
             }
             num2++;
         }
         num2 = 0x21;
         foreach (XName name2 in pair.Value.Item2)
         {
             InstanceValue value3;
             IObjectSerializer objectSerializer = ObjectSerializerFactory.GetObjectSerializer(base.Store.InstanceEncodingOption);
             if (saveWorkflowCommand.InstanceData.TryGetValue(name2, out value3))
             {
                 string str5 = string.Format(CultureInfo.InvariantCulture, "@value{0}=", new object[] { num2 });
                 string parameterName = string.Format(CultureInfo.InvariantCulture, "@value{0}_promotion{1}", new object[] { num2, num });
                 AddSerializedProperty(objectSerializer.SerializeValue(value3.Value), parameters, parameterName);
                 builder.Append(", ");
                 builder.Append(str5);
                 builder.Append(parameterName);
                 flag = true;
             }
             num2++;
         }
         if (flag)
         {
             SqlParameter parameter2 = new SqlParameter {
                 SqlDbType = SqlDbType.NVarChar,
                 Size = 400,
                 ParameterName = str,
                 Value = pair.Key
             };
             parameters.Add(parameter2);
             SqlParameter parameter3 = new SqlParameter {
                 SqlDbType = SqlDbType.UniqueIdentifier,
                 ParameterName = str2,
                 Value = base.InstancePersistenceContext.InstanceView.InstanceId
             };
             parameters.Add(parameter3);
             builder.Append(";");
             commandTextBuilder.AppendLine(builder.ToString());
             num++;
         }
     }
 }
Пример #24
0
        private void SerializePromotedProperties(SqlParameterCollection parameters, StringBuilder commandTextBuilder, SaveWorkflowCommand saveWorkflowCommand)
        {
            int num = 0;

            foreach (KeyValuePair <string, Tuple <List <XName>, List <XName> > > pair in base.Store.Promotions)
            {
                StringBuilder builder = new StringBuilder(0x200);
                int           num2    = 1;
                bool          flag    = false;
                string        str     = string.Format(CultureInfo.InvariantCulture, "@promotionName{0}", new object[] { num });
                string        str2    = string.Format(CultureInfo.InvariantCulture, "@instanceId{0}", new object[] { num });
                builder.Append(string.Format(CultureInfo.InvariantCulture, "exec {0}.[InsertPromotedProperties] ", new object[] { "[System.Activities.DurableInstancing]" }));
                builder.Append("@promotionName=");
                builder.Append(str);
                builder.Append(",");
                builder.Append("@instanceId=");
                builder.Append(str2);
                foreach (XName name in pair.Value.Item1)
                {
                    InstanceValue value2;
                    if (saveWorkflowCommand.InstanceData.TryGetValue(name, out value2))
                    {
                        if (!SerializationUtilities.IsPropertyTypeSqlVariantCompatible(value2))
                        {
                            throw FxTrace.Exception.AsError(new InstancePersistenceException(System.Activities.DurableInstancing.SR.CannotPromoteAsSqlVariant(value2.Value.GetType().ToString(), name.ToString())));
                        }
                        string       str3      = string.Format(CultureInfo.InvariantCulture, "@value{0}=", new object[] { num2 });
                        string       str4      = string.Format(CultureInfo.InvariantCulture, "@value{0}_promotion{1}", new object[] { num2, num });
                        SqlParameter parameter = new SqlParameter {
                            SqlDbType     = SqlDbType.Variant,
                            ParameterName = str4,
                            Value         = value2.Value ?? DBNull.Value
                        };
                        parameters.Add(parameter);
                        builder.Append(", ");
                        builder.Append(str3);
                        builder.Append(str4);
                        flag = true;
                    }
                    num2++;
                }
                num2 = 0x21;
                foreach (XName name2 in pair.Value.Item2)
                {
                    InstanceValue     value3;
                    IObjectSerializer objectSerializer = ObjectSerializerFactory.GetObjectSerializer(base.Store.InstanceEncodingOption);
                    if (saveWorkflowCommand.InstanceData.TryGetValue(name2, out value3))
                    {
                        string str5          = string.Format(CultureInfo.InvariantCulture, "@value{0}=", new object[] { num2 });
                        string parameterName = string.Format(CultureInfo.InvariantCulture, "@value{0}_promotion{1}", new object[] { num2, num });
                        AddSerializedProperty(objectSerializer.SerializeValue(value3.Value), parameters, parameterName);
                        builder.Append(", ");
                        builder.Append(str5);
                        builder.Append(parameterName);
                        flag = true;
                    }
                    num2++;
                }
                if (flag)
                {
                    SqlParameter parameter2 = new SqlParameter {
                        SqlDbType     = SqlDbType.NVarChar,
                        Size          = 400,
                        ParameterName = str,
                        Value         = pair.Key
                    };
                    parameters.Add(parameter2);
                    SqlParameter parameter3 = new SqlParameter {
                        SqlDbType     = SqlDbType.UniqueIdentifier,
                        ParameterName = str2,
                        Value         = base.InstancePersistenceContext.InstanceView.InstanceId
                    };
                    parameters.Add(parameter3);
                    builder.Append(";");
                    commandTextBuilder.AppendLine(builder.ToString());
                    num++;
                }
            }
        }
Пример #25
0
        protected override void GenerateSqlCommand(SqlCommand command)
        {
            string str;
            string str2;
            SaveWorkflowCommand instancePersistenceCommand = base.InstancePersistenceCommand as SaveWorkflowCommand;
            StringBuilder       commandTextBuilder         = new StringBuilder(0x200);
            double totalMilliseconds          = base.TimeoutHelper.RemainingTime().TotalMilliseconds;
            SqlParameterCollection parameters = command.Parameters;
            SqlParameter           parameter  = new SqlParameter {
                ParameterName = "@instanceId",
                SqlDbType     = SqlDbType.UniqueIdentifier,
                Value         = base.InstancePersistenceContext.InstanceView.InstanceId
            };

            parameters.Add(parameter);
            SqlParameter parameter2 = new SqlParameter {
                ParameterName = "@surrogateLockOwnerId",
                SqlDbType     = SqlDbType.BigInt,
                Value         = base.StoreLock.SurrogateLockOwnerId
            };

            parameters.Add(parameter2);
            SqlParameter parameter3 = new SqlParameter {
                ParameterName = "@handleInstanceVersion",
                SqlDbType     = SqlDbType.BigInt,
                Value         = base.InstancePersistenceContext.InstanceVersion
            };

            parameters.Add(parameter3);
            SqlParameter parameter4 = new SqlParameter {
                ParameterName = "@handleIsBoundToLock",
                SqlDbType     = SqlDbType.Bit,
                Value         = base.InstancePersistenceContext.InstanceView.IsBoundToLock
            };

            parameters.Add(parameter4);
            SqlParameter parameter5 = new SqlParameter {
                ParameterName = "@timerDurationMilliseconds",
                SqlDbType     = SqlDbType.BigInt,
                Value         = GetPendingTimerExpiration(instancePersistenceCommand) ?? DBNull.Value
            };

            parameters.Add(parameter5);
            SqlParameter parameter6 = new SqlParameter {
                ParameterName = "@unlockInstance",
                SqlDbType     = SqlDbType.Bit,
                Value         = instancePersistenceCommand.UnlockInstance
            };

            parameters.Add(parameter6);
            SqlParameter parameter7 = new SqlParameter {
                ParameterName = "@suspensionStateChange",
                SqlDbType     = SqlDbType.TinyInt,
                Value         = GetSuspensionReason(instancePersistenceCommand, out str, out str2)
            };

            parameters.Add(parameter7);
            SqlParameter parameter8 = new SqlParameter {
                ParameterName = "@suspensionReason",
                SqlDbType     = SqlDbType.NVarChar,
                Value         = str ?? DBNull.Value
            };

            parameters.Add(parameter8);
            SqlParameter parameter9 = new SqlParameter {
                ParameterName = "@suspensionExceptionName",
                SqlDbType     = SqlDbType.NVarChar,
                Size          = 450,
                Value         = str2 ?? DBNull.Value
            };

            parameters.Add(parameter9);
            SqlParameter parameter10 = new SqlParameter {
                ParameterName = "@isCompleted",
                SqlDbType     = SqlDbType.Bit,
                Value         = instancePersistenceCommand.CompleteInstance
            };

            parameters.Add(parameter10);
            SqlParameter parameter11 = new SqlParameter {
                ParameterName = "@isReadyToRun",
                SqlDbType     = SqlDbType.Bit,
                Value         = IsReadyToRun(instancePersistenceCommand)
            };

            parameters.Add(parameter11);
            SqlParameter parameter12 = new SqlParameter {
                ParameterName = "@workflowHostType",
                SqlDbType     = SqlDbType.UniqueIdentifier,
                Value         = GetWorkflowHostType(instancePersistenceCommand) ?? DBNull.Value
            };

            parameters.Add(parameter12);
            SqlParameter parameter13 = new SqlParameter {
                ParameterName = "@operationTimeout",
                SqlDbType     = SqlDbType.Int,
                Value         = (totalMilliseconds < 2147483647.0) ? Convert.ToInt32(totalMilliseconds) : 0x7fffffff
            };

            parameters.Add(parameter13);
            commandTextBuilder.AppendLine("set nocount on\r\n\t                                        set transaction isolation level read committed\t\t\r\n\t                                        set xact_abort on\r\n                                            begin transaction");
            this.ExtractServiceDeploymentInformation(instancePersistenceCommand, commandTextBuilder, parameters);
            commandTextBuilder.AppendLine("declare @result int");
            commandTextBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "exec @result = {0}.[SaveInstance] {1} ;", new object[] { "[System.Activities.DurableInstancing]", "@instanceId, @surrogateLockOwnerId, @handleInstanceVersion, @handleIsBoundToLock,\r\n@primitiveDataProperties, @complexDataProperties, @writeOnlyPrimitiveDataProperties, @writeOnlyComplexDataProperties, @metadataProperties,\r\n@metadataIsConsistent, @encodingOption, @timerDurationMilliseconds, @suspensionStateChange, @suspensionReason, @suspensionExceptionName, @keysToAssociate,\r\n@keysToComplete, @keysToFree, @concatenatedKeyProperties, @unlockInstance, @isReadyToRun, @isCompleted, @singleKeyId,\r\n@lastMachineRunOn, @executionStatus, @blockingBookmarks, @workflowHostType, @serviceDeploymentId, @operationTimeout" }));
            commandTextBuilder.AppendLine("if (@result = 0)");
            commandTextBuilder.AppendLine("begin");
            this.SerializeAssociatedData(parameters, instancePersistenceCommand, commandTextBuilder);
            commandTextBuilder.AppendLine("commit transaction");
            commandTextBuilder.AppendLine("end");
            commandTextBuilder.AppendLine("else");
            commandTextBuilder.AppendLine("rollback transaction");
            this.commandText = commandTextBuilder.ToString();
        }
Пример #26
0
        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;
            }
        }
        protected override void GenerateSqlCommand(SqlCommand command)
        {
            SaveWorkflowCommand saveWorkflowCommand = base.InstancePersistenceCommand as SaveWorkflowCommand;
            StringBuilder       commandTextBuilder  = new StringBuilder(SqlWorkflowInstanceStoreConstants.DefaultStringBuilderCapacity);
            double operationTimeout           = this.TimeoutHelper.RemainingTime().TotalMilliseconds;
            SqlParameterCollection parameters = command.Parameters;
            string suspensionReason;
            string suspensionExceptionName;

            parameters.Add(new SqlParameter {
                ParameterName = "@instanceId", SqlDbType = SqlDbType.UniqueIdentifier, Value = base.InstancePersistenceContext.InstanceView.InstanceId
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@surrogateLockOwnerId", SqlDbType = SqlDbType.BigInt, Value = base.StoreLock.SurrogateLockOwnerId
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@handleInstanceVersion", SqlDbType = SqlDbType.BigInt, Value = base.InstancePersistenceContext.InstanceVersion
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@handleIsBoundToLock", SqlDbType = SqlDbType.Bit, Value = base.InstancePersistenceContext.InstanceView.IsBoundToLock
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@timerDurationMilliseconds", SqlDbType = SqlDbType.BigInt, Value = (object)GetPendingTimerExpiration(saveWorkflowCommand) ?? DBNull.Value
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@unlockInstance", SqlDbType = SqlDbType.Bit, Value = saveWorkflowCommand.UnlockInstance
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@suspensionStateChange", SqlDbType = SqlDbType.TinyInt, Value = GetSuspensionReason(saveWorkflowCommand, out suspensionReason, out suspensionExceptionName)
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@suspensionReason", SqlDbType = SqlDbType.NVarChar, Value = (object)suspensionReason ?? DBNull.Value
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@suspensionExceptionName", SqlDbType = SqlDbType.NVarChar, Size = 450, Value = (object)suspensionExceptionName ?? DBNull.Value
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@isCompleted", SqlDbType = SqlDbType.Bit, Value = saveWorkflowCommand.CompleteInstance
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@isReadyToRun", SqlDbType = SqlDbType.Bit, Value = IsReadyToRun(saveWorkflowCommand)
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@workflowHostType", SqlDbType = SqlDbType.UniqueIdentifier, Value = (object)GetWorkflowHostType(saveWorkflowCommand) ?? DBNull.Value
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@operationTimeout", SqlDbType = SqlDbType.Int, Value = (operationTimeout < Int32.MaxValue) ? Convert.ToInt32(operationTimeout) : Int32.MaxValue
            });

            string parameterNames = null;

            if (base.Store.DatabaseVersion >= StoreUtilities.Version45)
            {
                string identityMetadataXml = SerializationUtilities.GetIdentityMetadataXml(saveWorkflowCommand);
                parameters.Add(new SqlParameter {
                    ParameterName = "@identityMetadata", SqlDbType = SqlDbType.Xml, Value = (object)identityMetadataXml ?? DBNull.Value
                });

                parameterNames = SaveWorkflowAsyncResult.storedProcedureParameters;
            }
            else
            {
                parameterNames = SaveWorkflowAsyncResult.storedProcedureParameters40;
            }

            commandTextBuilder.AppendLine(@"set nocount on
                                            set transaction isolation level read committed		
                                            set xact_abort on
                                            begin transaction");

            ExtractServiceDeploymentInformation(saveWorkflowCommand, commandTextBuilder, parameters);

            commandTextBuilder.AppendLine("declare @result int");
            commandTextBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "exec @result = {0}.[SaveInstance] {1} ;",
                                                        SqlWorkflowInstanceStoreConstants.DefaultSchema, parameterNames));
            commandTextBuilder.AppendLine("if (@result = 0)");
            commandTextBuilder.AppendLine("begin");

            SerializeAssociatedData(parameters, saveWorkflowCommand, commandTextBuilder);

            commandTextBuilder.AppendLine("commit transaction");
            commandTextBuilder.AppendLine("end");
            commandTextBuilder.AppendLine("else");
            commandTextBuilder.AppendLine("rollback transaction");

            this.commandText = commandTextBuilder.ToString();
        }
        void SerializePromotedProperties(SqlParameterCollection parameters, StringBuilder commandTextBuilder, SaveWorkflowCommand saveWorkflowCommand)
        {
            const int    SqlVariantStartColumn  = 1;
            const string promotionNameParameter = "@promotionName=";
            const string instanceIdParameter    = "@instanceId=";
            int          promotionNumber        = 0;

            foreach (KeyValuePair <string, Tuple <List <XName>, List <XName> > > promotion in base.Store.Promotions)
            {
                StringBuilder storedProcInvocationBuilder = new StringBuilder(SqlWorkflowInstanceStoreConstants.DefaultStringBuilderCapacity);
                int           column                = SqlVariantStartColumn;
                bool          addPromotion          = false;
                string        promotionNameArgument = string.Format(CultureInfo.InvariantCulture, "@promotionName{0}", promotionNumber);
                string        instanceIdArgument    = string.Format(CultureInfo.InvariantCulture, "@instanceId{0}", promotionNumber);

                storedProcInvocationBuilder.Append(string.Format(CultureInfo.InvariantCulture, "exec {0}.[InsertPromotedProperties] ", SqlWorkflowInstanceStoreConstants.DefaultSchema));
                storedProcInvocationBuilder.Append(promotionNameParameter);
                storedProcInvocationBuilder.Append(promotionNameArgument);
                storedProcInvocationBuilder.Append(",");
                storedProcInvocationBuilder.Append(instanceIdParameter);
                storedProcInvocationBuilder.Append(instanceIdArgument);

                foreach (XName name in promotion.Value.Item1)
                {
                    InstanceValue propertyValue;

                    if (saveWorkflowCommand.InstanceData.TryGetValue(name, out propertyValue))
                    {
                        if (!SerializationUtilities.IsPropertyTypeSqlVariantCompatible(propertyValue))
                        {
                            throw FxTrace.Exception.AsError(new InstancePersistenceException(SR.CannotPromoteAsSqlVariant(propertyValue.Value.GetType().ToString(), name.ToString())));
                        }

                        string parameterName = string.Format(CultureInfo.InvariantCulture, "@value{0}=", column);
                        string argumentName  = string.Format(CultureInfo.InvariantCulture, "@value{0}_promotion{1}", column, promotionNumber);
                        parameters.Add(new SqlParameter()
                        {
                            SqlDbType = SqlDbType.Variant, ParameterName = argumentName, Value = propertyValue.Value ?? DBNull.Value
                        });

                        storedProcInvocationBuilder.Append(", ");
                        storedProcInvocationBuilder.Append(parameterName);
                        storedProcInvocationBuilder.Append(argumentName);
                        addPromotion = true;
                    }
                    column++;
                }

                column = SqlVariantStartColumn + SqlWorkflowInstanceStoreConstants.MaximumPropertiesPerPromotion;

                foreach (XName name in promotion.Value.Item2)
                {
                    InstanceValue     propertyValue;
                    IObjectSerializer serializer = ObjectSerializerFactory.GetObjectSerializer(base.Store.InstanceEncodingOption);

                    if (saveWorkflowCommand.InstanceData.TryGetValue(name, out propertyValue))
                    {
                        string parameterName = string.Format(CultureInfo.InvariantCulture, "@value{0}=", column);
                        string argumentName  = string.Format(CultureInfo.InvariantCulture, "@value{0}_promotion{1}", column, promotionNumber);

                        SaveWorkflowAsyncResult.AddSerializedProperty(serializer.SerializeValue(propertyValue.Value), parameters, argumentName);
                        storedProcInvocationBuilder.Append(", ");
                        storedProcInvocationBuilder.Append(parameterName);
                        storedProcInvocationBuilder.Append(argumentName);
                        addPromotion = true;
                    }
                    column++;
                }

                if (addPromotion)
                {
                    parameters.Add(new SqlParameter()
                    {
                        SqlDbType = SqlDbType.NVarChar, Size = 400, ParameterName = promotionNameArgument, Value = promotion.Key
                    });
                    parameters.Add(new SqlParameter()
                    {
                        SqlDbType = SqlDbType.UniqueIdentifier, ParameterName = instanceIdArgument, Value = base.InstancePersistenceContext.InstanceView.InstanceId
                    });
                    storedProcInvocationBuilder.Append(";");
                    commandTextBuilder.AppendLine(storedProcInvocationBuilder.ToString());
                    promotionNumber++;
                }
            }
        }
        void SerializeAssociatedData(SqlParameterCollection parameters, SaveWorkflowCommand saveWorkflowCommand, StringBuilder commandTextBuilder)
        {
            if (saveWorkflowCommand.CompleteInstance && base.Store.InstanceCompletionAction == InstanceCompletionAction.DeleteAll)
            {
                parameters.Add(new SqlParameter {
                    ParameterName = "@keysToAssociate", SqlDbType = SqlDbType.Xml, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@singleKeyId", SqlDbType = SqlDbType.UniqueIdentifier, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@keysToComplete", SqlDbType = SqlDbType.Xml, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@keysToFree", SqlDbType = SqlDbType.Xml, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@concatenatedKeyProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@primitiveDataProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@complexDataProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@writeOnlyPrimitiveDataProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@writeOnlyComplexDataProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@metadataProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@metadataIsConsistent", SqlDbType = SqlDbType.Bit, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@encodingOption", SqlDbType = SqlDbType.TinyInt, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@lastMachineRunOn", SqlDbType = SqlDbType.NVarChar, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@executionStatus", SqlDbType = SqlDbType.NVarChar, Value = DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@blockingBookmarks", SqlDbType = SqlDbType.NVarChar, Value = DBNull.Value
                });

                return;
            }

            List <CorrelationKey> keysToAssociate = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToAssociate, base.Store.InstanceEncodingOption);
            List <CorrelationKey> keysToComplete  = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToComplete);
            List <CorrelationKey> keysToFree      = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToFree);

            ArraySegment <byte>[] dataProperties     = SerializationUtilities.SerializePropertyBag(saveWorkflowCommand.InstanceData, base.Store.InstanceEncodingOption);
            ArraySegment <byte>   metadataProperties = SerializationUtilities.SerializeMetadataPropertyBag(saveWorkflowCommand, base.InstancePersistenceContext, base.Store.InstanceEncodingOption);

            byte[] concatenatedKeyProperties = SerializationUtilities.CreateKeyBinaryBlob(keysToAssociate);
            bool   metadataConsistency       = (base.InstancePersistenceContext.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None);
            bool   singleKeyToAssociate      = (keysToAssociate != null && keysToAssociate.Count == 1);

            parameters.Add(new SqlParameter {
                ParameterName = "@keysToAssociate", SqlDbType = SqlDbType.Xml, Value = singleKeyToAssociate ? DBNull.Value : SerializationUtilities.CreateCorrelationKeyXmlBlob(keysToAssociate)
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@singleKeyId", SqlDbType = SqlDbType.UniqueIdentifier, Value = singleKeyToAssociate ? keysToAssociate[0].KeyId : (object)DBNull.Value
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@keysToComplete", SqlDbType = SqlDbType.Xml, Value = SerializationUtilities.CreateCorrelationKeyXmlBlob(keysToComplete)
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@keysToFree", SqlDbType = SqlDbType.Xml, Value = SerializationUtilities.CreateCorrelationKeyXmlBlob(keysToFree)
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@concatenatedKeyProperties", SqlDbType = SqlDbType.VarBinary, Size = -1, Value = (object)concatenatedKeyProperties ?? DBNull.Value
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@metadataIsConsistent", SqlDbType = SqlDbType.Bit, Value = metadataConsistency
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@encodingOption", SqlDbType = SqlDbType.TinyInt, Value = base.Store.InstanceEncodingOption
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@lastMachineRunOn", SqlDbType = SqlDbType.NVarChar, Size = 450, Value = SqlWorkflowInstanceStoreConstants.MachineName
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@executionStatus", SqlDbType = SqlDbType.NVarChar, Size = 450, Value = GetExecutionStatus(saveWorkflowCommand) ?? (object)DBNull.Value
            });
            parameters.Add(new SqlParameter {
                ParameterName = "@blockingBookmarks", SqlDbType = SqlDbType.NVarChar, Size = -1, Value = GetBlockingBookmarks(saveWorkflowCommand) ?? (object)DBNull.Value
            });

            ArraySegment <byte>[] properties = { dataProperties[0], dataProperties[1], dataProperties[2], dataProperties[3], metadataProperties };
            string[] dataPropertyParameters  = { "@primitiveDataProperties", "@complexDataProperties", "@writeOnlyPrimitiveDataProperties", @"writeOnlyComplexDataProperties", "@metadataProperties" };

            for (int i = 0; i < 5; i++)
            {
                SaveWorkflowAsyncResult.AddSerializedProperty(properties[i], parameters, dataPropertyParameters[i]);
            }

            this.SerializePromotedProperties(parameters, commandTextBuilder, saveWorkflowCommand);
        }
        void ExtractServiceDeploymentInformation(SaveWorkflowCommand saveWorkflowCommand, StringBuilder commandTextBuilder, SqlParameterCollection parameters)
        {
            InstanceValue instanceValue;
            //Extract the activation parameters
            string serviceName             = null;
            string serviceNamespace        = null;
            string site                    = null;
            string relativeApplicationPath = null;
            string relativeServicePath     = null;

            if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(PersistenceMetadataNamespace.ActivationType, out instanceValue))
            {
                if (PersistenceMetadataNamespace.ActivationTypes.WAS.Equals(instanceValue.Value))
                {
                    if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.Service, out instanceValue))
                    {
                        serviceName      = ((XName)instanceValue.Value).LocalName;
                        serviceNamespace = ((XName)instanceValue.Value).Namespace.NamespaceName;
                    }
                    if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SiteName, out instanceValue))
                    {
                        site = (string)instanceValue.Value;
                    }
                    if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.RelativeApplicationPath, out instanceValue))
                    {
                        relativeApplicationPath = (string)instanceValue.Value;
                    }
                    if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.RelativeServicePath, out instanceValue))
                    {
                        relativeServicePath = (string)instanceValue.Value;
                    }

                    byte[] serviceDeploymentHashBuffer = Encoding.Unicode.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}#{1}#{2}#{3}#{4}",
                                                                                                 serviceName ?? string.Empty, serviceNamespace ?? string.Empty, site ?? string.Empty, relativeApplicationPath ?? string.Empty, relativeServicePath ?? string.Empty));
                    this.serviceDeploymentHash = new Guid(HashHelper.ComputeHash(serviceDeploymentHashBuffer));

                    //Get the service id has been seen before, get it from the cache
                    GetServiceDeploymentId();
                }
                else
                {
                    throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(SR.NonWASActivationNotSupported));
                }
            }

            if ((this.serviceDeploymentHash != Guid.Empty) && (this.serviceDeploymentId == 0))
            {
                //This is the first time we see this service deployment so we need to create a new entry for it before creating the instance
                commandTextBuilder.AppendLine("declare @serviceDeploymentId bigint");
                commandTextBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "exec {0}.[CreateServiceDeployment] {1} ;",
                                                            SqlWorkflowInstanceStoreConstants.DefaultSchema, SaveWorkflowAsyncResult.createServiceDeploymentStoredProcedureParameters));

                parameters.Add(new SqlParameter {
                    ParameterName = "@serviceDeploymentHash", SqlDbType = SqlDbType.UniqueIdentifier, Value = this.serviceDeploymentHash
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@serviceName", Size = -1, SqlDbType = SqlDbType.NVarChar, Value = serviceName ?? (object)DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@serviceNamespace", Size = -1, SqlDbType = SqlDbType.NVarChar, Value = serviceNamespace ?? (object)DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@siteName", Size = -1, SqlDbType = SqlDbType.NVarChar, Value = site ?? (object)DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@relativeServicePath", Size = -1, SqlDbType = SqlDbType.NVarChar, Value = relativeServicePath ?? (object)DBNull.Value
                });
                parameters.Add(new SqlParameter {
                    ParameterName = "@relativeApplicationPath", Size = -1, SqlDbType = SqlDbType.NVarChar, Value = relativeApplicationPath ?? (object)DBNull.Value
                });
            }
            else
            {
                parameters.Add(new SqlParameter {
                    ParameterName = "@serviceDeploymentId", SqlDbType = SqlDbType.BigInt, Value = (this.serviceDeploymentId != 0) ? (object)this.serviceDeploymentId : (object)DBNull.Value
                });
            }
        }
Пример #31
0
        private Dictionary<XName, object> SerializeInstanceMetadata(InstancePersistenceContext context, SaveWorkflowCommand command)
        {
            Dictionary<XName, object> metadata = null;

            foreach (var property in command.InstanceMetadataChanges)
            {
                if (!property.Value.Options.HasFlag(InstanceValueOptions.WriteOnly))
                {
                    if (metadata == null)
                    {
                        metadata = new Dictionary<XName, object>();
                        // copy current metadata. note that we must rid of InstanceValue as it is not properly serializeable
                        foreach (var m in context.InstanceView.InstanceMetadata)
                        {
                            metadata.Add(m.Key, m.Value.Value);
                        }
                    }

                    if (metadata.ContainsKey(property.Key))
                    {
                        if (property.Value.IsDeletedValue) metadata.Remove(property.Key);
                        else metadata[property.Key] = property.Value.Value;
                    }
                    else
                    {
                        if (!property.Value.IsDeletedValue) metadata.Add(property.Key, property.Value.Value);
                    }
                }
            }

            if (metadata == null)
                metadata = new Dictionary<XName, object>();

            return metadata;
        }
 private static void UpdateKeyData(InstancePersistenceContext context, SaveWorkflowCommand saveWorkflowCommand)
 {
     InstanceView instanceView = context.InstanceView;
     foreach (KeyValuePair<Guid, IDictionary<XName, InstanceValue>> pair in saveWorkflowCommand.InstanceKeysToAssociate)
     {
         if (!instanceView.InstanceKeys.ContainsKey(pair.Key))
         {
             context.AssociatedInstanceKey(pair.Key);
             if (pair.Value != null)
             {
                 foreach (KeyValuePair<XName, InstanceValue> pair2 in pair.Value)
                 {
                     context.WroteInstanceKeyMetadataValue(pair.Key, pair2.Key, pair2.Value);
                 }
             }
         }
     }
     foreach (Guid guid in saveWorkflowCommand.InstanceKeysToComplete)
     {
         InstanceKeyView view2;
         if (instanceView.InstanceKeys.TryGetValue(guid, out view2) && (view2.InstanceKeyState != InstanceKeyState.Completed))
         {
             context.CompletedInstanceKey(guid);
         }
     }
     foreach (Guid guid2 in saveWorkflowCommand.InstanceKeysToFree)
     {
         InstanceKeyView view3;
         if (instanceView.InstanceKeys.TryGetValue(guid2, out view3))
         {
             context.UnassociatedInstanceKey(guid2);
         }
     }
     foreach (KeyValuePair<Guid, IDictionary<XName, InstanceValue>> pair3 in saveWorkflowCommand.InstanceKeyMetadataChanges)
     {
         if (pair3.Value != null)
         {
             foreach (KeyValuePair<XName, InstanceValue> pair4 in pair3.Value)
             {
                 context.WroteInstanceKeyMetadataValue(pair3.Key, pair4.Key, pair4.Value);
             }
         }
     }
     if (saveWorkflowCommand.CompleteInstance)
     {
         foreach (KeyValuePair<Guid, InstanceKeyView> pair5 in instanceView.InstanceKeys)
         {
             if ((pair5.Value != null) && (pair5.Value.InstanceKeyState == InstanceKeyState.Associated))
             {
                 context.CompletedInstanceKey(pair5.Key);
             }
         }
     }
 }
 private void ExtractServiceDeploymentInformation(SaveWorkflowCommand saveWorkflowCommand, StringBuilder commandTextBuilder, SqlParameterCollection parameters)
 {
     InstanceValue value2;
     string localName = null;
     string namespaceName = null;
     string str3 = null;
     string str4 = null;
     string str5 = null;
     if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(PersistenceMetadataNamespace.ActivationType, out value2))
     {
         if (!PersistenceMetadataNamespace.ActivationTypes.WAS.Equals(value2.Value))
         {
             throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(System.Activities.DurableInstancing.SR.NonWASActivationNotSupported));
         }
         if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.Service, out value2))
         {
             localName = ((XName) value2.Value).LocalName;
             namespaceName = ((XName) value2.Value).Namespace.NamespaceName;
         }
         if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SiteName, out value2))
         {
             str3 = (string) value2.Value;
         }
         if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.RelativeApplicationPath, out value2))
         {
             str4 = (string) value2.Value;
         }
         if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.RelativeServicePath, out value2))
         {
             str5 = (string) value2.Value;
         }
         object[] args = new object[] { localName ?? string.Empty, namespaceName ?? string.Empty, str3 ?? string.Empty, str4 ?? string.Empty, str5 ?? string.Empty };
         byte[] bytes = Encoding.Unicode.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}#{1}#{2}#{3}#{4}", args));
         this.serviceDeploymentHash = new Guid(HashHelper.ComputeHash(bytes));
         this.GetServiceDeploymentId();
     }
     if ((this.serviceDeploymentHash != Guid.Empty) && (this.serviceDeploymentId == 0L))
     {
         commandTextBuilder.AppendLine("declare @serviceDeploymentId bigint");
         commandTextBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "exec {0}.[CreateServiceDeployment] {1} ;", new object[] { "[System.Activities.DurableInstancing]", "@serviceDeploymentHash, @siteName, @relativeServicePath, @relativeApplicationPath,\r\n                @serviceName, @serviceNamespace, @serviceDeploymentId output" }));
         SqlParameter parameter = new SqlParameter {
             ParameterName = "@serviceDeploymentHash",
             SqlDbType = SqlDbType.UniqueIdentifier,
             Value = this.serviceDeploymentHash
         };
         parameters.Add(parameter);
         SqlParameter parameter2 = new SqlParameter {
             ParameterName = "@serviceName",
             Size = -1,
             SqlDbType = SqlDbType.NVarChar,
             Value = localName ?? DBNull.Value
         };
         parameters.Add(parameter2);
         SqlParameter parameter3 = new SqlParameter {
             ParameterName = "@serviceNamespace",
             Size = -1,
             SqlDbType = SqlDbType.NVarChar,
             Value = namespaceName ?? DBNull.Value
         };
         parameters.Add(parameter3);
         SqlParameter parameter4 = new SqlParameter {
             ParameterName = "@siteName",
             Size = -1,
             SqlDbType = SqlDbType.NVarChar,
             Value = str3 ?? DBNull.Value
         };
         parameters.Add(parameter4);
         SqlParameter parameter5 = new SqlParameter {
             ParameterName = "@relativeServicePath",
             Size = -1,
             SqlDbType = SqlDbType.NVarChar,
             Value = str5 ?? DBNull.Value
         };
         parameters.Add(parameter5);
         SqlParameter parameter6 = new SqlParameter {
             ParameterName = "@relativeApplicationPath",
             Size = -1,
             SqlDbType = SqlDbType.NVarChar,
             Value = str4 ?? DBNull.Value
         };
         parameters.Add(parameter6);
     }
     else
     {
         SqlParameter parameter7 = new SqlParameter {
             ParameterName = "@serviceDeploymentId",
             SqlDbType = SqlDbType.BigInt,
             Value = (this.serviceDeploymentId != 0L) ? ((object) this.serviceDeploymentId) : ((object) DBNull.Value)
         };
         parameters.Add(parameter7);
     }
 }
 private static SuspensionStateChange GetSuspensionReason(SaveWorkflowCommand saveWorkflowCommand, out string suspensionReason, out string suspensionExceptionName)
 {
     InstanceValue value2;
     IDictionary<XName, InstanceValue> instanceMetadataChanges = saveWorkflowCommand.InstanceMetadataChanges;
     SuspensionStateChange noChange = SuspensionStateChange.NoChange;
     suspensionReason = null;
     suspensionExceptionName = null;
     if (!instanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SuspendReason, out value2))
     {
         return noChange;
     }
     if (!value2.IsDeletedValue)
     {
         noChange = SuspensionStateChange.SuspendInstance;
         suspensionReason = (string) value2.Value;
         if (instanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SuspendException, out value2) && !value2.IsDeletedValue)
         {
             suspensionExceptionName = ((Exception) value2.Value).GetType().ToString();
         }
         return noChange;
     }
     return SuspensionStateChange.UnsuspendInstance;
 }
 private static bool IsReadyToRun(SaveWorkflowCommand saveWorkflowCommand)
 {
     InstanceValue value2;
     return (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.StatusPropertyName, out value2) && (((string) value2.Value) == "Executing"));
 }
        public static string GetIdentityMetadataXml(InstancePersistenceCommand command)
        {
            StringBuilder stringBuilder          = new StringBuilder(512);
            Guid          idHash                 = Guid.Empty;
            Guid          idAnyRevisionHash      = Guid.Empty;
            int           workflowIdentityFilter = (int)WorkflowIdentityFilter.Exact;

            IList <WorkflowIdentity> identityCollection = null;

            if (command is CreateWorkflowOwnerWithIdentityCommand)
            {
                InstanceValue instanceValueIdentityCollection       = null;
                CreateWorkflowOwnerWithIdentityCommand ownerCommand = command as CreateWorkflowOwnerWithIdentityCommand;

                if (ownerCommand.InstanceOwnerMetadata.TryGetValue(Workflow45Namespace.DefinitionIdentities, out instanceValueIdentityCollection))
                {
                    if (instanceValueIdentityCollection.Value != null)
                    {
                        identityCollection = instanceValueIdentityCollection.Value as IList <WorkflowIdentity>;
                        if (identityCollection == null)
                        {
                            string typeName = typeof(IList <>).Name.Replace("`1", "<" + typeof(WorkflowIdentity).Name + ">");
                            throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(SR.InvalidMetadataValue(Workflow45Namespace.DefinitionIdentities, typeName)));
                        }
                    }
                }

                InstanceValue instanceValue = null;
                if (ownerCommand.InstanceOwnerMetadata.TryGetValue(Workflow45Namespace.DefinitionIdentityFilter, out instanceValue))
                {
                    if (instanceValue.Value != null)
                    {
                        if (instanceValue.Value is WorkflowIdentityFilter)
                        {
                            workflowIdentityFilter = (int)instanceValue.Value;
                        }
                        else
                        {
                            workflowIdentityFilter = -1;
                        }

                        if (workflowIdentityFilter != (int)WorkflowIdentityFilter.Exact &&
                            workflowIdentityFilter != (int)WorkflowIdentityFilter.Any &&
                            workflowIdentityFilter != (int)WorkflowIdentityFilter.AnyRevision)
                        {
                            throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(SR.InvalidMetadataValue(Workflow45Namespace.DefinitionIdentityFilter, typeof(WorkflowIdentityFilter).Name)));
                        }
                    }
                }
            }
            else if (command is SaveWorkflowCommand)
            {
                InstanceValue       instanceValue = null;
                SaveWorkflowCommand saveCommand   = command as SaveWorkflowCommand;
                if (saveCommand.InstanceMetadataChanges.TryGetValue(Workflow45Namespace.DefinitionIdentity, out instanceValue))
                {
                    if (!instanceValue.IsDeletedValue && instanceValue.Value != null)
                    {
                        identityCollection = new Collection <WorkflowIdentity>();
                        if (!(instanceValue.Value is WorkflowIdentity))
                        {
                            throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(SR.InvalidMetadataValue(Workflow45Namespace.DefinitionIdentity, typeof(WorkflowIdentity).Name)));
                        }

                        identityCollection.Add((WorkflowIdentity)instanceValue.Value);
                    }
                }
                else
                {
                    // If identity isn't specified, we preserve the instance's existing identity
                    return(null);
                }
            }
            else
            {
                return(null);
            }

            if (identityCollection == null)
            {
                // Assume NULL Identity
                identityCollection = new Collection <WorkflowIdentity>();
                identityCollection.Add(null);
            }

            using (XmlWriter xmlWriter = XmlWriter.Create(stringBuilder))
            {
                xmlWriter.WriteStartDocument();
                xmlWriter.WriteStartElement("IdentityMetadata");

                // Write the Identity Collection
                xmlWriter.WriteStartElement("IdentityCollection");
                foreach (WorkflowIdentity id in identityCollection)
                {
                    xmlWriter.WriteStartElement("Identity");

                    if (id == null)
                    {
                        xmlWriter.WriteElementString("DefinitionIdentityHash", Guid.Empty.ToString());
                        xmlWriter.WriteElementString("DefinitionIdentityAnyRevisionHash", Guid.Empty.ToString());
                    }
                    else
                    {
                        idHash            = GetIdentityHash(id);
                        idAnyRevisionHash = GetIdentityAnyRevisionFilterHash(id);

                        xmlWriter.WriteElementString("DefinitionIdentityHash", idHash.ToString());
                        xmlWriter.WriteElementString("DefinitionIdentityAnyRevisionHash", idAnyRevisionHash.ToString());
                        xmlWriter.WriteElementString("Name", id.Name);

                        if (id.Package != null)
                        {
                            xmlWriter.WriteElementString("Package", id.Package);
                        }

                        if (id.Version != null)
                        {
                            xmlWriter.WriteElementString("Major", id.Version.Major.ToString(CultureInfo.InvariantCulture));
                            xmlWriter.WriteElementString("Minor", id.Version.Minor.ToString(CultureInfo.InvariantCulture));
                            if (id.Version.Build >= 0)
                            {
                                xmlWriter.WriteElementString("Build", id.Version.Build.ToString(CultureInfo.InvariantCulture));
                                if (id.Version.Revision >= 0)
                                {
                                    xmlWriter.WriteElementString("Revision", id.Version.Revision.ToString(CultureInfo.InvariantCulture));
                                }
                            }
                        }
                    }

                    xmlWriter.WriteEndElement();
                }
                xmlWriter.WriteEndElement();

                // Write the WorkflowIdentityFilter
                xmlWriter.WriteElementString("WorkflowIdentityFilter", workflowIdentityFilter.ToString(CultureInfo.InvariantCulture));

                xmlWriter.WriteEndElement();
            }
            return(stringBuilder.ToString());
        }
 private static string GetExecutionStatus(SaveWorkflowCommand saveWorkflowCommand)
 {
     string str = null;
     InstanceValue value2;
     if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.StatusPropertyName, out value2))
     {
         str = (string) value2.Value;
     }
     return str;
 }
 public static ArraySegment<byte> SerializeMetadataPropertyBag(SaveWorkflowCommand saveWorkflowCommand, InstancePersistenceContext context, InstanceEncodingOption instanceEncodingOption)
 {
     IObjectSerializer objectSerializer = ObjectSerializerFactory.GetObjectSerializer(instanceEncodingOption);
     Dictionary<XName, object> dictionary = new Dictionary<XName, object>();
     if (context.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None)
     {
         foreach (KeyValuePair<XName, InstanceValue> pair in context.InstanceView.InstanceMetadata)
         {
             if ((pair.Value.Options & InstanceValueOptions.WriteOnly) == InstanceValueOptions.None)
             {
                 dictionary.Add(pair.Key, pair.Value.Value);
             }
         }
     }
     foreach (KeyValuePair<XName, InstanceValue> pair2 in saveWorkflowCommand.InstanceMetadataChanges)
     {
         if (pair2.Value.IsDeletedValue)
         {
             if (context.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None)
             {
                 dictionary.Remove(pair2.Key);
             }
             else
             {
                 DeletedMetadataValue value2 = new DeletedMetadataValue();
                 dictionary[pair2.Key] = value2;
             }
         }
         else if ((pair2.Value.Options & InstanceValueOptions.WriteOnly) == InstanceValueOptions.None)
         {
             dictionary[pair2.Key] = pair2.Value.Value;
         }
     }
     if (dictionary.Count > 0)
     {
         return objectSerializer.SerializePropertyBag(dictionary);
     }
     return new ArraySegment<byte>();
 }
        static bool IsReadyToRun(SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceValue statusPropertyValue;

            if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.StatusPropertyName, out statusPropertyValue) &&
                ((string)statusPropertyValue.Value) == SqlWorkflowInstanceStoreConstants.ExecutingStatusPropertyValue)
            {
                return true;
            }

            return false;
        }
        static string GetBlockingBookmarks(SaveWorkflowCommand saveWorkflowCommand)
        {
            string blockingBookmarks = null;
            InstanceValue binaryBlockingBookmarks;

            if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.BinaryBlockingBookmarksPropertyName, out binaryBlockingBookmarks))
            {
                StringBuilder bookmarkListBuilder = new StringBuilder(SqlWorkflowInstanceStoreConstants.DefaultStringBuilderCapacity);
                IEnumerable<BookmarkInfo> activeBookmarks = binaryBlockingBookmarks.Value as IEnumerable<BookmarkInfo>;

                foreach (BookmarkInfo bookmarkInfo in activeBookmarks)
                {
                    bookmarkListBuilder.AppendFormat(CultureInfo.InvariantCulture, "[{0}: {1}]{2}", bookmarkInfo.BookmarkName, bookmarkInfo.OwnerDisplayName, Environment.NewLine);
                }

                blockingBookmarks = bookmarkListBuilder.ToString();
            }

            return blockingBookmarks;
        }
        void ExtractServiceDeploymentInformation(SaveWorkflowCommand saveWorkflowCommand, StringBuilder commandTextBuilder, SqlParameterCollection parameters)
        {
            InstanceValue instanceValue;
            //Extract the activation parameters
            string serviceName = null;
            string serviceNamespace = null;
            string site = null;
            string relativeApplicationPath = null;
            string relativeServicePath = null;

            if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(PersistenceMetadataNamespace.ActivationType, out instanceValue))
            {
                if (PersistenceMetadataNamespace.ActivationTypes.WAS.Equals(instanceValue.Value))
                {
                    if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.Service, out instanceValue))
                    {
                        serviceName = ((XName)instanceValue.Value).LocalName;
                        serviceNamespace = ((XName)instanceValue.Value).Namespace.NamespaceName;
                    }
                    if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SiteName, out instanceValue))
                    {
                        site = (string)instanceValue.Value;
                    }
                    if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.RelativeApplicationPath, out instanceValue))
                    {
                        relativeApplicationPath = (string)instanceValue.Value;
                    }
                    if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.RelativeServicePath, out instanceValue))
                    {
                        relativeServicePath = (string)instanceValue.Value;
                    }

                    byte[] serviceDeploymentHashBuffer = Encoding.Unicode.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}#{1}#{2}#{3}#{4}",
                        serviceName ?? string.Empty, serviceNamespace ?? string.Empty, site ?? string.Empty, relativeApplicationPath ?? string.Empty, relativeServicePath ?? string.Empty));
                    this.serviceDeploymentHash = new Guid(HashHelper.ComputeHash(serviceDeploymentHashBuffer));

                    //Get the service id has been seen before, get it from the cache
                    GetServiceDeploymentId();
                }
                else
                {
                    throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(SR.NonWASActivationNotSupported));
                }
            }

            if ((this.serviceDeploymentHash != Guid.Empty) && (this.serviceDeploymentId == 0))
            {
                //This is the first time we see this service deployment so we need to create a new entry for it before creating the instance
                commandTextBuilder.AppendLine("declare @serviceDeploymentId bigint");
                commandTextBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "exec {0}.[CreateServiceDeployment] {1} ;",
                    SqlWorkflowInstanceStoreConstants.DefaultSchema, SaveWorkflowAsyncResult.createServiceDeploymentStoredProcedureParameters));

                parameters.Add(new SqlParameter { ParameterName = "@serviceDeploymentHash", SqlDbType = SqlDbType.UniqueIdentifier, Value = this.serviceDeploymentHash });
                parameters.Add(new SqlParameter { ParameterName = "@serviceName", Size = -1, SqlDbType = SqlDbType.NVarChar, Value = serviceName ?? (object)DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@serviceNamespace", Size = -1, SqlDbType = SqlDbType.NVarChar, Value = serviceNamespace ?? (object)DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@siteName", Size = -1, SqlDbType = SqlDbType.NVarChar, Value = site ?? (object)DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@relativeServicePath", Size = -1, SqlDbType = SqlDbType.NVarChar, Value = relativeServicePath ?? (object)DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@relativeApplicationPath", Size = -1, SqlDbType = SqlDbType.NVarChar, Value = relativeApplicationPath ?? (object)DBNull.Value });
            }
            else
            {
                parameters.Add(new SqlParameter { ParameterName = "@serviceDeploymentId", SqlDbType = SqlDbType.BigInt, Value = (this.serviceDeploymentId != 0) ? (object)this.serviceDeploymentId : (object)DBNull.Value });
            }
        }
        static Int64? GetPendingTimerExpiration(SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceValue pendingTimerExpirationPropertyValue;

            if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.PendingTimerExpirationPropertyName, out pendingTimerExpirationPropertyValue))
            {
                DateTime pendingTimerExpiration = ((DateTime)pendingTimerExpirationPropertyValue.Value).ToUniversalTime();
                TimeSpan datetimeOffset = pendingTimerExpiration - DateTime.UtcNow;

                return (Int64)datetimeOffset.TotalMilliseconds;
            }

            return null;
        }
        void SerializePromotedProperties(SqlParameterCollection parameters, StringBuilder commandTextBuilder, SaveWorkflowCommand saveWorkflowCommand)
        {
            const int SqlVariantStartColumn = 1;
            const string promotionNameParameter = "@promotionName=";
            const string instanceIdParameter = "@instanceId=";
            int promotionNumber = 0;

            foreach (KeyValuePair<string, Tuple<List<XName>, List<XName>>> promotion in base.Store.Promotions)
            {
                StringBuilder storedProcInvocationBuilder = new StringBuilder(SqlWorkflowInstanceStoreConstants.DefaultStringBuilderCapacity);
                int column = SqlVariantStartColumn;
                bool addPromotion = false;
                string promotionNameArgument = string.Format(CultureInfo.InvariantCulture, "@promotionName{0}", promotionNumber);
                string instanceIdArgument = string.Format(CultureInfo.InvariantCulture, "@instanceId{0}", promotionNumber);

                storedProcInvocationBuilder.Append(string.Format(CultureInfo.InvariantCulture, "exec {0}.[InsertPromotedProperties] ", SqlWorkflowInstanceStoreConstants.DefaultSchema));
                storedProcInvocationBuilder.Append(promotionNameParameter);
                storedProcInvocationBuilder.Append(promotionNameArgument);
                storedProcInvocationBuilder.Append(",");
                storedProcInvocationBuilder.Append(instanceIdParameter);
                storedProcInvocationBuilder.Append(instanceIdArgument);

                foreach (XName name in promotion.Value.Item1)
                {
                    InstanceValue propertyValue;

                    if (saveWorkflowCommand.InstanceData.TryGetValue(name, out propertyValue))
                    {
                        if (!SerializationUtilities.IsPropertyTypeSqlVariantCompatible(propertyValue))
                        {
                            throw FxTrace.Exception.AsError(new InstancePersistenceException(SR.CannotPromoteAsSqlVariant(propertyValue.Value.GetType().ToString(), name.ToString())));
                        }

                        string parameterName = string.Format(CultureInfo.InvariantCulture, "@value{0}=", column);
                        string argumentName = string.Format(CultureInfo.InvariantCulture, "@value{0}_promotion{1}", column, promotionNumber);
                        parameters.Add(new SqlParameter() { SqlDbType = SqlDbType.Variant, ParameterName = argumentName, Value = propertyValue.Value ?? DBNull.Value });

                        storedProcInvocationBuilder.Append(", ");
                        storedProcInvocationBuilder.Append(parameterName);
                        storedProcInvocationBuilder.Append(argumentName);
                        addPromotion = true;
                    }
                    column++;
                }

                column = SqlVariantStartColumn + SqlWorkflowInstanceStoreConstants.MaximumPropertiesPerPromotion;

                foreach (XName name in promotion.Value.Item2)
                {
                    InstanceValue propertyValue;
                    IObjectSerializer serializer = ObjectSerializerFactory.GetObjectSerializer(base.Store.InstanceEncodingOption);

                    if (saveWorkflowCommand.InstanceData.TryGetValue(name, out propertyValue))
                    {
                        string parameterName = string.Format(CultureInfo.InvariantCulture, "@value{0}=", column);
                        string argumentName = string.Format(CultureInfo.InvariantCulture, "@value{0}_promotion{1}", column, promotionNumber);

                        SaveWorkflowAsyncResult.AddSerializedProperty(serializer.SerializeValue(propertyValue.Value), parameters, argumentName);
                        storedProcInvocationBuilder.Append(", ");
                        storedProcInvocationBuilder.Append(parameterName);
                        storedProcInvocationBuilder.Append(argumentName);
                        addPromotion = true;
                    }
                    column++;
                }

                if (addPromotion)
                {
                    parameters.Add(new SqlParameter() { SqlDbType = SqlDbType.NVarChar, Size = 400, ParameterName = promotionNameArgument, Value = promotion.Key });
                    parameters.Add(new SqlParameter() { SqlDbType = SqlDbType.UniqueIdentifier, ParameterName = instanceIdArgument, Value = base.InstancePersistenceContext.InstanceView.InstanceId });
                    storedProcInvocationBuilder.Append(";");
                    commandTextBuilder.AppendLine(storedProcInvocationBuilder.ToString());
                    promotionNumber++;
                }
            }
        }
        static Guid? GetWorkflowHostType(SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceValue instanceValue;
            if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowNamespace.WorkflowHostType, out instanceValue))
            {
                XName workflowHostType = instanceValue.Value as XName;

                if (workflowHostType == null)
                {
                    throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(SR.InvalidMetadataValue(WorkflowNamespace.WorkflowHostType, typeof(XName).Name)));
                }
                byte[] workflowHostTypeBuffer = Encoding.Unicode.GetBytes(((XName)instanceValue.Value).ToString());
                return new Guid(HashHelper.ComputeHash(workflowHostTypeBuffer));
            }
            return null;
        }
 private void SerializeAssociatedData(SqlParameterCollection parameters, SaveWorkflowCommand saveWorkflowCommand, StringBuilder commandTextBuilder)
 {
     if (saveWorkflowCommand.CompleteInstance && (base.Store.InstanceCompletionAction == InstanceCompletionAction.DeleteAll))
     {
         SqlParameter parameter = new SqlParameter {
             ParameterName = "@keysToAssociate",
             SqlDbType = SqlDbType.Xml,
             Value = DBNull.Value
         };
         parameters.Add(parameter);
         SqlParameter parameter2 = new SqlParameter {
             ParameterName = "@singleKeyId",
             SqlDbType = SqlDbType.UniqueIdentifier,
             Value = DBNull.Value
         };
         parameters.Add(parameter2);
         SqlParameter parameter3 = new SqlParameter {
             ParameterName = "@keysToComplete",
             SqlDbType = SqlDbType.Xml,
             Value = DBNull.Value
         };
         parameters.Add(parameter3);
         SqlParameter parameter4 = new SqlParameter {
             ParameterName = "@keysToFree",
             SqlDbType = SqlDbType.Xml,
             Value = DBNull.Value
         };
         parameters.Add(parameter4);
         SqlParameter parameter5 = new SqlParameter {
             ParameterName = "@concatenatedKeyProperties",
             SqlDbType = SqlDbType.VarBinary,
             Value = DBNull.Value
         };
         parameters.Add(parameter5);
         SqlParameter parameter6 = new SqlParameter {
             ParameterName = "@primitiveDataProperties",
             SqlDbType = SqlDbType.VarBinary,
             Value = DBNull.Value
         };
         parameters.Add(parameter6);
         SqlParameter parameter7 = new SqlParameter {
             ParameterName = "@complexDataProperties",
             SqlDbType = SqlDbType.VarBinary,
             Value = DBNull.Value
         };
         parameters.Add(parameter7);
         SqlParameter parameter8 = new SqlParameter {
             ParameterName = "@writeOnlyPrimitiveDataProperties",
             SqlDbType = SqlDbType.VarBinary,
             Value = DBNull.Value
         };
         parameters.Add(parameter8);
         SqlParameter parameter9 = new SqlParameter {
             ParameterName = "@writeOnlyComplexDataProperties",
             SqlDbType = SqlDbType.VarBinary,
             Value = DBNull.Value
         };
         parameters.Add(parameter9);
         SqlParameter parameter10 = new SqlParameter {
             ParameterName = "@metadataProperties",
             SqlDbType = SqlDbType.VarBinary,
             Value = DBNull.Value
         };
         parameters.Add(parameter10);
         SqlParameter parameter11 = new SqlParameter {
             ParameterName = "@metadataIsConsistent",
             SqlDbType = SqlDbType.Bit,
             Value = DBNull.Value
         };
         parameters.Add(parameter11);
         SqlParameter parameter12 = new SqlParameter {
             ParameterName = "@encodingOption",
             SqlDbType = SqlDbType.TinyInt,
             Value = DBNull.Value
         };
         parameters.Add(parameter12);
         SqlParameter parameter13 = new SqlParameter {
             ParameterName = "@lastMachineRunOn",
             SqlDbType = SqlDbType.NVarChar,
             Value = DBNull.Value
         };
         parameters.Add(parameter13);
         SqlParameter parameter14 = new SqlParameter {
             ParameterName = "@executionStatus",
             SqlDbType = SqlDbType.NVarChar,
             Value = DBNull.Value
         };
         parameters.Add(parameter14);
         SqlParameter parameter15 = new SqlParameter {
             ParameterName = "@blockingBookmarks",
             SqlDbType = SqlDbType.NVarChar,
             Value = DBNull.Value
         };
         parameters.Add(parameter15);
     }
     else
     {
         List<CorrelationKey> correlationKeys = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToAssociate, base.Store.InstanceEncodingOption);
         List<CorrelationKey> list2 = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToComplete);
         List<CorrelationKey> list3 = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToFree);
         ArraySegment<byte>[] segmentArray = SerializationUtilities.SerializePropertyBag(saveWorkflowCommand.InstanceData, base.Store.InstanceEncodingOption);
         ArraySegment<byte> segment = SerializationUtilities.SerializeMetadataPropertyBag(saveWorkflowCommand, base.InstancePersistenceContext, base.Store.InstanceEncodingOption);
         byte[] buffer = SerializationUtilities.CreateKeyBinaryBlob(correlationKeys);
         bool flag = base.InstancePersistenceContext.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None;
         bool flag2 = (correlationKeys != null) && (correlationKeys.Count == 1);
         SqlParameter parameter16 = new SqlParameter {
             ParameterName = "@keysToAssociate",
             SqlDbType = SqlDbType.Xml,
             Value = flag2 ? DBNull.Value : SerializationUtilities.CreateCorrelationKeyXmlBlob(correlationKeys)
         };
         parameters.Add(parameter16);
         SqlParameter parameter17 = new SqlParameter {
             ParameterName = "@singleKeyId",
             SqlDbType = SqlDbType.UniqueIdentifier,
             Value = flag2 ? ((object) correlationKeys[0].KeyId) : ((object) DBNull.Value)
         };
         parameters.Add(parameter17);
         SqlParameter parameter18 = new SqlParameter {
             ParameterName = "@keysToComplete",
             SqlDbType = SqlDbType.Xml,
             Value = SerializationUtilities.CreateCorrelationKeyXmlBlob(list2)
         };
         parameters.Add(parameter18);
         SqlParameter parameter19 = new SqlParameter {
             ParameterName = "@keysToFree",
             SqlDbType = SqlDbType.Xml,
             Value = SerializationUtilities.CreateCorrelationKeyXmlBlob(list3)
         };
         parameters.Add(parameter19);
         SqlParameter parameter20 = new SqlParameter {
             ParameterName = "@concatenatedKeyProperties",
             SqlDbType = SqlDbType.VarBinary,
             Size = -1,
             Value = buffer ?? DBNull.Value
         };
         parameters.Add(parameter20);
         SqlParameter parameter21 = new SqlParameter {
             ParameterName = "@metadataIsConsistent",
             SqlDbType = SqlDbType.Bit,
             Value = flag
         };
         parameters.Add(parameter21);
         SqlParameter parameter22 = new SqlParameter {
             ParameterName = "@encodingOption",
             SqlDbType = SqlDbType.TinyInt,
             Value = base.Store.InstanceEncodingOption
         };
         parameters.Add(parameter22);
         SqlParameter parameter23 = new SqlParameter {
             ParameterName = "@lastMachineRunOn",
             SqlDbType = SqlDbType.NVarChar,
             Size = 450,
             Value = SqlWorkflowInstanceStoreConstants.MachineName
         };
         parameters.Add(parameter23);
         SqlParameter parameter24 = new SqlParameter {
             ParameterName = "@executionStatus",
             SqlDbType = SqlDbType.NVarChar,
             Size = 450,
             Value = GetExecutionStatus(saveWorkflowCommand) ?? DBNull.Value
         };
         parameters.Add(parameter24);
         SqlParameter parameter25 = new SqlParameter {
             ParameterName = "@blockingBookmarks",
             SqlDbType = SqlDbType.NVarChar,
             Size = -1,
             Value = GetBlockingBookmarks(saveWorkflowCommand) ?? DBNull.Value
         };
         parameters.Add(parameter25);
         ArraySegment<byte>[] segmentArray2 = new ArraySegment<byte>[] { segmentArray[0], segmentArray[1], segmentArray[2], segmentArray[3], segment };
         string[] strArray = new string[] { "@primitiveDataProperties", "@complexDataProperties", "@writeOnlyPrimitiveDataProperties", "writeOnlyComplexDataProperties", "@metadataProperties" };
         for (int i = 0; i < 5; i++)
         {
             AddSerializedProperty(segmentArray2[i], parameters, strArray[i]);
         }
         this.SerializePromotedProperties(parameters, commandTextBuilder, saveWorkflowCommand);
     }
 }
        static void UpdateKeyData(InstancePersistenceContext context, SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceView instanceView = context.InstanceView;

            foreach (KeyValuePair<Guid, IDictionary<XName, InstanceValue>> keyEntry in saveWorkflowCommand.InstanceKeysToAssociate)
            {
                if (!instanceView.InstanceKeys.ContainsKey(keyEntry.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 key in saveWorkflowCommand.InstanceKeysToComplete)
            {
                InstanceKeyView existingKeyView;
                if (instanceView.InstanceKeys.TryGetValue(key, out existingKeyView))
                {
                    if (existingKeyView.InstanceKeyState != InstanceKeyState.Completed)
                    {
                        context.CompletedInstanceKey(key);
                    }
                }
            }

            foreach (Guid key in saveWorkflowCommand.InstanceKeysToFree)
            {
                InstanceKeyView existingKeyView;
                if (instanceView.InstanceKeys.TryGetValue(key, out existingKeyView))
                {
                    context.UnassociatedInstanceKey(key);
                }
            }

            foreach (KeyValuePair<Guid, IDictionary<XName, InstanceValue>> keyEntry in saveWorkflowCommand.InstanceKeyMetadataChanges)
            {
                if (keyEntry.Value != null)
                {
                    foreach (KeyValuePair<XName, InstanceValue> property in keyEntry.Value)
                    {
                        context.WroteInstanceKeyMetadataValue(keyEntry.Key, property.Key, property.Value);
                    }
                }
            }

            if (saveWorkflowCommand.CompleteInstance)
            {
                foreach (KeyValuePair<Guid, InstanceKeyView> instanceKeys in instanceView.InstanceKeys)
                {
                    if (instanceKeys.Value != null)
                    {
                        if (instanceKeys.Value.InstanceKeyState == InstanceKeyState.Associated)
                        {
                            context.CompletedInstanceKey(instanceKeys.Key);
                        }
                    }
                }
            }
        }
Пример #47
0
        private static bool IsReadyToRun(SaveWorkflowCommand saveWorkflowCommand)
        {
            InstanceValue value2;

            return(saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.StatusPropertyName, out value2) && (((string)value2.Value) == "Executing"));
        }
        void SerializeAssociatedData(SqlParameterCollection parameters, SaveWorkflowCommand saveWorkflowCommand, StringBuilder commandTextBuilder)
        {
            if (saveWorkflowCommand.CompleteInstance && base.Store.InstanceCompletionAction == InstanceCompletionAction.DeleteAll)
            {
                parameters.Add(new SqlParameter { ParameterName = "@keysToAssociate", SqlDbType = SqlDbType.Xml, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@singleKeyId", SqlDbType = SqlDbType.UniqueIdentifier, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@keysToComplete", SqlDbType = SqlDbType.Xml, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@keysToFree", SqlDbType = SqlDbType.Xml, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@concatenatedKeyProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@primitiveDataProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@complexDataProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@writeOnlyPrimitiveDataProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@writeOnlyComplexDataProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@metadataProperties", SqlDbType = SqlDbType.VarBinary, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@metadataIsConsistent", SqlDbType = SqlDbType.Bit, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@encodingOption", SqlDbType = SqlDbType.TinyInt, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@lastMachineRunOn", SqlDbType = SqlDbType.NVarChar, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@executionStatus", SqlDbType = SqlDbType.NVarChar, Value = DBNull.Value });
                parameters.Add(new SqlParameter { ParameterName = "@blockingBookmarks", SqlDbType = SqlDbType.NVarChar, Value = DBNull.Value });

                return;
            }

            List<CorrelationKey> keysToAssociate = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToAssociate, base.Store.InstanceEncodingOption);
            List<CorrelationKey> keysToComplete = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToComplete);
            List<CorrelationKey> keysToFree = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToFree);
            ArraySegment<byte>[] dataProperties = SerializationUtilities.SerializePropertyBag(saveWorkflowCommand.InstanceData, base.Store.InstanceEncodingOption);
            ArraySegment<byte> metadataProperties = SerializationUtilities.SerializeMetadataPropertyBag(saveWorkflowCommand, base.InstancePersistenceContext, base.Store.InstanceEncodingOption);
            byte[] concatenatedKeyProperties = SerializationUtilities.CreateKeyBinaryBlob(keysToAssociate);
            bool metadataConsistency = (base.InstancePersistenceContext.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None);
            bool singleKeyToAssociate = (keysToAssociate != null && keysToAssociate.Count == 1);

            parameters.Add(new SqlParameter { ParameterName = "@keysToAssociate", SqlDbType = SqlDbType.Xml, Value = singleKeyToAssociate ? DBNull.Value : SerializationUtilities.CreateCorrelationKeyXmlBlob(keysToAssociate) });
            parameters.Add(new SqlParameter { ParameterName = "@singleKeyId", SqlDbType = SqlDbType.UniqueIdentifier, Value = singleKeyToAssociate ? keysToAssociate[0].KeyId : (object)DBNull.Value });
            parameters.Add(new SqlParameter { ParameterName = "@keysToComplete", SqlDbType = SqlDbType.Xml, Value = SerializationUtilities.CreateCorrelationKeyXmlBlob(keysToComplete) });
            parameters.Add(new SqlParameter { ParameterName = "@keysToFree", SqlDbType = SqlDbType.Xml, Value = SerializationUtilities.CreateCorrelationKeyXmlBlob(keysToFree) });
            parameters.Add(new SqlParameter { ParameterName = "@concatenatedKeyProperties", SqlDbType = SqlDbType.VarBinary, Size = -1, Value = (object)concatenatedKeyProperties ?? DBNull.Value });
            parameters.Add(new SqlParameter { ParameterName = "@metadataIsConsistent", SqlDbType = SqlDbType.Bit, Value = metadataConsistency });
            parameters.Add(new SqlParameter { ParameterName = "@encodingOption", SqlDbType = SqlDbType.TinyInt, Value = base.Store.InstanceEncodingOption });
            parameters.Add(new SqlParameter { ParameterName = "@lastMachineRunOn", SqlDbType = SqlDbType.NVarChar, Size = 450, Value = SqlWorkflowInstanceStoreConstants.MachineName });
            parameters.Add(new SqlParameter { ParameterName = "@executionStatus", SqlDbType = SqlDbType.NVarChar, Size = 450, Value = GetExecutionStatus(saveWorkflowCommand) ?? (object)DBNull.Value });
            parameters.Add(new SqlParameter { ParameterName = "@blockingBookmarks", SqlDbType = SqlDbType.NVarChar, Size = -1, Value = GetBlockingBookmarks(saveWorkflowCommand) ?? (object)DBNull.Value });

            ArraySegment<byte>[] properties = { dataProperties[0], dataProperties[1], dataProperties[2], dataProperties[3], metadataProperties };
            string[] dataPropertyParameters = { "@primitiveDataProperties", "@complexDataProperties", "@writeOnlyPrimitiveDataProperties", @"writeOnlyComplexDataProperties", "@metadataProperties" };

            for (int i = 0; i < 5; i++)
            {
                SaveWorkflowAsyncResult.AddSerializedProperty(properties[i], parameters, dataPropertyParameters[i]);
            }

            this.SerializePromotedProperties(parameters, commandTextBuilder, saveWorkflowCommand);
        }
 private static Guid? GetWorkflowHostType(SaveWorkflowCommand saveWorkflowCommand)
 {
     InstanceValue value2;
     if (!saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowNamespace.WorkflowHostType, out value2))
     {
         return null;
     }
     XName name = value2.Value as XName;
     if (name == null)
     {
         throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(System.Activities.DurableInstancing.SR.InvalidWorkflowHostTypeValue(WorkflowNamespace.WorkflowHostType)));
     }
     return new Guid(HashHelper.ComputeHash(Encoding.Unicode.GetBytes(((XName) value2.Value).ToString())));
 }
 private static long? GetPendingTimerExpiration(SaveWorkflowCommand saveWorkflowCommand)
 {
     InstanceValue value2;
     if (saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.PendingTimerExpirationPropertyName, out value2))
     {
         DateTime time2 = (DateTime) value2.Value;
         TimeSpan span = (TimeSpan) (time2.ToUniversalTime() - DateTime.UtcNow);
         return new long?((long) span.TotalMilliseconds);
     }
     return null;
 }
Пример #51
0
 private void SerializeAssociatedData(SqlParameterCollection parameters, SaveWorkflowCommand saveWorkflowCommand, StringBuilder commandTextBuilder)
 {
     if (saveWorkflowCommand.CompleteInstance && (base.Store.InstanceCompletionAction == InstanceCompletionAction.DeleteAll))
     {
         SqlParameter parameter = new SqlParameter {
             ParameterName = "@keysToAssociate",
             SqlDbType     = SqlDbType.Xml,
             Value         = DBNull.Value
         };
         parameters.Add(parameter);
         SqlParameter parameter2 = new SqlParameter {
             ParameterName = "@singleKeyId",
             SqlDbType     = SqlDbType.UniqueIdentifier,
             Value         = DBNull.Value
         };
         parameters.Add(parameter2);
         SqlParameter parameter3 = new SqlParameter {
             ParameterName = "@keysToComplete",
             SqlDbType     = SqlDbType.Xml,
             Value         = DBNull.Value
         };
         parameters.Add(parameter3);
         SqlParameter parameter4 = new SqlParameter {
             ParameterName = "@keysToFree",
             SqlDbType     = SqlDbType.Xml,
             Value         = DBNull.Value
         };
         parameters.Add(parameter4);
         SqlParameter parameter5 = new SqlParameter {
             ParameterName = "@concatenatedKeyProperties",
             SqlDbType     = SqlDbType.VarBinary,
             Value         = DBNull.Value
         };
         parameters.Add(parameter5);
         SqlParameter parameter6 = new SqlParameter {
             ParameterName = "@primitiveDataProperties",
             SqlDbType     = SqlDbType.VarBinary,
             Value         = DBNull.Value
         };
         parameters.Add(parameter6);
         SqlParameter parameter7 = new SqlParameter {
             ParameterName = "@complexDataProperties",
             SqlDbType     = SqlDbType.VarBinary,
             Value         = DBNull.Value
         };
         parameters.Add(parameter7);
         SqlParameter parameter8 = new SqlParameter {
             ParameterName = "@writeOnlyPrimitiveDataProperties",
             SqlDbType     = SqlDbType.VarBinary,
             Value         = DBNull.Value
         };
         parameters.Add(parameter8);
         SqlParameter parameter9 = new SqlParameter {
             ParameterName = "@writeOnlyComplexDataProperties",
             SqlDbType     = SqlDbType.VarBinary,
             Value         = DBNull.Value
         };
         parameters.Add(parameter9);
         SqlParameter parameter10 = new SqlParameter {
             ParameterName = "@metadataProperties",
             SqlDbType     = SqlDbType.VarBinary,
             Value         = DBNull.Value
         };
         parameters.Add(parameter10);
         SqlParameter parameter11 = new SqlParameter {
             ParameterName = "@metadataIsConsistent",
             SqlDbType     = SqlDbType.Bit,
             Value         = DBNull.Value
         };
         parameters.Add(parameter11);
         SqlParameter parameter12 = new SqlParameter {
             ParameterName = "@encodingOption",
             SqlDbType     = SqlDbType.TinyInt,
             Value         = DBNull.Value
         };
         parameters.Add(parameter12);
         SqlParameter parameter13 = new SqlParameter {
             ParameterName = "@lastMachineRunOn",
             SqlDbType     = SqlDbType.NVarChar,
             Value         = DBNull.Value
         };
         parameters.Add(parameter13);
         SqlParameter parameter14 = new SqlParameter {
             ParameterName = "@executionStatus",
             SqlDbType     = SqlDbType.NVarChar,
             Value         = DBNull.Value
         };
         parameters.Add(parameter14);
         SqlParameter parameter15 = new SqlParameter {
             ParameterName = "@blockingBookmarks",
             SqlDbType     = SqlDbType.NVarChar,
             Value         = DBNull.Value
         };
         parameters.Add(parameter15);
     }
     else
     {
         List <CorrelationKey> correlationKeys = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToAssociate, base.Store.InstanceEncodingOption);
         List <CorrelationKey> list2           = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToComplete);
         List <CorrelationKey> list3           = CorrelationKey.BuildKeyList(saveWorkflowCommand.InstanceKeysToFree);
         ArraySegment <byte>[] segmentArray    = SerializationUtilities.SerializePropertyBag(saveWorkflowCommand.InstanceData, base.Store.InstanceEncodingOption);
         ArraySegment <byte>   segment         = SerializationUtilities.SerializeMetadataPropertyBag(saveWorkflowCommand, base.InstancePersistenceContext, base.Store.InstanceEncodingOption);
         byte[]       buffer      = SerializationUtilities.CreateKeyBinaryBlob(correlationKeys);
         bool         flag        = base.InstancePersistenceContext.InstanceView.InstanceMetadataConsistency == InstanceValueConsistency.None;
         bool         flag2       = (correlationKeys != null) && (correlationKeys.Count == 1);
         SqlParameter parameter16 = new SqlParameter {
             ParameterName = "@keysToAssociate",
             SqlDbType     = SqlDbType.Xml,
             Value         = flag2 ? DBNull.Value : SerializationUtilities.CreateCorrelationKeyXmlBlob(correlationKeys)
         };
         parameters.Add(parameter16);
         SqlParameter parameter17 = new SqlParameter {
             ParameterName = "@singleKeyId",
             SqlDbType     = SqlDbType.UniqueIdentifier,
             Value         = flag2 ? ((object)correlationKeys[0].KeyId) : ((object)DBNull.Value)
         };
         parameters.Add(parameter17);
         SqlParameter parameter18 = new SqlParameter {
             ParameterName = "@keysToComplete",
             SqlDbType     = SqlDbType.Xml,
             Value         = SerializationUtilities.CreateCorrelationKeyXmlBlob(list2)
         };
         parameters.Add(parameter18);
         SqlParameter parameter19 = new SqlParameter {
             ParameterName = "@keysToFree",
             SqlDbType     = SqlDbType.Xml,
             Value         = SerializationUtilities.CreateCorrelationKeyXmlBlob(list3)
         };
         parameters.Add(parameter19);
         SqlParameter parameter20 = new SqlParameter {
             ParameterName = "@concatenatedKeyProperties",
             SqlDbType     = SqlDbType.VarBinary,
             Size          = -1,
             Value         = buffer ?? DBNull.Value
         };
         parameters.Add(parameter20);
         SqlParameter parameter21 = new SqlParameter {
             ParameterName = "@metadataIsConsistent",
             SqlDbType     = SqlDbType.Bit,
             Value         = flag
         };
         parameters.Add(parameter21);
         SqlParameter parameter22 = new SqlParameter {
             ParameterName = "@encodingOption",
             SqlDbType     = SqlDbType.TinyInt,
             Value         = base.Store.InstanceEncodingOption
         };
         parameters.Add(parameter22);
         SqlParameter parameter23 = new SqlParameter {
             ParameterName = "@lastMachineRunOn",
             SqlDbType     = SqlDbType.NVarChar,
             Size          = 450,
             Value         = SqlWorkflowInstanceStoreConstants.MachineName
         };
         parameters.Add(parameter23);
         SqlParameter parameter24 = new SqlParameter {
             ParameterName = "@executionStatus",
             SqlDbType     = SqlDbType.NVarChar,
             Size          = 450,
             Value         = GetExecutionStatus(saveWorkflowCommand) ?? DBNull.Value
         };
         parameters.Add(parameter24);
         SqlParameter parameter25 = new SqlParameter {
             ParameterName = "@blockingBookmarks",
             SqlDbType     = SqlDbType.NVarChar,
             Size          = -1,
             Value         = GetBlockingBookmarks(saveWorkflowCommand) ?? DBNull.Value
         };
         parameters.Add(parameter25);
         ArraySegment <byte>[] segmentArray2 = new ArraySegment <byte>[] { segmentArray[0], segmentArray[1], segmentArray[2], segmentArray[3], segment };
         string[] strArray = new string[] { "@primitiveDataProperties", "@complexDataProperties", "@writeOnlyPrimitiveDataProperties", "writeOnlyComplexDataProperties", "@metadataProperties" };
         for (int i = 0; i < 5; i++)
         {
             AddSerializedProperty(segmentArray2[i], parameters, strArray[i]);
         }
         this.SerializePromotedProperties(parameters, commandTextBuilder, saveWorkflowCommand);
     }
 }
 private static string GetBlockingBookmarks(SaveWorkflowCommand saveWorkflowCommand)
 {
     string str = null;
     InstanceValue value2;
     if (!saveWorkflowCommand.InstanceData.TryGetValue(SqlWorkflowInstanceStoreConstants.BinaryBlockingBookmarksPropertyName, out value2))
     {
         return str;
     }
     StringBuilder builder = new StringBuilder(0x200);
     IEnumerable<BookmarkInfo> enumerable = value2.Value as IEnumerable<BookmarkInfo>;
     foreach (BookmarkInfo info in enumerable)
     {
         builder.AppendFormat(CultureInfo.InvariantCulture, "[{0}: {1}]{2}", new object[] { info.BookmarkName, info.OwnerDisplayName, Environment.NewLine });
     }
     return builder.ToString();
 }
Пример #53
0
        private void ExtractServiceDeploymentInformation(SaveWorkflowCommand saveWorkflowCommand, StringBuilder commandTextBuilder, SqlParameterCollection parameters)
        {
            InstanceValue value2;
            string        localName     = null;
            string        namespaceName = null;
            string        str3          = null;
            string        str4          = null;
            string        str5          = null;

            if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(PersistenceMetadataNamespace.ActivationType, out value2))
            {
                if (!PersistenceMetadataNamespace.ActivationTypes.WAS.Equals(value2.Value))
                {
                    throw FxTrace.Exception.AsError(new InstancePersistenceCommandException(System.Activities.DurableInstancing.SR.NonWASActivationNotSupported));
                }
                if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.Service, out value2))
                {
                    localName     = ((XName)value2.Value).LocalName;
                    namespaceName = ((XName)value2.Value).Namespace.NamespaceName;
                }
                if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.SiteName, out value2))
                {
                    str3 = (string)value2.Value;
                }
                if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.RelativeApplicationPath, out value2))
                {
                    str4 = (string)value2.Value;
                }
                if (saveWorkflowCommand.InstanceMetadataChanges.TryGetValue(WorkflowServiceNamespace.RelativeServicePath, out value2))
                {
                    str5 = (string)value2.Value;
                }
                object[] args  = new object[] { localName ?? string.Empty, namespaceName ?? string.Empty, str3 ?? string.Empty, str4 ?? string.Empty, str5 ?? string.Empty };
                byte[]   bytes = Encoding.Unicode.GetBytes(string.Format(CultureInfo.InvariantCulture, "{0}#{1}#{2}#{3}#{4}", args));
                this.serviceDeploymentHash = new Guid(HashHelper.ComputeHash(bytes));
                this.GetServiceDeploymentId();
            }
            if ((this.serviceDeploymentHash != Guid.Empty) && (this.serviceDeploymentId == 0L))
            {
                commandTextBuilder.AppendLine("declare @serviceDeploymentId bigint");
                commandTextBuilder.AppendLine(string.Format(CultureInfo.InvariantCulture, "exec {0}.[CreateServiceDeployment] {1} ;", new object[] { "[System.Activities.DurableInstancing]", "@serviceDeploymentHash, @siteName, @relativeServicePath, @relativeApplicationPath,\r\n                @serviceName, @serviceNamespace, @serviceDeploymentId output" }));
                SqlParameter parameter = new SqlParameter {
                    ParameterName = "@serviceDeploymentHash",
                    SqlDbType     = SqlDbType.UniqueIdentifier,
                    Value         = this.serviceDeploymentHash
                };
                parameters.Add(parameter);
                SqlParameter parameter2 = new SqlParameter {
                    ParameterName = "@serviceName",
                    Size          = -1,
                    SqlDbType     = SqlDbType.NVarChar,
                    Value         = localName ?? DBNull.Value
                };
                parameters.Add(parameter2);
                SqlParameter parameter3 = new SqlParameter {
                    ParameterName = "@serviceNamespace",
                    Size          = -1,
                    SqlDbType     = SqlDbType.NVarChar,
                    Value         = namespaceName ?? DBNull.Value
                };
                parameters.Add(parameter3);
                SqlParameter parameter4 = new SqlParameter {
                    ParameterName = "@siteName",
                    Size          = -1,
                    SqlDbType     = SqlDbType.NVarChar,
                    Value         = str3 ?? DBNull.Value
                };
                parameters.Add(parameter4);
                SqlParameter parameter5 = new SqlParameter {
                    ParameterName = "@relativeServicePath",
                    Size          = -1,
                    SqlDbType     = SqlDbType.NVarChar,
                    Value         = str5 ?? DBNull.Value
                };
                parameters.Add(parameter5);
                SqlParameter parameter6 = new SqlParameter {
                    ParameterName = "@relativeApplicationPath",
                    Size          = -1,
                    SqlDbType     = SqlDbType.NVarChar,
                    Value         = str4 ?? DBNull.Value
                };
                parameters.Add(parameter6);
            }
            else
            {
                SqlParameter parameter7 = new SqlParameter {
                    ParameterName = "@serviceDeploymentId",
                    SqlDbType     = SqlDbType.BigInt,
                    Value         = (this.serviceDeploymentId != 0L) ? ((object)this.serviceDeploymentId) : ((object)DBNull.Value)
                };
                parameters.Add(parameter7);
            }
        }