public void AddVariable <T>(string name, T obj, int recursionLevel) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (obj == null) { throw new ArgumentNullException(nameof(obj)); } if (recursionLevel < 0) { throw new ArgumentOutOfRangeException(nameof(recursionLevel), "Recursion level must be positive."); } if (Instances.ContainsKey(name)) { throw new InvalidOperationException("Variable with the name " + name + " already exists."); } Type type = typeof(T); if (!type.IsPublic) { throw new InvalidOperationException("Only variables of public type can be added."); } ((IDictionary <string, object>)_interpreter.Globals.globals).Add(name, obj); // Add instance. Instances.Add(name, new Member { Name = name, Type = type }); InstancesAndStaticsDirty = true; if (InstanceMembers.ContainsKey(type)) { return; } AddTypeImpl(type, recursionLevel); }
public bool Merge(GrainId grain, IGrainInfo other) { bool modified = false; foreach (var pair in other.Instances) { if (Instances.ContainsKey(pair.Key)) { continue; } Instances[pair.Key] = new ActivationInfo(pair.Value.SiloAddress, pair.Value.RegistrationStatus); modified = true; } if (modified) { VersionTag = rand.Next(); } if (SingleInstance && (Instances.Count > 0)) { // Grain is supposed to be in single activation mode, but we have two activations!! // Eventually we should somehow delegate handling this to the silo, but for now, we'll arbitrarily pick one value. var orderedActivations = Instances.OrderBy(pair => pair.Key); var activationToKeep = orderedActivations.First(); var activationsToDrop = orderedActivations.Skip(1); Instances.Clear(); Instances.Add(activationToKeep.Key, activationToKeep.Value); var list = new List <ActivationAddress>(1); foreach (var activation in activationsToDrop.Select(keyValuePair => ActivationAddress.GetAddress(keyValuePair.Value.SiloAddress, grain, keyValuePair.Key))) { list.Add(activation); InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget <ICatalog>(Constants.CatalogId, activation.Silo). DeleteActivations(list).Ignore(); list.Clear(); } return(true); } return(false); }
/// <summary> /// Returns the instance of specified type that is managed by the current <see cref="IFactoryProducedInstanceGroup" />. /// </summary> /// <typeparam name="T"> /// The type of the instance to return. /// </typeparam> /// <returns> /// The instance of specified type that is managed by the current <see cref="IFactoryProducedInstanceGroup" />. /// </returns> /// <exception cref="ArgumentException"> /// <typeparamref name="T" /> is not a supported type for the group. /// </exception> /// <exception cref="ObjectDisposedException"> /// The object is disposed. /// </exception> /// <exception cref="ObjectProductionException"> /// An exception was raised during object production. /// </exception> public T Get <T>() where T : class { var instanceType = typeof(T); using (var controlToken = StateControl.Enter()) { RejectIfDisposed(); if (Instances.TryGetValue(instanceType, out var extantInstance)) { return(extantInstance as T); } var newInstance = Factory.Produce(instanceType) as T; Instances.Add(instanceType, newInstance); ReferenceManager.AddObject(newInstance); return(newInstance); } }
public void GetPuttySessions() { PuttySessions = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\SimonTatham\PuTTY\Sessions").GetSubKeyNames().ToList(); if (!Settings.IncludePuttySessionsInList) { return; } foreach (var s in PuttySessions) { var inst = new Instance { IsPuttyInstance = true, State = InstatnceStates.Unknown, StateName = "Unknown", Name = s, Id = s }; Instances.Add(inst); } }
/// <summary> /// Create a MinecraftServer and add it to Instances /// </summary> /// <param name="startingPort">The starting port. Incremented for each server created</param> /// <param name="amount">Amount of instances to create</param> /// <param name="ram">RAM for each server</param> /// <param name="world">The world name</param> /// <param name="baseDir">The base/root directory of the application</param> /// <param name="seed">The world seed</param> public void Create(int startingPort, byte amount, string ram, string world, string baseDir, string seed) { for (byte i = 0; i < amount; i++) { //Create server.properties based on settings var pregenServerDir = Path.Combine(baseDir, "pregenServer-" + i); var fullPath = Path.Combine(baseDir, pregenServerDir); var properties = new ServerProperties(fullPath, startingPort + i, world, seed); Directory.CreateDirectory(fullPath); //Get the list and take the first file. var files = Directory.GetFiles(Path.Combine(baseDir, "cache"), "patched_*.jar"); var minecraftServer = new MinecraftServer(ram, properties, fullPath, files[0]); Instances.Add(minecraftServer); minecraftServer.Properties.Save(); } IO.CopyJarToDir(JarLocation, baseDir); }
public NdfObject CreateInstanceOf(NdfClass cls, bool isTopLevelInstance = true) { var newId = (uint)Instances.Count(); var inst = new NdfObject { Class = cls, Id = newId }; AddEmptyProperties(inst); Instances.Add(inst); if (isTopLevelInstance) { TopObjects.Add(inst.Id); inst.IsTopObject = true; } return(inst); }
public UIComponentRoot() { var container = new UIComponentContainer(); //TODO: Should we create this binding now or on Loaded? container.SetBinding( UIComponentContainer.ComponentProperty, new Binding() { Source = this, Path = new PropertyPath(nameof(this.Component)) } ); this.Content = container; lock (Instances) { Instances.Add(new WeakReference <UIComponentRoot>(this)); } OnActiveChanged(this); }
public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); if (Instances == null) { Instances = new List <BellOfTheDead>(); } Instances.Add(this); m_Chyloth = reader.ReadMobile() as Chyloth; m_Dragon = reader.ReadMobile() as SkeletalDragon; if (m_Chyloth != null) { m_Chyloth.Delete(); } }
private AdvancedVendor(string title) : base(title) { Trading = true; Female = Utility.RandomBool(); Name = NameList.RandomName(Female ? "female" : "male"); Race = Race.AllRaces.GetRandom(); Instances.Add(this); Timer.DelayCall( () => { if (OnCreated != null) { OnCreated(this); } }); }
public override void InitializeComponent(ICore core) { this.Adapter = new SnappingAdapter(this.Handle); this.Adapter.InitializeComponent(core); this.SetHook(this.DefaultHook); core.Components.Configuration.GetElement <TextConfigurationElement>( WindowSnappingBehaviourConfiguration.SECTION, WindowSnappingBehaviourConfiguration.STICKY ).ConnectValue(value => this.IsSticky = WindowSnappingBehaviourConfiguration.GetIsSticky(value, this.Adapter.Id)); lock (Instances) { Instances.Add(new WeakReference <SnappingWindow>(this)); } OnActiveChanged(this); UpdateStickyWindows(); base.InitializeComponent(core); }
public void LoadInstanceCache() { if (!File.Exists(CacheFile)) { return; } try { using (TextReader textReader = new StreamReader(CacheFile)) { XmlSerializer deserializer = new XmlSerializer(typeof(List <Instance>)); var instances = (List <Instance>)deserializer.Deserialize(textReader); textReader.Close(); instances.ForEach(a => Instances.Add(a)); if (listBox.Items.Count > 0) { listBox.SelectedIndex = 0; } } } catch { } // I know that this is bad }
public T CreateNewAppDomain <T>(string domainName) where T : class { // ReSharper disable once InvertIf if (AppDomains.FirstOrDefault(ad => ad.FriendlyName.Equals(domainName)) == null) { AppDomain domain = AppDomain.CreateDomain(domainName, AppDomain.CurrentDomain.Evidence, _appDomainSetup); AppDomains.Add(domain); // HARD-CODED constant Tracer.Instance.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "AppDomain {0} created.", domainName); //! This bypasses the Main method as it's not executing it. object instance = domain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName); Instances.Add(new KeyValuePair <string, object>(domainName, instance)); // HARD-CODED constant Tracer.Instance.TraceEvent(System.Diagnostics.TraceEventType.Verbose, 0, "AppDomain Instance {0} created.", typeof(T).FullName); //x return AppDomainInstances.Last() as T; return(instance as T); } return(null); }
public static ICrawler Create(string name, string url) { lock (_createLock) { ImageCrawler crawler = new ImageCrawler(); crawler.Name = name; crawler.Root = url; if (Instances.ContainsKey(name)) { Instances[name] = crawler; } else { Instances.Add(crawler.Name, crawler); } ImageCrawler.EnsureOne(crawler); return(crawler); } }
public Object this[String instanceName] { get { if (Instances.ContainsKey(instanceName)) { return(Instances[instanceName]); } else { return(null); } } set { if (Instances.ContainsKey(instanceName)) { Instances.Remove(instanceName); } Instances.Add(instanceName, value); } }
public void ReadInstances() { var lines = File.ReadAllLines(FilePath); int actualLine = 0; Instance instance; Task task; NumberOfInstances = Convert.ToInt32(lines[actualLine++]); for (int instanceNumber = 0; instanceNumber < NumberOfInstances; instanceNumber++) { instance = new Instance(); instance.Size = Convert.ToInt32(lines[actualLine++]); for (int taskNumber = 0; taskNumber < instance.Size; taskNumber++) { task = new Task(lines[actualLine++], taskNumber); instance.Tasks.Add(task); } Instances.Add(instance); } }
/// <summary> /// Saves the instance. /// </summary> /// <typeparam name="TInterface">The type of the interface.</typeparam> /// <typeparam name="TInstance">The type of the instance.</typeparam> /// <param name="instance">The instance.</param> private void SaveInstance <TInterface, TInstance>(TInstance instance) { if (instance == null) { throw new ArgumentNullException(nameof(instance)); } lock (Locker) { var interfaceType = typeof(TInterface); if (Instances.ContainsKey(interfaceType)) { Instances[interfaceType] = instance; _logger.Debug($"Instance de [{interfaceType}] remplacée."); } else { Instances.Add(interfaceType, instance); _logger.Debug($"Instance de [{interfaceType}] enregistrée."); } } }
public void CreateInstances() { var dlls = Directory.EnumerateFiles(PathToDlls, "*.dll", SearchOption.TopDirectoryOnly); foreach (var dll in dlls) { var assembly = Assembly.LoadFrom(dll); foreach (var type in assembly.ExportedTypes) { if (type.IsClass && typeof(TInterface).IsAssignableFrom(type)) { TInterface instance = Activator.CreateInstance(type) as TInterface; Instances.Add(new InstanceInfo <TInterface>( instance, type.Name, assembly.FullName)); } } } }
/// <summary> /// retrieves, finds and caches target damagehandlers for more /// efficient fetching in the future /// </summary> public static vp_DamageHandler GetDamageHandlerOfCollider(Collider col) { m_GetDamageHandlerOfColliderResult = null; // try to fetch a known damagehandler on this target, if (!Instances.TryGetValue(col, out m_GetDamageHandlerOfColliderResult)) { // no damagehandler info on record for this collider: see if we can find // one on the transform or any of its ancestors (the lowest ancestor with // a damagehandler will be cached as belonging to this collider) Transform t = col.transform; while ((t != null) && (m_GetDamageHandlerOfColliderResult == null)) { m_GetDamageHandlerOfColliderResult = t.GetComponent <vp_DamageHandler>(); t = t.parent; } Instances.Add(col, m_GetDamageHandlerOfColliderResult); // add result to the dictionary (even if null) } return(m_GetDamageHandlerOfColliderResult); }
private static FileDownloader DoGetInstance(Type type) { if (type == null) { throw new ArgumentException("Invalid arguments to get file downloader instance"); } var key = type.FullName + "_"; FileDownloader instance = null; if (Instances.ContainsKey(key)) { instance = Instances[key]; } if (instance == null) { Logger.GetInstance(typeof(FileDownloader)).Info("Initializing " + key + "..."); var constructor = type.GetConstructor(new Type[] { }); if (constructor != null) { instance = (FileDownloader)constructor.Invoke(new object[] { }); } } if (instance == null) { Logger.GetInstance(typeof(FileDownloader)).Info("Initializing " + typeof(HttpFileDownloader).FullName + "..."); instance = new HttpFileDownloader(); } lock (InstanceLock) { if (!Instances.ContainsKey(key)) { Instances.Add(key, instance); } } return(instance); }
public static WorkflowInstance Create(Workflow Workflow, Dictionary <string, object> Parameters) { var result = new WorkflowInstance(Workflow) { Parameters = Parameters, name = Workflow.name, Path = Workflow.Project.Path }; result.RelativeFilename = Workflow.RelativeFilename; result.projectid = Workflow.projectid; result.projectname = Workflow.Project.name;; var _ref = (result as IWorkflowInstance); foreach (var runner in Plugins.runPlugins) { if (!runner.onWorkflowStarting(ref _ref, false)) { throw new Exception("Runner plugin " + runner.Name + " declined running workflow instance"); } } if (global.isConnected) { result.owner = global.webSocketClient.user.name; result.ownerid = global.webSocketClient.user._id; } result.host = Environment.MachineName.ToLower(); result.fqdn = System.Net.Dns.GetHostEntry(Environment.MachineName).HostName.ToLower(); result.createApp(Workflow.Activity); lock (Instances) Instances.Add(result); foreach (var i in Instances.ToList()) { if (i.isCompleted) { lock (Instances) Instances.Remove(i); } } return(result); }
public void UpdateInstances(ServiceInstanceInfo[] instancesInfo) { lock (Instances) { List <InstanceView> childs = new List <InstanceView>(); foreach (var instance in instancesInfo) { if (_InstancesRef.ContainsKey(instance.LegacyInstanceGuid)) { _InstancesRef[instance.LegacyInstanceGuid].ServiceInstanceInfo = instance; } else { InstanceView iv = new InstanceView() { ServiceInstanceInfo = instance }; _InstancesRef[instance.LegacyInstanceGuid] = iv; if (iv.ParentID == Guid.Empty) { Instances.Add(iv); } else { childs.Add(iv); } } } foreach (var child in childs) { if (_InstancesRef.ContainsKey(child.ParentID)) { _InstancesRef[child.ParentID].ChildsSteps.Add(child); } } //TODO: ADD REMOVE ENDED } }
public Schedule(string name, bool enabled, ScheduleInfo info, params Action <Schedule>[] onTick) : base(TimeSpan.FromSeconds(1.0), TimeSpan.FromSeconds(1.0)) { UID = new CryptoHashCode(CryptoHashType.MD5, TimeStamp.Now + "+" + Utility.RandomDouble()); _Enabled = enabled; _Name = name ?? String.Empty; _Info = info ?? new ScheduleInfo(); Instances.Add(this); UpdateTicks(Now); if (onTick != null) { foreach (var a in onTick) { OnGlobalTick += a; } } Start(); }
public static async Task <Guid> StartInstanceAsync(ServerType type, int port) { var id = Guid.NewGuid(); var instance = new ServerInstance(id) { ServerType = type, ServerPort = port, ApiPort = await ClaimApiPortAsync(), }; instance.Start(DllLocation, Config.DllSource.DotNetPath); Instances.Add(instance); if (type == ServerType.World) { InstanceHeartBeats.Add(id.ToString(), 0); InstanceHealth.Add(id.ToString(), ServerHealth.Healthy); } return(id); }
private static async void FinishCreatingAsync(BackButton backButton, Frame frame, NavigationService service) { await Task.CompletedTask; // TODO: add this feature back in if you can figure out the reason for an err // await ClearExpiredCacheAsync(service); service.BackButtonHandling = backButton; frame.RequestedTheme = Settings.DefaultTheme; if (backButton == BackButton.Attach) { frame.RegisterPropertyChangedCallback(Frame.CanGoBackProperty, (s, args) => BackButtonService.UpdateBackButton(service.CanGoBack)); // frame.Navigated += (s, args) => BackButtonService.UpdateBackButton(service.CanGoBack); // BackButtonService.BackRequested += async (s, e) => e.Handled = await service.GoBackAsync(); Central.Messenger.Subscribe <Messages.BackRequestedMessage>(frame, async m => { await service.GoBackAsync(); }); } if (!Instances.Any()) { Default = service; } Instances.Add(service); Central.Messenger.Send(new Messages.NavigationServiceCreatedMessage { NavigationService = service, BackButtonHandling = backButton, IsDefault = Default == service, Dispatcher = service.GetDispatcher() }); }
private static Dns DoGetInstance(Type type, string resolver) { if (type == null || resolver == null) { throw new ArgumentException("Invalid arguments to get " + typeof(Dns).Name + " instance"); } var key = type.FullName + "_" + resolver; Dns instance = null; if (Instances.ContainsKey(key)) { instance = Instances[key]; } if (instance == null) { Logger.GetInstance(typeof(Dns)).Info("Initializing " + key + "..."); var constructor = type.GetConstructor(new[] { typeof(string) }); if (constructor != null) { instance = (Dns)constructor.Invoke(new object[] { resolver }); } } if (instance == null) { Logger.GetInstance(typeof(Dns)).Info("Initializing " + typeof(DefaultDns).FullName + "[" + resolver + "]..."); instance = new DefaultDns(resolver); } lock (InstancesLock) { if (!Instances.ContainsKey(key)) { Instances.Add(key, instance); } } return(instance); }
/// <summary> /// Loads the project from the specified file. /// </summary> public void Load(string fileName) { Clear(); FileName = fileName; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(fileName); XmlElement rootElem = xmlDoc.DocumentElement; Version = ProjectVersion.Parse(rootElem.GetChildAsString("ProjectVersion")); Description = rootElem.GetChildAsString("Description"); // load instances XmlNode instancesNode = rootElem.SelectSingleNode("Instances"); if (instancesNode != null) { XmlNodeList instanceNodes = instancesNode.SelectNodes("Instance"); string projectDir = Path.GetDirectoryName(FileName); foreach (XmlNode instanceNode in instanceNodes) { Instance instance = new Instance(); instance.LoadFromXml(instanceNode); instance.InstanceDir = Path.Combine(projectDir, "Instances", instance.Name); Instances.Add(instance); // fix instance ID if (instance.ID <= 0) { instance.ID = Instances.Count; } } } }
private static Logger DoGetInstance(Type type, string name) { if (type == null || name == null) { throw new ArgumentException("Invalid arguments to get logger instance"); } var key = type.FullName + "_" + name; Logger instance = null; if (Instances.ContainsKey(key)) { instance = Instances[key]; } if (instance == null) { Console.Error.WriteLine("Initializing " + key + "..."); var constructor = type.GetConstructor(new[] { typeof(string) }); if (constructor != null) { instance = (Logger)constructor.Invoke(new object[] { name }); } } if (instance == null) { Console.Error.WriteLine("Initializing " + typeof(ConsoleLogger).FullName + "[" + name + "]..."); instance = new ConsoleLogger(name); } lock (InstancesLock) { if (!Instances.ContainsKey(key)) { Instances.Add(key, instance); } } return(instance); }
private void ExecuteCreateInstance(Canvas canvas) { var position = Mouse.GetPosition(canvas); var selectedBreed = Regions.MainViewModel.Sidebar?.SelectedBreed; if (selectedBreed == null) { MessageBox.Show("Please select a Breed!"); return; } var centerX = (int)position.X; var centerY = (int)position.Y; var brushSize = Regions.MainViewModel.Sidebar.BrushSize; var radius = brushSize / 2; for (int i = -radius; i <= radius; i++) { var x = centerX + i * Region.TileWidth; if (x < 0 || x >= Region.Width * Region.TileWidth) { continue; } for (int j = -radius; j <= radius; j++) { var y = centerY + j * Region.TileHeight; if (y < 0 || y >= Region.Height * Region.TileHeight) { continue; } var instance = World.Instance.Spawn(selectedBreed.Id, Region.Id, new Microsoft.Xna.Framework.Vector2(x, y)); Region.instances.Add(instance); Instances.Add(new InstanceViewModel(selectedBreed, instance, this)); } } }
/// <summary> /// Enregistre une usine de fabrication d'instance d'une interface /// <para> /// L'usine sera utilisée lors de la première récupération de l'interface. /// Si une usine est déjà enregistrée pour cette interface, celle-ci est remplacée. /// </para> /// </summary> /// <remarks></remarks> /// <typeparam name="TInterface">Interface</typeparam> /// <typeparam name="TInstance">Instance de l'interface</typeparam> /// <param name="factory">Usine de fabrication</param> /// <exception cref="ArgumentNullException"></exception> public void RegisterFactory <TInterface, TInstance>(Func <TInstance> factory) where TInstance : class, TInterface, new() { if (factory == null) { throw new ArgumentNullException(nameof(factory)); } lock (Locker) { var interfaceType = typeof(TInterface); if (Instances.ContainsKey(interfaceType)) { Factories[interfaceType] = factory; _logger.Debug($"Usine de [{interfaceType}] remplacée."); } else { Instances.Add(interfaceType, null); Factories.Add(interfaceType, factory); _logger.Debug($"Usine de [{interfaceType}] enregistrée."); } } }
public static GameObject Clone(string name, string instanceId = null) { GameObject originalName = Get(name); if (originalName == null) { return(null); } GameObject original = UnityEngine.Object.Instantiate(originalName); if (original == null) { return(null); } if (instanceId != null) { Instances.Add(instanceId, original); } UnityEngine.Object.DontDestroyOnLoad(original); return(original); }