Ejemplo n.º 1
0
        /// <summary>Retrieve the current value and store it in our array of values.</summary>
        public virtual object GetValue()
        {
            object value = null;

            // If we're at the end of the capture window, apply the aggregation.
            if (this.aggregationFunction != null)
            {
                if (!this.inCaptureWindow)
                {
                    value = ApplyAggregation();
                }
            }
            else
            {
                value = locator.Get(variableName);

                if (value == null)
                {
                    Values.Add(null);
                }
                else
                {
                    if (value != null && value is IFunction)
                    {
                        value = (value as IFunction).Value();
                    }
                    else if (value.GetType().IsArray || value.GetType().IsClass)
                    {
                        try
                        {
                            value = ReflectionUtilities.Clone(value);
                        }
                        catch (Exception)
                        {
                            throw new Exception("Cannot report variable " + this.variableName +
                                                ". Variable is not of a reportable type. Perhaps " +
                                                " it is a PMF Function that needs a .Value appended to the name.");
                        }
                    }

                    if (!haveGotUnits)
                    {
                        IVariable var = locator.GetObject(variableName);
                        if (var != null)
                        {
                            Units = var.UnitsLabel;
                            if (Units != null && Units.StartsWith("(") && Units.EndsWith(")"))
                            {
                                Units = Units.Substring(1, Units.Length - 2);
                            }
                        }
                        haveGotUnits = true;
                    }

                    Values.Add(value);
                }
            }
            return(value);
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="locator"></param>
 /// <param name="pipelineScope">Optional: if null, retrieved from locator</param>
 /// <param name="serviceProviderTypeChecker"></param>
 /// <param name="httpContextProvider"></param>
 /// <param name="locatorScopeFactory"></param>
 public WebApiDependencyResolver(ILocator locator, IPipelineScope pipelineScope = null, IServiceProviderTypeChecker serviceProviderTypeChecker = null, IHttpContextProvider httpContextProvider = null, ILocatorScopedFactory locatorScopeFactory = null)
 {
     _Locator       = locator;
     _PipelineScope = pipelineScope ?? _Locator.Get <IPipelineScope>();
     _ServiceProviderTypeChecker = serviceProviderTypeChecker ?? locator.Get <IServiceProviderTypeChecker>();
     _HttpContextProvider        = httpContextProvider ?? locator.Get <IHttpContextProvider>();
     _LocatorScopeFactory        = locatorScopeFactory ?? locator.Get <ILocatorScopedFactory>();
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Attempts to see if given ILocator implementions IServiceProvider, otherwise creates one from the ILocatorAmbient
        /// </summary>
        /// <param name="locator"></param>
        /// <returns></returns>
        public static IServiceProvider GetServiceProvider(this ILocator locator)
        {
            if (locator is ILocatorScoped && locator is IServiceProvider)
            {
                return(locator as IServiceProvider);
            }
            var ambient = locator.Get <ILocatorAmbient>();

            return(ambient.Current is IServiceProvider serviceProvider
                ? serviceProvider
                : new DotNetStarter.ServiceProvider(ambient, locator.Get <IServiceProviderTypeChecker>(), locator.Get <IStartupConfiguration>()));
        }
Ejemplo n.º 4
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            var mainMenu      = _locator.Get <IMainMenuViewModel>();
            var login         = _locator.Get <ILoginViewModel>();
            var windowManager = _locator.Get <IWindowManager>();

            windowManager.OpenWindow(mainMenu);
            ShutdownMode = ShutdownMode.OnLastWindowClose;
            if (windowManager.OpenDialog(login, mainMenu) != true)
            {
                windowManager.CloseWindow(mainMenu);
            }
        }
Ejemplo n.º 5
0
        public void Erase(T id)
        {
            int pos = _locator.Get(id);

            Swap(pos, _ids.Count - 1);
            T outOfPlaceId = _ids[pos];

            _ids.RemoveAt(_ids.Count - 1);
            _locator.Remove(id);
            if (!Empty && !Equals(outOfPlaceId, id))
            {
                TrinkleUp(_locator.Get(outOfPlaceId));
                TrinkleDown(_locator.Get(outOfPlaceId));
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="locator"></param>
 /// <param name="reflectionHelper"></param>
 /// <param name="allowableNullForGetService"></param>
 /// <param name="allowableNullForGetServices"></param>
 public NullableDependencyResolverBase(ILocator locator, IReflectionHelper reflectionHelper = null, IEnumerable <Type> allowableNullForGetService = null, IEnumerable <Type> allowableNullForGetServices = null)
 {
     _Locator                     = locator;
     _ReflectionHelper            = reflectionHelper ?? _Locator.Get <IReflectionHelper>();
     _AllowableNullForGetService  = allowableNullForGetService;
     _AllowableNullForGetServices = allowableNullForGetServices;
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Opens scope for OWIN pipeline as an IServiceProvider, scopename and scopecontext are for DryIoc containers.
        /// </summary>
        /// <param name="app"></param>
        /// <param name="locator"></param>
        /// <param name="serviceProviderTypeChecker"></param>
        public static void UseScopedLocator(this IAppBuilder app, ILocator locator, IServiceProviderTypeChecker serviceProviderTypeChecker = null)
        {
            app.Use(new Func<AppFunc, AppFunc>(next => (async context =>
            {
                var scoped = TryGetHttpScopedLocator(context, locator) as ILocatorScoped;
                var hasScopedLocator = scoped is object;
                scoped = scoped ?? locator.Get<ILocatorScopedFactory>().CreateScope(); // create via factory

                var contextAccessor = scoped.Get<IContextAccessor>();
                (contextAccessor as IContextSetter)
                    .SetContexts(new MiddlewareContext(context), context);

                context[ScopedLocatorKeyInContext] = scoped;
                context[ScopedProviderKeyInContext] = new ServiceProvider
                (
                    serviceProviderTypeChecker ?? scoped.Get<IServiceProviderTypeChecker>(),
                    scoped.Get<ILocatorScopedAccessor>()
                );

                // perform remaining tasks
                await next.Invoke(context);

                if (!hasScopedLocator)
                    scoped?.Dispose();
            })));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Gets the value of the variable/expression.
        /// </summary>
        private object GetVariableValue()
        {
            object value = null;

            try
            {
                value = locator.Get(variableName);
            }
            catch (Exception)
            {
                // Swallow exception because reporting sum(Wheat.Root.PlantZone.WaterUptake) will
                // throw an exception before the crop is sown. We don't want this to stop the
                // simulation. Instead, simply report null.
            }
            if (value is IFunction function)
            {
                value = function.Value();
            }
            else if (value != null && (value.GetType().IsArray || value.GetType().IsClass))
            {
                try
                {
                    value = ReflectionUtilities.Clone(value);
                }
                catch (Exception err)
                {
                    throw new Exception($"Cannot report variable \"{variableName}\": Variable is a non-reportable type: \"{value?.GetType()?.Name}\".", err);
                }
            }

            return(value);
        }
Ejemplo n.º 9
0
        /// <summary>Stores a value into the values array.</summary>
        public void StoreValue()
        {
            object value = locator.Get(variableName);

            if (value == null)
            {
                throw new Exception($"Unable to locate report variable: {variableName}");
            }
            if (value is IFunction function)
            {
                value = function.Value();
            }
            else if (value != null && (value.GetType().IsArray || value.GetType().IsClass))
            {
                try
                {
                    value = ReflectionUtilities.Clone(value);
                }
                catch (Exception err)
                {
                    throw new Exception($"Cannot report variable \"{variableName}\": Variable is a non-reportable type: \"{value?.GetType()?.Name}\".", err);
                }
            }

            valuesToAggregate.Add(value);
        }
Ejemplo n.º 10
0
        /// <summary>Store a value.</summary>
        public void StoreValue()
        {
            object        value = null;
            VariableGroup group = null;

            if (!string.IsNullOrEmpty(groupByName))
            {
                value = locator.Get(groupByName);
                if (value == null)
                {
                    throw new Exception($"Unable to locate group by variable: {groupByName}");
                }

                group = groups.Find(g => g.GroupByValue != null && g.GroupByValue.Equals(value));
            }
            else if (groups.Count > 0)
            {
                group = groups[0];
            }

            if (group == null)
            {
                group = new VariableGroup(locator, value, variableName, aggregationFunction);
                groups.Add(group);
            }
            group.StoreValue();
        }
Ejemplo n.º 11
0
        /// <summary>Gets the value.</summary>
        /// <value>The value.</value>
        /// <exception cref="System.Exception">Cannot find value for  + Name +  XProperty:  + XProperty</exception>
        public double Value(int arrayIndex = -1)
        {
            // Shortcut exit when the Y values are all the same. Runs quicker.
            if (YsAreAllTheSame)
            {
                return(XYPairs.Y[0]);
            }


            string PropertyName = XProperty;
            object v            = locator.Get(PropertyName);

            if (v == null)
            {
                throw new Exception("Cannot find value for " + Name + " XProperty: " + XProperty);
            }
            double XValue;

            if (v is Array)
            {
                XValue = (double)(v as Array).GetValue(arrayIndex);
            }
            else if (v is IFunction)
            {
                XValue = (v as IFunction).Value(arrayIndex);
            }
            else
            {
                XValue = Convert.ToDouble(v, System.Globalization.CultureInfo.InvariantCulture);
            }
            return(XYPairs.ValueIndexed(XValue));
        }
Ejemplo n.º 12
0
        /// <summary>Gets the value.</summary>
        /// <value>The value.</value>
        public double Value(int arrayIndex = -1)
        {
            object s = locator.Get(PropertyName);

            string PropertyString;

            if (s == null)
            {
                PropertyString = "";
            }
            else if (s is Array)
            {
                PropertyString = (string)(s as Array).GetValue(arrayIndex);
            }
            else if (s is IFunction)
            {
                PropertyString = (s as IFunction).Value(arrayIndex).ToString();
            }
            else
            {
                PropertyString = (string)s;
            }

            bool stringCompareTrue = PropertyString.Equals(StringValue, StringComparison.CurrentCultureIgnoreCase);

            if (stringCompareTrue)
            {
                return(TrueValue.Value(arrayIndex));
            }
            else
            {
                return(FalseValue.Value(arrayIndex));
            }
        }
Ejemplo n.º 13
0
        /// <summary>Gets the value.</summary>
        /// <value>The value.</value>
        public double Value(int arrayIndex = -1)
        {
            object o = locator.Get(VariableName.Trim());

            if (o == null)
            {
                throw new Exception("Unable to locate " + VariableName.Trim() + " called from the variable reference function " + Apsim.FullPath(this));
            }

            if (o is IFunction)
            {
                return((o as IFunction).Value(arrayIndex));
            }
            else if (o is Array)
            {
                return(Convert.ToDouble((o as Array).GetValue(arrayIndex),
                                        System.Globalization.CultureInfo.InvariantCulture));
            }
            else
            {
                double doubleValue = Convert.ToDouble(o, System.Globalization.CultureInfo.InvariantCulture);
                if (double.IsNaN(doubleValue))
                {
                    throw new Exception("NaN (not a number) found when getting variable: " + VariableName);
                }
                return(doubleValue);
            }
        }
Ejemplo n.º 14
0
        /// <summary>Retrieve the current value and store it in our array of values.</summary>
        public virtual object GetValue()
        {
            object value = null;

            // If we're at the end of the capture window, apply the aggregation.
            if (this.aggregationFunction != null)
            {
                //if (!this.inCaptureWindow)
                value = ApplyAggregation();
                if (toHasNoYear && this.clock.Today.Day == this.toDate.Day && this.clock.Today.Month == this.toDate.Month)
                {
                    this.valuesToAggregate.Clear();
                }
            }
            else
            {
                value = locator.Get(variableName);

                if (value == null)
                {
                    Values.Add(null);
                }
                else
                {
                    if (value != null && value is IFunction)
                    {
                        value = (value as IFunction).Value();
                    }
                    else if (value.GetType().IsArray || value.GetType().IsClass)
                    {
                        try
                        {
                            value = ReflectionUtilities.Clone(value);
                        }
                        catch (Exception)
                        {
                            throw new Exception("Cannot report variable " + this.variableName +
                                                ". Variable is not of a reportable type. Perhaps " +
                                                " it is a PMF Function that needs a .Value appended to the name.");
                        }
                    }

                    Values.Add(value);
                }
            }
            return(value);
        }
Ejemplo n.º 15
0
        public void LocatorGetVariableWithArrayIndex()
        {
            Simulation sim = new Simulation();

            sim.Children.Add(new ModelA());
            sim.Children.Add(new ModelB());
            sim.Children.Add(new Zone());
            sim.Children[2].Children.Add(new ModelC());
            sim.Children[2].Children.Add(new ModelD());

            Simulations sims = Simulations.Create(new Model[] { sim });

            // locator for modelD
            ILocator locatorForD = sims.GetLocatorService(sim.Children[2].Children[1]);

            Assert.AreEqual(locatorForD.Get("[ModelC].C2[1]"), 6.0);
            Assert.AreEqual(locatorForD.Get("[ModelC].C2[2]"), 6.1);
            Assert.AreEqual(locatorForD.Get("[ModelC].C2[3]"), 6.2);
        }
Ejemplo n.º 16
0
        public void TestPropertyOfInterface()
        {
            Concrete2 c2        = new Concrete2();
            Concrete3 c3        = new Concrete3();
            Container container = new Container();

            Simulation sim = new Simulation();

            sim.Children.Add(container);
            Simulations sims = new Simulations();

            sims.Children.Add(sim);

            ILocator locator = sims.GetLocatorService(sim);

            container.Value = c2;
            Assert.AreEqual(2, locator.Get("[Container].Value.X"));
            container.Value = c3;
            Assert.AreEqual(3, locator.Get("[Container].Value.X"));
        }
        /// <summary>
        /// Gets a creator Func for given Type, not if not in a scoped context, there will be issues
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="alias"></param>
        /// <returns></returns>
        public Func <T, object> GetCreator <T>(string alias)
        {
            var creatorType = _RenderingTypeResolver.ResolveCreator <T>(alias);

            if (creatorType == null)
            {
                return(null);
            }

            return(_ScopedLocator.Get(creatorType) as Func <T, object>);
        }
Ejemplo n.º 18
0
        public void LocatorGetPropertyOfModelAtSpecificArrayElement()
        {
            Simulation sim = new Simulation();

            sim.Children.Add(new ModelF());
            sim.Children.Add(new ModelB());
            sim.Children.Add(new Zone());
            sim.Children[2].Children.Add(new ModelC());
            ModelE e = new ModelE();

            e.models[0].F = 20;
            e.models[1].F = 21;
            sim.Children[2].Children.Add(e);

            Simulations sims = Simulations.Create(new Model[] { sim });

            // locator for modelC
            ILocator locatorForC = sims.GetLocatorService(sim.Children[2].Children[0]);

            Assert.AreEqual(locatorForC.Get("[ModelE].E1[1].F"), 20);
            Assert.AreEqual(locatorForC.Get("[ModelE].E1[2].F"), 21);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Tries to get already scoped locator from HttpContextBase.Items dictionary
        /// </summary>
        /// <param name="environment"></param>
        /// <param name="rootLocator"></param>
        /// <returns></returns>
        internal static ILocator TryGetHttpScopedLocator(IDictionary<string, object> environment, ILocator rootLocator)
        {
            var reflectionHelper = rootLocator.Get<IReflectionHelper>();
            var httpContext = environment.Get<IServiceProvider>("System.Web.HttpContextBase", null);
            var httpContextItemProperty = httpContext is null ? null :
                    reflectionHelper.GetProperties(httpContext.GetType()).FirstOrDefault(x => string.CompareOrdinal(x.Name, "Items") == 0);

            if (httpContextItemProperty?.GetValue(httpContext) is IDictionary contextItemDict)
            {
                return contextItemDict[ScopedLocatorKeyInContext] as ILocator;
            }

            return null;
        }
Ejemplo n.º 20
0
        public void LocatorGetVariableWithRelativeAddress()
        {
            Simulation sim = new Simulation();

            sim.Children.Add(new ModelA());
            sim.Children.Add(new ModelB());
            sim.Children.Add(new Zone());
            sim.Children[2].Children.Add(new ModelC());
            sim.Children[2].Children.Add(new ModelD());

            Simulations sims = Simulations.Create(new Model[] { sim });

            // locator for zone
            ILocator locatorForZone = sims.GetLocatorService(sim.Children[2]);

            Assert.AreEqual(locatorForZone.Get("ModelC.C1"), 5);
        }
Ejemplo n.º 21
0
        public void LocatorGetModel()
        {
            Simulation sim = new Simulation();

            sim.Children.Add(new ModelA());
            sim.Children.Add(new ModelB());
            sim.Children.Add(new Zone());
            sim.Children[2].Children.Add(new ModelC());
            sim.Children[2].Children.Add(new ModelD());

            Simulations sims = Simulations.Create(new Model[] { sim });

            // locator for modelC
            ILocator locatorForC = sims.GetLocatorService(sim.Children[2].Children[0]);

            Assert.AreEqual(locatorForC.Get("[ModelA]"), sim.Children[0]);
        }
Ejemplo n.º 22
0
        public void LocatorGetVariableWithAbsoluteAddress()
        {
            Simulation sim = new Simulation();

            sim.Children.Add(new ModelA());
            sim.Children.Add(new ModelB());
            sim.Children.Add(new Zone());
            sim.Children[2].Children.Add(new ModelC());
            sim.Children[2].Children.Add(new ModelD());

            Simulations sims = Simulations.Create(new Model[] { sim });

            // locator for modelC
            ILocator locatorForC = sims.GetLocatorService(sim.Children[2].Children[0]);

            Assert.AreEqual(locatorForC.Get(".Simulations.Simulation.ModelA.A1"), 1);

            // locator for modelD
            ILocator locatorForD = sims.GetLocatorService(sim.Children[2].Children[1]);

            Assert.AreEqual(locatorForD.Get(".Simulations.Simulation.Zone.ModelD.D2.Year"), 2000);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Gets the value of the variable/expression.
        /// </summary>
        private object GetVariableValue()
        {
            object value = locator.Get(variableName);

            if (value is IFunction function)
            {
                value = function.Value();
            }
            else if (value != null && (value.GetType().IsArray || value.GetType().IsClass))
            {
                try
                {
                    value = ReflectionUtilities.Clone(value);
                }
                catch (Exception err)
                {
                    throw new Exception($"Cannot report variable \"{variableName}\": Variable is a non-reportable type: \"{value?.GetType()?.Name}\".", err);
                }
            }

            return(value);
        }
Ejemplo n.º 24
0
        /// <summary>Gets the value.</summary>
        /// <value>The value.</value>
        public double Value(int arrayIndex = -1)
        {
            object o;

            try
            {
                o = locator.Get(trimmedVariableName);
            }
            catch (Exception err)
            {
                throw new Exception($"Error while locating variable '{VariableName}' in variable reference '{this.FullPath}'", err);
            }

            // This should never happen: the locator is supposed to throw
            // if the variable cannot be found.
            if (o == null)
            {
                throw new Exception("Unable to locate " + trimmedVariableName + " called from the variable reference function " + FullPath);
            }

            if (o is IFunction)
            {
                return((o as IFunction).Value(arrayIndex));
            }
            else if (o is Array)
            {
                return(Convert.ToDouble((o as Array).GetValue(arrayIndex),
                                        System.Globalization.CultureInfo.InvariantCulture));
            }
            else
            {
                double doubleValue = Convert.ToDouble(o, System.Globalization.CultureInfo.InvariantCulture);
                if (double.IsNaN(doubleValue))
                {
                    throw new Exception("NaN (not a number) found when getting variable: " + VariableName);
                }
                return(doubleValue);
            }
        }
Ejemplo n.º 25
0
        /// <summary>Gets the value.</summary>
        /// <value>The value.</value>
        public double Value(int arrayIndex = -1)
        {
            object o = locator.Get(VariableName.Trim());

            if (o is IFunction)
            {
                return((o as IFunction).Value(arrayIndex));
            }
            else if (o is Array)
            {
                return(Convert.ToDouble((o as Array).GetValue(arrayIndex),
                                        System.Globalization.CultureInfo.InvariantCulture));
            }
            else
            {
                double doubleValue = Convert.ToDouble(o, System.Globalization.CultureInfo.InvariantCulture);
                if (double.IsNaN(doubleValue))
                {
                    throw new Exception("NaN (not a number) found when getting variable: " + VariableName);
                }
                return(doubleValue);
            }
        }
Ejemplo n.º 26
0
 public DisabledWebModuleHandler(ILocator locator) : base(locator.Get <ILocatorScopedFactory>(), locator)
 {
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="locator"></param>
 /// <param name="pipelineScope">Optional: if null, retrieved from locator</param>
 public WebApiDependencyResolver(ILocator locator, IPipelineScope pipelineScope) : this(locator, pipelineScope, serviceProviderTypeChecker : null)
 {
     _Locator       = locator;
     _PipelineScope = pipelineScope ?? _Locator.Get <IPipelineScope>();
 }
Ejemplo n.º 28
0
 protected virtual void Awake()
 {
     Locator    = LocatorProvider.Get();
     Vent       = Locator.Get(VentLocatorKey) as IMessageBus;
     Unregister = new Action[EventCapacity];
 }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="locator"></param>
 /// <param name="serviceProviderTypeChecker"></param>
 /// <param name="httpContextProvider"></param>
 public ScopedDependencyResolver(ILocator locator, IServiceProviderTypeChecker serviceProviderTypeChecker, IHttpContextProvider httpContextProvider)
 {
     _Locator = locator;
     _ServiceProviderTypeChecker = serviceProviderTypeChecker ?? locator.Get <IServiceProviderTypeChecker>();
     _HttpContextProvider        = httpContextProvider ?? locator.Get <IHttpContextProvider>();
 }