public static ConcreteBuild BuildSource(Type pluggedType, ConstructorInfo constructor, DependencyCollection dependencies, Policies policies) { ConcreteBuild plan = null; try { var ctorStep = BuildConstructorStep(pluggedType, constructor, dependencies, policies); plan = new ConcreteBuild(pluggedType, ctorStep); determineSetterSources(pluggedType, dependencies, policies, plan); } catch (StructureMapException e) { e.Push("Attempting to create a build plan for concrete type " + pluggedType.GetFullName()); throw; } catch (Exception e) { throw new StructureMapConfigurationException( "Attempting to create a build plan for concrete type " + pluggedType.GetFullName(), e); } return plan; }
public void enumerating_aggregates_the_dependencies() { var child1 = new DependencyCollection(); child1.Add(new Dependency("Bottles")); child1.Add(new Dependency("FubuCore")); var child2 = new DependencyCollection(); child2.Add(new Dependency("Bottles")); child2.Add(new Dependency("FubuCore")); child2.Add(new Dependency("FubuTestingSupport", "0.9.2.4")); child2.Add(new Dependency("RhinoMocks", "3.6.1")); theSolutionDependencies.Add(new Dependency("Bottles", "1.0.1.2")); theSolutionDependencies.Add(new Dependency("FubuCore", "1.0.1.5")); theSolutionDependencies.AddChild(child1); theSolutionDependencies.AddChild(child2); var expected = new[] { new Dependency("Bottles", "1.0.1.2"), new Dependency("FubuCore", "1.0.1.5"), new Dependency("FubuTestingSupport", "0.9.2.4"), new Dependency("RhinoMocks", "3.6.1") }; theSolutionDependencies.ShouldHaveTheSameElementsAs(expected); }
public static bool HasMissingPrimitives(ConstructorInfo ctor, DependencyCollection dependencies) { return ctor .GetParameters() .Where(x => x.ParameterType.IsSimple()) .Any(param => dependencies.FindByTypeOrName(param.ParameterType, param.Name) == null); }
public static ConstructorStep BuildConstructorStep(Type pluggedType, ConstructorInfo constructor, DependencyCollection dependencies, Policies policies) { var ctor = constructor ?? policies.SelectConstructor(pluggedType); if (ctor == null) { throw new StructureMapConfigurationException( "No public constructor could be selected for concrete type " + pluggedType.GetFullName()); } var ctorStep = new ConstructorStep(ctor); var multiples = findTypesWithMultipleParametersRequired(ctor); var ctorDependencies = ctor .GetParameters() .Select(x => { var dependency = multiples.Contains(x.ParameterType) ? dependencies.FindByTypeAndName(x.ParameterType, x.Name) : dependencies.FindByTypeOrName(x.ParameterType, x.Name); if (dependency == null && ( (x.DefaultValue != null && x.DefaultValue.GetType().Name != "DBNull"))) { dependency = x.DefaultValue; } return SourceFor(ConstructorArgument, x.Name, x.ParameterType, dependency); }); ctorStep.Add(ctorDependencies); return ctorStep; }
public static BuildUpPlan BuildUpPlan(Type pluggedType, DependencyCollection dependencies, Policies policies) { var plan = new BuildUpPlan(pluggedType); determineSetterSources(pluggedType, dependencies, policies, plan); return plan; }
public ConstructorInfo Find(Type pluggedType, DependencyCollection dependencies, PluginGraph graph) { return pluggedType .GetConstructors() .Where(x => !HasMissingPrimitives(x, dependencies)) .OrderByDescending(x => x.GetParameters().Count()) .FirstOrDefault(); }
public ConstructorInfo Find(Type pluggedType, DependencyCollection dependencies, PluginGraph graph) { // if this rule does not apply to the pluggedType, // just return null to denote "not applicable" if (!pluggedType.CanBeCastTo<BaseThing>()) return null; return pluggedType.GetConstructor(new[] {typeof (IWidget)}); }
private static void determineSetterSources(Type pluggedType, DependencyCollection dependencies, Policies policies, IHasSetters plan) { var setters = GetSetters(pluggedType); setters.Each(setter => determineSetterSource(dependencies, policies, setter, plan)); }
// ASP.NET expects registered services to be considered when selecting a ctor, SM doesn't by default. public ConstructorInfo Find(Type pluggedType, DependencyCollection dependencies, PluginGraph graph) => pluggedType.GetTypeInfo() .DeclaredConstructors .Select(ctor => new { Constructor = ctor, Parameters = ctor.GetParameters() }) .Where(x => x.Parameters.All(param => graph.HasFamily(param.ParameterType))) .OrderByDescending(x => x.Parameters.Length) .Select(x => x.Constructor) .FirstOrDefault();
public void can_override_and_last_one_in_wins() { var collection = new DependencyCollection(); collection.Add("foo", typeof(IGateway), gateway1); collection.Add("foo", typeof(IGateway), gateway2); collection.FindByTypeOrName(typeof(IGateway), "foo") .ShouldBeTheSameAs(gateway2); }
public void finds_the_dependency_from_a_child_collection() { var projectDependency = new Dependency("Bottles"); var projectDependencies = new DependencyCollection(); projectDependencies.Add(projectDependency); theSolutionDependencies.AddChild(projectDependencies); theSolutionDependencies.Find("Bottles").ShouldEqual(projectDependency); }
/// <summary> /// Constructs a instance of remote Closure Compiler /// </summary> /// <param name="closureCompilerServiceUrl">URL of Google Closure Compiler Service API</param> /// <param name="commonExternsDependencies">List of common JS-externs dependencies</param> /// <param name="defaultOptions">Default compilation options</param> public ClosureRemoteJsCompiler(string closureCompilerServiceUrl, DependencyCollection commonExternsDependencies, RemoteJsCompilationOptions defaultOptions) : base(commonExternsDependencies) { _closureCompilerServiceUrl = closureCompilerServiceUrl; _defaultOptions = defaultOptions; _defaultOptionsFormItems = (defaultOptions != null) ? ConvertCompilationOptionsToFormItems(_defaultOptions) : new List<FormItem>(); }
public void has_missing_primitives_positive_2() { var ctor = typeof(GuyWithPrimitiveArgs).GetConstructors().Single(); var dependencies = new DependencyCollection(); dependencies.Add("age", 1); // One is still missing GreediestConstructorSelector.HasMissingPrimitives(ctor, dependencies).ShouldBeTrue(); }
public void if_an_enumerable_type_and_there_is_no_exact_match_by_type_try_ienumerable_of_the_element_type() { var collection = new DependencyCollection(); var instance = new EnumerableInstance(new Instance[0]); collection.Add(typeof (IEnumerable<IGateway>), instance); collection.FindByTypeOrName(typeof (IList<IGateway>), null).ShouldBeTheSameAs(instance); collection.FindByTypeOrName(typeof (List<IGateway>), null).ShouldBeTheSameAs(instance); collection.FindByTypeOrName(typeof (IGateway[]), null).ShouldBeTheSameAs(instance); }
public void see_the_description_of_class_with_only_ctor_with_inline_depencencies() { var dependencies = new DependencyCollection(); dependencies.Add(typeof(Rule), new ColorRule("Red")); dependencies.Add(typeof(IWidget), new AWidget()); var build = ConcreteType.BuildSource(typeof(GuyWithOnlyCtor), null, dependencies, Policies.Default()); Debug.WriteLine(build.Description); }
public void uses_the_top_most_dependency() { var projectDependency = new Dependency("StructureMap"); var projectDependencies = new DependencyCollection(); projectDependencies.Add(projectDependency); var solutionDependency = new Dependency("StructureMap", "2.6.3", UpdateMode.Fixed); theSolutionDependencies.Add(solutionDependency); theSolutionDependencies.AddChild(projectDependencies); theSolutionDependencies.Find("StructureMap").ShouldEqual(solutionDependency); }
public void has_missing_primitives_negative() { var ctor = typeof(GuyWithPrimitiveArgs).GetConstructors().Single(); var dependencies = new DependencyCollection(); dependencies.Add("name", "Jeremy"); dependencies.Add(typeof(int), 41); // One is still missing GreediestConstructorSelector.HasMissingPrimitives(ctor, dependencies).ShouldBeFalse(); }
public BuildUpTester() { theDefaultGateway = new DefaultGateway(); var args = new ExplicitArguments(); args.Set<IGateway>(theDefaultGateway); session = BuildSession.Empty(args); theDependencies = new DependencyCollection { { "Age", 34 } }; target = null; }
public void add_and_retrieve_by_type_only() { var collection = new DependencyCollection(); collection.Add(typeof (IService), service1); collection.Add(typeof (IGateway), gateway3); collection.FindByTypeOrName(typeof (IGateway), "foo") .ShouldBe(gateway3); collection.FindByTypeOrName(typeof (IService), "anything") .ShouldBe(service1); }
public void add_and_retrieve_by_name_only() { var collection = new DependencyCollection(); collection.Add("foo", gateway1); collection.Add("bar", gateway2); collection.FindByTypeOrName(typeof (IGateway), "foo") .ShouldBeTheSameAs(gateway1); collection.FindByTypeOrName(typeof (IGateway), "bar") .ShouldBeTheSameAs(gateway2); }
public void SetUp() { TheDefaultGateway = new DefaultGateway(); var args = new ExplicitArguments(); args.Set<IGateway>(TheDefaultGateway); _session = BuildSession.Empty(args); theDependencies = new DependencyCollection {{"Age", 34}}; _target = null; }
public void use_most_specific_criteria_if_possible() { var collection = new DependencyCollection(); collection.Add("foo", typeof (IGateway), gateway1); collection.Add("bar", typeof (IGateway), gateway2); collection.Add("bar", typeof (IService), service1); collection.FindByTypeOrName(typeof (IGateway), "foo") .ShouldBeTheSameAs(gateway1); collection.FindByTypeOrName(typeof (IGateway), "bar") .ShouldBeTheSameAs(gateway2); collection.FindByTypeOrName(typeof (IService), "bar") .ShouldBeTheSameAs(service1); }
public void sends_the_constructor_args_and_parameters_to_the_visitor() { var dependencies = new DependencyCollection(); dependencies.Add(typeof (Rule), new ColorRule("Red")); dependencies.Add(typeof (IWidget), new AWidget()); var build = ConcreteType.BuildSource(typeof (GuyWithCtorAndArgs), null, dependencies, Policies.Default()); var visitor = new StubVisitor(); build.AcceptVisitor(visitor); visitor.Items.ShouldHaveTheSameElementsAs( "Constructor: Void .ctor(StructureMap.Testing.Widget3.IGateway, StructureMap.Testing.Widget.Rule)", "Set IWidget Widget = Value: StructureMap.Testing.Widget.AWidget", "Set IService Service = *Default of IService*" ); }
private static void determineSetterSource(DependencyCollection dependencies, Policies policies, PropertyInfo setter, IHasSetters plan) { var isMandatory = policies.IsMandatorySetter(setter); object dependency = null; if (setter.PropertyType.IsSimple() && !isMandatory) { dependency = dependencies.FindByTypeAndName(setter.PropertyType, setter.Name); } else { dependency = dependencies.FindByTypeOrName(setter.PropertyType, setter.Name); } if (dependency == null && !isMandatory) return; var source = SourceFor(SetterProperty, setter.Name, setter.PropertyType, dependency); plan.Add(setter.PropertyType, setter, source); }
public static DependencyCollection AddLogWriter(this DependencyCollection collection, ILogWriter logWriter) { collection.AddInstance(logWriter); return(collection); }
public static DependencyCollection AddDefaultConsoleLogWriter(this DependencyCollection collection, LogLevel level = LogLevel.Debug) { collection.AddInstance(new ConsoleLogWriter(level)); return(collection); }
public void Throw_Activate_Interface() { var provider = new DependencyCollection().BuildProvider(); Assert.Throws <InvalidOperationException>(() => provider.Activate <ISession>()); }
public AddinInfo() { dependencies = new DependencyCollection(); optionalDependencies = new DependencyCollection(); properties = new AddinPropertyCollectionImpl(); }
public MetricsInstallerShould() { _dependencies = new DependencyCollection(); }
public EmitterInstallerShould() { _dependencies = new DependencyCollection(); }
private AddinInfo() { dependencies = new DependencyCollection(); optionalDependencies = new DependencyCollection(); }
public bool ResolveDependencies(IProgressStatus statusMonitor, PackageCollection packages, out PackageCollection toUninstall, out DependencyCollection unresolved) { IProgressMonitor monitor = ProgressStatusMonitor.GetProgressMonitor(statusMonitor); return(ResolveDependencies(monitor, packages, out toUninstall, out unresolved)); }
public ISimulation InitializeInstance() { var container = new DependencyCollection(); Collection = container; IoCManager.InitThread(container, true); //TODO: This is a long term project that should eventually have parity with the actual server/client/SP IoC registration. // The goal is to be able to pull out all networking and frontend dependencies, and only have a core simulation running. // This does NOT replace the full RobustIntegrationTest, or regular unit testing. This simulation sits in the middle // and allows you to run integration testing only on the simulation. //Tier 1: System container.Register <ILogManager, LogManager>(); container.Register <IRuntimeLog, RuntimeLog>(); container.Register <IConfigurationManager, ConfigurationManager>(); container.Register <IDynamicTypeFactory, DynamicTypeFactory>(); container.Register <IDynamicTypeFactoryInternal, DynamicTypeFactory>(); container.Register <ILocalizationManager, LocalizationManager>(); container.Register <IModLoader, TestingModLoader>(); container.Register <IModLoaderInternal, TestingModLoader>(); container.RegisterInstance <ITaskManager>(new Mock <ITaskManager>().Object); var reflectionManager = new Mock <IReflectionManager>(); reflectionManager .Setup(x => x.FindTypesWithAttribute <MeansDataDefinition>()) .Returns(() => new[] { typeof(DataDefinition) }); reflectionManager .Setup(x => x.FindTypesWithAttribute(typeof(DataDefinition))) .Returns(() => new[] { typeof(EntityPrototype), typeof(TransformComponent), typeof(MetaDataComponent) }); reflectionManager .Setup(x => x.FindTypesWithAttribute <TypeSerializerAttribute>()) .Returns(() => new[] { typeof(StringSerializer) }); container.RegisterInstance <IReflectionManager>(reflectionManager.Object); // tests should not be searching for types container.RegisterInstance <IRobustSerializer>(new Mock <IRobustSerializer>().Object); container.RegisterInstance <IResourceManager>(new Mock <IResourceManager>().Object); // no disk access for tests container.RegisterInstance <IGameTiming>(new Mock <IGameTiming>().Object); // TODO: get timing working similar to RobustIntegrationTest //Tier 2: Simulation container.Register <IEntityManager, EntityManager>(); container.Register <IMapManager, MapManager>(); container.Register <IEntityLookup, SharedEntityLookup>(); container.Register <ISerializationManager, SerializationManager>(); container.Register <IComponentManager, ComponentManager>(); container.Register <IPrototypeManager, PrototypeManager>(); container.Register <IComponentFactory, ComponentFactory>(); container.Register <IComponentDependencyManager, ComponentDependencyManager>(); container.Register <IEntitySystemManager, EntitySystemManager>(); container.Register <IPhysicsManager, PhysicsManager>(); container.RegisterInstance <IPauseManager>(new Mock <IPauseManager>().Object); // TODO: get timing working similar to RobustIntegrationTest _diFactory?.Invoke(container); container.BuildGraph(); var logMan = container.Resolve <ILogManager>(); logMan.RootSawmill.AddHandler(new TestLogHandler("SIM")); var compFactory = container.Resolve <IComponentFactory>(); compFactory.Register <MetaDataComponent>(); compFactory.RegisterReference <MetaDataComponent, IMetaDataComponent>(); compFactory.Register <TransformComponent>(); compFactory.RegisterReference <TransformComponent, ITransformComponent>(); compFactory.Register <MapComponent>(); compFactory.RegisterReference <MapComponent, IMapComponent>(); compFactory.Register <MapGridComponent>(); compFactory.RegisterReference <MapGridComponent, IMapGridComponent>(); compFactory.Register <PhysicsComponent>(); compFactory.RegisterReference <PhysicsComponent, IPhysBody>(); _regDelegate?.Invoke(compFactory); var entityMan = container.Resolve <IEntityManager>(); entityMan.Initialize(); IoCManager.Resolve <IEntityLookup>().Initialize(); _systemDelegate?.Invoke(container.Resolve <IEntitySystemManager>()); entityMan.Startup(); var mapManager = container.Resolve <IMapManager>(); mapManager.Initialize(); mapManager.Startup(); container.Resolve <ISerializationManager>().Initialize(); var protoMan = container.Resolve <IPrototypeManager>(); protoMan.RegisterType(typeof(EntityPrototype)); _protoDelegate?.Invoke(protoMan); protoMan.Resync(); return(this); }
internal override void Resolve(IProgressMonitor monitor, AddinStore service, PackageCollection toInstall, PackageCollection toUninstall, PackageCollection required, DependencyCollection unresolved) { }
/// <summary> /// Generates a detailed error message /// </summary> /// <param name="errorDetails">Error details</param> /// <param name="sourceCode">Source code</param> /// <param name="currentFilePath">Path to current LESS-file</param> /// <param name="dependencies">List of dependencies</param> /// <returns>Detailed error message</returns> private static string FormatErrorDetails(JToken errorDetails, string sourceCode, string currentFilePath, DependencyCollection dependencies) { var type = errorDetails.Value<string>("type"); var message = errorDetails.Value<string>("message"); var filePath = errorDetails.Value<string>("fileName"); if (string.IsNullOrWhiteSpace(filePath)) { filePath = currentFilePath; } var lineNumber = errorDetails.Value<int>("lineNumber"); var columnNumber = errorDetails.Value<int>("columnNumber"); string newSourceCode = string.Empty; if (string.Equals(filePath, currentFilePath, StringComparison.OrdinalIgnoreCase)) { newSourceCode = sourceCode; } else { var dependency = dependencies.GetByUrl(filePath); if (dependency != null) { newSourceCode = dependency.Content; } } string sourceFragment = SourceCodeNavigator.GetSourceFragment(newSourceCode, new SourceCodeNodeCoordinates(lineNumber, columnNumber)); var errorMessage = new StringBuilder(); if (!string.IsNullOrWhiteSpace(type)) { errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_ErrorType, type); } errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Message, message); if (!string.IsNullOrWhiteSpace(filePath)) { errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_File, filePath); } if (lineNumber > 0) { errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_LineNumber, lineNumber.ToString(CultureInfo.InvariantCulture)); } if (columnNumber > 0) { errorMessage.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_ColumnNumber, columnNumber.ToString(CultureInfo.InvariantCulture)); } if (!string.IsNullOrWhiteSpace(sourceFragment)) { errorMessage.AppendFormatLine("{1}:{0}{0}{2}", Environment.NewLine, CoreStrings.ErrorDetails_SourceError, sourceFragment); } return errorMessage.ToString(); }
/// <summary> /// "Compiles" a LESS-code to CSS-code /// </summary> /// <param name="content">Text content written on LESS</param> /// <param name="path">Path to LESS-file</param> /// <param name="dependencies">List of dependencies</param> /// <param name="options">Compilation options</param> /// <returns>Translated LESS-code</returns> public string Compile(string content, string path, DependencyCollection dependencies, CompilationOptions options = null) { string newContent; CompilationOptions currentOptions; string currentOptionsString; if (options != null) { currentOptions = options; currentOptionsString = ConvertCompilationOptionsToJson(options).ToString(); } else { currentOptions = _defaultOptions; currentOptionsString = _defaultOptionsString; } string processedContent = content; string globalVariables = currentOptions.GlobalVariables; string modifyVariables = currentOptions.ModifyVariables; if (!string.IsNullOrWhiteSpace(globalVariables) || !string.IsNullOrWhiteSpace(modifyVariables)) { var contentBuilder = new StringBuilder(); if (!string.IsNullOrWhiteSpace(globalVariables)) { contentBuilder.AppendLine(ParseVariables(globalVariables, "GlobalVariables")); } contentBuilder.Append(content); if (!string.IsNullOrWhiteSpace(modifyVariables)) { contentBuilder.AppendLine(); contentBuilder.Append(ParseVariables(modifyVariables, "ModifyVariables")); } processedContent = contentBuilder.ToString(); } lock (_compilationSynchronizer) { Initialize(); try { var result = _jsEngine.Evaluate<string>(string.Format(COMPILATION_FUNCTION_CALL_TEMPLATE, JsonConvert.SerializeObject(processedContent), JsonConvert.SerializeObject(path), ConvertDependenciesToJson(dependencies), currentOptionsString)); var json = JObject.Parse(result); var errors = json["errors"] != null ? json["errors"] as JArray : null; if (errors != null && errors.Count > 0) { throw new LessCompilingException(FormatErrorDetails(errors[0], processedContent, path, dependencies)); } newContent = json.Value<string>("compiledCode"); } catch (JsRuntimeException e) { throw new LessCompilingException( JsRuntimeErrorHelpers.Format(e)); } } return newContent; }
public void is_valid_sad_path_with_setter_checks() { // This class needs all three of these things var dependencies = new DependencyCollection(); dependencies.Add("Name", "Jeremy"); dependencies.Add("Age", 40); //dependencies.Add("IsAwake", true); ConcreteType.BuildSource(typeof (GuyWithPrimitiveSetters), null, dependencies, Policies.Default()) .IsValid().ShouldBeFalse(); }
internal void ResolveDependency(IProgressMonitor monitor, Dependency dep, AddinPackage parentPackage, PackageCollection toInstall, PackageCollection toUninstall, PackageCollection installedRequired, DependencyCollection unresolved) { AddinDependency adep = dep as AddinDependency; if (adep == null) { return; } string nsid = Addin.GetFullId(parentPackage.Addin.Namespace, adep.AddinId, null); foreach (Package p in toInstall) { AddinPackage ap = p as AddinPackage; if (ap != null) { if (Addin.GetIdName(ap.Addin.Id) == nsid && ((AddinInfo)ap.Addin).SupportsVersion(adep.Version)) { return; } } } ArrayList addins = new ArrayList(); addins.AddRange(service.Registry.GetAddins()); addins.AddRange(service.Registry.GetAddinRoots()); foreach (Addin addin in addins) { if (Addin.GetIdName(addin.Id) == nsid && addin.SupportsVersion(adep.Version)) { AddinPackage p = AddinPackage.FromInstalledAddin(addin); if (!installedRequired.Contains(p)) { installedRequired.Add(p); } return; } } AddinRepositoryEntry[] avaddins = service.Repositories.GetAvailableAddins(); foreach (PackageRepositoryEntry avAddin in avaddins) { if (Addin.GetIdName(avAddin.Addin.Id) == nsid && ((AddinInfo)avAddin.Addin).SupportsVersion(adep.Version)) { toInstall.Add(AddinPackage.FromRepository(avAddin)); return; } } unresolved.Add(adep); }
public AssignableCollectorShould() { _collection = new DependencyCollection(); _contract = typeof(IBooRepository); _implementation = typeof(BooRepository); }
internal bool ResolveDependencies(IProgressMonitor monitor, PackageCollection packages, out PackageCollection toUninstall, out DependencyCollection unresolved) { PackageCollection requested = new PackageCollection(); requested.AddRange(packages); unresolved = new DependencyCollection(); toUninstall = new PackageCollection(); PackageCollection installedRequired = new PackageCollection(); for (int n = 0; n < packages.Count; n++) { Package p = packages [n]; p.Resolve(monitor, this, packages, toUninstall, installedRequired, unresolved); } if (unresolved.Count != 0) { foreach (Dependency dep in unresolved) { monitor.ReportError(string.Format("The package '{0}' could not be found in any repository", dep.Name), null); } return(false); } // Check that we are not uninstalling packages that are required // by packages being installed. foreach (Package p in installedRequired) { if (toUninstall.Contains(p)) { // Only accept to uninstall this package if we are // going to install a newer version. bool foundUpgrade = false; foreach (Package tbi in packages) { if (tbi.Equals(p) || tbi.IsUpgradeOf(p)) { foundUpgrade = true; break; } } if (!foundUpgrade) { return(false); } } } // Check that we are not trying to uninstall from a directory from // which we don't have write permissions foreach (Package p in toUninstall) { AddinPackage ap = p as AddinPackage; if (ap != null) { Addin ia = service.Registry.GetAddin(ap.Addin.Id); if (File.Exists(ia.AddinFile) && !HasWriteAccess(ia.AddinFile) && IsUserAddin(ia.AddinFile)) { monitor.ReportError(GetUninstallErrorNoRoot(ap.Addin), null); return(false); } } } // Check that we are not installing two versions of the same addin PackageCollection resolved = new PackageCollection(); resolved.AddRange(packages); bool error = false; for (int n = 0; n < packages.Count; n++) { AddinPackage ap = packages [n] as AddinPackage; if (ap == null) { continue; } for (int k = n + 1; k < packages.Count; k++) { AddinPackage otherap = packages [k] as AddinPackage; if (otherap == null) { continue; } if (ap.Addin.Id == otherap.Addin.Id) { if (ap.IsUpgradeOf(otherap)) { if (requested.Contains(otherap)) { monitor.ReportError("Can't install two versions of the same add-in: '" + ap.Addin.Name + "'.", null); error = true; } else { packages.RemoveAt(k); } } else if (otherap.IsUpgradeOf(ap)) { if (requested.Contains(ap)) { monitor.ReportError("Can't install two versions of the same add-in: '" + ap.Addin.Name + "'.", null); error = true; } else { packages.RemoveAt(n); n--; } } else { error = true; monitor.ReportError("Can't install two versions of the same add-in: '" + ap.Addin.Name + "'.", null); } break; } } } // Don't allow installing add-ins which are scheduled for uninstall foreach (Package p in packages) { AddinPackage ap = p as AddinPackage; if (ap != null && Registry.IsRegisteredForUninstall(ap.Addin.Id)) { error = true; monitor.ReportError("The addin " + ap.Addin.Name + " v" + ap.Addin.Version + " is scheduled for uninstallation. Please restart the application before trying to re-install it.", null); } } return(!error); }
internal DependencyScanner(DependencyCollection dependencyCollection) { _assemblies = new HashSet <Assembly>(); _alloverCollection = new List <IDependencyAllover>(); _dependencyCollection = dependencyCollection; }
public bool ResolveDependencies(IProgressStatus statusMonitor, AddinRepositoryEntry[] addins, out PackageCollection resolved, out PackageCollection toUninstall, out DependencyCollection unresolved) { resolved = new PackageCollection(); for (int n = 0; n < addins.Length; n++) { resolved.Add(AddinPackage.FromRepository(addins [n])); } return(ResolveDependencies(statusMonitor, resolved, out toUninstall, out unresolved)); }
private void _serverMain() { try { IoCManager.InitThread(DependencyCollection); ServerIoC.RegisterIoC(); IoCManager.Register <INetManager, IntegrationNetManager>(true); IoCManager.Register <IServerNetManager, IntegrationNetManager>(true); IoCManager.Register <IntegrationNetManager, IntegrationNetManager>(true); IoCManager.Register <ISystemConsoleManager, SystemConsoleManagerDummy>(true); IoCManager.Register <IModLoader, ModLoader>(true); IoCManager.Register <ModLoader, ModLoader>(true); IoCManager.RegisterInstance <IStatusHost>(new Mock <IStatusHost>().Object, true); _options?.InitIoC?.Invoke(); IoCManager.BuildGraph(); //ServerProgram.SetupLogging(); ServerProgram.InitReflectionManager(); var server = DependencyCollection.Resolve <IBaseServerInternal>(); if (_options?.ServerContentAssembly != null) { IoCManager.Resolve <ModLoader>().ServerContentAssembly = _options.ServerContentAssembly; } if (_options?.SharedContentAssembly != null) { IoCManager.Resolve <ModLoader>().SharedContentAssembly = _options.SharedContentAssembly; } if (_options != null) { _options.BeforeStart?.Invoke(); IoCManager.Resolve <IConfigurationManager>() .OverrideConVars(_options.CVarOverrides.Select(p => (p.Key, p.Value))); if (_options.ExtraPrototypes != null) { IoCManager.Resolve <IResourceManagerInternal>() .MountString("/Prototypes/__integration_extra.yml", _options.ExtraPrototypes); } } if (server.Start(() => new TestLogHandler("SERVER"))) { throw new Exception("Server failed to start."); } var gameLoop = new IntegrationGameLoop( DependencyCollection.Resolve <IGameTiming>(), _fromInstanceWriter, _toInstanceReader); server.OverrideMainLoop(gameLoop); server.MainLoop(); } catch (Exception e) { _fromInstanceWriter.TryWrite(new ShutDownMessage(e)); return; } _fromInstanceWriter.TryWrite(new ShutDownMessage(null)); }
/// <summary> /// "Compiles" a JS code /// </summary> /// <param name="content">Text content written on JS</param> /// <param name="path">Path to JS file</param> /// <param name="externsDependencies">List of JS externs dependencies</param> /// <returns>Compiled JS code</returns> public string Compile(string content, string path, DependencyCollection externsDependencies) { string newContent; DependencyCollection allExternsDependencies = new DependencyCollection(); var formItems = new List <FormItem>(); formItems.Add(new FormItem("js_code", content)); if (_options.CompilationLevel == CompilationLevel.Advanced && (_commonExternsDependencies.Count > 0 || externsDependencies.Count > 0)) { allExternsDependencies.AddRange(_commonExternsDependencies); foreach (Dependency externsDependency in externsDependencies) { if (!_commonExternsDependencies.ContainsUrl(externsDependency.Url)) { allExternsDependencies.Add(externsDependency); } } foreach (Dependency externsDependency in allExternsDependencies) { formItems.Add(new FormItem("js_externs", externsDependency.Content)); } } formItems.AddRange(_optionsFormItems); HttpContent httpContent = new CustomFormUrlEncodedContent(formItems); using (var client = new HttpClient()) { HttpResponseMessage response; try { response = client .PostAsync(new Uri(_closureCompilerServiceUrl), httpContent) .Result ; } catch (AggregateException e) { Exception innerException = e.InnerException; if (innerException != null) { if (innerException is HttpRequestException) { throw new Exception( string.Format(Strings.Minifiers_ClosureRemoteMinificationHttpRequestError, _closureCompilerServiceUrl), innerException); } throw innerException; } throw; } if (response.IsSuccessStatusCode) { var result = response.Content.ReadAsStringAsync().Result; var json = JObject.Parse(result); var serverErrors = json["serverErrors"] != null ? json["serverErrors"] as JArray : null; if (serverErrors != null && serverErrors.Count > 0) { throw new ClosureCompilationException( FormatErrorDetails(serverErrors[0], ErrorType.ServerError, path, allExternsDependencies) ); } var errors = json["errors"] != null ? json["errors"] as JArray : null; if (errors != null && errors.Count > 0) { throw new ClosureCompilationException( FormatErrorDetails(errors[0], ErrorType.Error, path, allExternsDependencies) ); } if (_options.Severity > 0) { var warnings = json["warnings"] != null ? json["warnings"] as JArray : null; if (warnings != null && warnings.Count > 0) { throw new ClosureCompilationException( FormatErrorDetails(warnings[0], ErrorType.Warning, path, allExternsDependencies) ); } } newContent = json.Value <string>("compiledCode"); } else { throw new AssetMinificationException( string.Format(Strings.Minifiers_ClosureRemoteMinificationInvalidHttpStatus, response.StatusCode)); } } return(newContent); }
public static DependencyCollection AddPool <T>(this DependencyCollection collection, T[] buffer) where T : class { collection.AddInstance <IPool <T> >(new Pool <T>(buffer)); return(collection); }
public void Throw_Activate_NotRegistered() { var provider = new DependencyCollection().BuildProvider(); Assert.Throws <KeyNotFoundException>(() => provider.Activate <FooRepository>()); }
/// <summary> /// Generates a detailed error message /// </summary> /// <param name="errorDetails">Error details</param> /// <param name="errorType">Error type</param> /// <param name="currentFilePath">Current file path</param> /// <param name="externsDependencies">List of JS externs dependencies</param> /// <returns>Detailed error message</returns> private static string FormatErrorDetails(JToken errorDetails, ErrorType errorType, string currentFilePath, DependencyCollection externsDependencies) { var errorMessageBuilder = new StringBuilder(); if (errorType == ErrorType.ServerError || errorType == ErrorType.Error) { errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Message, errorDetails.Value <string>("error")); } else if (errorType == ErrorType.Warning) { errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Message, errorDetails.Value <string>("warning")); } if (errorDetails["code"] != null) { errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_ErrorCode, errorDetails.Value <string>("code")); } if (errorDetails["type"] != null) { errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_Subcategory, errorDetails.Value <string>("type")); } if (errorDetails["file"] != null) { string filePath = null; string file = errorDetails.Value <string>("file"); Match errorFileMatch = _errorFileRegex.Match(file); if (errorFileMatch.Success) { GroupCollection errorFileGroups = errorFileMatch.Groups; string fileType = errorFileGroups["fileType"].Value; int fileIndex = int.Parse(errorFileGroups["fileIndex"].Value); if (string.Equals(fileType, "Externs", StringComparison.OrdinalIgnoreCase)) { Dependency externsDependency; try { externsDependency = externsDependencies[fileIndex]; } catch (ArgumentOutOfRangeException) { externsDependency = null; } if (externsDependency != null) { filePath = externsDependency.Url; } } } if (string.IsNullOrEmpty(filePath)) { filePath = currentFilePath; } errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_File, filePath); } if (errorDetails["lineno"] != null) { errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_LineNumber, errorDetails.Value <int>("lineno").ToString(CultureInfo.InvariantCulture)); } if (errorDetails["charno"] != null) { errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_ColumnNumber, errorDetails.Value <int>("charno").ToString(CultureInfo.InvariantCulture)); } if (errorDetails["line"] != null) { errorMessageBuilder.AppendFormatLine("{0}: {1}", CoreStrings.ErrorDetails_LineSource, errorDetails.Value <string>("line")); } return(errorMessageBuilder.ToString()); }
public LoggingInstallerShould() { _dependencies = new DependencyCollection() .AddLogWriter(Mock.Of <ILogWriter>()); }
/// <summary> /// Constructs a instance of Closure Compiler /// </summary> /// <param name="commonExternsDependencies">List of common JS externs dependencies</param> protected ClosureJsCompilerBase(DependencyCollection commonExternsDependencies) { _commonExternsDependencies = commonExternsDependencies; }
static async Task MainAsync(string[] args) { Console.WriteLine(Directory.GetCurrentDirectory()); var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("settings.json", optional: true, reloadOnChange: true).Build(); var discordToken = builder["Discord:Token"].ToString(); var challongeToken = builder["Challonge:Token"].ToString(); var restUrl = builder["REST:Url"].ToString(); var restUser = builder["REST:User"].ToString(); var restPassword = builder["REST:Password"].ToString(); Console.WriteLine($"LaDOSE.Net Discord Bot"); discord = new DiscordClient(new DiscordConfiguration { Token = discordToken, TokenType = TokenType.Bot }); discord.UseInteractivity(new InteractivityConfiguration { // default pagination behaviour to just ignore the reactions PaginationBehaviour = TimeoutBehaviour.Ignore, // default pagination timeout to 5 minutes PaginationTimeout = TimeSpan.FromMinutes(5), // default timeout for other actions to 2 minutes Timeout = TimeSpan.FromMinutes(2) }); var webService = new WebService(new Uri(restUrl), restUser, restPassword); //var challongeService = new ChallongeService(challongeToken); var cts = new CancellationTokenSource(); DependencyCollection dep = null; using (var d = new DependencyCollectionBuilder()) { d.AddInstance(new Dependencies() { Cts = cts, //ChallongeService = challongeService, WebService = webService }); dep = d.Build(); } var _cnext = discord.UseCommandsNext(new CommandsNextConfiguration() { CaseSensitive = false, EnableDefaultHelp = true, EnableDms = false, EnableMentionPrefix = true, StringPrefix = "!", IgnoreExtraArguments = true, Dependencies = dep }); _cnext.RegisterCommands <Result>(); _cnext.RegisterCommands <Twitch>(); _cnext.RegisterCommands <Shutdown>(); _cnext.RegisterCommands <Todo>(); _cnext.RegisterCommands <Hokuto>(); //discord.MessageCreated += async e => //{ // if (e.Message.Content.ToLower().Equals("!result")) // await e.Message.RespondAsync("Les Résultats du dernier Ranking : XXXX"); // if (e.Message.Content.ToLower().Equals("!twitch")) // await e.Message.RespondAsync("https://www.twitch.tv/LaDOSETV"); //}; discord.GuildMemberAdded += async e => { Console.WriteLine($"{e.Member.DisplayName} Joined"); await Task.Delay(0); //await e.Guild.GetDefaultChannel().SendMessageAsync($"Bonjour!"); }; await discord.ConnectAsync(); while (!cts.IsCancellationRequested) { await Task.Delay(200); } }
public Bot() { if (!File.Exists("config.json")) { new Config().SaveToFile("config.json"); #region !! Report to user that config has not been set yet !! (aesthetics) Console.BackgroundColor = ConsoleColor.Red; Console.ForegroundColor = ConsoleColor.Black; WriteCenter("▒▒▒▒▒▒▒▒▒▄▄▄▄▒▒▒▒▒▒▒", 2); WriteCenter("▒▒▒▒▒▒▄▀▀▓▓▓▀█▒▒▒▒▒▒"); WriteCenter("▒▒▒▒▄▀▓▓▄██████▄▒▒▒▒"); WriteCenter("▒▒▒▄█▄█▀░░▄░▄░█▀▒▒▒▒"); WriteCenter("▒▒▄▀░██▄░░▀░▀░▀▄▒▒▒▒"); WriteCenter("▒▒▀▄░░▀░▄█▄▄░░▄█▄▒▒▒"); WriteCenter("▒▒▒▒▀█▄▄░░▀▀▀█▀▒▒▒▒▒"); WriteCenter("▒▒▒▄▀▓▓▓▀██▀▀█▄▀▀▄▒▒"); WriteCenter("▒▒█▓▓▄▀▀▀▄█▄▓▓▀█░█▒▒"); WriteCenter("▒▒▀▄█░░░░░█▀▀▄▄▀█▒▒▒"); WriteCenter("▒▒▒▄▀▀▄▄▄██▄▄█▀▓▓█▒▒"); WriteCenter("▒▒█▀▓█████████▓▓▓█▒▒"); WriteCenter("▒▒█▓▓██▀▀▀▒▒▒▀▄▄█▀▒▒"); WriteCenter("▒▒▒▀▀▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒"); Console.BackgroundColor = ConsoleColor.Yellow; WriteCenter("WARNING", 3); Console.ResetColor(); WriteCenter("Thank you Mario!", 1); WriteCenter("But our config.json is in another castle!"); WriteCenter("(Please fill in the config.json that was generated.)", 2); WriteCenter("Press any key to exit..", 1); Console.SetCursorPosition(0, 0); Console.ReadKey(); #endregion Environment.Exit(0); } this._config = Config.LoadFromFile("config.json"); _client = new DiscordClient(new DiscordConfiguration() { AutoReconnect = true, EnableCompression = true, LogLevel = LogLevel.Debug, Token = _config.Token, TokenType = TokenType.Bot, UseInternalLogHandler = true }); _interactivity = _client.UseInteractivity(new InteractivityConfiguration() { PaginationBehaviour = TimeoutBehaviour.Delete, PaginationTimeout = TimeSpan.FromSeconds(30), Timeout = TimeSpan.FromSeconds(30) }); _starttimes = new StartTimes() { BotStart = DateTime.Now, SocketStart = DateTime.MinValue }; _cts = new CancellationTokenSource(); DependencyCollection dep = null; using (var d = new DependencyCollectionBuilder()) { d.AddInstance(new Dependencies() { Interactivity = this._interactivity, StartTimes = this._starttimes, Cts = this._cts, Config = this._config }); dep = d.Build(); } _cnext = _client.UseCommandsNext(new CommandsNextConfiguration() { CaseSensitive = false, EnableDefaultHelp = true, EnableDms = false, EnableMentionPrefix = true, StringPrefix = _config.Prefix, IgnoreExtraArguments = true, Dependencies = dep }); _cnext.RegisterCommands <Commands.Owner>(); _cnext.RegisterCommands <Commands.Interactivity>(); _cnext.RegisterCommands <Commands.Werewolve.Signup>(); _client.Ready += OnReadyAsync; }
public void is_valid_happy_path_with_ctor_checks() { // This class needs all three of these things var dependencies = new DependencyCollection(); dependencies.Add("name", "Jeremy"); dependencies.Add("age", 40); dependencies.Add("isAwake", true); ConcreteType.BuildSource(typeof (GuyWithPrimitives), null, dependencies, Policies.Default()) .IsValid().ShouldBeTrue(); }
/// <summary> /// Resolves add-in dependencies. /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="addins"> /// List of add-ins to check /// </param> /// <param name="resolved"> /// Packages that need to be installed. /// </param> /// <param name="toUninstall"> /// Packages that need to be uninstalled. /// </param> /// <param name="unresolved"> /// Add-in dependencies that could not be resolved. /// </param> /// <returns> /// True if all dependencies could be resolved. /// </returns> /// <remarks> /// This method can be used to get a list of all packages that have to be installed in order to install /// an add-in or set of add-ins. The list of packages to install will include the package that provides the /// add-in, and all packages that provide the add-in dependencies. In some cases, packages may need to /// be installed (for example, when an installed add-in needs to be upgraded). /// </remarks> public bool ResolveDependencies(IProgressStatus statusMonitor, AddinRepositoryEntry[] addins, out PackageCollection resolved, out PackageCollection toUninstall, out DependencyCollection unresolved) { return(store.ResolveDependencies(statusMonitor, addins, out resolved, out toUninstall, out unresolved)); }
/// <summary> /// Resolves add-in dependencies. /// </summary> /// <param name="statusMonitor"> /// Progress monitor where to show progress status /// </param> /// <param name="packages"> /// Packages that need to be installed. /// </param> /// <param name="toUninstall"> /// Packages that need to be uninstalled. /// </param> /// <param name="unresolved"> /// Add-in dependencies that could not be resolved. /// </param> /// <returns> /// True if all dependencies could be resolved. /// </returns> /// <remarks> /// This method can be used to get a list of all packages that have to be installed in order to satisfy /// the dependencies of a package or set of packages. The 'packages' argument must have the list of packages /// to be resolved. When resolving dependencies, if there is any additional package that needs to be installed, /// it will be added to the same 'packages' collection. In some cases, packages may need to /// be installed (for example, when an installed add-in needs to be upgraded). Those packages will be added /// to the 'toUninstall' collection. Packages that could not be resolved are added to the 'unresolved' /// collection. /// </remarks> public bool ResolveDependencies(IProgressStatus statusMonitor, PackageCollection packages, out PackageCollection toUninstall, out DependencyCollection unresolved) { return(store.ResolveDependencies(statusMonitor, packages, out toUninstall, out unresolved)); }
void InitBot(string[] args) { try { Console.WriteLine("[info] Welcome to my bot!"); _cts = new CancellationTokenSource(); // Load the config file(we'll create this shortly) Console.WriteLine("[info] Loading config file.."); _config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config.json", optional: false, reloadOnChange: true) .Build(); // Create the DSharpPlus client Console.WriteLine("[info] Creating discord client.."); _discord = new DiscordClient(new DiscordConfiguration { Token = _config.GetValue <string>("discord:token"), TokenType = TokenType.Bot }); // Create the interactivity module(I'll show you how to use this later on) _interactivity = _discord.UseInteractivity(new InteractivityConfiguration() { PaginationBehaviour = TimeoutBehaviour.Delete, // What to do when a pagination request times out PaginationTimeout = TimeSpan.FromSeconds(30), // How long to wait before timing out Timeout = TimeSpan.FromSeconds(30) // Default time to wait for interactive commands like waiting for a message or a reaction }); // Build dependancies and then create the commands module. DependencyCollection deps = BuildDeps(); _commands = _discord.UseCommandsNext(new CommandsNextConfiguration { StringPrefix = _config.GetValue <string>("discord:CommandPrefix"), // Load the command prefix(what comes before the command, eg "!" or "/") from our config file Dependencies = deps // Pass the dependancies }); // TODO: Add command loading! Console.WriteLine("[info] Loading command modules.."); Type type = typeof(IModule); // Get the type of our interface IEnumerable <Type> types = AppDomain.CurrentDomain.GetAssemblies() // Get the assemblies associated with our project .SelectMany(s => s.GetTypes()) // Get all the types .Where(p => type.IsAssignableFrom(p) && !p.IsInterface); // Filter to find any type that can be assigned to an IModule Type[] typeList = types as Type[] ?? types.ToArray(); // Convert to an array foreach (Type t in typeList) { _commands.RegisterCommands(t); // Loop through the list and register each command module with CommandsNext } Console.WriteLine($"[info] Loaded {typeList.Count()} modules."); RunAsync(args).Wait(); } catch (Exception ex) { // This will catch any exceptions that occur during the operation/setup of your bot. // Feel free to replace this with what ever logging solution you'd like to use. // I may do a guide later on the basic logger I implemented in my most recent bot. Console.Error.WriteLine(ex.ToString()); } }
/// <summary> /// Converts a list of dependencies to JSON /// </summary> /// <param name="dependencies">List of dependencies</param> /// <returns>List of dependencies in JSON format</returns> private static JArray ConvertDependenciesToJson(DependencyCollection dependencies) { var dependenciesJson = new JArray( dependencies .Where(d => d.Content != null) .Select(d => new JObject( new JProperty("path", d.Url), new JProperty("content", d.Content)) ) ); return dependenciesJson; }
internal override void Resolve(IProgressMonitor monitor, AddinStore service, PackageCollection toInstall, PackageCollection toUninstall, PackageCollection installedRequired, DependencyCollection unresolved) { Addin ia = service.Registry.GetAddin(Mono.Addins.Addin.GetIdName(info.Id)); if (ia != null) { Package p = AddinPackage.FromInstalledAddin(ia); if (!toUninstall.Contains(p)) { toUninstall.Add(p); } if (!info.SupportsVersion(ia.Version)) { // This addin breaks the api of the currently installed one, // it has to be removed, together with all dependencies Addin[] ainfos = service.GetDependentAddins(info.Id, true); foreach (Addin ainfo in ainfos) { p = AddinPackage.FromInstalledAddin(ainfo); if (!toUninstall.Contains(p)) { toUninstall.Add(p); } } } } foreach (Dependency dep in info.Dependencies) { service.ResolveDependency(monitor, dep, this, toInstall, toUninstall, installedRequired, unresolved); } }
private DependencyCollection combineDependencies() { var dependencies = new DependencyCollection(_configuredDependencies); Projects.Each(p => dependencies.AddChild(p.Dependencies)); return dependencies; }
/// <summary> /// Fills a list of virtual paths to other files required by the primary asset /// </summary> /// <param name="asset">Asset</param> /// <param name="commonExternsDependencies">List of common JS externs dependencies</param> /// <param name="assetExternsDependencies">List of asset JS externs dependencies</param> protected static void FillAssetVirtualPathDependencies(IAsset asset, DependencyCollection commonExternsDependencies, DependencyCollection assetExternsDependencies) { var paths = new List <string>(); paths.AddRange(asset.VirtualPathDependencies); if (commonExternsDependencies.Count > 0) { paths.AddRange(commonExternsDependencies .Where(d => d.IsObservable) .Select(d => d.Url) .ToList() ); } if (assetExternsDependencies.Count > 0) { paths.AddRange(assetExternsDependencies .Where(d => d.IsObservable) .Select(d => d.Url) .ToList() ); } paths = paths .Distinct(StringComparer.OrdinalIgnoreCase) .ToList() ; asset.VirtualPathDependencies = paths; }