/// <summary>
        /// Returns method that will call the function object.
        /// </summary>
        /// <param name="c"></param>
        /// <param name="Arguments"></param>
        /// <param name="FunctionName"></param>
        /// <returns></returns>
        public Func <object> FindFunction(IScopeContext c, IEnumerable <IExpression> Arguments, string fname)
        {
            // Get a list of all all functions that match the name we are using
            var allFuncs = ListOfFuncsWithName(fname);

            // Next, sort them by number of IExpression arguments. The more there are, the more we want to
            // try first. This isn't perfect, but it does establish a very definite precedence order.
            var byExpressionArgsUS = from m in allFuncs
                                     group m by m.GetParameters().Where(p => p.ParameterType.Name == "IExpression").Count();

            var byExpressionArgs = from g in byExpressionArgsUS
                                   orderby g.Key descending
                                   select g;

            // Now, run down them and see which ones match.
            var args   = Arguments.Select(a => new FunctionUtils.ArgEvalHolder(c, a)).ToArray();
            var method = (from mgroup in byExpressionArgs
                          from m in mgroup
                          where MatchArgList(m, args)
                          select m).FirstOrDefault();

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

            return(() => method.Invoke(null, ArgList(c, args, method.GetParameters()).ToArray()));
        }
Example #2
0
        /// <summary>
        /// Make sure that everything fits
        /// </summary>
        /// <param name="c"></param>
        public static void NormalizePlots(IScopeContext c)
        {
            c.ExecutionContext.AddPostCallHook("plot", "normalize", (obj, result) =>
            {
                var pc = result as DrawingContext;
                if (pc == null)
                    return result;

                pc.AddPreplotHook(plotContex =>
                {
                    var histToDraw = plotContex.ObjectsToDraw
                        .Select(o => o.NTObject)
                        .Where(o => o is ROOTNET.Interface.NTH1)
                        .Cast<ROOTNET.Interface.NTH1>();
                    if (histToDraw.Count() > 1)
                    {
                        var max = histToDraw.Select(p => FindPlotMaximum(p)).Max();
                        max = max * 1.10;

                        foreach (var p in histToDraw)
                        {
                            p.Maximum = max;
                        }
                    }
                });

                return result;
            });
        }
Example #3
0
        /// <summary>
        /// Turn off stat boxes if there is more than a single plot being shown.
        /// </summary>
        public static void TurnOffStatBoxesForMultiPlots(IScopeContext c)
        {
            c.ExecutionContext.AddPostCallHook("plot", "statsboxes", (obj, result) =>
            {
                var pc = result as DrawingContext;
                if (pc == null)
                    return result;

                pc.AddPreplotHook(plotContex =>
                {
                    if (plotContex.ObjectsToDraw.Count() > 1)
                    {
                        foreach (var p in plotContex.ObjectsToDraw)
                        {
                            if (p.NTObject is ROOTNET.Interface.NTH1)
                            {
                                (p.NTObject as ROOTNET.Interface.NTH1).Stats = false;
                            }
                        }
                    }
                });

                return result;
            });
        }
Example #4
0
        /// <summary>
        /// Is this a property name we know about, and can it do what we need it to do?
        /// </summary>
        /// <param name="c"></param>
        /// <param name="obj"></param>
        /// <param name="methodName"></param>
        /// <param name="args"></param>
        /// <returns></returns>
        public Tuple <bool, object> Evaluate(IScopeContext c, object obj, string methodName, object[] args)
        {
            // If we have multiple arguments, then we aren't doing anything
            if (args.Length > 1)
            {
                return(new Tuple <bool, object>(false, null));
            }

            // Get the type of the object
            var t = obj.GetType();

            // Now, see if we can't get the property name from there.
            var property = t.GetProperty(methodName);

            if (property == null)
            {
                return(new Tuple <bool, object>(false, null));
            }

            // Next, this is a get or set.
            if (args.Length == 0 && property.CanRead)
            {
                return(new Tuple <bool, object>(true, property.GetValue(obj)));
            }

            if (args.Length == 1 && property.CanWrite)
            {
                property.SetValue(obj, args[0]);
                return(new Tuple <bool, object>(true, obj));
            }

            // Failed if we got here!
            return(new Tuple <bool, object>(false, null));
        }
Example #5
0
 public CacheController(
     IConfiguration _config,
     IScopeContext _scopeContext,
     IFarmRegionBusiness _busFarmRegion,
     IFishPondBusiness _busFishPond,
     IProductGroupBusiness _busProductGroup,
     IProductSubgroupBusiness _busProductSubgroup,
     IProductUnitBusiness _busProductUnit,
     IExpenditureDocketTypeBusiness _busExpenditureDocketType,
     IStockIssueDocketTypeBusiness _busStockIssueDocketType,
     IStockReceiveDocketTypeBusiness _busStockReceiveDocketType,
     ITaxPercentBusiness _busTaxPercent,
     IWarehouseBusiness _busWarehouse,
     IWarehouseTypeBusiness _busWarehouseType
     )
 {
     config                    = _config;
     context                   = _scopeContext;
     busFarmRegion             = _busFarmRegion;
     busFishPond               = _busFishPond;
     busProductGroup           = _busProductGroup;
     busProductSubgroup        = _busProductSubgroup;
     busProductUnit            = _busProductUnit;
     busExpenditureDocketType  = _busExpenditureDocketType;
     busStockIssueDocketType   = _busStockIssueDocketType;
     busStockReceiveDocketType = _busStockReceiveDocketType;
     busTaxPercent             = _busTaxPercent;
     busWarehouse              = _busWarehouse;
     busWarehouseType          = _busWarehouseType;
 }
Example #6
0
        /// <summary>
        /// Returna plot that has as its content its value divided by its error, and zero errors.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public static NTH1 asSigma(IScopeContext ctx, NTH1 plot)
        {
            var result = plot.Clone() as NTH1;

            Tags.CopyTags(ctx, plot, result);

            result.Reset();

            // Besure to do the overflow bins as well.
            for (int i_bin_x = 0; i_bin_x < result.NbinsX + 2; i_bin_x++)
            {
                for (int i_bin_y = 0; i_bin_y < result.NbinsY + 2; i_bin_y++)
                {
                    for (int i_bin_z = 0; i_bin_z < result.NbinsZ + 2; i_bin_z++)
                    {
                        var v = plot.GetBinContent(i_bin_x, i_bin_y, i_bin_z);
                        var e = plot.GetBinError(i_bin_x, i_bin_y, i_bin_z);

                        var sig = e == 0 ? 0.0 : v / e;
                        result.SetBinContent(i_bin_x, i_bin_y, i_bin_z, sig);
                    }
                }
            }

            return(result);
        }
Example #7
0
        /// <summary>
        /// Add two dictionaries together. We just try to loop over everything one at a time.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="o1"></param>
        /// <param name="o2"></param>
        /// <returns></returns>
        public static Dictionary <object, object> OperatorPlus(IScopeContext ctx, IDictionary <object, object> o1, IDictionary <object, object> o2)
        {
            var r = new Dictionary <object, object>();

            foreach (var k in o1.Keys.Concat(o2.Keys).Distinct())
            {
                object v1 = null;
                object v2 = null;
                o1.TryGetValue(k, out v1);
                o2.TryGetValue(k, out v2);

                object opresult = null;
                if (v1 == null)
                {
                    opresult = v2;
                }
                else if (v2 == null)
                {
                    opresult = v1;
                }
                else
                {
                    var calc = new FunctionExpression("+", new ObjectValue(v1), new ObjectValue(v2));
                    opresult = calc.Evaluate(ctx);
                }
                if (opresult != null)
                {
                    r[k] = opresult;
                }
            }

            return(r);
        }
Example #8
0
        /// <summary>
        /// Open a local file. Only a local file.
        /// </summary>
        /// <param name="fname"></param>
        /// <returns></returns>
        public static object file(IScopeContext c, string fname)
        {
            // See if we can locate the file. If a relative path look relative to the
            // script directory.

            FileInfo fi = null;

            if (Path.IsPathRooted(fname))
            {
                fi = new FileInfo(fname);
            }
            else
            {
                // Located near the script?
                fi = new FileInfo(Path.Combine(c.ExecutionContext.CurrentScriptFile.DirectoryName, fname));
                if (!fi.Exists)
                {
                    fi = new FileInfo(fname);
                }
            }

            if (!fi.Exists)
            {
                throw new ArgumentException(string.Format("Unable to locate file {0}.", fi.FullName));
            }

            var f = ROOTNET.NTFile.Open(fi.FullName);

            if (f == null || !f.IsOpen())
            {
                throw new ArgumentException(string.Format("ROOT is unable to open file {0}.", fi.FullName));
            }

            return(f);
        }
Example #9
0
 /// <summary>
 /// Internal function to hide looking at all function objects.
 /// </summary>
 /// <param name="c"></param>
 /// <param name="arguments"></param>
 /// <param name="functionName"></param>
 /// <returns></returns>
 private Func <object> FindFunction(IScopeContext c, IEnumerable <IExpression> arguments, string functionName)
 {
     return(ExtensibilityControl.Get().FunctionFinders
            .Select(ff => ff.FindFunction(c, arguments, functionName))
            .Where(f => f != null)
            .FirstOrDefault());
 }
Example #10
0
        /// <summary>Inserts scoped container into pipeline and stores scoped container in context.
        ///
        /// Optionally registers instances in scope with provided action.</summary>
        /// <param name="app">App builder</param> <param name="container">Container</param>
        /// <param name="registerInScope">(optional) Action for registering something in scope before setting scope into context.</param>
        /// <param name="scopeContext">(optional) Specific scope context to use.
        /// If not specified using current container context. <see cref="AsyncExecutionFlowScopeContext"/> is default in .NET 4.5.</param>
        public static void UseDryIocOwinMiddleware(
            this IAppBuilder app, IContainer container,
            Action <IContainer> registerInScope = null,
            IScopeContext scopeContext          = null)
        {
            if (container.ScopeContext == null)
            {
                container = container.With(scopeContext: scopeContext ?? new AsyncExecutionFlowScopeContext());
            }

            app.Use(async(context, next) =>
            {
                using (var scope = container.OpenScope(Reuse.WebRequestScopeName))
                {
                    scope.UseInstance(context);
                    if (registerInScope != null)
                    {
                        registerInScope(scope);
                    }
                    context.Set(ScopedContainerKeyInContext, scope);
                    await next();
                }
            });

            app.UseRegisteredMiddlewares(container);
        }
Example #11
0
        /// <summary>
        /// Evaluate a string value.
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public object Evaluate(IScopeContext c)
        {
            // Find all variable subsitutions that have to be done in the string.
            var myl = _content;
            var m   = _findVarSub.Match(myl);

            while (m != null && m.Success)
            {
                var vname = m.Groups[1].Value;

                object result = null;
                try
                {
                    var exprTree = Grammar.ExpressionParser.End().Parse(vname);
                    result = exprTree.Evaluate(c);
                }
                catch { }

                int position = m.Groups[1].Index;
                if (result != null)
                {
                    var s = result.ToString();
                    myl       = myl.Replace("{" + vname + "}", s);
                    position += s.Length - 1;
                }
                else
                {
                    position += m.Groups[1].Length;
                }
                m = position > myl.Length ? null : _findVarSub.Match(myl, position);
            }
            return(myl);
        }
Example #12
0
        /// <summary>
        /// Include antoher source file. It is loaded and executed immediately, in the same global
        /// context.
        /// </summary>
        /// <param name="filename">Filename to include, if relative, w.r.t. the initially invoked script.</param>
        /// <returns>Returns whatever the last statement of the script returns.</returns>
        public static object include(IScopeContext c, string filename)
        {
            var content = FileOperations.readfile(c, filename);

            // Parse for comments, etc.

            var sb = new StringBuilder();

            using (var rdr = (new StringReader(content)))
            {
                foreach (var l in rdr.ReadFromReader())
                {
                    sb.AppendLine(l);
                }
            }

            // Now, push the script context, and off we go.

            c.ExecutionContext.ScriptFileContextPush(new FileInfo(filename));
            try
            {
                return(eval(c, sb.ToString()));
            }
            finally
            {
                c.ExecutionContext.ScriptFileContextPop();
            }
        }
Example #13
0
        public void ScopeContextEnlist(bool complete)
        {
            ScopeProvider scopeProvider = ScopeProvider;

            bool?         completed      = null;
            IScope        ambientScope   = null;
            IScopeContext ambientContext = null;

            Assert.IsNull(scopeProvider.AmbientScope);
            using (IScope scope = scopeProvider.CreateScope())
            {
                scopeProvider.Context.Enlist("name", c =>
                {
                    completed      = c;
                    ambientScope   = scopeProvider.AmbientScope;
                    ambientContext = scopeProvider.AmbientContext;
                });
                if (complete)
                {
                    scope.Complete();
                }
            }

            Assert.IsNull(scopeProvider.AmbientScope);
            Assert.IsNull(scopeProvider.AmbientContext);
            Assert.IsNotNull(completed);
            Assert.AreEqual(complete, completed.Value);
            Assert.IsNull(ambientScope);      // the scope is gone
            Assert.IsNotNull(ambientContext); // the context is still there
        }
Example #14
0
        /// <inheritdoc />
        public IScope DetachScope()
        {
            Scope ambientScope = AmbientScope;

            if (ambientScope == null)
            {
                throw new InvalidOperationException("There is no ambient scope.");
            }

            if (ambientScope.Detachable == false)
            {
                throw new InvalidOperationException("Ambient scope is not detachable.");
            }

            PopAmbientScope(ambientScope);
            PopAmbientScopeContext();

            Scope originalScope = AmbientScope;

            if (originalScope != ambientScope.OrigScope)
            {
                throw new InvalidOperationException($"The detatched scope ({ambientScope.GetDebugInfo()}) does not match the original ({originalScope.GetDebugInfo()})");
            }
            IScopeContext originalScopeContext = AmbientContext;

            if (originalScopeContext != ambientScope.OrigContext)
            {
                throw new InvalidOperationException($"The detatched scope context does not match the original");
            }

            ambientScope.OrigScope   = null;
            ambientScope.OrigContext = null;
            ambientScope.Attached    = false;
            return(ambientScope);
        }
Example #15
0
        /// <inheritdoc />
        public IScope CreateScope(
            IsolationLevel isolationLevel                      = IsolationLevel.Unspecified,
            RepositoryCacheMode repositoryCacheMode            = RepositoryCacheMode.Unspecified,
            IScopedNotificationPublisher notificationPublisher = null,
            bool?scopeFileSystems = null,
            bool callContext      = false,
            bool autoComplete     = false)
        {
            Scope ambientScope = AmbientScope;

            if (ambientScope == null)
            {
                IScopeContext ambientContext = AmbientContext;
                ScopeContext  newContext     = ambientContext == null ? new ScopeContext() : null;
                var           scope          = new Scope(this, _coreDebugSettings, _eventAggregator, _loggerFactory.CreateLogger <Scope>(), _fileSystems, false, newContext, isolationLevel, repositoryCacheMode, notificationPublisher, scopeFileSystems, callContext, autoComplete);
                // assign only if scope creation did not throw!
                PushAmbientScope(scope);
                if (newContext != null)
                {
                    PushAmbientScopeContext(newContext);
                }
                return(scope);
            }

            var nested = new Scope(this, _coreDebugSettings, _eventAggregator, _loggerFactory.CreateLogger <Scope>(), _fileSystems, ambientScope, isolationLevel, repositoryCacheMode, notificationPublisher, scopeFileSystems, callContext, autoComplete);

            PushAmbientScope(nested);
            return(nested);
        }
Example #16
0
        // protected TelemetryClient clienteTelemetria { get; }

        protected BaseController(IMediator mediator, IStringLocalizer <I18n> dicionario, IScopeContext scopeContext)
        {
            Mediator     = mediator;
            Dicionario   = dicionario;
            ScopeContext = scopeContext;
            // this.clienteTelemetria = clienteTelemetria;
        }
Example #17
0
        public void ScopeContextEnlistAgain(bool complete)
        {
            ScopeProvider scopeProvider = ScopeProvider;

            bool?completed  = null;
            bool?completed2 = null;

            Assert.IsNull(scopeProvider.AmbientScope);
            using (IScope scope = scopeProvider.CreateScope())
            {
                scopeProvider.Context.Enlist("name", c =>
                {
                    completed = c;

                    // at that point the scope is gone, but the context is still there
                    IScopeContext ambientContext = scopeProvider.AmbientContext;
                    ambientContext.Enlist("another", c2 => completed2 = c2);
                });
                if (complete)
                {
                    scope.Complete();
                }
            }

            Assert.IsNull(scopeProvider.AmbientScope);
            Assert.IsNull(scopeProvider.AmbientContext);
            Assert.IsNotNull(completed);
            Assert.AreEqual(complete, completed.Value);
            Assert.AreEqual(complete, completed2.Value);
        }
Example #18
0
        /// <summary>
        /// Given a 2D plot, map to a 1D plot assuming radial distances.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="plot"></param>
        /// <returns>1D plot of the 2D plot</returns>
        /// <remarks>
        /// - Radial conversion assumes that both coordinates are the same units. For example, if they are x and y distances.
        /// - Overflow & underflow bins are not handled.
        /// - Errors are not properly handled.
        /// </remarks>
        public static ROOTNET.Interface.NTH1 asRadial(IScopeContext ctx, ROOTNET.Interface.NTH2 plot)
        {
            // First, determine the distances
            var xmin = plot.Xaxis.GetBinLowEdge(1);
            var ymin = plot.Yaxis.GetBinLowEdge(1);
            var xmax = plot.Xaxis.GetBinUpEdge(plot.Xaxis.Nbins);
            var ymax = plot.Yaxis.GetBinUpEdge(plot.Yaxis.Nbins);

            var rmin = Math.Sqrt(xmin * xmin + ymin * ymin);
            var rmax = Math.Sqrt(xmax * xmax + ymax * ymax);

            var nbin = Math.Max(plot.Xaxis.Nbins, plot.Yaxis.Nbins);

            var result = new ROOTNET.NTH1F(plot.Name, plot.Title, nbin, rmin, rmax);

            // Loop over, adding everything in.
            for (int i_x = 1; i_x <= plot.Xaxis.Nbins; i_x++)
            {
                for (int i_y = 1; i_y <= plot.Yaxis.Nbins; i_y++)
                {
                    var x = plot.Xaxis.GetBinCenter(i_x);
                    var y = plot.Yaxis.GetBinCenter(i_y);
                    var r = Math.Sqrt(x * x + y * y);

                    result.Fill(r, plot.GetBinContent(i_x, i_y));
                }
            }

            return(result);
        }
Example #19
0
 public ProductService(
     FLSDbContext _context,
     IScopeContext _scopeContext
     ) : base(_context, _scopeContext)
 {
     context      = _context;
     scopeContext = _scopeContext;
 }
Example #20
0
        /// <summary>
        /// Scale the contents of a histogram up or down.
        /// </summary>
        /// <param name="h"></param>
        /// <param name="scaleFactor"></param>
        /// <returns></returns>
        public static ROOTNET.Interface.NTH1 OperatorMultiply(IScopeContext ctx, ROOTNET.Interface.NTH1 h, double scaleFactor)
        {
            var clone = h.Clone() as ROOTNET.Interface.NTH1;

            clone.Scale(scaleFactor);
            Tags.CopyTags(ctx, h, clone);
            return(clone);
        }
Example #21
0
        /// <summary>
        /// Rebin by a factor
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="plot"></param>
        /// <returns></returns>
        public static ROOTNET.Interface.NTH1 rebin(IScopeContext ctx, ROOTNET.Interface.NTH1 plot, int rebinFactor)
        {
            var np = plot.Clone() as ROOTNET.Interface.NTH1;

            Tags.CopyTags(ctx, plot, np);
            np.Rebin(rebinFactor);
            return(np);
        }
Example #22
0
        /// <summary>
        /// Set the minimum value for a plot
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="plot"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static ROOTNET.Interface.NTH1 minimum(IScopeContext ctx, ROOTNET.Interface.NTH1 plot, double value)
        {
            var np = plot.Clone() as ROOTNET.Interface.NTH1;

            Tags.CopyTags(ctx, plot, np);
            np.Minimum = value;
            return(np);
        }
Example #23
0
 public async Task Invoke(
     HttpContext httpContext,
     IScopeContext context
     )
 {
     context.AddHttpContext(httpContext);
     await _next(httpContext);
 }
 static public int GetMeContext(IScopeContext c)
 {
     if (c == null)
     {
         return(0);
     }
     return(12);
 }
Example #25
0
        public void DetachableScope()
        {
            ScopeProvider scopeProvider = ScopeProvider;

            Assert.IsNull(scopeProvider.AmbientScope);
            using (IScope scope = scopeProvider.CreateScope())
            {
                Assert.IsInstanceOf <Scope>(scope);
                Assert.IsNotNull(scopeProvider.AmbientScope);
                Assert.AreSame(scope, scopeProvider.AmbientScope);

                Assert.IsNotNull(scopeProvider.AmbientContext); // the ambient context
                Assert.IsNotNull(scopeProvider.Context);        // the ambient context too (getter only)
                IScopeContext context = scopeProvider.Context;

                IScope detached = scopeProvider.CreateDetachedScope();
                scopeProvider.AttachScope(detached);

                Assert.AreEqual(detached, scopeProvider.AmbientScope);
                Assert.AreNotSame(context, scopeProvider.Context);

                // nesting under detached!
                using (IScope nested = scopeProvider.CreateScope())
                {
                    Assert.Throws <InvalidOperationException>(() =>

                                                              // cannot detach a non-detachable scope
                                                              scopeProvider.DetachScope());
                    nested.Complete();
                }

                Assert.AreEqual(detached, scopeProvider.AmbientScope);
                Assert.AreNotSame(context, scopeProvider.Context);

                // can detach
                Assert.AreSame(detached, scopeProvider.DetachScope());

                Assert.AreSame(scope, scopeProvider.AmbientScope);
                Assert.AreSame(context, scopeProvider.AmbientContext);

                Assert.Throws <InvalidOperationException>(() =>

                                                          // cannot disposed a non-attached scope
                                                          // in fact, only the ambient scope can be disposed
                                                          detached.Dispose());

                scopeProvider.AttachScope(detached);
                detached.Complete();
                detached.Dispose();

                // has self-detached, and is gone!
                Assert.AreSame(scope, scopeProvider.AmbientScope);
                Assert.AreSame(context, scopeProvider.AmbientContext);
            }

            Assert.IsNull(scopeProvider.AmbientScope);
            Assert.IsNull(scopeProvider.AmbientContext);
        }
Example #26
0
        public void EventsDispatching_Scope(bool complete)
        {
            var           counter        = 0;
            IScope        ambientScope   = null;
            IScopeContext ambientContext = null;
            Guid          value          = Guid.Empty;

            var scopeProvider = GetScopeProvider(NullLoggerFactory.Instance) as ScopeProvider;

            DoThing1 += (sender, args) => { counter++; };
            DoThing2 += (sender, args) => { counter++; };
            DoThing3 += (sender, args) =>
            {
                ambientScope   = scopeProvider.AmbientScope;
                ambientContext = scopeProvider.AmbientContext;
                value          = scopeProvider.Context.Enlist("value", Guid.NewGuid, (c, o) => { });
                counter++;
            };

            Guid guid;

            using (var scope = scopeProvider.CreateScope())
            {
                Assert.IsNotNull(scopeProvider.AmbientContext);
                guid = scopeProvider.Context.Enlist("value", Guid.NewGuid, (c, o) => { });

                scope.Events.Dispatch(DoThing1, this, new SaveEventArgs <string>("test"));
                scope.Events.Dispatch(DoThing2, this, new SaveEventArgs <int>(0));
                scope.Events.Dispatch(DoThing3, this, new SaveEventArgs <decimal>(0));

                // events have been queued
                Assert.AreEqual(3, scope.Events.GetEvents(EventDefinitionFilter.All).Count());
                Assert.AreEqual(0, counter);

                if (complete)
                {
                    scope.Complete();
                }
            }

            if (complete)
            {
                // events have been raised
                Assert.AreEqual(3, counter);
                Assert.IsNull(ambientScope);      // scope was gone
                Assert.IsNotNull(ambientContext); // but not context
                Assert.AreEqual(guid, value);     // so we got the same value!
            }
            else
            {
                // else, no event has been raised
                Assert.AreEqual(0, counter);
            }

            // everything's gone
            Assert.IsNull(scopeProvider.AmbientScope);
            Assert.IsNull(scopeProvider.AmbientContext);
        }
Example #27
0
        /// <summary>First, inserts request scope into pipeline via <see cref="InsertOpenScope"/>.
        /// Then adds to application builder the registered OWIN middlewares
        /// wrapped in <see cref="DryIocWrapperMiddleware{TServiceMiddleware}"/> via <see cref="UseRegisteredMiddlewares"/>.</summary>
        /// <param name="app">App builder</param>
        /// <param name="container">Container</param>
        /// <param name="registerInScope">(optional) Action for using/registering instances in scope before setting scope into context.</param>
        /// <param name="scopeContext">(optional) Scope context to use. By default sets the <see cref="AsyncExecutionFlowScopeContext"/>.</param>
        /// <returns>App builder to enable method chaining.</returns>
        /// <remarks>IMPORTANT: if passed <paramref name="container"/> did not have a scope context set,
        /// then the new container with context will be created and used. If you want to hold on this new container,
        /// you may first call <see cref="InsertOpenScope"/>, store the result container,
        /// then call <see cref="UseRegisteredMiddlewares"/>.</remarks>
        public static IAppBuilder UseDryIocOwinMiddleware(
            this IAppBuilder app, IContainer container,
            Action <IResolverContext> registerInScope = null,
            IScopeContext scopeContext = null)
        {
            var containerWithAmbientContext = container.InsertOpenScope(app, registerInScope, scopeContext);

            return(app.UseRegisteredMiddlewares(containerWithAmbientContext));
        }
Example #28
0
 public ReportService(
     FLSDbContext _context,
     IScopeContext _scopeContext,
     IMapper _iMapper) : base(_context, _scopeContext)
 {
     context      = _context;
     scopeContext = _scopeContext;
     iMapper      = _iMapper;
 }
Example #29
0
 public FishPondService(
     FLSDbContext _context,
     IScopeContext _scopeContext,
     IMapper _iMapper)
 {
     context      = _context;
     scopeContext = _scopeContext;
     iMapper      = _iMapper;
 }
Example #30
0
 public StockIssueDocketDetailService(
     FLSDbContext _context,
     IScopeContext _scopeContext,
     IMapper _iMapper) : base(_context, _scopeContext)
 {
     context      = _context;
     scopeContext = _scopeContext;
     iMapper      = _iMapper;
 }
        /// <summary>Configures container to work with ASP.NET WepAPI by: 
        /// setting container scope context to <see cref="AsyncExecutionFlowScopeContext"/> (if scope context is not set already),
        /// registering HTTP controllers, setting filter provider and dependency resolver.</summary>
        /// <param name="container">Original container.</param> <param name="config">Http configuration.</param>
        /// <param name="controllerAssemblies">(optional) Assemblies to look for controllers, default is ExecutingAssembly.</param>
        /// <param name="scopeContext">(optional) Specific scope context to use, by default method sets
        /// <see cref="AsyncExecutionFlowScopeContext"/>, only if container does not have context specified already.</param>
        /// <param name="throwIfUnresolved">(optional) Instructs DryIoc to throw exception
        /// for unresolved type instead of fallback to default Resolver.</param>
        /// <returns>New container.</returns>
        public static IContainer WithWebApi(this IContainer container, HttpConfiguration config,
            IEnumerable<Assembly> controllerAssemblies = null, IScopeContext scopeContext = null,
            Func<Type, bool> throwIfUnresolved = null)
        {
            container.ThrowIfNull();

            if (container.ScopeContext == null)
                container = container.With(scopeContext: scopeContext ?? new AsyncExecutionFlowScopeContext());
                
            container.RegisterWebApiControllers(config, controllerAssemblies);

            container.SetFilterProvider(config.Services);

            InsertRegisterRequestMessageHandler(config);

            config.DependencyResolver = new DryIocDependencyResolver(container, throwIfUnresolved);

            return container;
        }
 public void Bind(Type concreteType, IScopeContext existingBinding, string identifier)
 {
     Optimizer.SetImplementationType(concreteType, existingBinding, identifier);
 }
 public void Unbind(Type type, IScopeContext scopeContext, string identifier)
 {
     Optimizer.RemoveImplementationType(type, scopeContext, identifier);
 }
 private IScopeContext LocateInLoadedAssembliesAndCache(Type type, string named, IScopeContext item)
 {
     if (!logSupressor.ContainsKey(type))
     {
         logSupressor.TryAdd(type, true);
         Logging.DebugMessage($"Type scanning initiated. Looking for implementations of {type.FullName} {GetNameString(named)}");
     }
     var items = AssemblyScanner.LocateInLoadedAssemblies(type);
     foreach (var scopeContext in items)
     {
         Optimizer.SetImplementationType(type, scopeContext, scopeContext.ImplementationKey);
         if (scopeContext.ImplementationKey == named)
             item = scopeContext;
     }
     return item;
 }
 public void Unbind(Type type, IScopeContext scopeContext, string identifier)
 {
     throw new NotImplementedException();
 }
 public void Bind(Type concreteType, IScopeContext existingBinding, string identifier)
 {
     throw new NotImplementedException();
 }
Example #37
0
        /// <summary>Creates new container from original one with <see cref="HttpContextScopeContext"/>.
        /// Then registers MVC controllers in container, 
        /// sets <see cref="DryIocFilterAttributeFilterProvider"/> as filter provider,
        /// and at last sets container as <see cref="DependencyResolver"/>.</summary>
        /// <param name="container">Original container.</param>
        /// <param name="controllerAssemblies">(optional) By default uses <see cref="GetReferencedAssemblies"/>.</param>
        /// <param name="scopeContext">Specific scope context to use, by default MVC uses <see cref="HttpContextScopeContext"/>.</param>
        /// <returns>New container with applied Web context.</returns>
        public static IContainer WithMvc(this IContainer container, 
            IEnumerable<Assembly> controllerAssemblies = null, IScopeContext scopeContext = null)
        {
            container.ThrowIfNull();

            if (scopeContext == null && !(container.ScopeContext is HttpContextScopeContext))
                scopeContext = new HttpContextScopeContext();
            if (scopeContext != null)
                container = container.With(scopeContext: scopeContext);

            container.RegisterMvcControllers(controllerAssemblies);

            container.SetFilterAttributeFilterProvider(FilterProviders.Providers);

            DependencyResolver.SetResolver(new DryIocDependencyResolver(container));

            return container;
        }