Beispiel #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ResourcePreparationTaskAndValidity"/> struct.
 /// </summary>
 internal ResourcePreparationTaskAndValidity(Task preparationTask, ResourceState finalState)
     : this()
 {
     Requires.NotNull(preparationTask, nameof(preparationTask));
     this.PreparationTask = preparationTask;
     this.State           = finalState;
 }
        /// <summary>
        ///     Wait for a resource to reach the specified state.
        /// </summary>
        /// <typeparam name="TResource">
        ///     The resource type.
        /// </typeparam>
        /// <param name="resourceId">
        ///     The resource Id.
        /// </param>
        /// <param name="targetState">
        ///     The resource state to wait for.
        /// </param>
        /// <param name="timeout">
        ///     The amount of time to wait for the resource to reach the target state.
        /// </param>
        /// <param name="cancellationToken">
        ///     An optional cancellation token that can be used to cancel the request.
        /// </param>
        /// <returns>
        ///     The resource (or <c>null</c> if the resource has been deleted).
        /// </returns>
        /// <exception cref="TimeoutException">
        ///     The timeout period elapsed before the resource reached the target state.
        /// </exception>
        /// <exception cref="CloudControlException">
        ///     The target resource was not found with the specified Id, and <paramref name="targetState"/> is not <see cref="ResourceState.Deleted"/>
        /// </exception>
        public async Task <TResource> WaitForState <TResource>(Guid resourceId, ResourceState targetState, TimeSpan timeout, CancellationToken cancellationToken = default(CancellationToken))
            where TResource : Resource
        {
            Stopwatch stopwatch = Stopwatch.StartNew();

            Func <Guid, CancellationToken, Task <Resource> > loader = CreateResourceLoader <TResource>();
            Resource resource = await loader(resourceId, cancellationToken);

            while (resource != null && resource.State != targetState)
            {
                if (stopwatch.Elapsed > timeout)
                {
                    throw new TimeoutException($"Timed out after waiting {timeout.TotalSeconds} seconds for {typeof(TResource).Name} '{resourceId}' to reach state '{targetState}'.");
                }

                resource = await loader(resourceId, cancellationToken);
            }

            if (resource == null && targetState != ResourceState.Deleted)
            {
                throw new CloudControlException($"{typeof(TResource).Name} not found with Id '{resourceId}'.");
            }

            return((TResource)resource);
        }
Beispiel #3
0
 public Signal(string name) : base(name, ResourceType.Signal)
 {
     Name           = name;
     ResouceType    = ResourceType.Signal;
     ResourceStates = new ResourceState();
     ResourceStates.SetState("SensorIsSet", false);
 }
Beispiel #4
0
        /// <summary>
        /// Returns true if MetaClub instances are equal
        /// </summary>
        /// <param name="other">Instance of MetaClub to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(MetaClub other)
        {
            if (ReferenceEquals(null, other))
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Id == other.Id ||
                     Id != null &&
                     Id.Equals(other.Id)
                     ) &&
                 (
                     ResourceState == other.ResourceState ||
                     ResourceState != null &&
                     ResourceState.Equals(other.ResourceState)
                 ) &&
                 (
                     Name == other.Name ||
                     Name != null &&
                     Name.Equals(other.Name)
                 ));
        }
Beispiel #5
0
        private void btnSend_Click(object sender, EventArgs e)
        {
            CFXEnvelope msg;

            if (currentState == ResourceState.Off)
            {
                msg = new CFXEnvelope(new StationStateChanged()
                {
                    NewState         = ResourceState.On,
                    OldState         = currentState,
                    OldStateDuration = DateTime.Now - lastStateChange,
                });
            }
            else
            {
                msg = new CFXEnvelope(new StationStateChanged()
                {
                    NewState         = ResourceState.Off,
                    OldState         = currentState,
                    OldStateDuration = DateTime.Now - lastStateChange,
                });
            }

            lastStateChange = msg.TimeStamp;
            currentState    = (msg.MessageBody as StationStateChanged).NewState;

            theEndpoint.Publish(msg);
        }
 public virtual void Handle(ResourceEvent @event)
 {
     try
     {
         this.writeLock.Lock();
         Path resourcePath = @event.GetLocalResourceRequest().GetPath();
         Log.Debug("Processing " + resourcePath + " of type " + @event.GetType());
         ResourceState oldState = this.stateMachine.GetCurrentState();
         ResourceState newState = null;
         try
         {
             newState = this.stateMachine.DoTransition(@event.GetType(), @event);
         }
         catch (InvalidStateTransitonException e)
         {
             Log.Warn("Can't handle this event at current state", e);
         }
         if (oldState != newState)
         {
             Log.Info("Resource " + resourcePath + (localPath != null ? "(->" + localPath + ")"
                                          : string.Empty) + " transitioned from " + oldState + " to " + newState);
         }
     }
     finally
     {
         this.writeLock.Unlock();
     }
 }
 /// <summary>
 /// Gets the hash code
 /// </summary>
 /// <returns>Hash code</returns>
 public override int GetHashCode()
 {
     unchecked // Overflow is fine, just wrap
     {
         var hashCode = 41;
         // Suitable nullity checks etc, of course :)
         if (Id != null)
         {
             hashCode = hashCode * 59 + Id.GetHashCode();
         }
         if (ResourceState != null)
         {
             hashCode = hashCode * 59 + ResourceState.GetHashCode();
         }
         if (Primary != null)
         {
             hashCode = hashCode * 59 + Primary.GetHashCode();
         }
         if (Name != null)
         {
             hashCode = hashCode * 59 + Name.GetHashCode();
         }
         if (Distance != null)
         {
             hashCode = hashCode * 59 + Distance.GetHashCode();
         }
         return(hashCode);
     }
 }
Beispiel #8
0
        public async Task <IActionResult> Post(string groupId, string resourceId, string actionname, uint?duration = null)
        {
            ScampResource res = await _resourceRepository.GetResource(resourceId);

            if (res == null)
            {
                return(new HttpStatusCodeResult(404)); // not found
            }
            ResourceAction action   = WebJobController.GetAction(actionname);
            ResourceState  newState = ResourceState.Unknown;

            switch (action)
            {
            case ResourceAction.Start:
                newState = ResourceState.Starting;
                break;

            case ResourceAction.Stop:
                newState = ResourceState.Stopping;
                break;
            }

            if (await CanManageResource(res, action))
            {
                await _volatileStorageController.UpdateResourceState(resourceId, newState);

                _webJobController.SubmitActionInQueue(resourceId, action, duration);
            }

            return(new HttpStatusCodeResult(204));
        }
Beispiel #9
0
        /// <summary>
        /// Determines if a given <see cref="ResourceState"/> is invalid, which means it contains both write and read states, or multiple write states
        /// </summary>
        public static bool IsInvalid(this ResourceState flags)
        {
            int numWriteFlags = BitOperations.PopCount((uint)(flags & ResourceState.AllWritableFlags));

            // you can only have 1 or 0 write flags
            // you can have multiple read flags, but only if there are no write flags
            return(numWriteFlags > 1 || (numWriteFlags == 1 && flags.HasReadOnlyFlags()));
        }
Beispiel #10
0
 /// <summary>
 /// Attempts to add another <see cref="ResourceState"/> to the barrier
 /// </summary>
 /// <param name="add">The <see cref="ResourceState"/> to try and add</param>
 /// <returns><see langword="true"/> if it succeeded, else <see langword="false"/></returns>
 public bool TryAddState(ResourceState add)
 {
     if (add.IsReadOnly() && ((ResourceState)Barrier.Anonymous.Transition.StateAfter).IsReadOnly())
     {
         Barrier.Anonymous.Transition.StateAfter |= (D3D12_RESOURCE_STATES)add;
         return(true);
     }
     return(false);
 }
Beispiel #11
0
    void InitializeResources()
    {
        ResourceState rs = FindObjectOfType <ResourceState>();

        _wood    = rs.nWood;
        _iron    = rs.nIron;
        _food    = rs.nFood;
        _weapons = rs.nWeapons;
    }
Beispiel #12
0
        public async Task Load(TIn input)
        {
            _state.Value = ResourceState.FromLoading(true);

            try {
                _state.Value = ResourceState.FromData(await _execute(input));
            } catch (Exception ex) {
                _state.Value = ResourceState.FromException(ex);
            }
        }
Beispiel #13
0
        public ThemeSwitcher(string assemblyDir = null)
        {
            var reader    = new CacheableResourceReader <Theme>();
            var rootDir   = assemblyDir ?? Directory.GetParent(Assembly.GetCallingAssembly().Location).ToString();
            var themeDir  = Path.Combine(rootDir, "Themes");
            var resources = new ResourceDirectory <Theme>(new ThemeKeyValueGenerator(), themeDir, "*.xaml");

            _finder = new ResourceFinder <Theme>(resources);
            _state  = new ResourceState <Theme>(new ResourceUpdater <Theme>(reader, Application.Current.Resources.MergedDictionaries));
        }
 public ResourceButtonViewModel(ResourceScreenItem model, ResourceScreen screen,
                                ICommand actionCommand, bool isTicketSelected, bool userPermittedToMerge, ResourceState state)
 {
     _actionCommand        = actionCommand;
     _screen               = screen;
     _isTicketSelected     = isTicketSelected;
     _userPermittedToMerge = userPermittedToMerge;
     AccountState          = state;
     Model = model;
 }
Beispiel #15
0
        public Localizer(string assemblyDir = null)
        {
            var reader    = new ResourceReader <Language>();
            var rootDir   = assemblyDir ?? Directory.GetParent(Assembly.GetCallingAssembly().Location).ToString();
            var dirPath   = Path.Combine(rootDir, "Languages");
            var resources = new ResourceDirectory <Language>(new LanguageKeyValueGenerator(), dirPath, "*.xaml");

            _finder = new ResourceFinder <Language>(resources);
            _state  = new ResourceState <Language>(new ResourceUpdater <Language>(reader, Application.Current.Resources.MergedDictionaries));
        }
Beispiel #16
0
        /// <summary>
        /// checks if the finished conditions are not already fulfilled
        /// </summary>
        /// <returns></returns>
        public bool NeedsToExecute()
        {
            // it needs to excecute if there are no finish conditions
            if (FinishConditions == null)
            {
                return(true);
            }

            // evaluate every finishcondition (return true if the evaluation is false)
            return(!ResourceState.Evaluate(FinishConditions));
        }
Beispiel #17
0
        public void MarkPersistent(string item)
        {
            ResourceState state;

            if (!_itemCounts.TryGetValue(item, out state))
            {
                state             = new ResourceState();
                _itemCounts[item] = state;
            }
            state.Persist = true;
        }
Beispiel #18
0
 public Resource(Guid id, Guid?containerId, Guid?storageId, Guid?traderId, Type type, ResourceSubtype subtype, ResourceState state, Vector3D position, QuaternionD rotation)
 {
     Id          = id;
     ContainerId = containerId;
     StorageId   = storageId;
     TraderId    = traderId;
     Type        = type ?? throw new ArgumentNullException(nameof(type));
     Subtype     = subtype;
     State       = state;
     Position    = position;
     Rotation    = rotation;
 }
Beispiel #19
0
 void Awake()
 {
     // Singleton code
     if (instance == null)
     {
         instance = this;
     }
     else if (instance != this)
     {
         Destroy(gameObject);
     }
 }
Beispiel #20
0
 public void SetResourceState(ResourceState newResState)
 {
     if (null != newResState)
     {
         newResState.AddRef();
     }
     if (null != resState)
     {
         resState.SubRef();
     }
     resState = newResState;
 }
    private void Start()
    {
        PreviousResources = ResourceState.High;

        providers   = new ResourceContainer();
        OnResource += OnProviderResource;
        if (GetComponent <TimeUpdate>() is TimeUpdate timer)
        {
            timer.OnTick += OnTick;
        }
        ;
    }
Beispiel #22
0
        public void Collect(string item)
        {
            ResourceState state;

            if (!_itemCounts.TryGetValue(item, out state))
            {
                state             = new ResourceState();
                _itemCounts[item] = state;
            }
            state.Count++;
            OnResourceChange.Invoke(item, state.Count);
        }
Beispiel #23
0
        private bool NextActivityIsEqual(ResourceState resourceState, string activityKey)
        {
            var nextActivity = resourceState.ActivityQueue.Peek();

            if (nextActivity == null)
            {
                Agent.DebugMessage($"No next activity for {resourceState.ResourceDefinition.Name} in resource activity queue");
                return(false);
            }
            Agent.DebugMessage($"Next activity is {nextActivity.GetKey} but should be {activityKey} ");
            return(nextActivity.GetKey == activityKey);
        }
Beispiel #24
0
        public static string GetLocalizedText(this ResourceState <Language> state, string key)
        {
            var translatedText = Application.Current.TryFindResource(key);

            if (translatedText is string)
            {
                return(translatedText as string);
            }
            else
            {
                return("Laguage files may be broken. Please reinstall.");
            }
        }
Beispiel #25
0
        public bool SetResourceDetails(string ResourceUrl, ResourceState resourceState)
        {
            ResourceDetails resourceDetails = this.dictRegisteredResources.Values.
                                              Where(resource => resource.ResourceUrl.Equals(ResourceUrl)).
                                              FirstOrDefault();

            if (resourceDetails != null)
            {
                resourceDetails.State = resourceState;
                return(true);
            }
            return(false);
        }
Beispiel #26
0
        /// <summary>
        /// Converts a semi state code to its E10 equivalent.
        /// </summary>
        /// <param name="state"></param>
        /// <returns></returns>
        public static ResourceState GetSemiE58State(ResourceState state)
        {
            ResourceState result = ResourceState.NST;
            int           code   = ((int)state / 100) * 100;

            result = (ResourceState)code;
            if (!System.Enum.IsDefined(typeof(ResourceState), result))
            {
                result = ResourceState.NST;
            }

            return(result);
        }
Beispiel #27
0
        public static ResourceStates ToResourceStates(this ResourceState value)
        {
            switch (value)
            {
            case ResourceState.RenderTarget:
                return(ResourceStates.RenderTarget);

            case ResourceState.Present:
                return(ResourceStates.Present);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
    public static D3D12_RESOURCE_STATES GetD3D12ResourceStates(ResourceState resourceState)
    {
        if (resourceState == ResourceState.ReadOnly)
        {
            return(D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE);
        }

        if (resourceState == ResourceState.ReadWrite)
        {
            return(D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
        }

        return(ThrowHelper.ThrowArgumentException <D3D12_RESOURCE_STATES>("The target resource state is not valid."));
    }
Beispiel #29
0
        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            if (!theEndpoint.IsOpen)
            {
                return;
            }

            List <CFXEnvelope> messages = new List <CFXEnvelope>();

            //WorkStarted ws = new WorkStarted();
            //ws.TransactionID = Guid.NewGuid();
            //ws.Lane = "Lane1";
            //ws.Units.Add(new UnitPosition() { UnitIdentifier = "11122456", PositionNumber = 1, PositionName = "1" });
            //messages.Add(CFXEnvelope.FromCFXMessage(ws));

            //WorkCompleted wc = new WorkCompleted();
            //wc.TransactionID = ws.TransactionID;
            //wc.Result = WorkResult.Failed;
            //messages.Add(CFXEnvelope.FromCFXMessage(wc));

            ResourceState[] states = new ResourceState []
            {
                ResourceState.SDT_Setup,
                ResourceState.PRD_RegularWork,
                ResourceState.SBY_NoProduct
            };

            ResourceState newState = lastState;
            Random        r        = new Random();

            while (newState == lastState)
            {
                newState = states[r.Next(0, 2)];
            }

            CFXEnvelope env = new CFXEnvelope(new StationStateChanged()
            {
                NewState         = newState,
                OldState         = lastState,
                OldStateDuration = DateTime.Now - lastStateChange
            });

            messages.Add(env);

            lastState       = (env.MessageBody as StationStateChanged).NewState;
            lastStateChange = DateTime.Now;

            //theEndpoint.Publish(ws);
            theEndpoint.PublishMany(messages);
        }
Beispiel #30
0
    void SaveResourceState()
    {
        ResourceState rs = FindObjectOfType <ResourceState>();

        if (!rs)
        {
            return;
        }

        rs.nWood    = _wood;
        rs.nIron    = _iron;
        rs.nFood    = _food;
        rs.nWeapons = _weapons;
    }
Beispiel #31
0
        internal IEnumerator Load()
        {
            state = ResourceState.Downloading;
            www = new WWW(url);
            yield return www;
            if (Disposed)
                yield break;

            state = ResourceState.Downloaded;
            yield return AfterLoad();
        }
        public async Task<DomainClientForAdmin> SetStateAsync(string id, ResourceState state)
        {
            // Update company
            CompanyEntity company = await _companyRepository.GetAsync(id);
            if (company == null)
            {
                throw new NotFoundException();
            }

            company.State = (int)state;
            await _companyRepository.UpdateAsync(company);

            // Update users
            await Task.WhenAll(company.Users.Select(async p =>
            {
                UserEntity user = await _userRepository.GetAsync(p);
                user.State = (int)state;
                await _userRepository.UpdateAsync(user);
            }));

            return await GetClientDataAsync(company);
        }
        public async Task UpdateResourceState(string resourceId, ResourceState state)
        {
            // get current resource state
            CurrentResourceState updatedState = await this.GetResourceState(resourceId);
            if (updatedState == null)
                updatedState = new CurrentResourceState(resourceId);

            // update with new state
            updatedState.State = state;

            // save update
            await UpdateResourceState(updatedState);
        }
Beispiel #34
0
        internal IEnumerator AfterLoad()
        {
            // 从Preload处恢复的时候,Preload很可能还没有加载完
            while (!www.isDone)
            {
                if (Disposed)
                    yield break;
                yield return null;
            }

            string error = www.error;
            byte[] rawData = www.bytes;
            www.Dispose();
            www = null;

            if (string.IsNullOrEmpty(error))
            {
                yield return OnDownloaded(rawData);
            }
            else
            {
                loadFailed = true;
                Log.Error("资源加载错误! Url:", url, "\nType:", GetType(), "\nError:", error);
                state = ResourceState.Complete;
                NotifyComplete();
            }
        }
Beispiel #35
0
        internal void CopyFrom(PreloadResource preloaded)
        {
            this.url = preloaded.url;
            this.state = preloaded.state;
            this.loadFailed = preloaded.loadFailed;

             // 把preload的www的所有权转移给自己
            this.www = preloaded.www;
            preloaded.www = null;
        }
Beispiel #36
0
        internal IEnumerator OnDownloaded(byte[] rawData)
        {
            this.rawData = rawData;

            // not implement
            // unpack here

            yield return OnPrepareData();
            if (Disposed)
                yield break;

            state = ResourceState.Complete;
            NotifyComplete();
        }
Beispiel #37
0
        protected override void OnDispose()
        {
            OnLoadComplete = null;

            if (www != null)
            {
                www.Dispose();
                www = null;
            }

            manager.RemoveResource(this);
            manager = null;
            state = ResourceState.Disposed;

            base.OnDispose();
        }
Beispiel #38
0
    /// <summary>
    /// Attempts to harvest the resource type associated with this world resource for the amount specified and drops 
    /// it into the resource container "resource"
    /// </summary>
    /// <param name="resource">The resource container</param>
    /// <param name="amount">The amount of that resource to move</param>
    private void HarvestResource(Resource resource, int amount)
    {
        if (ResourceState == global::ResourceState.Active)
        {
            if (!isInfinite)
                currentAmount = Mathf.Clamp( (currentAmount - amount) + resource.AddResource(this.resource, amount), 0, maxAmount);
            else
                resource.AddResource(this.resource, amount);

            if (currentAmount == 0 && !isInfinite)
                ResourceState = global::ResourceState.Dying;
            if (!isInfinite && !regenerates && currentAmount == 0)
            {
                ResourceState = global::ResourceState.Dying;
            }
        }
    }