Beispiel #1
0
        private void Deactivate(bool storeUnloadData)
        {
            if (!IsActivated)
            {
                return;
            }

            m_Diagnostics.Log(
                LevelToLog.Trace,
                HostConstants.LogPrefix,
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.DatasetProxy_LogMessage_DeactivatingDataset_WithId,
                    Id));

            m_Connection.OnSwitchToEditMode      -= HandleOnSwitchToEditMode;
            m_Connection.OnSwitchToExecutingMode -= HandleOnSwitchToExecutingMode;

            m_Connection.Close();
            m_Connection = null;
            m_DataProxy  = null;

            if (storeUnloadData)
            {
                m_DistributionLocation.Current = null;
            }

            RaiseOnDeactivated();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DatasetStorageProxy"/> class.
        /// </summary>
        /// <param name="connection">The object that stores the information used to connect with the actual dataset application.</param>
        /// <param name="selector">The object that handles the selection of part groups for the current dataset.</param>
        /// <param name="compositionLayer">The object that stores the composition of the part groups and parts in the dataset.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="connection"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="compositionLayer"/> is <see langword="null" />.
        /// </exception>
        public DatasetStorageProxy(
            DatasetOnlineInformation connection,
            GroupSelector selector,
            IProxyCompositionLayer compositionLayer)
        {
            {
                Lokad.Enforce.Argument(() => connection);
                Lokad.Enforce.Argument(() => selector);
                Lokad.Enforce.Argument(() => compositionLayer);
            }

            m_Selector = selector;
            m_CompositionLayer = compositionLayer;
            m_Connection = connection;
            m_Connection.OnTimelineUpdate +=
                (s, e) =>
                {
                    m_CompositionLayer.ReloadFromDataset();
                };
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DatasetStorageProxy"/> class.
        /// </summary>
        /// <param name="connection">The object that stores the information used to connect with the actual dataset application.</param>
        /// <param name="selector">The object that handles the selection of part groups for the current dataset.</param>
        /// <param name="compositionLayer">The object that stores the composition of the part groups and parts in the dataset.</param>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="connection"/> is <see langword="null" />.
        /// </exception>
        /// <exception cref="ArgumentNullException">
        ///     Thrown if <paramref name="compositionLayer"/> is <see langword="null" />.
        /// </exception>
        public DatasetStorageProxy(
            DatasetOnlineInformation connection,
            GroupSelector selector,
            IProxyCompositionLayer compositionLayer)
        {
            {
                Lokad.Enforce.Argument(() => connection);
                Lokad.Enforce.Argument(() => selector);
                Lokad.Enforce.Argument(() => compositionLayer);
            }

            m_Selector                     = selector;
            m_CompositionLayer             = compositionLayer;
            m_Connection                   = connection;
            m_Connection.OnTimelineUpdate +=
                (s, e) =>
            {
                m_CompositionLayer.ReloadFromDataset();
            };
        }
Beispiel #4
0
        private Task Activate(
            DistributionLocations preferredLocation,
            Func <IEnumerable <DistributionSuggestion>, SelectedProposal> machineSelector,
            ICollectNotifications notifications,
            CancellationToken token,
            bool storeLocation)
        {
            {
                Debug.Assert(!Owner.IsClosed, "The owner should not be closed.");
                Debug.Assert(preferredLocation != DistributionLocations.None, "A distribution location should be specified.");
            }

            if (IsActivated)
            {
                return(Task.Factory.StartNew(
                           () => { },
                           token,
                           TaskCreationOptions.None,
                           new CurrentThreadTaskScheduler()));
            }

            if (m_IsActivating)
            {
                var onActivated = Observable.FromEventPattern <EventArgs>(
                    h => OnActivated += h,
                    h => OnActivated -= h)
                                  .Take(1);
                var onDeactivated = Observable.FromEventPattern <EventArgs>(
                    h => OnDeactivated += h,
                    h => OnDeactivated -= h)
                                    .Take(1);

                return(Observable.Amb(onActivated, onDeactivated)
                       .ToTask(token));
            }

            m_Diagnostics.Log(
                LevelToLog.Trace,
                HostConstants.LogPrefix,
                string.Format(
                    CultureInfo.InvariantCulture,
                    Resources.DatasetProxy_LogMessage_ActivatingDataset_WithId,
                    Id));

            m_IsActivating = true;
            try
            {
                var request = new DatasetActivationRequest
                {
                    DatasetToActivate      = this,
                    PreferredLocations     = preferredLocation,
                    ExpectedLoadPerMachine = new ExpectedDatasetLoad
                    {
                        OnDiskSizeInBytes   = StoredAt.StoredSizeInBytes(),
                        InMemorySizeInBytes = StoredAt.StoredSizeInBytes(),
                        RelativeMemoryExpansionWhileRunning = 2.0,
                        RelativeOnDiskExpansionAfterRunning = 2.0,
                    },
                };

                var suggestedPlans = m_ConstructorArgs.DistributionPlanGenerator(request, token);
                var selection      = suggestedPlans.Select(plan => new DistributionSuggestion(plan));
                var selectedPlan   = machineSelector(selection);
                if (token.IsCancellationRequested || selectedPlan.WasSelectionCanceled)
                {
                    return(Task.Factory.StartNew(
                               () => { },
                               token,
                               TaskCreationOptions.None,
                               new CurrentThreadTaskScheduler()));
                }

                RaiseOnProgressOfCurrentAction(0, Resources.Progress_ActivatingDataset, false);
                var task             = selectedPlan.Plan.Accept(token, RaiseOnProgressOfCurrentAction);
                var continuationTask = task.ContinueWith(
                    t =>
                {
                    try
                    {
                        if (t.Exception != null)
                        {
                            m_Diagnostics.Log(
                                LevelToLog.Error,
                                HostConstants.LogPrefix,
                                string.Format(
                                    CultureInfo.InvariantCulture,
                                    Resources.DatasetProxy_LogMessage_FailedToActivateDataset_WithException,
                                    Id,
                                    t.Exception));

                            // Obviously not activated so ...
                            RaiseOnProgressOfCurrentAction(100, string.Empty, false);
                            RaiseOnDeactivated();

                            notifications.StoreNotification(Resources.Notifications_FailedToActivateDataset);
                            return;
                        }

                        var online   = t.Result;
                        m_Connection = online;
                        m_Connection.OnSwitchToEditMode      += HandleOnSwitchToEditMode;
                        m_Connection.OnSwitchToExecutingMode += HandleOnSwitchToExecutingMode;

                        m_DataProxy = m_ProxyBuilder(m_Connection);

                        if (storeLocation)
                        {
                            m_DistributionLocation.Current = selectedPlan.Plan.MachineToDistributeTo;
                        }

                        m_Diagnostics.Log(
                            LevelToLog.Trace,
                            HostConstants.LogPrefix,
                            string.Format(
                                CultureInfo.InvariantCulture,
                                Resources.DatasetProxy_LogMessage_DatasetActivationComplete_WithId,
                                Id));

                        RaiseOnActivated();
                    }
                    finally
                    {
                        m_IsActivating = false;
                    }
                },
                    TaskContinuationOptions.ExecuteSynchronously);

                return(continuationTask);
            }
            catch (Exception)
            {
                // Only clean this up if the whole thing falls over
                m_IsActivating = false;
                throw;
            }
        }
        public void Notification()
        {
            var commandHub = new Mock<ISendCommandsToRemoteEndpoints>();
            var id = new DatasetId();
            var endpoint = EndpointIdExtensions.CreateEndpointIdForCurrentProcess();
            var networkId = NetworkIdentifier.ForLocalMachine();
            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);

            var notificationList = new SortedList<Type, INotificationSet>
                {
                    {
                        typeof(IMockNotificationSetWithTypedEventHandler),
                        new Mock<IMockNotificationSetWithTypedEventHandler>().Object
                    },
                };

            var datasetNotifications = new Mock<IDatasetApplicationNotifications>();
            var notificationHub = new Mock<INotifyOfRemoteEndpointEvents>();
            {
                notificationHub.Setup(
                        h => h.NotificationsFor<IMockNotificationSetWithTypedEventHandler>(It.IsAny<EndpointId>()))
                    .Returns((IMockNotificationSetWithTypedEventHandler)notificationList.Values[0]);
                notificationHub.Setup(n => n.NotificationsFor<IDatasetApplicationNotifications>(It.IsAny<EndpointId>()))
                    .Callback<EndpointId>(e => Assert.AreSame(endpoint, e))
                    .Returns(datasetNotifications.Object);
            }

            var info = new DatasetOnlineInformation(
                id,
                endpoint,
                networkId,
                commandHub.Object,
                notificationHub.Object,
                systemDiagnostics);
            var notifications = info.Notification<IMockNotificationSetWithTypedEventHandler>();
            Assert.AreSame(notificationList.Values[0], notifications);
        }
        public void Create()
        {
            var commandHub = new Mock<ISendCommandsToRemoteEndpoints>();
            var id = new DatasetId();
            var endpoint = EndpointIdExtensions.CreateEndpointIdForCurrentProcess();
            var networkId = NetworkIdentifier.ForLocalMachine();
            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);

            var notifications = new Mock<IDatasetApplicationNotifications>();
            var notificationHub = new Mock<INotifyOfRemoteEndpointEvents>();
            {
                notificationHub.Setup(n => n.HasNotificationsFor(It.IsAny<EndpointId>()))
                    .Returns(true);
                notificationHub.Setup(n => n.NotificationsFor<IDatasetApplicationNotifications>(It.IsAny<EndpointId>()))
                    .Callback<EndpointId>(e => Assert.AreSame(endpoint, e))
                    .Returns(notifications.Object);
            }

            var info = new DatasetOnlineInformation(
                id,
                endpoint,
                networkId,
                commandHub.Object,
                notificationHub.Object,
                systemDiagnostics);
            Assert.AreSame(id, info.Id);
            Assert.AreSame(endpoint, info.Endpoint);
            Assert.AreSame(networkId, info.RunsOn);
        }
        public void Close()
        {
            var id = new DatasetId();
            var endpoint = EndpointIdExtensions.CreateEndpointIdForCurrentProcess();
            var networkId = NetworkIdentifier.ForLocalMachine();
            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);

            var datasetCommands = new Mock<IDatasetApplicationCommands>();
            {
                datasetCommands.Setup(d => d.Close())
                    .Returns(
                        Task.Factory.StartNew(
                            () => { },
                            new CancellationToken(),
                            TaskCreationOptions.None,
                            new CurrentThreadTaskScheduler()))
                    .Verifiable();
            }

            var commandHub = new Mock<ISendCommandsToRemoteEndpoints>();
            {
                commandHub.Setup(h => h.HasCommandFor(It.IsAny<EndpointId>(), It.IsAny<Type>()))
                    .Returns(true);
                commandHub.Setup(h => h.CommandsFor<IDatasetApplicationCommands>(It.IsAny<EndpointId>()))
                    .Returns(datasetCommands.Object);
            }

            var notifications = new Mock<IDatasetApplicationNotifications>();
            var notificationHub = new Mock<INotifyOfRemoteEndpointEvents>();
            {
                notificationHub.Setup(n => n.HasNotificationsFor(It.IsAny<EndpointId>()))
                    .Returns(true);
                notificationHub.Setup(n => n.NotificationsFor<IDatasetApplicationNotifications>(It.IsAny<EndpointId>()))
                    .Callback<EndpointId>(e => Assert.AreSame(endpoint, e))
                    .Returns(notifications.Object);
            }

            var info = new DatasetOnlineInformation(
                id,
                endpoint,
                networkId,
                commandHub.Object,
                notificationHub.Object,
                systemDiagnostics);
            info.Close();

            datasetCommands.Verify(d => d.Close(), Times.Once());
        }
        public void AvailableNotifications()
        {
            var commandHub = new Mock<ISendCommandsToRemoteEndpoints>();
            var id = new DatasetId();
            var endpoint = EndpointIdExtensions.CreateEndpointIdForCurrentProcess();
            var networkId = NetworkIdentifier.ForLocalMachine();
            var systemDiagnostics = new SystemDiagnostics((p, s) => { }, null);

            var notificationList = new Dictionary<Type, INotificationSet>
                {
                    {
                        typeof(IMockNotificationSetWithEventHandler),
                        new Mock<IMockNotificationSetWithEventHandler>().Object
                    },
                    {
                        typeof(IMockNotificationSetWithTypedEventHandler),
                        new Mock<IMockNotificationSetWithTypedEventHandler>().Object
                    },
                    {
                        typeof(IMockNotificationSetForInternalUse),
                        new Mock<IMockNotificationSetForInternalUse>().Object
                    },
                };

            var datasetNotifications = new Mock<IDatasetApplicationNotifications>();
            var notificationHub = new Mock<INotifyOfRemoteEndpointEvents>();
            {
                notificationHub.Setup(h => h.AvailableNotificationsFor(It.IsAny<EndpointId>()))
                    .Returns(notificationList.Keys);
                notificationHub.Setup(h => h.NotificationsFor(It.IsAny<EndpointId>(), It.IsAny<Type>()))
                    .Returns<EndpointId, Type>((e, t) => notificationList[t]);
                notificationHub.Setup(n => n.NotificationsFor<IDatasetApplicationNotifications>(It.IsAny<EndpointId>()))
                    .Callback<EndpointId>(e => Assert.AreSame(endpoint, e))
                    .Returns(datasetNotifications.Object);
            }

            var info = new DatasetOnlineInformation(
                id,
                endpoint,
                networkId,
                commandHub.Object,
                notificationHub.Object,
                systemDiagnostics);
            var notifications = info.AvailableNotifications();

            Assert.AreEqual(2, notifications.Count());
        }