Esempio n. 1
0
        public static T ReconfigureInstance <T>(T instance, Type type, IComponentDirectory directory)
        {
            IRequiresConfiguration  required = new TypeRequiredConfiguration(type, instance);
            IComponentConfiguration config   = new StandardConfiguration();

            return((T)ConfigureComponentWithRequirements(required, config, directory));
        }
Esempio n. 2
0
        internal LocalApplication(
            IComponentDirectory parentDirectory,
            ApplicationDesc application,
            Guid instanceGuid,
            ulong instanceNumber)
        {
            this.instanceGuid   = instanceGuid;
            this.instanceNumber = instanceNumber;

            string iname = application.Name + " " + instanceGuid.ToString();

            this.applicationDescriptor = application;

            localDirectory = new ComponentDirectory(parentDirectory, iname);

            localDirectory.Register(
                new Instance(
                    localDirectory.GetInstance <DatabaseManager>().Find("/"), "WorkingDirectory"));

            localDirectory.Register(new Instance(this, "Process"));

            foreach (IComponentProvider provider in application.Components)
            {
                localDirectory.Register(provider);
            }
        }
        public object GetInstance(IComponentDirectory componentDirectory, object clientInstance, string requirementName, string requirementType)
        {
            if (!IsApplicationLive())
            {
                return(null);
            }

            return(provider.GetInstance(componentDirectory, clientInstance, requirementName, requirementType));
        }
Esempio n. 4
0
 private static bool HasComponent(IComponentDirectory componentDirectory, string typeName)
 {
     try
     {
         // Console.Out.WriteLine(".. HasComponent {0}", typeName);
         return(componentDirectory.FindByType(typeName).Length > 0);
     }
     catch (Exception) { return(false); }
 }
Esempio n. 5
0
        /// <summary>
        /// Sets up the bridge in the new appdomain
        /// </summary>
        /// <param name="parentDirectory">Parent component directory</param>
        /// <param name="app">Application descriptor</param>
        /// <param name="guid">Application instance GUID</param>
        /// <param name="appInstance">Self application instance to link into the directory</param>
        internal void Setup(IComponentDirectory parentDirectory, ApplicationDesc app, Guid guid, IApplicationInstance appInstance, IAssemblyLoader xassemblyLoader)
        {
            assemblyLoader = xassemblyLoader;

            string iname = app.Name + " " + guid;

            // Console.Out.WriteLine("Creating process: {0}", iname);
            AppDomain.CurrentDomain.TypeResolve     += new ResolveEventHandler(CurrentDomain_TypeResolve);
            AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);

            this.directory = new ComponentDirectory(parentDirectory, iname);
            this.directory.Register(
                new Instance(
                    this.directory.GetInstance <DatabaseManager>().Find("/")));

            IComponentProvider appProvider = null;

            /** register self as process **/
            this.directory.Register(
                new Instance(appInstance, "Self"));

            /*******************************************************************************************
            * TODO: SECURITY: this is where we would re-register views of already registered (kernel)
            * providers to shadow the originals
            *******************************************************************************************/

            foreach (IComponentProvider provider in app.Components)
            {
                this.directory.Register(provider);

                if (provider.MatchedName == app.ApplicationComponent)
                {
                    appProvider = provider;
                }
            }

            if (appProvider == null)
            {
                throw new Exception(
                          String.Format(
                              "The application {0} cannot be set up because the application component was not found",
                              app.Name));
            }

            this.appInstance = this.directory.GetInstance(appProvider.MatchedName) as IApplicationBase;

            if (app == null)
            {
                throw new Exception(
                          String.Format(
                              "The application {0} cannot be set up because the application component cannot be instantiated",
                              app.Name));
            }

            /* a-ok */
        }
Esempio n. 6
0
        public void Apply(IComponentDirectory toolDirectory)
        {
            string dum1, dum2;

            MatchThrow(path, out dum1, out dum2);

            Node <object>        node = manager.Find(path);
            TypedStream <object> obj  = node.Open(Type.GetType(typeName), attribute.OpenMode);

            toolDirectory.Register(new Instance(obj, name));
        }
 private bool IsApplicationLive()
 {
     if (!appInstance.IsRunning)
     {
         if (directory != null)
         {
             directory.UnRegister(this);
             directory = null;
         }
         return(false);
     }
     return(true);
 }
Esempio n. 8
0
        string[] RegisterAutoParametrization(IComponentDirectory destination, string[] args)
        {
            // We must add auto parametrization.
            ConfiguredComponent typeProvider = destination.FindByName(
                applicationDescriptor.ApplicationComponent)[0] as ConfiguredComponent;

            Type type = typeProvider.ComponentType;

            if (type.GetCustomAttributes(typeof(AutoParametrizeAttribute), true).Length > 0)
            {
                return(AutoParametrization.PerformAutoParametrization(type, localDirectory, args));
            }
            return(args.Clone() as string[]);
        }
Esempio n. 9
0
        public object GetInstance(IComponentDirectory componentDirectory, object clientInstance, string requirementName, string requirementType)
        {
            if (constructor == null)
            {
                constructor = Type.GetType(className).GetConstructor(Type.EmptyTypes);
                if (constructor == null)
                {
                    throw new Exception(
                              String.Format(
                                  "SimpleClass provider: Type {0} does not provide a default constructor", className));
                }
            }

            return(constructor.Invoke(null));
        }
Esempio n. 10
0
        private static object ConfigureComponentWithRequirements(
            IRequiresConfiguration requiredConfiguration,
            IComponentConfiguration configuration,
            IComponentDirectory componentDirectory)
        {
            // 3. fill in the other parameters from the component directory
            foreach (IRequirement req in requiredConfiguration.Requirements)
            {
                // Console.Out.WriteLine(">> Requirement: {0}", req.Name);
                if (configuration.Values.ContainsKey(req.Name))
                {
                    // Console.Out.WriteLine(" ... Contains Key");
                    req.SetValue(configuration.Values[req.Name].GetInstance(req.Type));
                }
                else
                {
                    if (req.Default != null)
                    {
                        // Console.Out.WriteLine(" ... Has Default");
                        // NEW CONFIGURED COMPONENT THAT IS
                        req.SetValue(
                            componentDirectory.ConfigureInlineComponent(
                                new Instance(
                                    req.Default.GetInstance(req.Type))));
                    }
                    else if (HasComponent(componentDirectory, req.Type))
                    {
                        // Console.Out.WriteLine(" ... Setting By ICD");
                        req.SetValue(componentDirectory.GetInstanceByType(req.Type));
                    }
                    else if (req.Hard)
                    {
                        throw new ComponentConfigurationException(
                                  null,
                                  String.Format("ComponentOS KERNEL PANIC! I have no value for: {0}", req.Name));
                    }
                }
            }

            if (requiredConfiguration.Instance is IComponentPostInitialization)
            {
                (requiredConfiguration.Instance as IComponentPostInitialization).PostComponentInit(componentDirectory);
            }

            return(requiredConfiguration.Instance);
        }
        public override object GetInstance(
            IComponentDirectory componentDirectory,
            object clientInstance,
            string requirementName,
            string requirementType)
        {
            IRequiresConfiguration old = this.requiredConfiguration;

            try
            {
                requiredConfiguration = requiredConfiguration.Clone();
                return(base.GetInstance(componentDirectory, clientInstance, requirementName, requirementType));
            }
            finally
            {
                requiredConfiguration = old;
            }
        }
Esempio n. 12
0
        /// <summary>
        /// Performs auto-parametrization on arbitary object.
        /// </summary>
        /// <param name="arguments">The arguments that will be matched with properties.</param>
        /// <param name="directory">The component directory, to resolve links. May be null.</param>
        public static string[] PerformAutoParametrization(Type targetType, IComponentDirectory directory, string[] arguments)
        {
            List <string> unprocessed = new List <string>();

            // We go for each.
            foreach (string argument in arguments)
            {
                // We check for '='.
                if (!argument.Contains("="))
                {
                    unprocessed.Add(argument);
                    continue;
                }

                // We split to two parts on this index.
                int    index = argument.IndexOf('=');
                string first = argument.Substring(0, index).Trim();
                string last  = argument.Substring(index + 1).Trim();

                // We try to find target's type property with that name to find the correct mask.
                Type maskType = typeof(string);

                // We extract correct type.
                // FIXME: also consider aliases or "case invariant" matching!
                PropertyInfo info = targetType.GetProperty(first);
                if (info != null && info.CanWrite)
                {
                    maskType = info.PropertyType;
                }


                IComponentProvider provider = ExtractValue(maskType, first, last, directory);
                if (provider != null)
                {
                    directory.Register(provider);
                }
                else
                {
                    unprocessed.Add(argument);
                }
            }

            return(unprocessed.ToArray());;
        }
Esempio n. 13
0
        internal static AuthoredPackage LoadFromXML(XmlDocument doc, IComponentDirectory environment, string srcUrl)
        {
            /** let's load our stuff **/
            XmlElement ipackageNode = doc["InstallPackage"] as XmlElement;

            if (new Version(ipackageNode.GetAttribute("xversion")) > expectedVersion)
            {
                throw new UnsupportedPackageFormatException("Expected xversion " + expectedVersion);
            }

            AuthoredPackage package =
                environment.ConfigureInlineComponent(authoredPackageProvider) as AuthoredPackage;

            package.name           = ipackageNode.GetAttribute("name");
            package.id             = new Guid(ipackageNode.GetAttribute("id"));
            package.publisherName  = ipackageNode.GetAttribute("publisher");
            package.sourceLocation = srcUrl;

            // package.environment = new AuthoredInstallEnvironment(package);
            package.environment.LoadFromXML(doc);

            /** commands **/
            if (ipackageNode["PreInstallCheck"] != null)
            {
                ImportCommands(ipackageNode["PreInstallCheck"], package.preInstallCheck, environment);
            }

            if (ipackageNode["Installation"] != null)
            {
                ImportCommands(ipackageNode["Installation"], package.installation, environment);
            }

            if (ipackageNode["PreUninstallCheck"] != null)
            {
                ImportCommands(ipackageNode["PreUninstallCheck"], package.preUninstallCheck, environment);
            }

            if (ipackageNode["Uninstallation"] != null)
            {
                ImportCommands(ipackageNode["Uninstallation"], package.uninstallation, environment);
            }

            return(package);
        }
Esempio n. 14
0
        public void PostComponentInit(IComponentDirectory directory)
        {
            concurrencyCount = (uint)(System.Environment.ProcessorCount * workerThreadsPerCore);

            for (int i = 0; i < System.Environment.ProcessorCount; ++i)
            {
                CPUWorkUnit masterWorkUnit = null;

                for (int j = 0; j < workerThreadsPerCore; ++j)
                {
                    IComponentConfiguration config = new StandardConfiguration();
                    config.Values["CoreNumber"]  = new Simple(i);
                    config.Values["SliceNumber"] = new Simple(j);
                    if (masterWorkUnit != null)
                    {
                        config.Values["Previous"] = new Simple(masterWorkUnit);
                    }
                    config.Values["SlicesPerCore"] = new Simple((int)workerThreadsPerCore);

                    ConfiguredComponent component = new ConfiguredComponent(
                        typeof(CPUWorkUnit).FullName,
                        config);

                    CPUWorkUnit wu =
                        Components.ConfigureInlineComponent(component) as CPUWorkUnit;

                    this.registry.Register(wu);

                    if (j == 0)
                    {
                        masterWorkUnit = wu;
                    }
                }
            }

            controlThread = new Thread(Controller);

            controlThreadTimer =
                new Timer(Schedule, null, TimeSpan.Zero, DefaultTimeSlice);
        }
Esempio n. 15
0
        public object GetInstance(IComponentDirectory componentDirectory, object clientInstance,
                                  string requirementName, string requirementType)
        {
            // We obtain root object
            // FIXME: should we use those parameters
            object rootObject = root.GetInstance(componentDirectory, clientInstance,
                                                 requirementName, requirementType);

            // We create a view proxy.
            ConstructorInfo[] info = viewType.GetConstructors(
                BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

            foreach (ConstructorInfo constructor in info)
            {
                if (constructor.GetParameters().Length == 1)
                {
                    // We call first contructor with such parameters.
                    return(constructor.Invoke(new object[] { rootObject }));
                }
            }

            throw new Exception("Could not create view.");
        }
Esempio n. 16
0
        /// <summary>
        /// Application instance that lives in a dedicated app domain
        /// </summary>
        /// <param name="parentDirectory"></param>
        /// <param name="application"></param>
        /// <param name="instanceGuid"></param>
        internal AppDomainApplication(
            IComponentDirectory parentDirectory,
            ApplicationDesc application,
            Guid instanceGuid,
            ulong instanceNumber)
        {
            this.instanceGuid   = instanceGuid;
            this.instanceNumber = instanceNumber;

            string iname = application.Name + " " + instanceGuid.ToString();

            appDomain = AppDomain.CreateDomain(iname);

            /* create instance and unwrap the caller so that all the stuff happens in its own domain */
            this.bridge = appDomain.CreateInstanceAndUnwrap(
                typeof(Bridge).Assembly.FullName,
                typeof(Bridge).FullName) as Bridge;

            this.applicationDescriptor = application;

            /* set up the instance */
            this.bridge.Setup(parentDirectory, application, instanceGuid, this, parentDirectory.GetInstance <IAssemblyLoader>());
            this.bridge.Callback = this;
        }
        public IApplicationInstance Run(string path, string verb, string[] args, IComponentDirectory environ)
        {
            ApplicationDesc app = null;

            try
            {
                app = databaseManager.Find <ApplicationDesc>(path).Object;
            }
            catch (Exception)
            {
            }

            if (app == null)
            {
                throw new Exception(
                          String.Format(
                              "There is no application present at: '{0}'", path));
            }

            ComponentDirectory localEnvironment = new ComponentDirectory(this.componentDirectory, path);

            foreach (IComponentProvider component in environ.RegisteredProviders)
            {
                localEnvironment.Register(component);
            }

            LocalApplication application = new LocalApplication(
                localEnvironment,
                app, Guid.NewGuid(), NewInstanceNumber(app));

            application.Callback = this;
            applicationInstances.Add(application);
            application.Start(verb, args);

            return(application);
        }
Esempio n. 18
0
 public void Apply(IComponentDirectory toolDirectory)
 {
     // We apply as enum.
     toolDirectory.Register(new Instance(value, name));
 }
Esempio n. 19
0
        public virtual object GetInstance(
            IComponentDirectory componentDirectory,
            object clientInstance,
            string requirementName,
            string requirementType)
        {
            ComponentDirectory = componentDirectory;

            {
                object instance = requiredConfiguration.Instance;
                if (instance != null)
                {
                    return(instance);
                }
            }


            // 1. compute the best pre-initializer to use

            int currentScore = 0;
            int maxScore     = Int32.MinValue;
            IRequiresConfiguration currentInitializer = null;

            foreach (IRequiresConfiguration initializer in requiredConfiguration.PreInitializers)
            {
                // Console.Out.WriteLine("Initializer...");
                currentScore = 0;
                bool canUse = true;
                foreach (IRequirement req in initializer.Requirements)
                {
                    if (req.Default == null)
                    {
                        /* find the value */
                        if (configuration.Values.ContainsKey(req.Name))
                        {
                            currentScore++;
                        }
                        else if (HasComponent(componentDirectory, req.Type))
                        {
                            currentScore++;
                        }
                        else if (req.Hard)
                        {
                            /* DEBUG: Console.Out.WriteLine("Missing Parameter: {0} {1}", req.Type, req.Name); */
                            if (req.Hard)
                            {
                                canUse = false; break;
                            }
                        }
                        else
                        {
                            currentScore--;
                        }
                    }
                }

                if (canUse && (currentScore > maxScore))
                {
                    currentInitializer = initializer;
                    maxScore           = currentScore;
                }
            }
            // 1.1 give up if no pre-initializer can be used (because of unfulfillable hard requirements)
            if (currentInitializer == null)
            {
                throw new ComponentConfigurationException(this, "The component cannot be instantiated; No compatible pre-initializer exists");
            }

            // 1.2 give up if after pre-initialization, the object cannot be used (because of unfulfillable hard requirements)
            foreach (IRequirement req in requiredConfiguration.Requirements)
            {
                if (req.Default == null && req.Hard)
                {
                    /* if it's been solved through a pre-initializer */
                    bool found = false;
                    foreach (IRequirement reqpre in currentInitializer.Requirements)
                    {
                        if (reqpre.Name == req.Name)
                        {
                            found = true; break;
                        }
                    }

                    if (!found)
                    {
                        if (!req.ValueTypesOnly)
                        {
                            // query the ICD by type
                            if (HasComponent(componentDirectory, req.Type))
                            {
                                continue;
                            }
                        }

                        throw new ComponentConfigurationException(
                                  this,
                                  String.Format(
                                      "The component cannot be instantiated; After pre-initialization, the {0} requirement is not satisfied",
                                      req.Name));
                    }
                }
            }
            // 2. fill in the pre-initializer
            foreach (IRequirement req in currentInitializer.Requirements)
            {
                // Console.Out.WriteLine(">> PreInitializer Requirement: {0}", req.Name);
                if (configuration.Values.ContainsKey(req.Name))
                {
                    // Console.Out.WriteLine(" ... Contains Key");
                    req.SetValue(configuration.Values[req.Name].GetInstance(req.Type));
                }
                else
                {
                    if (req.Default != null)
                    {
                        // Console.Out.WriteLine(" ... Has Default");
                        req.SetValue(
                            componentDirectory.ConfigureInlineComponent(
                                new Instance(
                                    req.Default.GetInstance(req.Type))));
                    }
                    else if (HasComponent(componentDirectory, req.Type))
                    {
                        // Console.Out.WriteLine(" ... Setting By ICD (type={0})", req.Type);
                        req.SetValue(componentDirectory.GetInstanceByType(req.Type));
                    }
                    else if (req.Hard)
                    {
                        throw new ComponentConfigurationException(
                                  this,
                                  String.Format("ComponentOS KERNEL PANIC! I have no value for: {0}", req.Name));
                    }
                }
            }
            requiredConfiguration.Preinitialize(currentInitializer);

            return(ConfigureComponentWithRequirements(requiredConfiguration, configuration, componentDirectory));
        }
Esempio n. 20
0
 public void PostComponentInit(IComponentDirectory directory)
 {
     MeasurePerformance(TimeSpan.FromSeconds(1));
 }
Esempio n. 21
0
        private static void ImportCommands(XmlElement xmlElement, List <ICommand> list, IComponentDirectory componentEnvironment)
        {
            foreach (XmlNode node in xmlElement.ChildNodes)
            {
                if (!(node is XmlElement))
                {
                    continue;
                }
                XmlElement cmdElement = node as XmlElement;

                try
                {
                    string asmName = "assembly";  string asm = "SharpMedia";
                    string nspName = "namespace"; string nsp = "SharpMedia.Components.Installation.Commands";

                    if (cmdElement.HasAttribute(asmName))
                    {
                        asm = cmdElement.GetAttribute(asmName);
                    }
                    if (cmdElement.HasAttribute(nspName))
                    {
                        nsp = cmdElement.GetAttribute(nspName);
                    }

                    /* fix the instance */
                    object instance = componentEnvironment.ConfigureInlineComponent(
                        new ConfiguredComponent(
                            String.Format("{0}.{1},{2}", nsp, cmdElement.Name, asm),
                            new StandardConfiguration(cmdElement)));


                    foreach (XmlAttribute attrib in cmdElement.Attributes)
                    {
                        if (attrib.Name == asmName || attrib.Name == nspName)
                        {
                            continue;
                        }

                        PropertyInfo pinfo = instance.GetType().GetProperty(attrib.Name);
                        if (pinfo == null)
                        {
                            throw new Exception(String.Format("Command {0} does not support the {1} parameter", instance.GetType(), attrib.Name));
                        }

                        if (!pinfo.PropertyType.IsArray)
                        {
                            pinfo.SetValue(instance, attrib.Value, null);
                        }
                        else
                        {
                            pinfo.SetValue(instance, attrib.Value.Split(','), null);
                        }
                    }
                    list.Add(instance as ICommand);
                }
                catch (Exception e)
                {
                    throw new UnsupportedPackageFormatException("Command " + cmdElement.Name + " did not read properly", e);
                }
            }
        }
Esempio n. 22
0
 object IComponentProvider.GetInstance(IComponentDirectory componentDirectory,
                                       object clientInstance, string requirementName, string requirementType)
 {
     // For now just return this, configuration may come later.
     return(this);
 }
Esempio n. 23
0
        /// <summary>
        /// Extracts a value.
        /// </summary>
        /// <param name="targetType"></param>
        /// <param name="value"></param>
        /// <param name="directory"></param>
        /// <returns></returns>
        private static IComponentProvider ExtractValue(Type targetType, string name, string value, IComponentDirectory directory)
        {
            // We first check if it is a link.
            if (value.Length == 0)
            {
                return(null);
            }

            // We try to transform to specific type.
            return(new Instance(Configuration.ConfigurationValues.Simple.StringToType(targetType, value), name, false, true));
        }
Esempio n. 24
0
 public void Apply(IComponentDirectory toolDirectory)
 {
     MatchThrow(path);
 }
Esempio n. 25
0
 public ComponentDirectory(IComponentDirectory parent, string myName)
     : this()
 {
     this.namespaceName = myName;
     this.parent        = parent;
 }
Esempio n. 26
0
 public object GetInstance(IComponentDirectory componentDirectory, object clientInstance, string requirementName, string requirementType)
 {
     return(provider.GetInstance(componentDirectory, clientInstance, requirementName, requirementType));
 }
Esempio n. 27
0
 public object GetInstance(IComponentDirectory componentDirectory, object clientInstance, string requirementName, string requirementType)
 {
     return(instance);
 }