示例#1
0
        private void EditButton_Click(object sender, EventArgs e)
        {
            if (typeString == "Folder")
            {
                if (list.ID == Guid.Empty)
                {
                    // trace page navigation
                    TraceHelper.StartMessage("ListPage: Navigate to FolderEditor");

                    // Navigate to the FolderEditor page
                    NavigationService.Navigate(
                        new Uri(String.Format("/FolderEditor.xaml?ID={0}", folder.ID),
                                UriKind.Relative));
                }
                else
                {
                    // trace page navigation
                    TraceHelper.StartMessage("ListPage: Navigate to ListEditor");

                    // Navigate to the FolderEditor page
                    NavigationService.Navigate(
                        new Uri(String.Format("/ListEditor.xaml?ID={0}&FolderID={1}", list.ID, folder.ID),
                                UriKind.Relative));
                }
            }
            else
            {
                // trace page navigation
                TraceHelper.StartMessage("ListPage: Navigate to TagEditor");

                // Navigate to the TagEditor page
                NavigationService.Navigate(
                    new Uri(String.Format("/TagEditor.xaml?ID={0}", tag.ID),
                            UriKind.Relative));
            }
        }
        protected virtual void PessimisticControlContextWriteStrategy(IConcurrencyControlContext context, T obj)
        {
            if (string.IsNullOrWhiteSpace((context as PessimisticConcurrencyContext).LockId))
            {
                throw new ArgumentNullException("context.LockId", "LockId cannot be null or empty");
            }

            var blobProperties = new BlobProperties();

            var binarizedObject = this.BinarizeObjectForStreaming(blobProperties, obj);

            var updateRequest = BlobRequest.Put(
                this.GetUri(context.ObjectId),
                BlobRequestTimeout,
                blobProperties,
                BlobType.BlockBlob,
                (context as PessimisticConcurrencyContext).LockId,
                0);

            using (var writer = new BinaryWriter(updateRequest.GetRequestStream(), Encoding.Default))
            {
                writer.Write(binarizedObject);
            }

            this.Account.Credentials.SignRequest(updateRequest);

            using (var response = updateRequest.GetResponse())
            {
                if (response is HttpWebResponse &&
                    !HttpStatusCode.Created.Equals((response as HttpWebResponse).StatusCode))
                {
                    TraceHelper.TraceError("Error writing leased blob '{0}': {1}", context.ObjectId, (response as HttpWebResponse).StatusDescription);
                    throw new InvalidOperationException((response as HttpWebResponse).StatusDescription);
                }
            }
        }
        static OrchestrationRuntimeState GetOrCreateInstanceState(Stream stateStream, string sessionId, DataConverter dataConverter, out string blobKey)
        {
            OrchestrationRuntimeState runtimeState;

            blobKey = string.Empty;
            if (stateStream == null)
            {
                TraceHelper.TraceSession(
                    TraceEventType.Information,
                    "RuntimeStateStreamConverter-GetOrCreateInstanceStateNewSession",
                    sessionId,
                    "No session state exists, creating new session state.");
                runtimeState = new OrchestrationRuntimeState();
            }
            else
            {
                if (stateStream.Position != 0)
                {
                    throw TraceHelper.TraceExceptionSession(
                              TraceEventType.Error,
                              "RuntimeStateStreamConverter-GetOrCreateInstanceStatePartiallyConsumed",
                              sessionId,
                              new ArgumentException("Stream is partially consumed"));
                }

                string serializedState = null;
                using (var reader = new StreamReader(stateStream))
                {
                    serializedState = reader.ReadToEnd();
                }

                runtimeState = DeserializeToRuntimeStateWithFallback(serializedState, dataConverter, sessionId, out blobKey);
            }

            return(runtimeState);
        }
示例#4
0
        private void recoverRunningWorkflows()
        {
            IList <Guid> workflowIds = LoadNonBlockedWorkflowIds();

            foreach (Guid workflowId in workflowIds)
            {
                try
                {
                    Runtime.GetWorkflow(workflowId).Load();
                }
                catch (Exception e)
                {
                    String errorMessage = RM.Get_Error_PersistenceServiceException(e.ToString());

                    TraceHelper.Trace(errorMessage);

                    RaiseServicesExceptionNotHandledEvent(
                        new PersistenceException(errorMessage, e),
                        workflowId);

                    continue;
                }
            }
        }
        /// <summary>
        /// Executes the supplied action until successful or the supplied number of attempts is reached
        /// </summary>
        public static async Task ExecuteWithRetries(Func <Task> retryAction, string sessionId, string operation,
                                                    int numberOfAttempts, int delayInAttemptsSecs)
        {
            if (numberOfAttempts == 0)
            {
                // No attempts are requested to execute the action
                return;
            }

            int retryCount = numberOfAttempts;
            ExceptionDispatchInfo lastException = null;

            while (retryCount-- > 0)
            {
                try
                {
                    await retryAction();

                    return;
                }
                catch (Exception exception) when(!IsFatal(exception))
                {
                    TraceHelper.TraceSession(
                        TraceEventType.Warning,
                        "ExecuteWithRetry-Failure",
                        sessionId,
                        $"Error attempting operation {operation}. Attempt count: {numberOfAttempts - retryCount}. Exception: {exception.Message}\n\t{exception.StackTrace}");
                    lastException = ExceptionDispatchInfo.Capture(exception);
                }

                await Task.Delay(TimeSpan.FromSeconds(delayInAttemptsSecs));
            }

            TraceHelper.Trace(TraceEventType.Error, "ExecuteWithRetry-RetriesExhausted", "Exhausted all retries for operation " + operation);
            TraceHelper.TraceExceptionSession(TraceEventType.Error, "ExecuteWithRetryRetriesExhausted", sessionId, lastException).Throw();
        }
示例#6
0
        public async Task <ActionResult> New(SurveyModel contentModel)
        {
            var temporarySurveyModel = GetTemporarySurveyModel();

            if (temporarySurveyModel == null)
            {
                return(this.RedirectToAction("New"));
            }

            if (temporarySurveyModel.Questions == null || temporarySurveyModel.Questions.Count <= 0)
            {
                this.ModelState.AddModelError("ContentModel.Questions", string.Format(CultureInfo.InvariantCulture, "Please add at least one question to the survey."));
            }

            contentModel.Questions = temporarySurveyModel.Questions;
            if (!this.ModelState.IsValid)
            {
                var model = this.CreatePageViewData(contentModel);
                model.Title = "New Survey";
                SaveTemporarySurveyModel(temporarySurveyModel);
                return(this.View(model));
            }

            try
            {
                await this.surveyManagementService.PublishSurveyAsync(contentModel.ToSurvey());
            }
            catch (Exception ex)
            {
                TraceHelper.TraceError(ex.TraceInformation());
                throw;
            }

            ClearTemporarySurvey();
            return(this.RedirectToAction("Index"));
        }
示例#7
0
        /// <summary>
        /// Callback to query task info
        /// </summary>
        /// <param name="obj">null object</param>
        public void CallbackToQueryTaskInfo(object obj)
        {
            TraceHelper.TraceEvent(this.sessionid, TraceEventType.Verbose, "[JobMonitorEntry] Enters CallbackToQueryTaskInfo method, {0}", obj);

            bool reset = (bool)obj;

            if (reset)
            {
                try
                {
                    TraceHelper.TraceEvent(this.sessionid, TraceEventType.Verbose, "[JobMonitorEntry] Refresh job properties.");
                    this.schedulerJob.Refresh();
                }
                catch (Exception e)
                {
                    TraceHelper.TraceEvent(this.sessionid, TraceEventType.Warning, "[JobMonitorEntry] Failed to refresh job properties: {0}", e);

                    // Try to reset the job instance
                    try
                    {
                        this.ResetSchedulerJob();
                    }
                    catch (Exception ex)
                    {
                        TraceHelper.TraceEvent(this.sessionid, TraceEventType.Error, "[JobMonitorEntry] Failed to reset service job instance: {0}", ex);
                    }
                }

                TraceHelper.TraceEvent(this.sessionid, TraceEventType.Verbose, "[JobMonitorEntry] ResetPreviousValues.");
                this.ResetPreviousValues();
            }

            // Query task info won't throw exceptions
            TraceHelper.TraceEvent(this.sessionid, TraceEventType.Verbose, "[JobMonitorEntry] Call QueryTaskInfo");
            this.QueryTaskInfo();
        }
示例#8
0
        private void DeleteButton_Click(object sender, EventArgs e)
        {
            // if this is a new list, delete just does the same thing as cancel
            if (list == null)
            {
                CancelButton_Click(sender, e);
                return;
            }

            MessageBoxResult result = MessageBox.Show("delete this list?", "confirm delete", MessageBoxButton.OKCancel);
            if (result != MessageBoxResult.OK)
                return;

            // enqueue the Web Request Record
            RequestQueue.EnqueueRequestRecord(RequestQueue.UserQueue,
                new RequestQueue.RequestRecord()
                {
                    ReqType = RequestQueue.RequestRecord.RequestType.Delete,
                    Body = list
                });

            // remove the item from the viewmodel
            folder.Items.Remove(list);

            // save the changes to local storage
            StorageHelper.WriteFolder(folder);

            // trigger a sync with the Service 
            App.ViewModel.SyncWithService();

            // trace page navigation
            TraceHelper.StartMessage("ListEditor: Navigate back");

            // Navigate back to the main page
            NavigationService.GoBack();
        }
示例#9
0
        public ActionResult GridResult(bool?active, string searchTerm = "", int pageNumber = 1, int pageSize = 10, int?selectedId = null)
        {
            try
            {
                var retrieveInvestorsAndProducts = new RetrieveInvestorsAndProducts
                {
                    Active     = active,
                    SearchTerm = searchTerm,
                    PageNumber = pageNumber,
                    PageSize   = pageSize
                };

                var investorsAndProductsRetrieved = _productServiceFacade.RetrieveInvestorsAndProducts(retrieveInvestorsAndProducts) ?? new InvestorsAndProductsRetrieved {
                    Investors = new List <Investor>()
                };

                var model = new InvestorConfigurationViewModel
                {
                    Investors   = investorsAndProductsRetrieved.Investors,
                    Active      = active,
                    TotalItems  = investorsAndProductsRetrieved.TotalItems,
                    PageCount   = investorsAndProductsRetrieved.TotalPages,
                    CurrentPage = investorsAndProductsRetrieved.CurrentPage,
                    SelectedId  = selectedId
                };

                model = GridHelper.GetStartEndPage <InvestorConfigurationViewModel>(model, pageSize);

                return(PartialView("SystemAdmin/InvestorConfiguration/_investorgridresult", model));
            }
            catch (Exception exception)
            {
                TraceHelper.Error(TraceCategory.LoanCenter, "InvestorConfigurationController::GridResult", exception, Guid.Empty, _userAccountId);
                return(ShowErrorMessage());
            }
        }
        /// <summary>
        /// Stops the work item dispatcher with optional forced flag
        /// </summary>
        /// <param name="forced">Flag indicating whether to stop gracefully and wait for work item completion or just stop immediately</param>
        public async Task StopAsync(bool forced)
        {
            if (!isStarted)
            {
                return;
            }

            await slimLock.WaitAsync();

            try
            {
                if (!isStarted)
                {
                    return;
                }

                isStarted = false;

                TraceHelper.Trace(TraceEventType.Information, "WorkItemDispatcherStop-Begin", $"WorkItemDispatcher('{name}') stopping. Id {id}.");
                if (!forced)
                {
                    int retryCount = 7;
                    while ((concurrentWorkItemCount > 0 || activeFetchers > 0) && retryCount-- >= 0)
                    {
                        TraceHelper.Trace(TraceEventType.Information, "WorkItemDispatcherStop-Waiting", $"WorkItemDispatcher('{name}') waiting to stop. Id {id}. WorkItemCount: {concurrentWorkItemCount}, ActiveFetchers: {activeFetchers}");
                        await Task.Delay(4000);
                    }
                }

                TraceHelper.Trace(TraceEventType.Information, "WorkItemDispatcherStop-End", $"WorkItemDispatcher('{name}') stopped. Id {id}.");
            }
            finally
            {
                slimLock.Release();
            }
        }
 private void Step()
 {
     UpdateFrameInput();
     if (IsReplay)
     {
         if (curFrameIdx < frames.Count)
         {
             Replay(curFrameIdx);
             curFrameIdx++;
         }
     }
     else
     {
         Recoder();
         //send hash
         netClient.Send(new Msg_HashCode()
         {
             tick = curFrameIdx,
             hash = GetHash()
         });
         TraceHelper.TraceFrameState();
         curFrameIdx++;
     }
 }
示例#12
0
        /*private int GetSelectedIndex( List<DocumentCategory> documentCategories, Document document )
         * {
         *  if ( documentCategories == null )
         *      throw new ArgumentNullException( "documentCategories", "Document Categories list is null" );
         *
         *  if ( document == null )
         *      throw new ArgumentNullException( "document", "Document object is null." );
         *
         *  int index = 0;
         *  int resultIndex = 0;
         *  foreach ( var documentCategory in documentCategories )
         *  {
         *      if ( documentCategory.DocumentCategoryId == document.DocumentCategory.DocumentCategoryId )
         *      {
         *          resultIndex = index;
         *          break;
         *      }
         *      index++;
         *  }
         *  return resultIndex;
         * }*/

        private List <DropDownItem> ConvertDocumentCategoriesToListItems(List <DocumentCategory> documentCategories)
        {
            List <DropDownItem> listItems = null;

            try
            {
                listItems = new List <DropDownItem>();
                foreach (DocumentCategory document in documentCategories)
                {
                    listItems.Add(new DropDownItem()
                    {
                        Selected = false,
                        Text     = document.Name,
                        Value    = document.DocumentCategoryId.ToString()
                    });
                }
            }
            catch (Exception ex)
            {
                TraceHelper.Error(TraceCategory.ConciergeDocumentDownloader, "Unable to convert list of DocumentCategory to drop down items.", ex);
                throw;
            }
            return(listItems);
        }
示例#13
0
 /// <summary>
 /// WaitOrTimerCallback root method
 /// </summary>
 /// <param name="state">indicate the state</param>
 /// <param name="timedOut">indicate the timedOut</param>
 public void WaitOrTimerCallbackRoot(object state, bool timedOut)
 {
     try
     {
         this.callbackDelegate.DynamicInvoke(state, timedOut);
     }
     catch (ThreadAbortException)
     {
     }
     catch (AppDomainUnloadedException)
     {
     }
     catch (Exception e)
     {
         if (!this.sessionId.Equals("0"))
         {
             TraceHelper.TraceEvent(this.sessionId, TraceEventType.Critical, "[ThreadHelper] Exception catched at root: {0}", e);
         }
         else
         {
             TraceHelper.TraceEvent(TraceEventType.Critical, "[ThreadHelper] Exception catched at root: {0}", e);
         }
     }
 }
示例#14
0
        public bool IsInterestedStatusChange(BuildStatusChangeEvent changeEvent, Mapping mapping, Change statusChange)
        {
            bool isComputerMatch = IsComputerMatch(mapping.Computer);

            string wildcardQuality = Properties.Settings.Default.BuildQualityWildcard;
            bool   isOldValueMatch = IsQualityMatch(statusChange.OldValue, mapping.OriginalQuality, wildcardQuality);
            bool   isNewValueMatch = IsQualityMatch(statusChange.NewValue, mapping.NewQuality, wildcardQuality);
            bool   isUserPermitted = IsUserPermitted(changeEvent, mapping);

            TraceHelper.TraceInformation(TraceSwitches.TfsDeployer,
                                         "Mapping evaluation details:\n" +
                                         "    MachineName={0}, MappingComputer={1}\n" +
                                         "    BuildOldStatus={2}, BuildNewStatus={3}\n" +
                                         "    MappingOrigQuality={4}, MappingNewQuality={5}\n" +
                                         "    UserIsPermitted={6}, EventCausedBy={7}",
                                         Environment.MachineName, mapping.Computer, statusChange.OldValue, statusChange.NewValue, mapping.OriginalQuality, mapping.NewQuality, isUserPermitted, changeEvent.ChangedBy);

            TraceHelper.TraceInformation(TraceSwitches.TfsDeployer,
                                         "Eval results:\n" +
                                         "    isComputerMatch={0}, isOldValueMatch={1}, isNewValueMatch={2}, isUserPermitted={3}",
                                         isComputerMatch, isOldValueMatch, isNewValueMatch, isUserPermitted);

            return(isComputerMatch && isOldValueMatch && isNewValueMatch && isUserPermitted);
        }
示例#15
0
        private static void AddConnection(NetConnection connection)
        {
            TraceHelper.WriteLine("RUI: {0}", connection.RemoteUniqueIdentifier);
            KulamiPeer peer;

            if (!Peers.ContainsKey(connection.RemoteUniqueIdentifier))
            {
                peer = new KulamiPeer(connection);
                Peers[connection.RemoteUniqueIdentifier] = peer;

                if (OnDiscovery != null)
                {
                    OnDiscovery(peer, new EventArgs());
                }
            }
            else
            {
                Peers[connection.RemoteUniqueIdentifier].Connection = connection;
            }

            peer = Peers[connection.RemoteUniqueIdentifier];
            peer.SendName();
            peer.SendLobby();
        }
示例#16
0
        // Override the OnElementChanged method so we can tweak this renderer post-initial setup
        protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs <Entry> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                try
                {
                    Typeface font = Typeface.CreateFromAsset(Forms.Context.Assets, "fonts/Lato-Regular.ttf");
                    Control.SetTypeface(font, TypefaceStyle.Normal);
                    Control.SetTextColor(global::Android.Graphics.Color.Black);
                    Control.SetTextSize(Android.Util.ComplexUnitType.Sp, Config.DefaultFontSize);
                    Control.SetBackgroundColor(Android.Graphics.Color.White);
                    Control.SetHintTextColor(Android.Graphics.Color.Gray);
                }
                catch (Exception exc)
                {
                    var failureInfo = TraceHelper.ExceptionToString(exc);
                    Console.WriteLine("BybStandardEntryRenderer: OnElementChanged(): Exception " + failureInfo);

                    return;
                }
            }
        }
        public void SetupInteractionManagerEventInput()
        {
            TraceHelper.Log("MotionControllerInput:SetupInteractionManagerEventInput()");
#if UNITY_5
            InteractionManager.SourceDetected += InteractionManager_SourceDetected;
            InteractionManager.SourceLost     += InteractionManager_SourceLost;
            InteractionManager.SourceUpdated  += InteractionManager_SourceUpdated;
            InteractionManager.SourcePressed  += InteractionManager_SourcePressed;
#else
            InteractionManager.InteractionSourceDetected += InteractionManager_SourceDetected;
            InteractionManager.InteractionSourceLost     += InteractionManager_SourceLost;
            InteractionManager.InteractionSourceUpdated  += InteractionManager_SourceUpdated;
            InteractionManager.InteractionSourcePressed  += InteractionManager_SourcePressed;
#endif

            // Add any already detected devices to the list
            foreach (var sourceState in InteractionManager.GetCurrentReading())
            {
                if (sourceState.source.supportsPointing)
                {
                    this.AddDevice(sourceState.source);
                }
            }
        }
示例#18
0
 /// <summary>
 /// Query task info
 /// </summary>
 private async Task StartMonitorAsync()
 {
     try
     {
         TraceHelper.TraceEvent(this.sessionid, TraceEventType.Verbose, "[AzureBatchJobMonitorEntry] Start Azure Batch Job Monitor.");
         // RetryManager mgr = new RetryManager(new ExponentialRandomBackoffRetryTimer(1 * 1000, 10 * 1000));
         // await mgr.InvokeWithRetryAsync(() => await batchJobMonitor.StartAsync(), ex => true);
         RetryManager retry = SoaHelper.GetDefaultExponentialRetryManager();
         await RetryHelper <Task> .InvokeOperationAsync(
             async() =>
         {
             await this.batchJobMonitor.StartAsync();
             return(null);
         },
             async (e, r) => await Task.FromResult <object>(new Func <object>(() => { TraceHelper.TraceEvent(this.sessionid, TraceEventType.Warning, "[AzureBatchJobMonitorEntry] Exception thrown when trigger start Azure Batch Job Monitor: {0} ", e, r.RetryCount); return(null); }).Invoke()),
             retry);
     }
     catch (Exception e)
     {
         TraceHelper.TraceEvent(this.sessionid, TraceEventType.Warning, "[AzureBatchJobMonitorEntry] Exception thrown when trigger start Azure Batch Job Monitor: {0}", e);
     }
 }
示例#19
0
        /// <summary>
        /// Callback when Azure Batch Monitor report jon state
        /// </summary>
        private async void JobMonitor_OnReportJobState(Telepathy.Session.Data.JobState state, List <TaskInfo> stateChangedTaskList, bool shouldExit)
        {
            if (state != this.currentState)
            {
                lock (this.changeJobStateLock)
                {
                    if (state != this.currentState)
                    {
                        this.currentState = state;
                        if (this.context != null)
                        {
                            try
                            {
                                TraceHelper.TraceEvent(this.sessionid, TraceEventType.Information, "[AzureBatchJobMonitorEntry] Job state change event triggered, new state received from AzureBatchJobMonitor: {0}", state);
                                ISchedulerNotify proxy = this.context;
                                proxy.JobStateChanged(state);
                            }
                            catch (System.ObjectDisposedException e)
                            {
                                TraceHelper.TraceEvent(this.sessionid, TraceEventType.Error, "[AzureBatchJobMonitorEntry] Callback channel is disposed: {0}, lose connection to broker.", e);
                                this.context = null;
                            }
                            catch (CommunicationException e)
                            {
                                // Channel is aborted, set the context to null
                                TraceHelper.TraceEvent(this.sessionid, TraceEventType.Error, "[AzureBatchJobMonitorEntry] Callback channel is aborted: {0}", e);
                                this.context = null;
                            }
                            catch (Exception e)
                            {
                                TraceHelper.TraceEvent(this.sessionid, TraceEventType.Error, "[AzureBatchJobMonitorEntry] Failed to trigger job state change event: {0}", e);
                            }
                        }
                    }
                }
            }

            if (stateChangedTaskList != null)
            {
                if (this.context != null)
                {
                    try
                    {
                        ISchedulerNotify proxy = this.context;
                        await proxy.TaskStateChanged(stateChangedTaskList);

                        TraceHelper.TraceEvent(this.sessionid, TraceEventType.Information, "[AzureBatchJobMonitorEntry] Task state change event triggered.");
                    }
                    catch (System.ObjectDisposedException e)
                    {
                        TraceHelper.TraceEvent(this.sessionid, TraceEventType.Error, "[AzureBatchJobMonitorEntry] Callback channel is disposed: {0}, lose connection to broker", e);
                        this.context = null;
                    }
                    catch (CommunicationException e)
                    {
                        // Channel is aborted, set the context to null
                        TraceHelper.TraceEvent(this.sessionid, TraceEventType.Error, "[AzureBatchJobMonitorEntry] Callback channel is aborted: {0}", e);
                        this.context = null;
                    }
                    catch (Exception e)
                    {
                        TraceHelper.TraceEvent(this.sessionid, TraceEventType.Error, "[AzureBatchJobMonitorEntry] Failed to trigger task state change event: {0}", e);
                    }
                }
            }

            if (shouldExit)
            {
                if (this.Exit != null)
                {
                    TraceHelper.TraceEvent(this.sessionid, TraceEventType.Information, "[AzureBatchJobMonitorEntry] Exit AzureBatchJobMonitor Entry");
                    this.Exit(this, EventArgs.Empty);
                }
            }
        }
示例#20
0
        /// <summary>
        /// start service host by serviceInfo
        /// </summary>
        /// <param name="serviceInfo"></param>
        /// <returns></returns>
        public static int OpenService(ServiceInfo serviceInfo)
        {
            void SetEnvironment()
            {
                if (serviceInfo.Environment == null)
                {
                    TraceHelper.TraceVerbose(Utility.GetJobId(), "No environment fond.");
                    return;
                }

                foreach (var env in serviceInfo.Environment)
                {
                    Environment.SetEnvironmentVariable(env.Key, env.Value);
                    TraceHelper.TraceVerbose(Utility.GetJobId(), $"Set environment {env.Key}={env.Value}.");
                }
            }

            async Task <string[]> DownloadDependFiles()
            {
                if (serviceInfo.DependFiles != null && serviceInfo.DependFiles.Any())
                {
                    var downloadTasks = serviceInfo.DependFiles.Select(fileInfo => StandaloneDataClient.DownloadFileFromSasAsync(
                                                                           fileInfo.Value,
                                                                           Path.Combine(Path.Combine(Path.GetTempPath(), "ExcelOffloading"), Path.GetFileName(fileInfo.Key))));
                    return(await Task.WhenAll(downloadTasks));
                }
                else
                {
                    TraceHelper.TraceVerbose(Utility.GetJobId(), "No depend files fond.");
                    return(new string[0]);
                }
            }

            Environment.SetEnvironmentVariable(Constant.JobIDEnvVar, serviceInfo.JobId.ToString());
            Environment.SetEnvironmentVariable(Constant.TaskIDEnvVar, serviceInfo.TaskId.ToString());
            Environment.SetEnvironmentVariable(Constant.CoreIdsEnvVar, serviceInfo.CoreId.ToString());
            Environment.SetEnvironmentVariable(Constant.ServiceConfigFileNameEnvVar, serviceInfo.FileName);
            if (!string.IsNullOrEmpty(serviceInfo.RegistrationPath))
            {
                Environment.SetEnvironmentVariable(Constant.RegistryPathEnv, serviceInfo.RegistrationPath);
            }
            else
            {
                Environment.SetEnvironmentVariable(Constant.RegistryPathEnv, Path.Combine(Environment.CurrentDirectory, defaultRegistryPath));
            }

            TraceHelper.TraceVerbose(Utility.GetJobId(), $"Set {Constant.RegistryPathEnv} to {Environment.GetEnvironmentVariable(Constant.RegistryPathEnv)}");

            // use default values for following environment variables
            Environment.SetEnvironmentVariable(Constant.ProcNumEnvVar, "1");
            Environment.SetEnvironmentVariable(Constant.NetworkPrefixEnv, Constant.EnterpriseNetwork);
            Environment.SetEnvironmentVariable(Constant.ServiceInitializationTimeoutEnvVar, "60000");
            Environment.SetEnvironmentVariable(Constant.CancelTaskGracePeriodEnvVar, "15");
            Environment.SetEnvironmentVariable(Constant.ServiceConfigMaxMessageEnvVar, "65536");
            Environment.SetEnvironmentVariable(Constant.ServiceConfigServiceOperatonTimeoutEnvVar, "86400000");

            // the local host process won't be preempted by the scheduler
            Environment.SetEnvironmentVariable(Constant.EnableMessageLevelPreemptionEnvVar, bool.FalseString);

            SetEnvironment();
            var dependFilePath = DownloadDependFiles().GetAwaiter().GetResult();

            Environment.SetEnvironmentVariable(Constant.DataServiceSharedFileEnvVar, string.Join(";", dependFilePath));

#if DEBUG
            #region For EndpointNotFoundException test
            try
            {
                string strWaitPeriod = ConfigurationManager.AppSettings["Test_WaitPeriodBeforeStartup"];
                if (!string.IsNullOrEmpty(strWaitPeriod))
                {
                    int waitPeriodInMilliSecond = int.Parse(strWaitPeriod);
                    Console.Error.WriteLine("Debug: waiting {0} ms before startup service", waitPeriodInMilliSecond);
                    Thread.Sleep(waitPeriodInMilliSecond);
                }
            }
            catch (Exception)
            {
                // do nothing
            }
            #endregion
#endif

            jobId = Utility.GetJobId();

            string serviceConfigFullPath;

            bool onAzure = SoaHelper.IsOnAzure();
            TraceHelper.TraceInfo(
                jobId,
                "OnAzure = {0}",
                onAzure);

            bool bOpenDummy = false;
            try
            {
                string serviceConfigFileName = Environment.GetEnvironmentVariable(Constant.ServiceConfigFileNameEnvVar);

                // exit if no such env var
                if (string.IsNullOrEmpty(serviceConfigFileName))
                {
                    bOpenDummy = true;
                    Console.Error.WriteLine(StringTable.ServiceConfigFileNameNotSpecified);
                    return(ErrorCode.ServiceHost_ServiceConfigFileNameNotSpecified);
                }

                if (onAzure)
                {
                    string localCacheFolder = Utility.GetServiceLocalCacheFullPath();
                    serviceConfigFullPath = Path.Combine(localCacheFolder, serviceConfigFileName);
                }
                else
                {
                    serviceConfigFullPath = GetServiceInfo(serviceConfigFileName);
                }

                if (!File.Exists(serviceConfigFullPath))
                {
                    bOpenDummy = true;
                    Console.Error.WriteLine(StringTable.CantFindServiceRegistrationFile, serviceConfigFullPath);
                    return(ErrorCode.ServiceHost_ServiceRegistrationFileNotFound);
                }

                TraceHelper.TraceInfo(
                    jobId,
                    "ServiceConfigFullPath = {0}",
                    serviceConfigFullPath);
                ServiceRegistration registration;
                string assemblyFullPath;
                int    errorCode = Utility.GetServiceRegistration(serviceConfigFullPath, onAzure, out registration, out assemblyFullPath);
                if (errorCode != ErrorCode.Success)
                {
                    bOpenDummy = true;
                    return(errorCode);
                }

                // Open the host in another application domain
                AppDomain domain = CreateNewServiceDomain(serviceConfigFullPath, assemblyFullPath);



                using (CcpServiceHostWrapper host =
                           CreateInstanceFromAndUnwrap <CcpServiceHostWrapper>(
                               domain,
                               Assembly.GetExecutingAssembly().Location,
                               serviceConfigFullPath,
                               onAzure,
                               ServiceHostRuntimeConfiguration.Standalone))
                {
                    host.Initialize();
                    host.Run();
                    TraceHelper.TraceInfo(
                        jobId,
                        "Sleep...");

                    if (ServiceHostRuntimeConfiguration.Standalone)
                    {
                        // Endless listening, till service info deleted.
                        while (true)
                        {
                            lock (ServiceInfo.s_lock)
                            {
                                if (SvcHostMgmtRestServer.Info == null)
                                {
                                    TraceHelper.TraceInfo(
                                        jobId,
                                        "Close service host!");
                                    host.Dispose();
                                    return(0);
                                }
                            }
                            Thread.Sleep(1000);
                        }
                    }
                    else
                    {
                        // Endless waiting, till it's being killed
                        Thread.Sleep(Timeout.Infinite);
                    }
                }
            }
            catch (Exception e)
            {
                Console.Error.WriteLine(e.Message);

                TraceHelper.TraceError(
                    jobId,
                    e.ToString());

                // Failed to open service, fall back to open an dummy service.
                bOpenDummy = true;
            }
            finally
            {
                if (bOpenDummy)
                {
                    OpenDummyService(onAzure);
                }
            }

            return(0);
        }
示例#21
0
        /// <summary>
        /// If HpcServiceHost is launched to run a pre/post task, launch the pre/post task
        /// </summary>
        private static bool RunPrePostTask(ref uint exitCode)
        {
            bool   prePostTaskExists      = false;
            string prePostTaskCommandLine = Environment.GetEnvironmentVariable(Constant.PrePostTaskCommandLineEnvVar);

            // Check if pre/post task exists
            prePostTaskExists = !string.IsNullOrEmpty(prePostTaskCommandLine);

            // if so run it
            if (prePostTaskExists)
            {
                string serviceWorkingDirectory = null;

                // Working directory is the service assembly's directory. If we are on Azure, change to the service package's dir. If
                //  not on azure use service assemblies directory from service config which is passed to svchost via env var so we dont
                //  need to read the svc config file again on every CN (which is slow)
                if (SoaHelper.IsOnAzure())
                {
                    serviceWorkingDirectory = Utility.GetServiceLocalCacheFullPath();
                }
                else
                {
                    serviceWorkingDirectory = Environment.ExpandEnvironmentVariables(
                        Environment.GetEnvironmentVariable(Constant.PrePostTaskOnPremiseWorkingDirEnvVar));
                }

                NativeMethods.STARTUPINFO startupInfo = new NativeMethods.STARTUPINFO();
                startupInfo.cb = Marshal.SizeOf(typeof(NativeMethods.STARTUPINFO));

                NativeMethods.PROCESS_INFORMATION processInfo = new NativeMethods.PROCESS_INFORMATION();

                StringBuilder commandLine = new StringBuilder();

                // Run command from comspec (like node manager babysitter) to ensure env vars are expanded and command runs as if launched from node manager
                commandLine.AppendFormat("\"{0}\" /S /c \"{1}\"", Environment.GetEnvironmentVariable("ComSpec"), prePostTaskCommandLine);

                TraceHelper.TraceInfo(
                    jobId,
                    "Executing '{0}'",
                    prePostTaskCommandLine);

                // Start the task
                bool ret = NativeMethods.CreateProcess(null,
                                                       commandLine,
                                                       IntPtr.Zero,
                                                       IntPtr.Zero,
                                                       true,
                                                       NativeMethods.CREATE_UNICODE_ENVIRONMENT,
                                                       IntPtr.Zero,
                                                       serviceWorkingDirectory,
                                                       ref startupInfo,
                                                       out processInfo);

                // If CreateProcess succeeded
                if (ret)
                {
                    using (SafeWaitHandle processHandle = new SafeWaitHandle(processInfo.hProcess, true))
                        using (SafeWaitHandle threadHandle = new SafeWaitHandle(processInfo.hThread, true))
                        {
                            if (processHandle.IsClosed || processHandle.IsInvalid)
                            {
                                TraceHelper.TraceError(
                                    jobId,
                                    "Process handle is invalid or closed. Task commandline = {0}",
                                    commandLine);

                                exitCode = 1;
                                return(true);
                            }

                            // Wait for task to complete
                            NativeMethods.WaitForSingleObject(processInfo.hProcess, Timeout.Infinite);

                            // Trace the results
                            NativeMethods.GetExitCodeProcess(new SafeProcessHandle(processInfo.hProcess, false), out exitCode);

                            TraceHelper.TraceInfo(
                                jobId,
                                "ExitCode = {0}",
                                exitCode);
                        }
                }
                else
                {
                    int errorCode = Marshal.GetLastWin32Error();

                    TraceHelper.TraceError(
                        jobId,
                        "Cannot start pre/post task: '{0}'. Exit code = {1}",
                        prePostTaskCommandLine, errorCode);

                    exitCode = (uint)errorCode;
                }
            }

            return(prePostTaskExists);
        }
示例#22
0
        public static async Task <BrokeredMessage> GetBrokeredMessageFromObjectAsync(
            object serializableObject,
            CompressionSettings compressionSettings,
            ServiceBusMessageSettings messageSettings,
            OrchestrationInstance instance,
            string messageType,
            IOrchestrationServiceBlobStore orchestrationServiceBlobStore,
            DateTime messageFireTime)
        {
            if (serializableObject == null)
            {
                throw new ArgumentNullException(nameof(serializableObject));
            }

            if (compressionSettings.Style == CompressionStyle.Legacy)
            {
                return(new BrokeredMessage(serializableObject)
                {
                    SessionId = instance?.InstanceId
                });
            }

            if (messageSettings == null)
            {
                messageSettings = new ServiceBusMessageSettings();
            }

            bool disposeStream = true;
            var  rawStream     = new MemoryStream();

            Utils.WriteObjectToStream(rawStream, serializableObject);

            try
            {
                BrokeredMessage brokeredMessage = null;

                if (compressionSettings.Style == CompressionStyle.Always ||
                    (compressionSettings.Style == CompressionStyle.Threshold &&
                     rawStream.Length > compressionSettings.ThresholdInBytes))
                {
                    Stream compressedStream = Utils.GetCompressedStream(rawStream);
                    var    rawLen           = rawStream.Length;
                    TraceHelper.TraceInstance(
                        TraceEventType.Information,
                        "GetBrokeredMessageFromObject-CompressionStats",
                        instance,
                        () =>
                        "Compression stats for " + (messageType ?? string.Empty) + " : " +
                        brokeredMessage?.MessageId +
                        ", uncompressed " + rawLen + " -> compressed " + compressedStream.Length);

                    if (compressedStream.Length < messageSettings.MessageOverflowThresholdInBytes)
                    {
                        brokeredMessage = GenerateBrokeredMessageWithCompressionTypeProperty(compressedStream, FrameworkConstants.CompressionTypeGzipPropertyValue);
                    }
                    else
                    {
                        brokeredMessage = await GenerateBrokeredMessageWithBlobKeyPropertyAsync(compressedStream, orchestrationServiceBlobStore, instance, messageSettings, messageFireTime, FrameworkConstants.CompressionTypeGzipPropertyValue);
                    }
                }
                else
                {
                    if (rawStream.Length < messageSettings.MessageOverflowThresholdInBytes)
                    {
                        brokeredMessage = GenerateBrokeredMessageWithCompressionTypeProperty(rawStream, FrameworkConstants.CompressionTypeNonePropertyValue);
                        disposeStream   = false;
                    }
                    else
                    {
                        brokeredMessage = await GenerateBrokeredMessageWithBlobKeyPropertyAsync(rawStream, orchestrationServiceBlobStore, instance, messageSettings, messageFireTime, FrameworkConstants.CompressionTypeNonePropertyValue);
                    }
                }

                brokeredMessage.SessionId = instance?.InstanceId;
                // TODO : Test more if this helps, initial tests shows not change in performance
                // brokeredMessage.ViaPartitionKey = instance?.InstanceId;

                return(brokeredMessage);
            }
            finally
            {
                if (disposeStream)
                {
                    rawStream.Dispose();
                }
            }
        }
示例#23
0
        public async Task Invoke(HttpContext context)
        {
            string pagePath = context.Request.ServerVariables["PATH_TRANSLATED"];

            CompiledPage cpage = null;

            if (_scriptCache.ContainsKey(pagePath))
            {
                cpage = _scriptCache[pagePath];
                //don't use it if updated
                if (cpage.CompileTime < File.GetLastWriteTime(pagePath))
                {
                    cpage = null;
                }
            }

            if (cpage == null)
            {
                try
                {
                    cpage = _aspHost.ProcessPageFromFile(pagePath);
                    _scriptCache[pagePath] = cpage;
                }
                catch (VBScriptCompilerException ex)
                {
                    AspHelper.RenderError(context.Response, ex);
                    return;
                }
            }

            ScriptScope pageScope = _aspHost.CreateScope();

            pageScope.SetVariable("response", new AspResponse(context));
            pageScope.SetVariable("request", new AspRequest(context));
            pageScope.SetVariable("session", new AspSession(context));
            pageScope.SetVariable("server", new AspServer(context));
            pageScope.SetVariable("application", new AspApplication(context));
            AspObjectContext ctx = new AspObjectContext();

            pageScope.SetVariable("objectcontext", ctx);
            pageScope.SetVariable("getobjectcontext", ctx);
            //responseScope.SetVariable("err", new Microsoft.VisualBasic.ErrObject());
            //Used to get the literals
            pageScope.SetVariable("literals", cpage.Literals);

            try
            {
                object o = cpage.Code.Execute(pageScope);
            }
            catch (ThreadAbortException)
            {
                //Do nothing since we get this normally when calling response.redirect
            }
            catch (Exception ex)
            {
                if (_aspHost.Configuration.Trace)
                {
                    TraceHelper th     = (TraceHelper)pageScope.GetVariable(VBScript.TRACE_PARAMETER);
                    string      source = string.Format("{0} ({1},{2})-({3},{4})", th.Source, th.StartLine, th.StartColumn, th.EndLine, th.EndColumn);
                    throw new VBScriptRuntimeException(ex, source);
                }
                throw;
            }
        }
示例#24
0
        static TaskMessage ProcessWorkflowCompletedTaskDecision(
            OrchestrationCompleteOrchestratorAction completeOrchestratorAction,
            OrchestrationRuntimeState runtimeState,
            bool includeDetails,
            out bool continuedAsNew)
        {
            ExecutionCompletedEvent executionCompletedEvent;

            continuedAsNew = (completeOrchestratorAction.OrchestrationStatus == OrchestrationStatus.ContinuedAsNew);
            if (completeOrchestratorAction.OrchestrationStatus == OrchestrationStatus.ContinuedAsNew)
            {
                executionCompletedEvent = new ContinueAsNewEvent(completeOrchestratorAction.Id,
                                                                 completeOrchestratorAction.Result);
            }
            else
            {
                executionCompletedEvent = new ExecutionCompletedEvent(completeOrchestratorAction.Id,
                                                                      completeOrchestratorAction.Result,
                                                                      completeOrchestratorAction.OrchestrationStatus);
            }

            runtimeState.AddEvent(executionCompletedEvent);

            TraceHelper.TraceInstance(
                runtimeState.OrchestrationStatus == OrchestrationStatus.Failed ? TraceEventType.Warning : TraceEventType.Information,
                "TaskOrchestrationDispatcher-InstanceCompleted",
                runtimeState.OrchestrationInstance,
                "Instance Id '{0}' completed in state {1} with result: {2}",
                runtimeState.OrchestrationInstance,
                runtimeState.OrchestrationStatus,
                completeOrchestratorAction.Result);
            TraceHelper.TraceInstance(
                TraceEventType.Information,
                "TaskOrchestrationDispatcher-InstanceCompletionEvents",
                runtimeState.OrchestrationInstance,
                () => Utils.EscapeJson(DataConverter.Serialize(runtimeState.Events, true)));

            // Check to see if we need to start a new execution
            if (completeOrchestratorAction.OrchestrationStatus == OrchestrationStatus.ContinuedAsNew)
            {
                var taskMessage  = new TaskMessage();
                var startedEvent = new ExecutionStartedEvent(-1, completeOrchestratorAction.Result)
                {
                    OrchestrationInstance = new OrchestrationInstance
                    {
                        InstanceId  = runtimeState.OrchestrationInstance.InstanceId,
                        ExecutionId = Guid.NewGuid().ToString("N")
                    },
                    Tags           = runtimeState.Tags,
                    ParentInstance = runtimeState.ParentInstance,
                    Name           = runtimeState.Name,
                    Version        = completeOrchestratorAction.NewVersion ?? runtimeState.Version
                };

                taskMessage.OrchestrationInstance = startedEvent.OrchestrationInstance;
                taskMessage.Event = startedEvent;

                return(taskMessage);
            }

            // If this is a Sub Orchestration, and not tagged as fire-and-forget,
            // then notify the parent by sending a complete message
            if (runtimeState.ParentInstance != null &&
                !OrchestrationTags.IsTaggedAsFireAndForget(runtimeState.Tags))
            {
                var taskMessage = new TaskMessage();
                if (completeOrchestratorAction.OrchestrationStatus == OrchestrationStatus.Completed)
                {
                    var subOrchestrationCompletedEvent =
                        new SubOrchestrationInstanceCompletedEvent(-1, runtimeState.ParentInstance.TaskScheduleId,
                                                                   completeOrchestratorAction.Result);

                    taskMessage.Event = subOrchestrationCompletedEvent;
                }
                else if (completeOrchestratorAction.OrchestrationStatus == OrchestrationStatus.Failed ||
                         completeOrchestratorAction.OrchestrationStatus == OrchestrationStatus.Terminated)
                {
                    var subOrchestrationFailedEvent =
                        new SubOrchestrationInstanceFailedEvent(-1, runtimeState.ParentInstance.TaskScheduleId,
                                                                completeOrchestratorAction.Result,
                                                                includeDetails ? completeOrchestratorAction.Details : null);

                    taskMessage.Event = subOrchestrationFailedEvent;
                }

                if (taskMessage.Event != null)
                {
                    taskMessage.OrchestrationInstance = runtimeState.ParentInstance.OrchestrationInstance;
                    return(taskMessage);
                }
            }

            return(null);
        }
示例#25
0
        /// <summary>
        /// Runs the worker once to send e-mails.
        /// </summary>
        public override void RunOnce()
        {
            // If this method is already running, then leave the already running alone, and return.
            // If it is not running, set the value os locker to 1 to indicate that now it is running.
            if (Interlocked.Exchange(ref locker, 1) != 0)
            {
                return;
            }

            Trace.TraceInformation("EmailSenderWorker.RunOnce(): service in execution");
            var emailsSent = 0;

            try
            {
                var utcNow = this.GetUtcNow();
                using (var db = this.CreateNewCerebelloEntities())
                {
                    Trace.TraceInformation("EmailSenderWorker.RunOnce(): this.CreateNewCerebelloEntities()");

                    var next40H = utcNow.AddHours(40.0);

                    // One e-mail will be sent 40 hours before the appointment.
                    var items = db.Appointments
                                .Where(a => a.Start > utcNow && a.Start < next40H && !a.ReminderEmailSent)
                                .Where(a => a.PatientId != null)
                                .Select(
                        a => new
                    {
                        Appointment = a,
                        Practice    = db.Practices.FirstOrDefault(p => p.Id == a.PracticeId),
                        a.Patient,
                        a.Patient.Person,
                        a.Doctor,
                        DoctorPerson = a.Doctor.Users.FirstOrDefault().Person,
                    })
                                .Select(
                        a => new
                    {
                        a.Appointment,
                        EmailViewModel = new PatientEmailModel
                        {
                            PatientEmail    = a.Person.Email,
                            PatientName     = a.Person.FullName,
                            PracticeUrlId   = a.Practice.UrlIdentifier,
                            PatientGender   = (TypeGender)a.Person.Gender,
                            PracticeName    = a.Practice.Name,
                            DoctorName      = a.DoctorPerson.FullName,
                            DoctorGender    = (TypeGender)a.DoctorPerson.Gender,
                            AppointmentDate = a.Appointment.Start,

                            PracticeEmail     = a.Practice.Email,
                            PracticePhoneMain = a.Practice.PhoneMain,
                            PracticePhoneAlt  = a.Practice.PhoneAlt,
                            PracticeSiteUrl   = a.Practice.SiteUrl,
                            PracticePabx      = a.Practice.PABX,
                            PracticeAddress   = new AddressViewModel
                            {
                                StateProvince = a.Practice.Address.StateProvince,
                                City          = a.Practice.Address.City,
                                Neighborhood  = a.Practice.Address.Neighborhood,
                                Street        = a.Practice.Address.Street,
                                Complement    = a.Practice.Address.Complement,
                                CEP           = a.Practice.Address.CEP,
                            },

                            // todo: is it correct to send these informations to the patient
                            // maybe this info is not suited to the outside world
                            DoctorPhone = a.DoctorPerson.PhoneCell ?? a.DoctorPerson.PhoneLand,
                            DoctorEmail = a.DoctorPerson.Email,
                        }
                    })
                                .ToArray();

                    Trace.TraceInformation("EmailSenderWorker.RunOnce(): got list of appointments from database");

                    bool traceMessageCreated = false;
                    bool traceEmailSent      = false;
                    bool traceEmailNotSent   = false;
                    bool traceDbSaved        = false;
                    foreach (var eachItem in items)
                    {
                        if (string.IsNullOrWhiteSpace(eachItem.EmailViewModel.PatientEmail))
                        {
                            continue;
                        }

                        // Rendering message bodies from partial view.
                        var emailViewModel = eachItem.EmailViewModel;
                        var toAddress      = new MailAddress(emailViewModel.PatientEmail, emailViewModel.PatientName);
                        var mailMessage    = this.CreateEmailMessage("AppointmentReminderEmail", toAddress, emailViewModel);

                        if (!traceMessageCreated)
                        {
                            Trace.TraceInformation("EmailSenderWorker.RunOnce(): var mailMessage = { rendered e-mail message }");
                        }
                        traceMessageCreated = true;

                        if (this.TrySendEmail(mailMessage))
                        {
                            if (!traceEmailSent)
                            {
                                Trace.TraceInformation("EmailSenderWorker.RunOnce(): this.TrySendEmail(mailMessage) => true");
                            }
                            traceEmailSent = true;

                            emailsSent++;
                            this.EmailsCount++;
                            eachItem.Appointment.ReminderEmailSent = true;
                            db.SaveChanges();

                            if (!traceDbSaved)
                            {
                                Trace.TraceInformation("EmailSenderWorker.RunOnce(): db.SaveChanges()");
                            }
                            traceDbSaved = true;
                        }
                        else
                        {
                            if (!traceEmailNotSent)
                            {
                                Trace.TraceInformation("EmailSenderWorker.RunOnce(): this.TrySendEmail(mailMessage) => false");
                            }
                            traceEmailNotSent = true;
                        }
                    }

                    Trace.TraceInformation(string.Format("EmailSenderWorker.RunOnce(): emailsSent => {0}", emailsSent));
                }
            }
            catch (Exception ex)
            {
                Trace.TraceError(string.Format("EmailSenderWorker.RunOnce(): exception while trying to send e-mails: {0}", TraceHelper.GetExceptionMessage(ex)));
            }

            // setting locker value to 0
            if (Interlocked.Exchange(ref locker, 0) != 1)
            {
                throw new Exception("The value of locker should be 1 before setting it to 0.");
            }
        }
示例#26
0
        static bool ReconcileMessagesWithState(TaskOrchestrationWorkItem workItem)
        {
            foreach (TaskMessage message in workItem.NewMessages)
            {
                OrchestrationInstance orchestrationInstance = message.OrchestrationInstance;
                if (string.IsNullOrWhiteSpace(orchestrationInstance?.InstanceId))
                {
                    throw TraceHelper.TraceException(
                              TraceEventType.Error,
                              "TaskOrchestrationDispatcher-OrchestrationInstanceMissing",
                              new InvalidOperationException("Message does not contain any OrchestrationInstance information"));
                }

                if (workItem.OrchestrationRuntimeState.Events.Count == 1 && message.Event.EventType != EventType.ExecutionStarted)
                {
                    // we get here because of:
                    //      i) responses for scheduled tasks after the orchestrations have been completed
                    //      ii) responses for explicitly deleted orchestrations
                    return(false);
                }

                TraceHelper.TraceInstance(
                    TraceEventType.Information,
                    "TaskOrchestrationDispatcher-ProcessEvent",
                    orchestrationInstance,
                    "Processing new event with Id {0} and type {1}",
                    message.Event.EventId,
                    message.Event.EventType);

                if (message.Event.EventType == EventType.ExecutionStarted)
                {
                    if (workItem.OrchestrationRuntimeState.Events.Count > 1)
                    {
                        // this was caused due to a dupe execution started event, swallow this one
                        TraceHelper.TraceInstance(
                            TraceEventType.Warning,
                            "TaskOrchestrationDispatcher-DuplicateStartEvent",
                            orchestrationInstance,
                            "Duplicate start event.  Ignoring event with Id {0} and type {1} ",
                            message.Event.EventId,
                            message.Event.EventType);
                        continue;
                    }
                }
                else if (!string.IsNullOrWhiteSpace(orchestrationInstance.ExecutionId)
                         &&
                         !string.Equals(orchestrationInstance.ExecutionId,
                                        workItem.OrchestrationRuntimeState.OrchestrationInstance.ExecutionId))
                {
                    // eat up any events for previous executions
                    TraceHelper.TraceInstance(
                        TraceEventType.Warning,
                        "TaskOrchestrationDispatcher-ExecutionIdMismatch",
                        orchestrationInstance,
                        "ExecutionId of event does not match current executionId.  Ignoring event with Id {0} and type {1} ",
                        message.Event.EventId,
                        message.Event.EventType);
                    continue;
                }

                workItem.OrchestrationRuntimeState.AddEvent(message.Event);
            }

            return(true);
        }
示例#27
0
        /// <summary>
        /// Method to process a new work item
        /// </summary>
        /// <param name="workItem">The work item to process</param>
        protected async Task <bool> OnProcessWorkItemAsync(TaskOrchestrationWorkItem workItem)
        {
            var messagesToSend       = new List <TaskMessage>();
            var timerMessages        = new List <TaskMessage>();
            var orchestratorMessages = new List <TaskMessage>();
            var isCompleted          = false;
            var continuedAsNew       = false;
            var isInterrupted        = false;

            // correlation
            CorrelationTraceClient.Propagate(() => CorrelationTraceContext.Current = workItem.TraceContext);

            ExecutionStartedEvent continueAsNewExecutionStarted = null;
            TaskMessage           continuedAsNewMessage         = null;
            IList <HistoryEvent>  carryOverEvents = null;
            string carryOverStatus = null;

            OrchestrationRuntimeState runtimeState = workItem.OrchestrationRuntimeState;

            runtimeState.AddEvent(new OrchestratorStartedEvent(-1));

            OrchestrationRuntimeState originalOrchestrationRuntimeState = runtimeState;

            OrchestrationState instanceState = null;

            if (!ReconcileMessagesWithState(workItem))
            {
                // TODO : mark an orchestration as faulted if there is data corruption
                TraceHelper.TraceSession(
                    TraceEventType.Error,
                    "TaskOrchestrationDispatcher-DeletedOrchestration",
                    runtimeState.OrchestrationInstance?.InstanceId,
                    "Received result for a deleted orchestration");
                isCompleted = true;
            }
            else
            {
                do
                {
                    continuedAsNew        = false;
                    continuedAsNewMessage = null;

                    TraceHelper.TraceInstance(
                        TraceEventType.Verbose,
                        "TaskOrchestrationDispatcher-ExecuteUserOrchestration-Begin",
                        runtimeState.OrchestrationInstance,
                        "Executing user orchestration: {0}",
                        DataConverter.Serialize(runtimeState.GetOrchestrationRuntimeStateDump(), true));

                    if (workItem.Cursor == null)
                    {
                        workItem.Cursor = await ExecuteOrchestrationAsync(runtimeState);
                    }
                    else
                    {
                        await ResumeOrchestrationAsync(workItem.Cursor);
                    }

                    IReadOnlyList <OrchestratorAction> decisions = workItem.Cursor.LatestDecisions.ToList();

                    TraceHelper.TraceInstance(
                        TraceEventType.Information,
                        "TaskOrchestrationDispatcher-ExecuteUserOrchestration-End",
                        runtimeState.OrchestrationInstance,
                        "Executed user orchestration. Received {0} orchestrator actions: {1}",
                        decisions.Count,
                        string.Join(", ", decisions.Select(d => d.Id + ":" + d.OrchestratorActionType)));

                    foreach (OrchestratorAction decision in decisions)
                    {
                        TraceHelper.TraceInstance(
                            TraceEventType.Information,
                            "TaskOrchestrationDispatcher-ProcessOrchestratorAction",
                            runtimeState.OrchestrationInstance,
                            "Processing orchestrator action of type {0}",
                            decision.OrchestratorActionType);
                        switch (decision.OrchestratorActionType)
                        {
                        case OrchestratorActionType.ScheduleOrchestrator:
                            messagesToSend.Add(
                                ProcessScheduleTaskDecision((ScheduleTaskOrchestratorAction)decision, runtimeState,
                                                            IncludeParameters));
                            break;

                        case OrchestratorActionType.CreateTimer:
                            var timerOrchestratorAction = (CreateTimerOrchestratorAction)decision;
                            timerMessages.Add(ProcessCreateTimerDecision(timerOrchestratorAction, runtimeState));
                            break;

                        case OrchestratorActionType.CreateSubOrchestration:
                            var createSubOrchestrationAction = (CreateSubOrchestrationAction)decision;
                            orchestratorMessages.Add(
                                ProcessCreateSubOrchestrationInstanceDecision(createSubOrchestrationAction,
                                                                              runtimeState, IncludeParameters));
                            break;

                        case OrchestratorActionType.SendEvent:
                            var sendEventAction = (SendEventOrchestratorAction)decision;
                            orchestratorMessages.Add(
                                ProcessSendEventDecision(sendEventAction, runtimeState));
                            break;

                        case OrchestratorActionType.OrchestrationComplete:
                            OrchestrationCompleteOrchestratorAction completeDecision = (OrchestrationCompleteOrchestratorAction)decision;
                            TaskMessage workflowInstanceCompletedMessage             =
                                ProcessWorkflowCompletedTaskDecision(completeDecision, runtimeState, IncludeDetails, out continuedAsNew);
                            if (workflowInstanceCompletedMessage != null)
                            {
                                // Send complete message to parent workflow or to itself to start a new execution
                                // Store the event so we can rebuild the state
                                carryOverEvents = null;
                                if (continuedAsNew)
                                {
                                    continuedAsNewMessage         = workflowInstanceCompletedMessage;
                                    continueAsNewExecutionStarted = workflowInstanceCompletedMessage.Event as ExecutionStartedEvent;
                                    if (completeDecision.CarryoverEvents.Any())
                                    {
                                        carryOverEvents = completeDecision.CarryoverEvents.ToList();
                                        completeDecision.CarryoverEvents.Clear();
                                    }
                                }
                                else
                                {
                                    orchestratorMessages.Add(workflowInstanceCompletedMessage);
                                }
                            }

                            isCompleted = !continuedAsNew;
                            break;

                        default:
                            throw TraceHelper.TraceExceptionInstance(
                                      TraceEventType.Error,
                                      "TaskOrchestrationDispatcher-UnsupportedDecisionType",
                                      runtimeState.OrchestrationInstance,
                                      new NotSupportedException("decision type not supported"));
                        }

                        // Underlying orchestration service provider may have a limit of messages per call, to avoid the situation
                        // we keep on asking the provider if message count is ok and stop processing new decisions if not.
                        //
                        // We also put in a fake timer to force next orchestration task for remaining messages
                        int totalMessages = messagesToSend.Count + orchestratorMessages.Count + timerMessages.Count;
                        if (this.orchestrationService.IsMaxMessageCountExceeded(totalMessages, runtimeState))
                        {
                            TraceHelper.TraceInstance(
                                TraceEventType.Information,
                                "TaskOrchestrationDispatcher-MaxMessageCountReached",
                                runtimeState.OrchestrationInstance,
                                "MaxMessageCount reached.  Adding timer to process remaining events in next attempt.");

                            if (isCompleted || continuedAsNew)
                            {
                                TraceHelper.TraceInstance(
                                    TraceEventType.Information,
                                    "TaskOrchestrationDispatcher-OrchestrationAlreadyCompleted",
                                    runtimeState.OrchestrationInstance,
                                    "Orchestration already completed.  Skip adding timer for splitting messages.");
                                break;
                            }

                            var dummyTimer = new CreateTimerOrchestratorAction
                            {
                                Id     = FrameworkConstants.FakeTimerIdToSplitDecision,
                                FireAt = DateTime.UtcNow
                            };

                            timerMessages.Add(ProcessCreateTimerDecision(dummyTimer, runtimeState));
                            isInterrupted = true;
                            break;
                        }
                    }

                    // finish up processing of the work item
                    if (!continuedAsNew && runtimeState.Events.Last().EventType != EventType.OrchestratorCompleted)
                    {
                        runtimeState.AddEvent(new OrchestratorCompletedEvent(-1));
                    }

                    if (isCompleted)
                    {
                        TraceHelper.TraceSession(TraceEventType.Information, "TaskOrchestrationDispatcher-DeletingSessionState", workItem.InstanceId, "Deleting session state");
                        if (runtimeState.ExecutionStartedEvent != null)
                        {
                            instanceState = Utils.BuildOrchestrationState(runtimeState);
                        }
                    }
                    else
                    {
                        if (continuedAsNew)
                        {
                            TraceHelper.TraceSession(
                                TraceEventType.Information,
                                "TaskOrchestrationDispatcher-UpdatingStateForContinuation",
                                workItem.InstanceId,
                                "Updating state for continuation");

                            runtimeState = new OrchestrationRuntimeState();
                            runtimeState.AddEvent(new OrchestratorStartedEvent(-1));
                            runtimeState.AddEvent(continueAsNewExecutionStarted);
                            runtimeState.Status = workItem.OrchestrationRuntimeState.Status ?? carryOverStatus;
                            carryOverStatus     = workItem.OrchestrationRuntimeState.Status;

                            if (carryOverEvents != null)
                            {
                                foreach (var historyEvent in carryOverEvents)
                                {
                                    runtimeState.AddEvent(historyEvent);
                                }
                            }

                            runtimeState.AddEvent(new OrchestratorCompletedEvent(-1));
                            workItem.OrchestrationRuntimeState = runtimeState;

                            TaskOrchestration newOrchestration = this.objectManager.GetObject(
                                runtimeState.Name,
                                continueAsNewExecutionStarted.Version);

                            workItem.Cursor = new OrchestrationExecutionCursor(
                                runtimeState,
                                newOrchestration,
                                new TaskOrchestrationExecutor(
                                    runtimeState,
                                    newOrchestration,
                                    orchestrationService.EventBehaviourForContinueAsNew),
                                latestDecisions: null);

                            if (workItem.LockedUntilUtc < DateTime.UtcNow.AddMinutes(1))
                            {
                                await orchestrationService.RenewTaskOrchestrationWorkItemLockAsync(workItem);
                            }
                        }

                        instanceState = Utils.BuildOrchestrationState(runtimeState);
                    }
                } while (continuedAsNew);
            }

            workItem.OrchestrationRuntimeState = originalOrchestrationRuntimeState;

            runtimeState.Status = runtimeState.Status ?? carryOverStatus;

            await this.orchestrationService.CompleteTaskOrchestrationWorkItemAsync(
                workItem,
                runtimeState,
                continuedAsNew?null : messagesToSend,
                orchestratorMessages,
                continuedAsNew?null : timerMessages,
                continuedAsNewMessage,
                instanceState);

            workItem.OrchestrationRuntimeState = runtimeState;

            return(isCompleted || continuedAsNew || isInterrupted);
        }
示例#28
0
        async Task OnProcessWorkItemSessionAsync(TaskOrchestrationWorkItem workItem)
        {
            if (workItem.Session == null)
            {
                // Legacy behavior
                await OnProcessWorkItemAsync(workItem);

                return;
            }

            var isExtendedSession = false;
            var processCount      = 0;

            try
            {
                while (true)
                {
                    // If the provider provided work items, execute them.
                    if (workItem.NewMessages?.Count > 0)
                    {
                        bool isCompletedOrInterrupted = await OnProcessWorkItemAsync(workItem);

                        if (isCompletedOrInterrupted)
                        {
                            break;
                        }

                        processCount++;
                    }

                    // Fetches beyond the first require getting an extended session lock, used to prevent starvation.
                    if (processCount > 0 && !isExtendedSession)
                    {
                        isExtendedSession = this.concurrentSessionLock.Acquire();
                        if (!isExtendedSession)
                        {
                            TraceHelper.Trace(TraceEventType.Verbose, "OnProcessWorkItemSession-MaxOperations", "Failed to acquire concurrent session lock.");
                            break;
                        }
                    }

                    TraceHelper.Trace(TraceEventType.Verbose, "OnProcessWorkItemSession-StartFetch", "Starting fetch of existing session.");
                    Stopwatch timer = Stopwatch.StartNew();

                    // Wait for new messages to arrive for the session. This call is expected to block (asynchronously)
                    // until either new messages are available or until a provider-specific timeout has expired.
                    workItem.NewMessages = await workItem.Session.FetchNewOrchestrationMessagesAsync(workItem);

                    if (workItem.NewMessages == null)
                    {
                        break;
                    }

                    TraceHelper.Trace(
                        TraceEventType.Verbose,
                        "OnProcessWorkItemSession-EndFetch",
                        $"Fetched {workItem.NewMessages.Count} new message(s) after {timer.ElapsedMilliseconds} ms from existing session.");
                    workItem.OrchestrationRuntimeState.NewEvents.Clear();
                }
            }
            finally
            {
                if (isExtendedSession)
                {
                    TraceHelper.Trace(
                        TraceEventType.Verbose,
                        "OnProcessWorkItemSession-Release",
                        $"Releasing extended session after {processCount} batch(es).");
                    this.concurrentSessionLock.Release();
                }
            }
        }
 private void OnApplicationFocus(bool focus)
 {
     TraceHelper.LogDiff("OnApplicationFocus: " + focus, TraceCacheGrouping.LifeCycle);
 }
 private void OnApplicationPause(bool pause)
 {
     TraceHelper.LogDiff("OnApplicationPause: " + pause, TraceCacheGrouping.LifeCycle);
 }