public void Check(ConstructorInfo info, Dependency parent) { if (info.IsPrivate && !info.ReflectedType.IsAbstract) { parent.Add(new ProblemDependency(string.Format("This is a private constructor"))); } }
public void SpecialVersionConstraintsWithBranch() { var dep = new Dependency("@cba_a3->=1.0.0.4-beta"); dep.Name.Should().Be("@cba_a3"); dep.Version.Should().Be(">=1.0.0.4"); dep.Branch.Should().Be("beta"); }
public void SpecialVersion() { var dep = new Dependency("@cba_a3-1983.12.24"); dep.Name.Should().Be("@cba_a3"); dep.Version.Should().Be("1983.12.24"); dep.Branch.Should().BeNull(); }
public void SpecialName2() { var dep = new Dependency("@cba_a3-xx-1-1-1.0.2-beta"); dep.Name.Should().Be("@cba_a3-xx-1-1"); dep.Version.Should().Be("1.0.2"); dep.Branch.Should().Be("beta"); }
public void JustName() { var dep = new Dependency("@cba_a3"); dep.Name.Should().Be("@cba_a3"); dep.Version.Should().BeNull(); dep.Branch.Should().BeNull(); }
public void CollectsAllBindingsAndLoadsThemDistinctOnKernel() { var loadedModules = new List<INinjectModule>(); A.CallTo(() => this.kernel.Load(A<IEnumerable<INinjectModule>>._)) .Invokes((IEnumerable<INinjectModule> modules) => loadedModules.AddRange(modules)); var dependencyA = new DependencyA(); var dependencyB = new DependencyB(); var dependencyDefinitionA = new Dependency<IDependencyA>(bind => bind.ToConstant(dependencyA).InTransientScope()); var dependencyDefinitionB = new Dependency<IDependencyB>(bind => bind.ToConstant(dependencyB).InSingletonScope()); this.testee.Load( new FeatureA( dependencyDefinitionA, dependencyDefinitionB), new FeatureB( dependencyDefinitionA, dependencyDefinitionB), new FeatureC()); loadedModules.Select(_ => _.GetType().Name) .Should().Contain( new[] { typeof(ModuleA), typeof(ModuleB), typeof(ModuleC), typeof(ModuleD) }.Select(_ => _.Name)) .And.BeEquivalentTo(loadedModules.Select(_ => _.GetType().Name).Distinct()); }
/// <summary> /// 注册依赖服务对象 /// </summary> /// <param name="dependency">依赖服务对象</param> /// <exception cref="ArgumentNullException"></exception> public void RegisterDependency(Dependency dependency) { if (dependency == null) throw new ArgumentNullException(nameof(dependency)); _container.Add(dependency); }
public void Standard() { var dep = new Dependency("@cba_a3-1.0.0.4"); dep.Name.Should().Be("@cba_a3"); dep.Version.Should().Be("1.0.0.4"); dep.Branch.Should().BeNull(); }
public void IsMajorConflict_returns_false_for_identical_version_numbers() { var dependency = new Dependency(); dependency.LibAssembly = GetNewAssemblyNameWithVersion(1, 2, 3, 4); dependency.ReferencedAssembly = GetNewAssemblyNameWithVersion(1, 2, 3, 4); Assert.That(dependency.IsMajorConflict, Is.False, "should not report a conflict if the version numbers are identical"); }
public void Check(FieldInfo info, Dependency parent) { // Dependency parent = new Dependency(info.); bool isInterface = info.FieldType.IsInterface; bool isAbstract = info.FieldType.IsAbstract; bool isNotSealed = !info.FieldType.IsSealed; string message = ""; if (isInterface) { message = string.Format("Field {0} is interface {1}", info.Name, info.FieldType.Name); } else if (isAbstract) { message = string.Format("Field {0} is an abstract class {1} and can be inherited from", info.Name,info.FieldType.Name); } else if (isNotSealed) { message = string.Format("Field {0} is non sealed {1} and can be inherited from", info.Name, info.FieldType.Name); } parent.Add(new Dependency(message)); // if (parent.AlreadyContains(info.FieldType)) // { // parent.Add(new Dependency(message)); // } // else // { // parent.Add(new Dependency(info.FieldType, message)); // } }
public void Check(MethodInfo info, Dependency parent) { if (!info.IsFinal && (info.IsVirtual || info.IsAbstract)) { parent.Add(new Dependency(string.Format(" {0}() can be overriden", info.Name))); } }
public static SqlServerDocumentDbRegistration RegisterSqlServerDocumentDb (this IWindsorContainer @this, SqlServerDocumentDbRegistration registration, string connectionName, Dependency sessionInterceptor = null) { Contract.Requires(registration != null); Contract.Requires(!connectionName.IsNullOrWhiteSpace()); //We don't want to get any old interceptor that might have been registered by someone else. sessionInterceptor = sessionInterceptor ?? Dependency.OnValue<IDocumentDbSessionInterceptor>(NullOpDocumentDbSessionInterceptor.Instance); var connectionString = Dependency.OnValue(typeof(string),@this.Resolve<IConnectionStringProvider>().GetConnectionString(connectionName).ConnectionString); @this.Register( Component.For<IDocumentDb>() .ImplementedBy<SqlServerDocumentDb>() .DependsOn(connectionString) .LifestylePerWebRequest() .Named(registration.DocumentDbName), Component.For(Seq.OfTypes<IDocumentDbSession, IDocumentDbUpdater, IDocumentDbReader, IDocumentDbBulkReader, IUnitOfWorkParticipant, IDocumentUpdatedNotifier>()) .ImplementedBy<DocumentDbSession>() .DependsOn(registration.DocumentDb, sessionInterceptor) .LifestylePerWebRequest() .Named(registration.SessionName) ); @this.WhenTesting() .ReplaceDocumentDb(registration.DocumentDbName); return registration; }
private object ConvertIdentifier( object value, Item item, Direction direction, Guid providerId, string itemType) { if (value != null && !string.IsNullOrWhiteSpace(value.ToString())) { if (direction == Direction.Packaging) { var guid = Dependencies.ConvertIdentifier(value.ToString(), IdentifierReplaceDirection.FromNodeIdToGuid); // add dependency for the item var name = string.Concat(itemType, " from picker"); var dependency = new Dependency(name, guid, providerId); item.Dependencies.Add(dependency); return guid; } else if (direction == Direction.Extracting) { return Dependencies.ConvertIdentifier(value.ToString(), IdentifierReplaceDirection.FromGuidToNodeId); } } return value; }
protected override void Before_each_spec() { packageTree = CreateStub<IPackageTree>(); dependency = new Dependency("Test", "Test"); updater = CreateStub<IDependentUpdater>(); dependencyPaths = new List<string>(); executor = new DependentUpdaterExecutor(new[] { updater }); }
public void IsMajorConflict_returns_true_for_version_numbers_with_1st_number_different() { var dependency = new Dependency(); dependency.LibAssembly = GetNewAssemblyNameWithVersion(2, 2, 3, 8); dependency.ReferencedAssembly = GetNewAssemblyNameWithVersion(1, 2, 3, 8); Assert.That(dependency.IsMajorConflict, Is.True, "should report a conflict if the version number 1st number is different"); }
public void IsMajorConflict_returns_false_for_version_numbers_with_only_3rd_and_4th_number_different() { var dependency = new Dependency(); dependency.LibAssembly = GetNewAssemblyNameWithVersion(1, 2, 5, 4); dependency.ReferencedAssembly = GetNewAssemblyNameWithVersion(1, 2, 3, 8); Assert.That(dependency.IsMajorConflict, Is.False, "should not report a conflict if the version numbers are same except for 3rd and 4th numbers"); }
public void IsConflicted_returns_true_for_conflict_of_nonbreaking_change_number() { var dependency = new Dependency(); dependency.LibAssembly = GetNewAssemblyNameWithVersion(1, 2, 5, 4); dependency.ReferencedAssembly = GetNewAssemblyNameWithVersion(1, 2, 3, 4); Assert.That(dependency.IsConflicted, Is.True, "should report a minor conflict if the version numbers are not the same"); }
public static void Composition() { var dependency = new Dependency(); var thing = new Thing(dependency); var relyOnThing = new RelyOnThing(thing); }
public static CacheDependency Get( string key ) { Dependency dep = new Dependency(key); lock (deps) { deps.Add(dep); } return dep; }
public void Cannot_figure_out_how_to_map_a_registered_concrete_list_to_an_interface() { var dependency = new Dependency(); var list = new List<Dependency>(); list.Add(dependency); mocker.SetInstance(list); var thing = mocker.Create<ThingThatHasDependencies>(); thing.FindOne().ShouldBeNull(); }
public void Can_register_and_resolve_a_list_with_an_explicit_type_provided_to_SetInstance() { var dependency = new Dependency(); var list = new List<Dependency>(); list.Add(dependency); mocker.SetInstance<IList<Dependency>>(list); var thing = mocker.Create<ThingThatHasDependencies>(); thing.FindOne().ShouldBeSameAs(dependency); }
public void Can_register_and_resolve_a_list_using_the_declared_type() { var dependency = new Dependency(); IList<Dependency> list = new List<Dependency>(); list.Add(dependency); mocker.SetInstance(list); var thing = mocker.Create<ThingThatHasDependencies>(); thing.FindOne().ShouldBeSameAs(dependency); }
public static OutputEntry FindMatch(List<Rule> rules, Dependency dep) { foreach (var rule in rules) { var match = rule.Process(dep); if (match != null) return match; } return null; }
private static void Validate(Dependency[] parsedDependencies) { parsedDependencies.ToList().ForEach(d => { var branch = GetDependencyBranch(d, parsedDependencies); branch.ToList() .ForEach(currentTask => { if (TaskOccursMoreThanOnce(branch, currentTask)) throw new CyclicDependencyException(); }); }); }
public void DealsWithDependencies() { var dependencyInstance = new Dependency(); var container = new SimpleContainer(); container.RegisterInstance<Dependency>(dependencyInstance); var policy = new TransientLifetimePolicy(typeof(Target), container); var instance = policy.GetInstance() as Target; Assert.IsNotNull(instance); Assert.AreEqual(dependencyInstance, instance.Dependency); }
private void nugets(XElement document, Solution solution) { var nugets = document.Element("Nugets"); if (nugets == null) return; foreach (var depElement in nugets.Descendants()) { var dependency = new Dependency(); fillProperties(depElement, dependency); solution.AddDependency(dependency); } }
public void Build(ref Job job) { PerfTimer hpt = new PerfTimer(); hpt.Start(); try { if (job.Modules.ContainsKey(job.JobName)) { root = new Dependency<IModule>((IModule)job.Modules[job.JobName], job.JobName); job.Dependencies.Add(root.Name.Trim(), root); foreach (string key in job.OrderedModuleList) { if (key.Equals(job.JobName)) { continue; } IModule m = (IModule)job.Modules[key]; Dependency<IModule> d = new Dependency<IModule>(m, m.Name); if (m.Inputs == null) { root.Children.AddDependency(d); job.Dependencies.Add(d.Name.Trim(), d); } else { foreach (string s in m.Inputs) { if (job.Dependencies.ContainsKey(s.Trim())) { ((Dependency<IModule>)job.Dependencies[s.Trim()]).Children.AddDependency(d); } } job.Dependencies.Add(d.Name.Trim(), d); } } } } catch (Exception ex) { log.Error(ex); } hpt.Stop(); log.InfoFormat("Building job {0} took {1} seconds.", job.JobName, hpt.Duration); }
protected override void DoChecks(MethodBase mehodBeingChecked, MethodBodyInfo methodBody, Dependency parent) { foreach (ILInstruction instruction in methodBody.Instructions) { if (instruction is InlineMethodInstruction) { InlineMethodInstruction line = instruction as InlineMethodInstruction; if (line.Method.IsVirtual) { parent.Add(new VirtualMethodCallDependency(line.Method.ReflectedType.Name, line.Method.Name)); } } } }
/// <summary> /// 添加依赖服务对象到容器中 /// </summary> /// <param name="dependency">依赖服务对象</param> /// <exception cref="ArgumentNullException"></exception> public void Add(Dependency dependency) { if (dependency == null) throw new ArgumentNullException(nameof(dependency)); lock (_sync) { var serviceType = dependency.ServiceType; if (_dependencyDictionary.ContainsKey(serviceType)) { _dependencyDictionary[serviceType].Add(dependency); } else { _dependencyDictionary.Add(serviceType, dependency); } } }
private static string[] GetDependencyBranch(Dependency dependency, Dependency[] parsedDependencies) { var branch = new List<string> { dependency.SecondTask }; var nextDependency = parsedDependencies.SingleOrDefault(d => d.SecondTask == dependency.FirstTask); var dependencyCount = 0; while (nextDependency != null && dependencyCount < parsedDependencies.Count()) { var currDependency = nextDependency; branch.Add(currDependency.SecondTask); nextDependency = parsedDependencies.SingleOrDefault(d => d.SecondTask == currDependency.FirstTask); dependencyCount++; } return branch.ToArray(); }
// method: determine whether the given Dependency is met // public static bool isMet(this Dependency dependency) => (dependency.requisite ? (dependency.requisite.state() == dependency.requisition.asBoolean()) : false.returnWithError("dependency requisite not given") );
private static void DependencyHandler_OnDependencyRemoved(DependencyHandler handler, Dependency dependency) { // Handle deletion of the dependency in question // That would include removing it from the config.SharedDir, removing it from Android.mk, removing it from bmbfmod.json var mk = androidMkProvider.GetFile(); if (mk != null) { // Remove module mk.Modules.RemoveAll(m => m.Id.Equals(dependency.Id, StringComparison.OrdinalIgnoreCase)); // Main module, remove shared library var module = mk.Modules.LastOrDefault(); if (module != null) { module.RemoveSharedLibrary(dependency.Id); } } // TODO: Remove from bmbfmod.json var cfg = configProvider.GetConfig(); // If we have it in our met dependencies if (cfg != null) { resolver.RemoveDependency(cfg, dependency); } }
static UserRepository() { isPublicDemo = Dependency.Resolve <IConfigurationManager>() .AppSetting("IsPublicDemo", typeof(string)) as string == "1"; }
public override IDependency BeforeAdd( string projectPath, ITargetFramework targetFramework, IDependency dependency, ImmutableDictionary <string, IDependency> .Builder worldBuilder, IReadOnlyDictionary <string, IProjectDependenciesSubTreeProvider> subTreeProviderByProviderType, IImmutableSet <string> projectItemSpecs, out bool filterAnyChanges) { filterAnyChanges = false; if (!dependency.TopLevel) { return(dependency); } if (dependency.Flags.Contains(DependencyTreeFlags.SdkSubTreeNodeFlags)) { // This is an SDK dependency. // // Try to find a package dependency with the same name. string packageId = Dependency.GetID(targetFramework, PackageRuleHandler.ProviderTypeString, modelId: dependency.Name); if (worldBuilder.TryGetValue(packageId, out IDependency package) && package.Resolved) { // Set to resolved, and copy dependencies. filterAnyChanges = true; return(dependency.ToResolved( schemaName: ResolvedSdkReference.SchemaName, dependencyIDs: package.DependencyIDs)); } } else if (dependency.Flags.Contains(DependencyTreeFlags.PackageNodeFlags) && dependency.Resolved) { // This is a package dependency. // // Try to find an SDK dependency with the same name. string sdkId = Dependency.GetID(targetFramework, SdkRuleHandler.ProviderTypeString, modelId: dependency.Name); if (worldBuilder.TryGetValue(sdkId, out IDependency sdk)) { // We have an SDK dependency for this package. Such dependencies, when implicit, are created // as unresolved by SdkRuleHandler, and are only marked resolved here once we have resolved the // corresponding package. // // Set to resolved, and copy dependencies. filterAnyChanges = true; sdk = sdk.ToResolved( schemaName: ResolvedSdkReference.SchemaName, dependencyIDs: dependency.DependencyIDs); worldBuilder[sdk.Id] = sdk; } } return(dependency); }
internal static bool MatchGalleryAppDependencies(Dependency dependency, string[] dependencyIds) { List <Dependency> nested = null; // Web PI ver. 0.2 if (dependency.LogicalAnd.Count > 0) { nested = dependency.LogicalAnd; } else if (dependency.LogicalOr.Count > 0) { nested = dependency.LogicalOr; } // Web PI ver. 2.0.1.0 else if (dependency.And.Count > 0) { nested = dependency.And; } else if (dependency.Or.Count > 0) { nested = dependency.Or; } if (nested != null) { // Check LogicalAnd conditions if (nested == dependency.LogicalAnd || nested == dependency.And) { foreach (Dependency ndep in nested) { if (!MatchGalleryAppDependencies(ndep, dependencyIds)) { return(false); } } // return(true); } // if (nested == dependency.LogicalOr || nested == dependency.Or) { bool matchOK = false; // foreach (Dependency ndep in nested) { if (MatchGalleryAppDependencies(ndep, dependencyIds)) { matchOK = true; } } // return(matchOK); } } // Non-empty dependencies should be filtered out if do not match if (!String.IsNullOrEmpty(dependency.ProductId)) { return(Array.Exists <string>(dependencyIds, x => String.Equals(x, dependency.ProductId, StringComparison.InvariantCultureIgnoreCase))); } // Empty dependencies always match everything return(true); }
public static void Main(string[] args) { // replace these options with your satellite and api key var tracerOptions = new Options("TEST_TOKEN").WithSatellite(new SatelliteOptions("localhost", 9996, true)); var container = new WindsorContainer(); // during registration, pass your options to the concrete LightStep Tracer implementation container.Register(Component.For <ITracer>().ImplementedBy <Tracer>().DependsOn(Dependency.OnValue("options", tracerOptions))); var tracer = container.Resolve <ITracer>(); // create some spans for (var i = 0; i < 500; i++) { using (var scope = tracer.BuildSpan("testParent").WithTag("testSpan", "true").StartActive(true)) { scope.Span.Log("test"); tracer.ActiveSpan.Log($"iteration {i}"); Console.WriteLine("sleeping for a bit"); Thread.Sleep(new Random().Next(5, 10)); var innerSpan = tracer.BuildSpan("childSpan").Start(); innerSpan.SetTag("innerTestTag", "true"); Console.WriteLine("sleeping more..."); Thread.Sleep(new Random().Next(10, 20)); innerSpan.Finish(); } } // note that OpenTracing.ITracer does not have flush as a method, so to manually flush you'll need to // get a cast of the tracer. Tracer t = (Tracer)tracer; t.Flush(); }
private Dependency CreateDependency(WorkingGraph graph, Item from, Item to, string pathMarker, bool isStart, bool isEnd, bool isMatchedByCountMatch, bool isLoopBack) { Dependency d = FromTo(graph, from, to); d.MarkPathElement(pathMarker, 0, isStart: isStart, isEnd: isEnd, isMatchedByCountSymbol: isMatchedByCountMatch, isLoopBack: isLoopBack); return d; }
public WindsorContainer Build() { var container = new WindsorContainer(); container.AddFacility <TypedFactoryFacility>(); container.Kernel.Resolver.AddSubResolver(new ArrayResolver(container.Kernel)); container.Register(Component.For <ITextFileReader>() .ImplementedBy <TextFileReader>()); container.Register(Component.For <ISpiral>() .ImplementedBy <Spiral>()); container.Register(Component.For <ICloudLayouter>() .ImplementedBy <CircularCloudLayouter>() .LifestyleTransient() ); container.Register(Component.For <IMapper <string, IEnumerable <string> > >() .ImplementedBy <TextSplitter>() ); container.Register( Component.For <IWordConverter>().ImplementedBy <ToLowerConverter>(), Component.For <IWordConverter>().ImplementedBy <BasicFormWordConverter>()); container.Register(Component.For <ITextPreprocessor>() .ImplementedBy <TextPreprocessor>()); container.Register(Component.For <IProvider <IEnumerable <string> > >() .ImplementedBy <StopWordsProvider>()); container.Register(Component.For <IProvider <IEnumerable <string> > >() .ImplementedBy <SourceWordsProvider>()); container.Register(Component.For <IWordFilter>() .ImplementedBy <StopWordFilter>()); container.Register(Component.For <IFrequencyWordsAnalyzer>() .ImplementedBy <FrequencyWordsAnalyzer>()); container.Register(Component.For <IImageSettings>() .ImplementedBy <ImageSettings>()); container.Register(Component.For <IFontSettings>() .ImplementedBy <FontSettings>()); container.Register(Component.For <ICloudSettings>() .ImplementedBy <CloudSettings>()); container.Register(Component.For <ITagsCloudCreator>() .ImplementedBy <TagsCloudCreator>() .DependsOn(Dependency.OnComponent <IProvider <IEnumerable <string> >, SourceWordsProvider>())); container.Register(Component.For <ITagsCloudVisualizer>() .ImplementedBy <TagsCloudVisualizer>()); container.Register(Component.For <IUserInterface>() .ImplementedBy <ConsoleUi>()); return(container); }
public List <Project> AnalyzeProject(string projectPath, bool runRestore, bool includeTransitiveDependencies, int transitiveDepth) { var dependencyGraph = _dependencyGraphService.GenerateDependencyGraph(projectPath); if (dependencyGraph == null) { return(null); } var projects = new List <Project>(); foreach (var packageSpec in dependencyGraph.Projects.Where(p => p.RestoreMetadata.ProjectStyle == ProjectStyle.PackageReference)) { // Restore the packages if (runRestore) { _dotNetRestoreService.Restore(packageSpec.FilePath); } // Load the lock file string lockFilePath = _fileSystem.Path.Combine(packageSpec.RestoreMetadata.OutputPath, "project.assets.json"); var lockFile = LockFileUtilities.GetLockFile(lockFilePath, NullLogger.Instance); // Create a project var project = new Project(packageSpec.Name, packageSpec.FilePath, packageSpec.RestoreMetadata.Sources.Select(s => s.SourceUri).ToList(), packageSpec.Version); projects.Add(project); // Get the target frameworks with their dependencies foreach (var targetFrameworkInformation in packageSpec.TargetFrameworks) { var targetFramework = new TargetFramework(targetFrameworkInformation.FrameworkName); project.TargetFrameworks.Add(targetFramework); var target = lockFile.Targets.FirstOrDefault(t => t.TargetFramework.Equals(targetFrameworkInformation.FrameworkName)); if (target != null) { foreach (var projectDependency in targetFrameworkInformation.Dependencies) { var projectLibrary = target.Libraries.FirstOrDefault(library => string.Equals(library.Name, projectDependency.Name, StringComparison.OrdinalIgnoreCase)); bool isDevelopmentDependency = false; if (projectLibrary != null) { // Determine whether this is a development dependency var packageIdentity = new PackageIdentity(projectLibrary.Name, projectLibrary.Version); var packageInfo = LocalFolderUtility.GetPackageV3(packageSpec.RestoreMetadata.PackagesPath, packageIdentity, NullLogger.Instance); if (packageInfo != null) { isDevelopmentDependency = packageInfo.GetReader().GetDevelopmentDependency(); } } var dependency = new Dependency(projectDependency.Name, projectDependency.LibraryRange.VersionRange, projectLibrary?.Version, projectDependency.AutoReferenced, false, isDevelopmentDependency); targetFramework.Dependencies.Add(dependency); // Process transitive dependencies for the library if (includeTransitiveDependencies) { AddDependencies(targetFramework, projectLibrary, target, 1, transitiveDepth); } } } } } return(projects); }
private async Task TryConnect() { Action <string> ConnectionFailed = message => ConnectionEstablished?.Invoke(this, ViewModelEventArgs.Error(message)); Action <string> ConnectionSuccessful = message => ConnectionEstablished?.Invoke(this, ViewModelEventArgs.Information(message)); if (string.IsNullOrWhiteSpace(address)) { ConnectionFailed("Please, fill in the Address of the device."); return; } if (string.IsNullOrWhiteSpace(port)) { port = "80"; } IsConnecting = true; var client = Dependency.Resolve <HttpClient>(); try { using (var body = new StringContent(Protocol.HelloMessage, Encoding.UTF8, "application/xml")) { using (var response = await client.PostAsync("http://" + address + ":" + port + "/", body)) { if (response.IsSuccessStatusCode) { var content = await response.Content.ReadAsStringAsync(); if (content != null) { if (content == Protocol.HelloReply) { var connection = Dependency.Resolve <Connection>(); connection.Address = address; connection.Port = Convert.ToInt32(port); HasConnection = true; ConnectionSuccessful("Success"); } else { ConnectionFailed("Device did not respond correctly. Error may be in the network."); } } else { ConnectionFailed("Device is not responding correctly."); } } else { ConnectionFailed("Connection was not properly established with the device."); } } } } catch (Exception ex) { ConnectionFailed("Device did not respond. Reason:\r\n" + ex.Message); } IsConnecting = false; }
internal static void WriteViolation(Dependency dependency) { Logger.WriteViolation(dependency, simpleRuleOutput: false); }
public override async Task ProcessAsync(TagHelperContext tagHelperContext, TagHelperOutput output) { var display = (DisplayHelper)_displayHelperFactory.CreateHelper(ViewContext); // Extract all attributes from the tag helper to var properties = output.Attributes .Where(x => !InternalProperties.Contains(x.Name)) .ToDictionary(x => LowerKebabToPascalCase(x.Name), x => (object)x.Value.ToString()) ; if (string.IsNullOrWhiteSpace(Type)) { Type = output.TagName; } if (string.IsNullOrWhiteSpace(Cache) && output.Attributes.ContainsName("cache-id")) { Cache = Convert.ToString(output.Attributes["cache-id"].Value); } if (string.IsNullOrWhiteSpace(Context) && output.Attributes.ContainsName("cache-context")) { Context = Convert.ToString(output.Attributes["cache-context"].Value); } if (string.IsNullOrWhiteSpace(Dependency) && output.Attributes.ContainsName("cache-dependency")) { Dependency = Convert.ToString(output.Attributes["cache-dependency"].Value); } if (string.IsNullOrWhiteSpace(Tag) && output.Attributes.ContainsName("cache-tag")) { Tag = Convert.ToString(output.Attributes["cache-tag"].Value); } if (!Duration.HasValue && output.Attributes.ContainsName("cache-duration")) { TimeSpan timespan; if (TimeSpan.TryParse(Convert.ToString(output.Attributes["cache-duration"].Value), out timespan)) { Duration = timespan; } } var shape = _shapeFactory.Create(Type, Arguments.From(properties)); if (!string.IsNullOrWhiteSpace(Cache)) { var metadata = shape.Metadata; metadata.Cache(Cache); if (Duration.HasValue) { metadata.Cache().During(Duration.Value); } if (!string.IsNullOrWhiteSpace(Context)) { var contexts = Context.Split(Separators, StringSplitOptions.RemoveEmptyEntries); metadata.Cache().AddContext(contexts); } if (!string.IsNullOrWhiteSpace(Tag)) { var tags = Tag.Split(Separators, StringSplitOptions.RemoveEmptyEntries); metadata.Cache().AddTag(tags); } if (!string.IsNullOrWhiteSpace(Dependency)) { var dependency = Dependency.Split(Separators, StringSplitOptions.RemoveEmptyEntries); metadata.Cache().AddDependency(dependency); } } output.Content.SetHtmlContent(await display.ShapeExecuteAsync(shape)); // We don't want any encapsulating tag around the shape output.TagName = null; }
/// <summary> /// Determine whether to replace a dependency with a new version. /// </summary> /// <param name="oldDependency">Previous version of the dependency.</param> /// <param name="newDependency">New version of the dependency.</param> /// <returns>true if the dependency should be replaced, false otherwise.</returns> public virtual bool ShouldReplaceDependency(Dependency oldDependency, Dependency newDependency) { return(false); }
public ModelBinder(Dependency dependency) { this.Dependency = dependency; }
private bool ValidateFirstTimeUser(ref string username, string password) { var throttler = new Throttler("ValidateUser:"******"Error on directory first time authentication", ex, this.GetType()); return(false); } try { string salt = null; var hash = UserRepository.GenerateHash(password, ref salt); var displayName = entry.FirstName + " " + entry.LastName; var email = entry.Email.TrimToNull() ?? (username + "@yourdefaultdomain.com"); username = entry.Username.TrimToNull() ?? username; using (var connection = SqlConnections.NewFor <UserRow>()) using (var uow = new UnitOfWork(connection)) { var fld = UserRow.Fields; var userId = (int?)new SqlInsert(fld.TableName) .Set(fld.Username, username) .Set(fld.Source, "ldap") .Set(fld.DisplayName, displayName) .Set(fld.Email, email) .Set(fld.PasswordHash, hash) .Set(fld.PasswordSalt, salt) .Set(fld.IsActive, 1) .Set(fld.InsertDate, DateTime.Now) .Set(fld.InsertUserId, 1) .Set(fld.LastDirectoryUpdate, DateTime.Now) .ExecuteAndGetID(connection); uow.Commit(); UserRetrieveService.RemoveCachedUser(userId, username); } return(true); } catch (Exception ex) { Log.Error("Error while importing directory user", ex, this.GetType()); return(false); } }
//<snippetGetSolutionDependencies7> /// <summary> /// Shows how to get a more friendly message based on information within the dependency /// <param name="dependency">A Dependency returned from the RetrieveDependentComponents message</param> /// </summary> public void DependencyReport(Dependency dependency) { //These strings represent parameters for the message. String dependentComponentName = ""; String dependentComponentTypeName = ""; String dependentComponentSolutionName = ""; String requiredComponentName = ""; String requiredComponentTypeName = ""; String requiredComponentSolutionName = ""; //The ComponentType global Option Set contains options for each possible component. RetrieveOptionSetRequest componentTypeRequest = new RetrieveOptionSetRequest { Name = "componenttype" }; RetrieveOptionSetResponse componentTypeResponse = (RetrieveOptionSetResponse)_serviceProxy.Execute(componentTypeRequest); OptionSetMetadata componentTypeOptionSet = (OptionSetMetadata)componentTypeResponse.OptionSetMetadata; // Match the Component type with the option value and get the label value of the option. foreach (OptionMetadata opt in componentTypeOptionSet.Options) { if (dependency.DependentComponentType.Value == opt.Value) { dependentComponentTypeName = opt.Label.UserLocalizedLabel.Label; } if (dependency.RequiredComponentType.Value == opt.Value) { requiredComponentTypeName = opt.Label.UserLocalizedLabel.Label; } } //The name or display name of the compoent is retrieved in different ways depending on the component type dependentComponentName = getComponentName(dependency.DependentComponentType.Value, (Guid)dependency.DependentComponentObjectId); requiredComponentName = getComponentName(dependency.RequiredComponentType.Value, (Guid)dependency.RequiredComponentObjectId); // Retrieve the friendly name for the dependent solution. Solution dependentSolution = (Solution)_serviceProxy.Retrieve ( Solution.EntityLogicalName, (Guid)dependency.DependentComponentBaseSolutionId, new ColumnSet("friendlyname") ); dependentComponentSolutionName = dependentSolution.FriendlyName; // Retrieve the friendly name for the required solution. Solution requiredSolution = (Solution)_serviceProxy.Retrieve ( Solution.EntityLogicalName, (Guid)dependency.RequiredComponentBaseSolutionId, new ColumnSet("friendlyname") ); requiredComponentSolutionName = requiredSolution.FriendlyName; //Display the message Console.WriteLine("The {0} {1} in the {2} depends on the {3} {4} in the {5} solution.", dependentComponentName, dependentComponentTypeName, dependentComponentSolutionName, requiredComponentName, requiredComponentTypeName, requiredComponentSolutionName); }
private bool ValidateExistingUser(ref string username, string password, UserDefinition user) { username = user.Username; if (user.IsActive != 1) { if (Log.IsInfoEnabled) { Log.Error(String.Format("Inactive user login attempt: {0}", username), this.GetType()); } return(false); } // prevent more than 50 invalid login attempts in 30 minutes var throttler = new Throttler("ValidateUser:"******"site" || user.Source == "sign" || directoryService == null) { if (validatePassword()) { throttler.Reset(); return(true); } return(false); } if (user.Source != "ldap") { throw new ArgumentOutOfRangeException("userSource"); } if (!string.IsNullOrEmpty(user.PasswordHash) && user.LastDirectoryUpdate != null && user.LastDirectoryUpdate.Value.AddHours(1) >= DateTime.Now) { if (validatePassword()) { throttler.Reset(); return(true); } return(false); } DirectoryEntry entry; try { entry = directoryService.Validate(username, password); if (entry == null) { return(false); } throttler.Reset(); } catch (Exception ex) { Log.Error("Error on directory access", ex, this.GetType()); // couldn't access directory. allow user to login with cached password if (!user.PasswordHash.IsTrimmedEmpty()) { if (validatePassword()) { throttler.Reset(); return(true); } return(false); } throw; } try { string salt = user.PasswordSalt.TrimToNull(); var hash = UserRepository.GenerateHash(password, ref salt); var displayName = entry.FirstName + " " + entry.LastName; var email = entry.Email.TrimToNull() ?? user.Email ?? (username + "@yourdefaultdomain.com"); using (var connection = SqlConnections.NewFor <UserRow>()) using (var uow = new UnitOfWork(connection)) { var fld = UserRow.Fields; new SqlUpdate(fld.TableName) .Set(fld.DisplayName, displayName) .Set(fld.PasswordHash, hash) .Set(fld.PasswordSalt, salt) .Set(fld.Email, email) .Set(fld.LastDirectoryUpdate, DateTime.Now) .WhereEqual(fld.UserId, user.UserId) .Execute(connection, ExpectedRows.One); uow.Commit(); UserRetrieveService.RemoveCachedUser(user.UserId, username); } return(true); } catch (Exception ex) { Log.Error("Error while updating directory user", ex, this.GetType()); return(true); } }
internal static IWindsorContainer BuildContainer() { string assemblyName; Func <SAPbobsCOM.Company>[] companyFactory = (customCompanyFactory == null) ? new Func <SAPbobsCOM.Company>[] { SAPServiceFactory.CompanyFactory } : customCompanyFactory; Container = new WindsorContainer(); Container.Kernel.Resolver.AddSubResolver(new ArrayResolver(Container.Kernel)); // proxy for forms. Container.Register(Component.For <IInterceptor>().ImplementedBy <FormProxy>().Named("formProxy")); // proxy for FormEvents Container.Register(Component.For <IInterceptor>().ImplementedBy <EventProxy>().Named("eventProxy")); // proxy for Transactions Container.Register(Component.For <IInterceptor>().ImplementedBy <TransactionProxy>().Named("transactionProxy")); // forms are Transient. Container.Register(Classes.FromThisAssembly().IncludeNonPublicTypes().InNamespace("Dover.Framework.Form") .WithService.DefaultInterfaces().LifestyleTransient()); // SAP App Facttory. Container.Register(Component.For <SAPbouiCOM.Application>().UsingFactoryMethod(SAPServiceFactory.ApplicationFactory)); // company factory (use default, that initializes DI API from App if none was provided). for (int i = 0; i < companyFactory.Length; i++) { Container.Register(Component.For <SAPbobsCOM.Company>().UsingFactoryMethod(companyFactory[i]).Named("company" + i)); } for (int i = 0; i < companyFactory.Length; i++) { Container.Register(Component.For <BusinessOneDAO>().ImplementedBy <BusinessOneDAOSQLImpl>() .DependsOn(Dependency.OnComponent(typeof(SAPbobsCOM.Company), "company" + i)).Named("b1dao" + i)); } string runningFolder = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory); // AddinManager registration. If I'm an AddIn, get addinManager from AppDomain, so // both (addin AppDomain and inception AppDomain) references the same implementation. AddinManager addinManager = (AddinManager)AppDomain.CurrentDomain.GetData("frameworkManager"); if (addinManager != null) { addinManagerSponsor = new Sponsor <AddinManager>(addinManager); Container.Register(Component.For <AddinManager>().Instance(addinManager)); } AppEventHandler appEventHandler = (AppEventHandler)AppDomain.CurrentDomain.GetData("appHandler"); if (appEventHandler != null) { appEventHandlerSponsor = new Sponsor <AppEventHandler>(appEventHandler); Container.Register(Component.For <AppEventHandler>().Instance(appEventHandler)); } // Service registration, they are singleton. Container.Register(Classes.FromThisAssembly().IncludeNonPublicTypes().InNamespace("Dover.Framework.Service") .WithService.DefaultInterfaces().LifestyleSingleton()); // DAO registration. Abstract classes, they're singleton. Container.Register(Component.For <BusinessOneUIDAO>().ImplementedBy <BusinessOneUIDAOImpl>()); Container.Register(Component.For <AssemblyDAO>().ImplementedBy <AssemblyDAOImpl>()); Container.Register(Component.For <PermissionDAO>().ImplementedBy <PermissionDAOSQLImpl>()); // Core and MicroCore Container.Register(Component.For <MicroCore>().LifestyleSingleton()); Container.Register(Component.For <MicroBoot>().LifestyleSingleton()); Container.Register(Component.For <Boot>().LifestyleSingleton()); assemblyName = Assembly.GetEntryAssembly() == null ? (string)AppDomain.CurrentDomain.GetData("assemblyName") : Assembly.GetEntryAssembly().GetName().Name; if (assemblyName == "Framework") { #if DEBUG CheckProxy(Assembly.Load(assemblyName)); // if passed on debug tests, we do not need this on production. #endif assemblyName = "Dover"; // Framework should be threated the same as Dover. } if (!File.Exists(assemblyName + ".config")) { assemblyName = "DoverTemp"; // Temp AppDomain logging. } Container.AddFacility <LoggingFacility>(f => f.UseLog4Net(assemblyName + ".config")); var logger = Container.Resolve <ILogger>(); logger.Debug(DebugString.Format(Messages.StartupFolder, runningFolder)); SAPServiceFactory.Logger = logger; var b1dao = Container.Resolve <BusinessOneDAO>(); SAPAppender.B1DAO = b1dao; return(Container); }
/// <summary> /// Creates the manifest document from the provided intermediates. Discards a previous /// manifest document if present. /// </summary> /// <param name="intermediates">Intermediates to process into the AppX manifest.</param> public void ProcessIntermediates(IEnumerable <Intermediate> intermediates) { this.document = null; this.Files = new List <PackageFile>(); Package package = null; Version minNetfx = null; Version maxNetfx = null; SortedSet <string> supportedProducts = new SortedSet <string>(StringComparer.OrdinalIgnoreCase); XElement xContent = new XElement(VsixNamespace + "Content"); XElement xReferences = new XElement(VsixNamespace + "References"); foreach (Intermediate intermediate in intermediates) { foreach (PackageItem item in intermediate.Items) { if (item.System) { continue; } // Files are processed differently since we need to go search for them on disk and such. if (item is File) { PackageFile packageFile; if (PackageFile.TryCreate(backend, (File)item, out packageFile)) { this.Files.Add(packageFile); } } else if (item is Package) { if (package == null) { package = (Package)item; } else { this.backend.OnMessage(new CompilerMessageEventArgs(CompilerMessage.HighlanderElement("Package"), item)); } } else if (item is Prerequisite) { Prerequisite prereq = (Prerequisite)item; switch (prereq.On.ToLowerInvariant()) { case "netfx": if (null == minNetfx) { if (prereq.Version == null) { this.backend.OnMessage(new CompilerMessageEventArgs(CompilerMessage.RequiredAttribute("Prerequisite", "Version"), prereq)); } else { minNetfx = prereq.Version; } if (prereq.MaxVersion != null) { maxNetfx = prereq.MaxVersion; } } else { this.backend.OnMessage(new CompilerMessageEventArgs(CompilerMessage.HighlanderElementWithAttributeValue("Prerequisite", "On", prereq.On), prereq)); } break; case "vs": if (prereq.Version == null) { this.backend.OnMessage(new CompilerMessageEventArgs(CompilerMessage.RequiredAttribute("Prerequisite", "Version"), prereq)); } else { string edition = Product.GetEdition(prereq); if (String.IsNullOrEmpty(edition)) { this.backend.OnMessage(new CompilerMessageEventArgs(CompilerMessage.RequiredAttribute("Vsix", "Product.Edition"), prereq)); } else { // Ensure that if the edition matches one of the well known values that it has the appropriate casing. string[] editionMatches = new string[] { "IntegratedShell", "Pro", "Premium", "Ultimate", "VWDExpress", "VCSExpress", "VBExpress", "VCExpress", "Express_All" }; foreach (string editionMatch in editionMatches) { if (edition.Equals(editionMatch, StringComparison.OrdinalIgnoreCase)) { edition = editionMatch; break; } } supportedProducts.Add(String.Concat(prereq.Version.ToString(), "\\", edition)); } } break; default: this.backend.OnMessage(new CompilerMessageEventArgs(CompilerMessage.InvalidAttributeValue("Prerequisite", "On", prereq.On), prereq)); break; } } else if (item is Dependency) { Dependency dependency = (Dependency)item; XElement reference = new XElement(VsixNamespace + "Reference", new XAttribute("Id", dependency.Name), new XElement(VsixNamespace + "Name", dependency.Publisher) ); if (dependency.Version != null) { reference.Add(new XAttribute("MinVersion", dependency.Version.ToString())); } if (dependency.MaxVersion != null) { reference.Add(new XAttribute("MaxVersion", dependency.MaxVersion.ToString())); } xReferences.Add(reference); } else if (item is Vspackage) { Vspackage vspackage = (Vspackage)item; // TODO: verify file specified string pkgdef = VsixManifest.StripRootFolderReference(vspackage.File.Path); // TODO: warn if file extension not .pkgdef. xContent.Add(new XElement(VsixNamespace + "VsPackage", pkgdef)); } } } if (package != null) { // TODO: verify DisplayName <= 50 chars // TODO: verify Description <= 1000 chars // TODO: verify Manufacturer // TODO: verify Version // TODO: verify Languages[0] only one. XElement xIdentifier = new XElement(VsixNamespace + "Identifier", new XAttribute("Id", package.Name), new XElement(VsixNamespace + "Name", package.DisplayName), new XElement(VsixNamespace + "Author", package.Manufacturer), new XElement(VsixNamespace + "Version", package.Version.ToString()), new XElement(VsixNamespace + "Description", package.Description), new XElement(VsixNamespace + "Locale", this.backend.Languages[0].LCID) ); string image = (package.Image == null) ? null : package.Image.NonqualifiedName; if (!string.IsNullOrEmpty(image)) { xIdentifier.Add(VsixNamespace + "Icon", image); } xIdentifier.Add(new XElement(VsixNamespace + "InstalledByMsi", "false")); XElement xSupportedProducts = new XElement(VsixNamespace + "SupportedProducts"); xIdentifier.Add(xSupportedProducts); string previonsVersion = null; XElement xVisualStudio = null; foreach (string supported in supportedProducts) { string[] versionEdition = supported.Split(new char[] { '\\' }, 2); if (!versionEdition[0].Equals(previonsVersion)) { xVisualStudio = new XElement(VsixNamespace + "VisualStudio", new XAttribute("Version", versionEdition[0])); xSupportedProducts.Add(xVisualStudio); previonsVersion = versionEdition[0]; } xVisualStudio.Add(new XElement(VsixNamespace + "Edition", versionEdition[1])); } if (null != minNetfx) { XElement xSupportedFrameworkRuntime = new XElement(VsixNamespace + "SupportedFrameworkRuntimeEdition", new XAttribute("MinVersion", minNetfx.ToString()) ); if (null != maxNetfx) { xSupportedFrameworkRuntime.Add(new XAttribute("MaxVersion", maxNetfx.ToString())); } xIdentifier.Add(xSupportedFrameworkRuntime); } if (package.Framework) { xIdentifier.Add(VsixNamespace + "SystemComponent", "true"); } // Now put the manifest together. XElement xRoot = new XElement(VsixNamespace + "Vsix", new XAttribute("Version", "1.0"), xIdentifier ); if (xReferences.HasElements) { xRoot.Add(xReferences); } if (xContent.HasElements) { xRoot.Add(xContent); } this.document = new XDocument(xRoot); } }
/// <summary> /// Registers all future entities and related generators into the container. /// </summary> /// <param name="application">Result application.</param> /// <param name="prototype">Prototype model.</param> /// <param name="projectName">Name of result project containing this entities, used for namespace and folder.</param> /// <param name="container">Container storing all IGenerableFile instances.</param> public static void RegisterEntities(Prototype prototype, string projectName, WindsorContainer container) { foreach (var entity in prototype.Entities) { container.Register( Component.For <EntityGenerator>() .ImplementedBy <EntityGenerator>() .LifestyleSingleton() .DependsOn(Dependency.OnValue("projectName", projectName)).DependsOn(Dependency.OnValue("modelParameters", entity)).Named(entity.Name) ); container.Register(Component.For <DataFactoryGenerator>() .ImplementedBy <DataFactoryGenerator>() .LifestyleSingleton() .DependsOn(Dependency.OnValue("projectName", projectName)) .DependsOn(Dependency.OnValue("entityName", entity.Name)) .Named(entity.Name + nameof(DataFactoryGenerator))); } }
public void Usage(Dependency root) { var usages = new CalculateUsage(root, this.Usages, this.Interfaces); usages.Calculate(root); }
public ListResponse <TranslationItem> List(TranslationListRequest request) { var result = new ListResponse <TranslationItem>(); var availableKeys = GetAllAvailableLocalTextKeys(); var targetLanguageID = request.TargetLanguageID.TrimToNull(); var customTranslations = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); var textsFilePath = GetUserTextsFilePath(targetLanguageID); if (File.Exists(textsFilePath)) { var json = JsonConfigHelper.LoadConfig <Dictionary <string, JToken> >(textsFilePath); JsonLocalTextRegistration.ProcessNestedDictionary(json, "", customTranslations); foreach (var key in customTranslations.Keys) { availableKeys.Add(key); } } var sorted = new string[availableKeys.Count]; availableKeys.CopyTo(sorted); Array.Sort(sorted); var registry = Dependency.Resolve <ILocalTextRegistry>(); targetLanguageID = targetLanguageID ?? ""; var sourceLanguageID = request.SourceLanguageID.TrimToEmpty(); result.Entities = new List <TranslationItem>(); Func <string, string> effective = delegate(string key) { if (key.StartsWith("Navigation.")) { key = key.Substring("Navigation.".Length); return(key.Split(new char[] { '/' }).Last()); } else if (key.StartsWith("Forms.") && key.Contains(".Categories.")) { return(key.Split(new char[] { '.' }).Last().TrimToNull()); } return(key); }; foreach (var key in sorted) { string customText; if (!customTranslations.TryGetValue(key, out customText)) { customText = null; } result.Entities.Add(new TranslationItem { Key = key, SourceText = registry.TryGet(sourceLanguageID, key) ?? effective(key), TargetText = registry.TryGet(targetLanguageID, key) ?? effective(key), CustomText = customText }); } return(result); }
public void AddDependency(Dependency dep) { Dependencies.Add(dep); }
private static IEnumerable <string> GetRepoNamesOrDefault(Dependency dependency) { return(dependency.RepoNames ?? new[] { GetDefaultRepoNameFromUrl(dependency.Uri) }); }
public InstallProjectDependency(string project, Dependency dependency) { _project = project; _dependency = dependency; }
public EMAOfNumbers(int period) : base(period) { smoothingConstant = (float)2 / (period + 1); _sma = new SMAOfNumbers(period); Dependency.Register(_sma); }
/// <summary> /// Provides the custom hook for VisitDependency. This will only be called if the dependency /// was specified in the whitelist. /// </summary> /// <param name="directory">The directory of the project.</param> /// <param name="dependency">The <see cref="Dependency"/> to visit.</param> /// <returns></returns> protected abstract ReturnCode OnVisitDependency(string directory, Dependency dependency);
public Service(Dependency dependency, OptionalDependency optionalDependency = null) { _dependency = dependency; _optionalDependency = optionalDependency; }
public void GetComponentFromStaticField_GetsValue() { Entities.ForEach((ref EcsTestDataEntity tde) => { tde.value0 = GetComponent <EcsTestData>(tde.value1).value; }).Schedule(); Dependency.Complete(); }
private void WriteSourceBuildMetadata(string sourceBuildMetadataPath, string repoGitDir, Dependency dependency) { foreach (string repoName in GetRepoNamesOrDefault(dependency)) { string propsPath = Path.Combine(sourceBuildMetadataPath, $"{repoName}.props"); string commitCount = GetCommitCount(repoGitDir, dependency.Sha); DerivedVersion derivedVersion = GetVersionInfo(dependency.Version, commitCount); var repoProps = new Dictionary <string, string> { ["GitCommitHash"] = dependency.Sha, ["GitCommitCount"] = commitCount, ["GitCommitDate"] = GetCommitDate(repoGitDir, dependency.Sha), ["OfficialBuildId"] = derivedVersion.OfficialBuildId, ["OutputPackageVersion"] = dependency.Version, ["PreReleaseVersionLabel"] = derivedVersion.PreReleaseVersionLabel, ["IsStable"] = string.IsNullOrWhiteSpace(derivedVersion.PreReleaseVersionLabel) ? "true" : "false", }; WritePropsFile(propsPath, repoProps); } }