Ejemplo n.º 1
0
        public override void EvaluateInternal(H holder, MemberInfo groupKey)
        {
            // вычисляем переменную из котрой следует получить значения
            CalculatedVariable <H, T, I> basedVar = (CalculatedVariable <H, T, I>)DependsOn.Single();

            basedVar.Evaluate(holder, groupKey, LastMoniker);

            // для каждого периода времени вычисляем значение переменной
            foreach (var tp in Period.Periods.Select((t, i) => new TimeArg <I>(t, i, groupKey, Period.Name, this.Name)))
            {
                I        next      = Period.Periods.FirstOrDefault(p => Operator.GreaterThan(p, tp.T));
                var      subPeriod = basedVar.Period.Between(tp.T, next);
                List <T> result    = Activator.CreateInstance <List <T> >();
                Int32    c         = 0;
                foreach (I s in subPeriod)
                {
                    var ta = new TimeArg <I>(s, c++, groupKey, basedVar.Period.Name, basedVar.Name);
                    result.Add((T)basedVar.Results[ta]);
                }

                Results.Add(tp, result);
                // если требуется вернуть значение переменной, то записываем результат в свойство
                // holder, это свойство будет содержить список значений всех переменных на момент времени t
                if (Readers.Any())
                {
                    ApplyValueForHolder(holder, tp);
                    ExecuteAllReaders(tp);
                }
            }
        }
Ejemplo n.º 2
0
 /// <summary>
 /// This finally will always run on the same thread as the last task that runs
 /// </summary>
 public ITask Finally(Action handler)
 {
     Guard.ArgumentNotNull(handler, "handler");
     finallyHandler += handler;
     DependsOn?.Finally(handler);
     return(this);
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Catch runs right when the exception happens (on the same thread)
 /// Chain will be cancelled
 /// </summary>
 public ITask Catch(Action <Exception> handler)
 {
     Guard.ArgumentNotNull(handler, "handler");
     faultHandler += e => { handler(e); return(false); };
     DependsOn?.Catch(handler);
     return(this);
 }
        public override void EvaluateInternal(H holder, MemberInfo groupKey)
        {
            // вычисляем переменную из котрой следует получить значения
            CalculatedVariable <H, T, I> basedVar = (CalculatedVariable <H, T, I>)DependsOn.Single();

            // check basedVar.Period == this.Period; (они должны совпадать)
            basedVar.Evaluate(holder, groupKey, LastMoniker);

            var periods = Period.Periods.Select((t, i) => new TimeArg <I>(t, i, groupKey, Period.Name, this.Name));

            if (Shift >= 0)
            {
                ShiftData(basedVar, periods, Shift);
            }
            else
            {
                var p2 = Period.Periods.Reverse().Select((t, i) => new TimeArg <I>(t, i, groupKey, Period.Name, this.Name));
                ShiftData(basedVar, p2, -Shift);
            }

            foreach (var tp in periods)
            {
                if (Readers.Any())
                {
                    ApplyValueForHolder(holder, tp);
                    ExecuteAllReaders(tp);
                }
            }
        }
Ejemplo n.º 5
0
        public override void EvaluateInternal(H holder, MemberInfo groupKey)
        {
            // вычисляем переменную из котрой следует получить значения
            CalculatedVariable <H, T, I> basedVar = (CalculatedVariable <H, T, I>)DependsOn.Single();

            // вычислять не требуется, т.к. переменная должна быть уже вычислена в более глубокой группе

            // для каждого периода времени вычисляем значение переменной
            foreach (var tp in Period.Periods.Select((t, i) => new TimeArg <I>(t, i, groupKey, Period.Name, this.Name)))
            {
                Dictionary <K, T> result = Activator.CreateInstance <Dictionary <K, T> >();
                //foreach (var p in basedVar.Results.Where(pair => pair.Key.T == tp.T && pair.Key.ForMember.ParentMember == groupKey))
                foreach (var p in basedVar.Results.Where(pair => Operator.Equal(pair.Key.T, tp.T) && pair.Key.ForGroupMember.Parents.Contains(groupKey)))
                {
                    result.Add((K)p.Key.GroupKey, p.Value);
                }

                Results.Add(tp, result);
                // если требуется вернуть значение переменной, то записываем результат в свойство
                // holder, это свойство будет содержить список значений всех переменных на момент времени t
                if (Readers.Any())
                {
                    ApplyValueForHolder(holder, tp);
                    ExecuteAllReaders(tp);
                }
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Catch runs right when the exception happens (on the same threaD)
 /// Return true if you want the task to completely successfully
 /// </summary>
 public ITask Catch(Func <Exception, bool> handler)
 {
     Guard.ArgumentNotNull(handler, "handler");
     CatchInternal(handler);
     DependsOn?.Catch(handler);
     return(this);
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Function to serialize this file into an XML element.
        /// </summary>
        /// <returns>An XML element containing the serialized contents of the file object.</returns>
        internal XElement Serialize()
        {
            var result = new XElement(EditorFileNode,
                                      new XAttribute(EditorFilePathAttr, FilePath),
                                      new XAttribute(EditorFilePlugInTypeAttr, PlugInType ?? string.Empty));

            if (DependsOn.Count > 0)
            {
                // Serialize any dependencies.
                result.Add(new XElement(EditorDependenciesNodeRoot, DependsOn.Serialize()));
            }

            if (Attributes.Count == 0)
            {
                return(result);
            }

            // Add custom attributes.
            var root = new XElement(EditorFileCustomNodeRoot);

            foreach (KeyValuePair <string, string> attr in Attributes.Where(attr => !string.IsNullOrWhiteSpace(attr.Key)))
            {
                root.Add(new XElement(EditorFileCustomNode, new XAttribute(EditorCustomNameAttr, attr.Key), attr.Value));
            }

            result.Add(root);

            return(result);
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Catch runs right when the exception happens (on the same threaD)
 /// Return true if you want the task to completely successfully
 /// </summary>
 public ITask Catch(Func <Exception, bool> handler)
 {
     Guard.ArgumentNotNull(handler, "handler");
     faultHandler += handler;
     DependsOn?.Catch(handler);
     return(this);
 }
Ejemplo n.º 9
0
 internal void SetFaultHandler(TaskBase handler)
 {
     Task.ContinueWith(t => handler.Start(t), Token,
                       TaskContinuationOptions.OnlyOnFaulted,
                       TaskManager.GetScheduler(handler.Affinity));
     DependsOn?.SetFaultHandler(handler);
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of <see cref="ModuleInfo"/>.
        /// </summary>
        /// <param name="name">The module's name.</param>
        /// <param name="type">The module <see cref="Type"/>'s AssemblyQualifiedName.</param>
        /// <param name="dependsOn">The modules this instance depends on.</param>
        /// <exception cref="ArgumentNullException">An <see cref="ArgumentNullException"/> is thrown if <paramref name="dependsOn"/> is <see langword="null"/>.</exception>
        public ModuleInfo(string name, string type, params string[] dependsOn)
        {
            if (Type.GetType(type) == null)
            {
                throw new ArgumentNullException(nameof(type));
            }
            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (dependsOn == null)
            {
                throw new ArgumentNullException(nameof(dependsOn));
            }

            ModuleName = name;
            ModuleType = type;
            foreach (string dependency in dependsOn)
            {
                if (!DependsOn.Contains(dependency))
                {
                    DependsOn.Add(dependency);
                }
            }
        }
Ejemplo n.º 11
0
 /// <summary>
 /// </summary>
 /// <returns>true if any task on the chain is marked as exclusive</returns>
 public bool IsChainExclusive()
 {
     if (Affinity == TaskAffinity.Exclusive)
     {
         return(true);
     }
     return(DependsOn?.IsChainExclusive() ?? false);
 }
Ejemplo n.º 12
0
        protected override void FindDependentVariables(IEnumerable <MetaVariable <H, I> > allVariables)
        {
            visitor.DependedProperties.Clear();
            visitor.Visit(Writer.Body);

            // добавляем все переменные связанные со свойствами, упоминаемыми в Writer.Body
            DependsOn.AddRange(allVariables.Where(d => visitor.DependedProperties.Contains(d.MetaProperty)));
        }
Ejemplo n.º 13
0
 public ITask Finally <T>(T taskToContinueWith)
     where T : ITask
 {
     Guard.ArgumentNotNull(taskToContinueWith, nameof(taskToContinueWith));
     continuationOnAlways = (TaskBase)(object)taskToContinueWith;
     continuationOnAlways.SetDependsOn(this);
     DependsOn?.SetFaultHandler(continuationOnAlways);
     return(continuationOnAlways);
 }
Ejemplo n.º 14
0
 public void ToStringTest()
 {
     DependsOn.Windows(() => {
         string formatted1 = PathStringPool.Get(Path).ToString(PathStringFormatterTests.Format);
         Assert.AreEqual(Resources.PathStringToStringResult, formatted1);
         string formatted2 = PathStringPool.Get(Path).ToString("");
         Assert.AreEqual(Path, formatted2);
     });
 }
Ejemplo n.º 15
0
 /// <inheritdoc/>
 public override int GetHashCode()
 {
     unchecked
     {
         var hashCode = DependsOn?.GetHashCode() ?? 0;
         hashCode = (hashCode * 397) ^ Timeout.GetHashCode();
         hashCode = (hashCode * 397) ^ Recover.GetHashCode();
         return(hashCode);
     }
 }
Ejemplo n.º 16
0
        public void FormatTest()
        {
            DependsOn.Windows(() => {
                var path      = PathStringPool.Get(PathStringTests.Path);
                var formatter = new PathStringFormatter();

                string formatted = formatter.Format(Format, path, null);
                Assert.AreEqual(Resources.PathStringToStringResult, formatted);
            });
        }
Ejemplo n.º 17
0
 internal virtual ITask Finally <T>(T continuation)
     where T : ITask
 {
     Guard.ArgumentNotNull(continuation, "continuation");
     continuation.SetDependsOn(this);
     this.continuation       = (TaskBase)(object)continuation;
     this.continuationAlways = true;
     DependsOn?.SetFaultHandler((TaskBase)(object)continuation);
     return(continuation);
 }
 public override DscResourceDto ToResourceDto()
 {
     return(new Dto.MergedPreferenceTests.MockDto
     {
         ResourceStepName = ResourceStepName,
         DependsOn = DependsOn.Select(x => x.ToResourceDto()).ToList(),
         Ensure = Ensure,
         ResourceName = ResourceName
     });
 }
Ejemplo n.º 19
0
 internal virtual ITask Finally <T>(T taskToContinueWith)
     where T : TaskBase
 {
     Guard.ArgumentNotNull(taskToContinueWith, nameof(taskToContinueWith));
     continuation       = (TaskBase)(object)taskToContinueWith;
     continuationAlways = true;
     continuation.SetDependsOn(this);
     DependsOn?.SetFaultHandler((TaskBase)(object)continuation);
     return(continuation);
 }
Ejemplo n.º 20
0
        public override void RejectChanges()
        {
            DependsOn.RejectChanges();

            Download.RejectChanges();
            BaseFiles.RejectChanges();
            ActiveFiles.RejectChanges();
            SubMods.RejectChanges();
            base.RejectChanges();
        }
Ejemplo n.º 21
0
 public void AddDependsOn(Project p)
 {
     if (!DependsOn.Contains(p))
     {
         DependsOn.Add(p);
     }
     if (!p.IsDependencyFor.Contains(this))
     {
         p.IsDependencyFor.Add(this);
     }
 }
Ejemplo n.º 22
0
 public override DscResourceDto ToResourceDto()
 {
     return(new ChocolateySourceDto
     {
         ChocoPackageSource = ChocoPackageSource,
         Ensure = Ensure,
         ResourceStepName = ResourceStepName,
         ResourceName = ResourceName,
         DependsOn = DependsOn?.Select(x => x.ToResourceDto()).ToList()
     });
 }
        /// <summary>
        /// Throws an exception if the <see cref="BsipaManifest"/> is not valid.
        /// </summary>
        /// <param name="requiresBsipa"></param>
        /// <exception cref="ManifestValidationException"/>
        /// <exception cref="BsipaDependsOnException"/>
        public void Validate(bool requiresBsipa)
        {
            var nullProps = json.Linq.Where(n =>
                                            n.Value == null || (n.Value.ToString() == string.Empty)).Select(n => n.Key).ToArray();

            foreach (var prop in nullProps)
            {
                json.Remove(prop);
            }
            List <string> invalidProperties = new List <string>();

            if (string.IsNullOrWhiteSpace(Id))
            {
                invalidProperties.Add(nameof(Id));
            }
            if (string.IsNullOrWhiteSpace(Name))
            {
                invalidProperties.Add(nameof(Name));
            }
            if (string.IsNullOrWhiteSpace(Author))
            {
                invalidProperties.Add(nameof(Author));
            }
            if (string.IsNullOrWhiteSpace(Version))
            {
                invalidProperties.Add(nameof(Version));
            }
            if (string.IsNullOrWhiteSpace(GameVersion) && requiresBsipa)
            {
                invalidProperties.Add(nameof(GameVersion));
            }
            if (string.IsNullOrWhiteSpace(GetDescription()))
            {
                invalidProperties.Add(nameof(Description));
            }
            if (requiresBsipa && !(DependsOn?.TryGetValue("BSIPA", out _) ?? false))
            {
                throw new BsipaDependsOnException();
            }
            if (invalidProperties.Count > 0)
            {
                string message;
                if (invalidProperties.Count == 1)
                {
                    message = $"The property '{invalidProperties.First()}' cannot be empty.";
                }
                else
                {
                    message = $"The properties '{string.Join(", ", invalidProperties)}' cannot be empty.";
                }
                throw new ManifestValidationException(message, invalidProperties);
            }
        }
Ejemplo n.º 24
0
 /// <summary>
 /// This does not set a dependency between the two tasks. Instead,
 /// the Start method grabs the state of the previous task to pass on
 /// to the next task via previousSuccess and previousException
 /// </summary>
 /// <param name="handler"></param>
 internal void SetFaultHandler(TaskBase handler)
 {
     Task.ContinueWith(t =>
     {
         Token.ThrowIfCancellationRequested();
         handler.Start(t);
     },
                       Token,
                       TaskContinuationOptions.OnlyOnFaulted,
                       TaskManager.GetScheduler(handler.Affinity));
     DependsOn?.SetFaultHandler(handler);
 }
Ejemplo n.º 25
0
        public ITask Finally(Action <bool, Exception> continuation, TaskAffinity affinity = TaskAffinity.Concurrent)
        {
            Guard.ArgumentNotNull(continuation, "continuation");
            var ret = new ActionTask(Token, continuation, this, true)
            {
                Affinity = affinity, Name = "Finally"
            };

            DependsOn?.SetFaultHandler(ret);
            ret.ContinuationIsFinally = true;
            return(ret);
        }
Ejemplo n.º 26
0
        public ITask Finally(Action <bool, Exception> actionToContinueWith, TaskAffinity affinity = TaskAffinity.Concurrent)
        {
            Guard.ArgumentNotNull(actionToContinueWith, nameof(actionToContinueWith));
            var ret = Then(new ActionTask(Token, actionToContinueWith)
            {
                Affinity = affinity, Name = "Finally"
            }, true);

            DependsOn?.SetFaultHandler(ret);
            ret.ContinuationIsFinally = true;
            return(ret);
        }
Ejemplo n.º 27
0
        protected Exception GetThrownException()
        {
            if (DependsOn == null)
            {
                return(null);
            }

            if (DependsOn.Task.Status == TaskStatus.Faulted)
            {
                var exception = DependsOn.Task.Exception;
                return(exception?.InnerException ?? exception);
            }
            return(DependsOn.GetThrownException());
        }
Ejemplo n.º 28
0
        public virtual ManifestModuleInfo LoadFromExternalManifest(ExternalModuleManifest manifest, ExternalModuleManifestVersion version)
        {
            if (manifest == null)
            {
                throw new ArgumentNullException(nameof(manifest));
            }

            ModuleName = manifest.Id;
            if (version.Dependencies != null)
            {
                foreach (var dependency in version.Dependencies)
                {
                    DependsOn.Add(dependency.Id);
                }
            }

            Id              = manifest.Id;
            Version         = version.SemanticVersion;
            VersionTag      = version.VersionTag;
            PlatformVersion = version.PlatformSemanticVersion;
            ReleaseNotes    = version.ReleaseNotes;
            Ref             = version.PackageUrl;

            if (version.Dependencies != null)
            {
                Dependencies.AddRange(version.Dependencies.Select(x => new ModuleIdentity(x.Id, SemanticVersion.Parse(x.Version))));
            }
            if (version.Incompatibilities != null)
            {
                Incompatibilities.AddRange(version.Incompatibilities.Select(x => new ModuleIdentity(x.Id, SemanticVersion.Parse(x.Version))));
            }

            Title       = manifest.Title;
            Description = manifest.Description;
            Authors     = manifest.Authors;
            Owners      = manifest.Owners;
            LicenseUrl  = manifest.LicenseUrl;
            ProjectUrl  = manifest.ProjectUrl;
            IconUrl     = manifest.IconUrl;
            RequireLicenseAcceptance = manifest.RequireLicenseAcceptance;
            Copyright = manifest.Copyright;
            Tags      = manifest.Tags;
            Identity  = new ModuleIdentity(Id, Version);
            if (manifest.Groups != null)
            {
                Groups.AddRange(manifest.Groups);
            }
            return(this);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Function to clone an object.
        /// </summary>
        /// <returns>
        /// The cloned object.
        /// </returns>
        public EditorFile Clone()
        {
            var result = new EditorFile(_filePath)
            {
                DependsOn  = DependsOn.Clone(),
                PlugInType = PlugInType
            };

            foreach (KeyValuePair <string, string> attrib in Attributes)
            {
                result.Attributes[attrib.Key] = attrib.Value;
            }

            return(result);
        }
Ejemplo n.º 30
0
        public void SetDependency(params ThreadTask[] tasks)
        {
            var list = DependsOn.ToList();

            list.AddRange(tasks);

            // clear finished from list
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Finished)
                {
                    list.RemoveAt(i);
                    i--;
                }
            }
            DependsOn = list.ToArray();
        }