Beispiel #1
0
        public static List <object> GetInstances(Type InterfaceType)
        {
            string name = InterfaceType.Name;

            if (!Instances.ContainsKey(name))
            {
                lock (_lock)
                {
                    if (!Instances.ContainsKey(name))
                    {
                        List <object> Result = new List <object>();
                        var           types  = GetImplementationTypes(InterfaceType);
                        foreach (var item in types)
                        {
                            var instance = Activator.CreateInstance(item);
                            if (instance != null)
                            {
                                Result.Add(instance);
                            }
                        }

                        Instances[name] = Result;
                    }
                }
            }

            return(Instances[name]);
        }
Beispiel #2
0
    public static bool Load(UInt32 id, UInt32 characterID, ModelType model_type, string name, Vector3 position)
    {
        if (Instances.Count() >= Max)
        {
            return(false);
        }

        if (Instances.ContainsKey(id))
        {
            return(false);
        }

        GameObject prefab;

        if (ObjectManager.PlayerModels.TryGetValue(model_type, out prefab))
        {
            var character = UnityEngine.Object.Instantiate(ObjectManager.PlayerModels[model_type])
                            .AddComponent <Character>()
                            .Initialize <ClientActor>(characterID, name);
            character.transform.position = position;
            Instances[id] = new Client(id, character);
        }

        return(true);
    }
Beispiel #3
0
        /// <summary>
        /// Indicates whether or not an instance was cached by the specified keys.
        /// </summary>
        /// <param name="successful">
        /// Was the check successful (e.g., wouldn't be successful if the lock
        /// timeout expired).
        /// </param>
        /// <param name="keys">
        /// Optional. The keys to store/retrieve a value by. Each key combination will
        /// be treated as a separate cache.
        /// </param>
        /// <returns>
        /// True, if an item was cached by the specified keys; otherwise, false.
        /// </returns>
        public bool WasCached(out bool successful, params string[] keys)
        {
            var lockTaken = default(bool);

            try
            {
                Monitor.TryEnter(InstanceLock, LockTimeout, ref lockTaken);
                if (lockTaken)
                {
                    successful = true;
                    return(LastCache.HasValue
                        ? Instances.ContainsKey(keys)
                        : false);
                }
                else
                {
                    CacheSettings.FailedLockHandler(LockTimeout);
                    successful = false;
                    return(false);
                }
            }
            finally
            {
                if (lockTaken)
                {
                    Monitor.Exit(InstanceLock);
                }
            }
        }
Beispiel #4
0
        /// <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.");
                }
            }
        }
        /// <summary>
        /// Gets an instance of the configuration for a given publication
        /// </summary>
        /// <param name="publication"></param>
        /// <returns></returns>
        public static TridionConfigurationManager GetInstance(Publication publication)
        {
            log.Debug(">>GetInstance called for " + publication.Id);

            // locking to make threadsafe
            // this prevents errors like 'given key was not present in the dictionary'
            lock (lock1)
            {
                if (!Instances.ContainsKey(publication.Id))
                {
                    log.Debug("no instance found, creating new one");
                    AddInstance(publication);
                }
                else
                {
                    log.Debug(string.Format("found instance, publication revision date {0}, config file modification date {1}, cache date {2}", publication.RevisionDate, ConfigurationModificationDate, InstanceCacheDates[publication.Id]));
                    if (InstanceCacheDates[publication.Id].CompareTo(publication.RevisionDate) < 0 || InstanceCacheDatesFS[publication.Id].CompareTo(ConfigurationModificationDate) < 0)
                    {
                        log.Debug("creating new instance");
                        RemoveInstance(publication);
                        AddInstance(publication);
                    }
                }
            }
            return(Instances[publication.Id]);
        }
Beispiel #6
0
 internal static Tweaker Lookup(string hostname)
 {
     if (!Instances.ContainsKey(hostname))
     {
         Instances[hostname] = new Tweaker(hostname);
     }
     return(Instances[hostname]);
 }
Beispiel #7
0
 public static uSplitAuthorizationCodeFlow GetInstance(AccountConfig config)
 {
     if (!Instances.ContainsKey(config.UniqueId))
     {
         Instances[config.UniqueId] = new uSplitAuthorizationCodeFlow(config);
     }
     return(Instances[config.UniqueId]);
 }
Beispiel #8
0
        public object Resolve(Type type)
        {
            if (Instances.ContainsKey(type))
            {
                return(Instances[type]);
            }

            throw new ArgumentException("unregistered dependency");
        }
Beispiel #9
0
        public static S Instance(string name)
        {
            if (!Instances.ContainsKey(name))
            {
                throw new UndefinedNameError(name);
            }

            return(Instances[name]);
        }
 public void AddInstances(GlobalGeometryPartBlockNew part, IEnumerable <Matrix4> instanceWorldMatrices)
 {
     if (!Instances.ContainsKey(part))
     {
         Instances[part] = new List <Matrix4>(instanceWorldMatrices);
         return;
     }
     Instances[part].AddRange(instanceWorldMatrices);
 }
 public void RegisterInstance(Type service, object implementation)
 {
     if (!Instances.ContainsKey(service))
     {
         Instances.Add(service, new List <object> {
             implementation
         });
     }
 }
Beispiel #12
0
    public static FormulaStringFx GetInstance(string formatString)
    {
        if (!Instances.ContainsKey(formatString))
        {
            Instances[formatString] = new FormulaStringFx(formatString);
        }

        return(Instances[formatString]);
    }
Beispiel #13
0
 public void AddActivation(ActivationId act, SiloAddress silo)
 {
     if (SingleInstance && (Instances.Count > 0) && !Instances.ContainsKey(act))
     {
         throw new InvalidOperationException(
                   "Attempting to add a second activation to an existing grain in single activation mode");
     }
     Instances[act] = new ActivationInfo(silo);
     VersionTag     = rand.Next();
 }
Beispiel #14
0
        /// <summary>
        /// Sets the autostart instance in the registry and saves it.
        /// </summary>
        public static void SetAutoStart(string name)
        {
            if (!Instances.ContainsKey(name))
            {
                throw new InvalidKSPInstanceKraken(name);
            }

            _AutoStartInstance = name;
            PopulateRegistryWithInstances();
        }
Beispiel #15
0
        /// <summary>
        /// Sets the current instance.
        /// Throws an InvalidKSPInstanceKraken if not found.
        /// </summary>
        public static void SetCurrentInstance(string name)
        {
            // TODO: Should we disallow this if _CurrentInstance is already set?

            if (!Instances.ContainsKey(name))
            {
                throw new InvalidKSPInstanceKraken(name);
            }

            _CurrentInstance = Instances[name];
        }
Beispiel #16
0
        public static Printer Get(Subsystem ss)
        {
            if (Instances.ContainsKey(ss))
            {
                return(Instances[ss]);
            }

            var instance = new Printer();

            Instances[ss] = instance;
            return(instance);
        }
    public void RegisterLazy(Type service, Func <object> factory)
    {
        if (factory is null)
        {
            throw new ArgumentNullException(nameof(factory));
        }

        if (!Instances.ContainsKey(service))
        {
            Instances.Add(service, new List <object> {
                factory()
            });
        }
    }
Beispiel #18
0
        public static bool InitializeInstance(Type rInterfaceType, IInterface rInterface)
        {
            if (!rInterfaceType.IsInterface)
            {
                return(false);
            }

            if (Instances.ContainsKey(rInterfaceType))
            {
                return(false);
            }

            Instances[rInterfaceType] = rInterface;
            return(true);
        }
        public Dictionary <SiloAddress, List <ActivationAddress> > 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 mapping = new Dictionary <SiloAddress, List <ActivationAddress> >();
                foreach (var activationPair in activationsToDrop)
                {
                    var activation = ActivationAddress.GetAddress(activationPair.Value.SiloAddress, grain, activationPair.Key);

                    List <ActivationAddress> activationsToRemoveOnSilo;
                    if (!mapping.TryGetValue(activation.Silo, out activationsToRemoveOnSilo))
                    {
                        activationsToRemoveOnSilo = mapping[activation.Silo] = new List <ActivationAddress>(1);
                    }

                    activationsToRemoveOnSilo.Add(activation);
                }

                return(mapping);
            }

            return(null);
        }
Beispiel #20
0
        public static ICrawler CreateMine(string url)
        {
            ICrawler result = null;
            string   name   = "{0}"._Format(DefaultConfiguration.GetAppSetting("ApplicationName", "UNKNOWN"));

            if (Instances.ContainsKey(name))
            {
                result = Instances[name];
            }
            else
            {
                result = Create(name, url);
            }

            return(result);
        }
Beispiel #21
0
        // Actual worker for GetPreferredInstance()
        internal static KSP _GetPreferredInstance()
        {
            // First check if we're part of a portable install
            // Note that this *does not* register in the registry.
            string path = KSP.PortableDir();

            if (path != null)
            {
                return(new KSP(path));
            }

            // Return the autostart, if we can find it.
            if (AutoStartInstance != null)
            {
                // We check both null and "" as we can't write NULL to the registry, so we write an empty string instead
                // This is neccessary so we can indicate that the user wants to reset the current AutoStartInstance without clearing the windows registry keys!
                if (AutoStartInstance == "")
                {
                    return(null);
                }

                if (Instances.ContainsKey(AutoStartInstance))
                {
                    return(Instances[AutoStartInstance]);
                }
            }

            // If we only know of a single instance, return that.
            if (Instances.Count == 1)
            {
                // Surely there's a better way to get the singleton value than this?
                var keys = new List <string>(Instances.Keys);
                return(Instances[keys[0]]);
            }

            // If we know of no instances, try to find one.
            if (Instances.Count == 0)
            {
                return(FindAndRegisterDefaultInstance());
            }

            // Otherwise, we know of too many instances!
            // We don't know which one to pick, so we return null.

            return(null);
        }
Beispiel #22
0
        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);
                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);
                    CatalogFactory.GetSystemTarget(Constants.CatalogId, activation.Silo).
                    DeleteActivations(list).Ignore();

                    list.Clear();
                }
                return(true);
            }
            return(false);
        }
Beispiel #23
0
        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 AddActivation(ActivationId act, SiloAddress silo)
        {
            if (SingleInstance && (Instances.Count > 0) && !Instances.ContainsKey(act))
            {
                throw new InvalidOperationException(
                          "Attempting to add a second activation to an existing grain in single activation mode");
            }
            IActivationInfo info;

            if (Instances.TryGetValue(act, out info))
            {
                if (info.SiloAddress.Equals(silo))
                {
                    // just refresh, no need to generate new VersionTag
                    return(false);
                }
            }
            Instances[act] = new ActivationInfo(silo, MultiClusterStatus.Owned);
            VersionTag     = rand.Next();
            return(true);
        }
        /// <summary>
        ///     Récupère l'instance d'une interface
        ///     <para>
        ///         Renvoie <c>null</c> si l'interface est introuvable.
        ///     </para>
        /// </summary>
        /// <typeparam name="TInterface">Type de l'interface</typeparam>
        /// <returns>Instance de l'interface</returns>
        public TInterface GetInstance <TInterface>()
        {
            lock (Locker)
            {
                var type = typeof(TInterface);
                if (!Instances.ContainsKey(type))
                {
                    _logger.Warn($"Interface introuvable : [{type}].");
                    return(default(TInterface));
                }

                var instance = Instances[type];

                if (instance == null)
                {
                    return(CreateInstance <TInterface>());
                }

                return((TInterface)Instances[type]);
            }
        }
        /// <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.");
                }
            }
        }
        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);
        }
Beispiel #28
0
 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);
     }
 }
Beispiel #29
0
        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);
            }
        }
        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);
        }