Example #1
0
        /// <returns>a Zetbox TypeRef for a given System.Type</returns>
        public static TypeRef ToRef(this Type t, IReadOnlyZetboxContext ctx)
        {
            if (t == null)
            {
                throw new ArgumentNullException("t");
            }
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            // TODO: think about and implement naked types (i.e. without arguments)
            if (t.IsGenericTypeDefinition)
            {
                throw new ArgumentOutOfRangeException("t");
            }

            var result = GetFromCache(t, ctx);

            if (result != null)
            {
                return(result);
            }

            result = LookupByType(ctx, ctx.GetQuery <TypeRef>(), t);
            if (result != null)
            {
                AddToCache(t, result, ctx);
            }

            return(result);
        }
        public static CompoundObject GetCompoundObjectDefinition(this ICompoundObject obj, IReadOnlyZetboxContext ctx)
        {
            if (obj == null) { throw new ArgumentNullException("obj"); }
            if (ctx == null) { throw new ArgumentNullException("ctx"); }

            return GetCompoundObjectDefinition(ctx.GetInterfaceType(obj), ctx);
        }
Example #3
0
        /// <summary>
        /// Initializes caches for the provider of the given Context
        /// </summary>
        /// <param name="metaCtx">the context used to access the meta data</param>
        private void CreateInvokeInfosForDataTypes(IReadOnlyZetboxContext metaCtx)
        {
            if (metaCtx == null)
            {
                throw new ArgumentNullException("metaCtx");
            }

            foreach (var objClass in metaCtx.GetQuery <CompoundObject>())
            {
                try
                {
                    CreateInvokeInfosForAssembly(objClass);
                }
                catch (Exception ex)
                {
                    Log.Warn("Exception in CreateInvokeInfosForObjectClasses", ex);
                }
            }

            // put this in separate loop to avoid mono bug #701187
            // see https://bugzilla.novell.com/show_bug.cgi?id=701187
            foreach (var objClass in metaCtx.GetQuery <ObjectClass>())
            {
                try
                {
                    CreateInvokeInfosForAssembly(objClass);
                }
                catch (Exception ex)
                {
                    Log.Warn("Exception in CreateInvokeInfosForObjectClasses", ex);
                }
            }
        }
Example #4
0
 public static void ExportFromContext(IReadOnlyZetboxContext ctx, string filename, string[] schemaModules, string[] ownerModules)
 {
     using (var s = new FileSystemPackageProvider(filename, BasePackageProvider.Modes.Write))
     {
         ExportFromContext(ctx, s, schemaModules, ownerModules);
     }
 }
Example #5
0
 public static void ExportFromContext(IReadOnlyZetboxContext ctx, Stream stream, string[] schemaModules, string[] ownerModules, string streamDescription)
 {
     using (var s = new StreamPackageProvider(stream, BasePackageProvider.Modes.Write, streamDescription))
     {
         ExportFromContext(ctx, s, schemaModules, ownerModules);
     }
 }
Example #6
0
 public static void ExportFromContext(IReadOnlyZetboxContext ctx, Stream stream, string[] schemaModules, string[] ownerModules, string streamDescription)
 {
     using (var s = new StreamPackageProvider(stream, BasePackageProvider.Modes.Write, streamDescription))
     {
         ExportFromContext(ctx, s, schemaModules, ownerModules);
     }
 }
Example #7
0
        public static TCacheItem TransientState <TCacheItem>(this IReadOnlyZetboxContext ctx, string transientCacheKey, Func <TCacheItem> getter)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }
            if (string.IsNullOrEmpty(transientCacheKey))
            {
                throw new ArgumentNullException("transientCacheKey");
            }
            if (getter == null)
            {
                throw new ArgumentNullException("getter");
            }

            if (!ctx.TransientState.ContainsKey(transientCacheKey))
            {
                var result = getter();
                ctx.TransientState[transientCacheKey] = result;
                return(result);
            }
            else
            {
                // Cachehit
                // Maybe count it here
                return((TCacheItem)ctx.TransientState[transientCacheKey]);
            }
        }
Example #8
0
 public static void ExportFromContext(IReadOnlyZetboxContext ctx, string filename, string[] schemaModules, string[] ownerModules)
 {
     using (var s = new FileSystemPackageProvider(filename, BasePackageProvider.Modes.Write))
     {
         ExportFromContext(ctx, s, schemaModules, ownerModules);
     }
 }
Example #9
0
        public static void CollectChildClasses(this ObjectClass cls, IReadOnlyZetboxContext ctx, List <ObjectClass> children, bool includeAbstract)
        {
            if (cls == null)
            {
                throw new ArgumentNullException("cls");
            }
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }
            if (children == null)
            {
                throw new ArgumentNullException("children");
            }

            var nextChildren = ctx
                               .GetQuery <ObjectClass>()
                               .Where(oc => oc.BaseObjectClass != null && oc.BaseObjectClass.ID == cls.ID)
                               .ToList();

            if (nextChildren.Count() > 0)
            {
                foreach (ObjectClass oc in nextChildren)
                {
                    if (includeAbstract || !oc.IsAbstract)
                    {
                        children.Add(oc);
                    }
                    CollectChildClasses(oc, ctx, children, includeAbstract);
                }
                ;
            }
        }
Example #10
0
        /// <summary>
        /// Initializes this CustomActionsManager. This method is thread-safe and won't do
        /// anything if the ActionsManager is already initialized.
        /// </summary>
        public virtual void Init(IReadOnlyZetboxContext ctx)
        {
            lock (_initLock)
            {
                var implType = this.GetType();
                if (_initImpls.ContainsKey(implType))
                {
                    return;
                }
                try
                {
                    Log.InfoFormat("Initializing Actions for [{0}] by [{1}]", ExtraSuffix, implType.Name);
                    Log.TraceTotalMemory("Before BaseCustomActionsManager.Init()");

                    ReflectMethods(ctx);
                    CreateInvokeInfosForDataTypes(ctx);

                    foreach (var key in _reflectedMethods.Where(i => !_attachedMethods.ContainsKey(i.Key)).Select(i => i.Key))
                    {
                        Log.Warn(string.Format("Couldn't find any method for Invocation {0}", key));
                    }

                    Log.TraceTotalMemory("After BaseCustomActionsManager.Init()");
                }
                finally
                {
                    _initImpls[implType] = implType;
                }
            }
        }
Example #11
0
        public IEnumerable <T> Find(IReadOnlyZetboxContext ctx)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            return(ctx.FindPersistenceObjects <T>(_guid));
        }
Example #12
0
        public static CompoundObject GetCompoundObjectDefinition(this InterfaceType ifType, IReadOnlyZetboxContext ctx)
        {
            if (ctx == null) { throw new ArgumentNullException("ctx"); }

            Type type = ifType.Type;
            CompoundObject result;
            result = ctx.TransientState("__CompoundObjectExtensions__GetCompoundObjectDefinition__", type, () => ctx.GetQuery<CompoundObject>().First(o => o.Module.Namespace == type.Namespace && o.Name == type.Name));

            return result;
        }
Example #13
0
        private static void AddToCache(Type t, TypeRef tr, IReadOnlyZetboxContext ctx)
        {
            if (!ctx.TransientState.ContainsKey(transientCacheKey))
            {
                ctx.TransientState[transientCacheKey] = new Dictionary <Type, TypeRef>();
            }
            var cache = (Dictionary <Type, TypeRef>)ctx.TransientState[transientCacheKey];

            cache[t] = tr;
        }
Example #14
0
        public static Interface GetIExportableInterface(this IReadOnlyZetboxContext ctx)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            // TODO: use named objects
            return(ctx.GetQuery <Zetbox.App.Base.Interface>().First(o => o.Name == "IExportable" && o.Module.Name == "ZetboxBase"));
        }
Example #15
0
 private static void PrimeCaches(Toolkit?tk, IReadOnlyZetboxContext ctx)
 {
     if (_pmdCache == null)
     {
         _pmdCache = new ViewModelDescriptorCache(ctx);
     }
     if (tk.HasValue && !_viewCaches.ContainsKey(tk.Value))
     {
         _viewCaches[tk.Value] = ViewDescriptorToolkitCache.Content.CreateCache(tk.Value, ctx);
     }
 }
Example #16
0
        public static ObjectClass GetObjectClass(this IDataObject obj, IReadOnlyZetboxContext ctx)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            return(ctx.FindPersistenceObject <ObjectClass>(obj.ObjectClassID));
        }
 public override IServerCollectionHandler GetServerCollectionHandler(
     IReadOnlyZetboxContext ctx,
     InterfaceType aType,
     InterfaceType bType,
     RelationEndRole endRole)
 {
     if (ctx == null) throw new ArgumentNullException("ctx");
     return GetServerCollectionHandlerHelper(
         typeof(ServerCollectionHandler<,,,>),
         ctx.ToImplementationType(aType),
         ctx.ToImplementationType(bType),
         endRole);
 }
Example #18
0
        private static TypeRef GetFromCache(Type t, IReadOnlyZetboxContext ctx)
        {
            if (!ctx.TransientState.ContainsKey(transientCacheKey))
            {
                ctx.TransientState[transientCacheKey] = new Dictionary <Type, TypeRef>();
            }
            var cache = (Dictionary <Type, TypeRef>)ctx.TransientState[transientCacheKey];

            if (cache.ContainsKey(t))
            {
                return(cache[t]);
            }
            return(null);
        }
Example #19
0
            public static Content CreateCache(Toolkit tk, IReadOnlyZetboxContext ctx)
            {
                var result = new Content();

                // All View Descriptors for the given Toolkit
                result._allVDCache = new ReadOnlyCollection <ViewDescriptor>(
                    ctx.GetQuery <ViewDescriptor>().WithEagerLoading().Where(obj => obj.Toolkit == tk).ToList());

                // Dictionary by Kind
                result._vdCache = result._allVDCache.Where(obj => obj.ControlKind != null).GroupBy(obj => obj.ControlKind)
                                  .ToDictionary(g => g.Key.ExportGuid, g => new ReadOnlyCollection <ViewDescriptor>(g.ToList()));

                return(result);
            }
Example #20
0
        public static ObjectClass GetObjectClass(this Type type, IReadOnlyZetboxContext ctx)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            ObjectClass result = ctx.TransientState("__ObjectClassExtensions__GetObjectClass__", type.FullName, () => ctx.GetQuery <ObjectClass>().First(o => o.Module.Namespace == type.Namespace && o.Name == type.Name));

            return(result);
        }
Example #21
0
        /// <returns>a Zetbox TypeRef for a given System.Type</returns>
        public static TypeRef ToRef(this Type t, IReadOnlyZetboxContext ctx)
        {
            if (t == null) { throw new ArgumentNullException("t"); }
            if (ctx == null) { throw new ArgumentNullException("ctx"); }

            // TODO: think about and implement naked types (i.e. without arguments)
            if (t.IsGenericTypeDefinition) { throw new ArgumentOutOfRangeException("t"); }

            var result = GetFromCache(t, ctx);
            if (result != null) return result;

            result = LookupByType(ctx, ctx.GetQuery<TypeRef>(), t);
            if (result != null)  AddToCache(t, result, ctx);

            return result;
        }
Example #22
0
 public void Submitted(IReadOnlyZetboxContext ctx, IEnumerable<IDataObject> added, IEnumerable<IDataObject> modified, IEnumerable<Tuple<InterfaceType, int>> deleted)
 {
     _queue.Enqueue(new IndexUpdate()
     {
         added = added.Select(obj => new Tuple<InterfaceType, int, IndexUpdate.Text>(
             ctx.GetInterfaceType(obj),
             obj.ID,
             Rebuilder.ExtractText(obj, _formatter, _resolver)
         )).ToList().AsReadOnly(),
         modified = modified.Select(obj => new Tuple<InterfaceType, int, IndexUpdate.Text>(
             ctx.GetInterfaceType(obj),
             obj.ID,
             Rebuilder.ExtractText(obj, _formatter, _resolver)
         )).ToList().AsReadOnly(),
         deleted = deleted.ToList().AsReadOnly()
     });
 }
Example #23
0
        public ToStringFilterModel(IReadOnlyZetboxContext frozenCtx)
            : base()
        {
            if (frozenCtx == null)
            {
                throw new ArgumentNullException("frozenCtx");
            }
            base.IsServerSideFilter = false;
            base.Label         = FilterModelsResources.ToStringFilterModel_Label;
            base.ViewModelType = ViewModelDescriptors.Zetbox_Client_Presentables_FilterViewModels_SingleValueFilterViewModel.Find(frozenCtx);
            base.FilterArguments.Add(new FilterArgumentConfig(
                                         new ClassValueModel <string>(base.Label, FilterModelsResources.ToStringFilterModel_Description, true, false),
                                         ViewModelDescriptors.Zetbox_Client_Presentables_ValueViewModels_ClassValueViewModel_1_System_String_.Find(frozenCtx)
                                         ));

            base.RefreshOnFilterChanged = false;
        }
Example #24
0
        private static TypeRef LookupByType(IReadOnlyZetboxContext ctx, IQueryable <TypeRef> source, Type t)
        {
            // TODO: think about and implement naked types (i.e. without arguments)
            if (t.IsGenericTypeDefinition)
            {
                throw new ArgumentOutOfRangeException("t");
            }

            if (t.IsGenericType)
            {
                string fullName  = t.GetGenericTypeDefinition().FullName;
                var    args      = t.GetGenericArguments().Select(arg => arg.ToRef(ctx)).ToArray();
                var    argsCount = args.Count();
                foreach (var tRef in source.Where(tRef
                                                  => tRef.Assembly.Name == t.Assembly.FullName &&
                                                  tRef.FullName == fullName &&
                                                  tRef.GenericArguments.Count == argsCount))
                {
                    bool equal = true;
                    for (int i = 0; i < tRef.GenericArguments.Count; i++)
                    {
                        equal &= args[i] == tRef.GenericArguments[i];
                        if (!equal)
                        {
                            break;
                        }
                    }
                    if (equal)
                    {
                        return(tRef);
                    }
                }
                return(null);
            }
            else
            {
                // ToList: Workaround Case 1212
                return(source.FirstOrDefault(tRef
                                             => tRef.Assembly.Name == t.Assembly.FullName &&
                                             tRef.FullName == t.FullName &&
                                             tRef.GenericArguments.Count == 0));
            }
        }
Example #25
0
        public static void CollectChildClasses(this ObjectClass cls, IReadOnlyZetboxContext ctx, List<ObjectClass> children, bool includeAbstract)
        {
            if (cls == null) throw new ArgumentNullException("cls");
            if (ctx == null) throw new ArgumentNullException("ctx");
            if (children == null) throw new ArgumentNullException("children");

            var nextChildren = ctx
                .GetQuery<ObjectClass>()
                .Where(oc => oc.BaseObjectClass != null && oc.BaseObjectClass.ID == cls.ID)
                .ToList();

            if (nextChildren.Count() > 0)
            {
                foreach (ObjectClass oc in nextChildren)
                {
                    if (includeAbstract || !oc.IsAbstract) children.Add(oc);
                    CollectChildClasses(oc, ctx, children, includeAbstract);
                };
            }
        }
Example #26
0
        private static void WriteStartDocument(IPackageProvider s, IReadOnlyZetboxContext ctx, IEnumerable <Zetbox.App.Base.Module> moduleList)
        {
            XmlWriter writer = s.Writer;

            writer.WriteStartDocument();
            if (moduleList.Count() == 1)
            {
                // use exported module as default namespace
                writer.WriteStartElement("ZetboxPackaging", "http://dasz.at/Zetbox");
                foreach (var module in moduleList)
                {
                    writer.WriteAttributeString("xmlns", module.Name, null, module.Namespace);
                }
            }
            else
            {
                writer.WriteStartElement("ZetboxPackaging", "http://dasz.at/Zetbox");
                foreach (var module in moduleList)
                {
                    writer.WriteAttributeString("xmlns", module.Name, null, module.Namespace);
                }
            }

            DateTime?lastChanged = new DateTime?[] {
                ctx.GetQuery <Zetbox.App.Base.Assembly>().Max(d => d.ChangedOn),
                ctx.GetQuery <Zetbox.App.Base.BaseParameter>().Max(d => d.ChangedOn),
                ctx.GetQuery <Zetbox.App.Base.Constraint>().Max(d => d.ChangedOn),
                ctx.GetQuery <Zetbox.App.Base.DataType>().Max(d => d.ChangedOn),
                ctx.GetQuery <Zetbox.App.Base.DefaultPropertyValue>().Max(d => d.ChangedOn),
                ctx.GetQuery <Zetbox.App.Base.EnumerationEntry>().Max(d => d.ChangedOn),
                ctx.GetQuery <Zetbox.App.Base.Method>().Max(d => d.ChangedOn),
                ctx.GetQuery <Zetbox.App.Base.Module>().Max(d => d.ChangedOn),
                ctx.GetQuery <Zetbox.App.Base.Property>().Max(d => d.ChangedOn),
                ctx.GetQuery <Zetbox.App.Base.Relation>().Max(d => d.ChangedOn),
                ctx.GetQuery <Zetbox.App.Base.RelationEnd>().Max(d => d.ChangedOn),
                ctx.GetQuery <Zetbox.App.Base.TypeRef>().Max(d => d.ChangedOn)
            }.Max();

            writer.WriteAttributeString("date", XmlConvert.ToString(lastChanged ?? DateTime.Now, XmlDateTimeSerializationMode.Utc));
        }
Example #27
0
 private static Zetbox.App.Base.Module[] GetModules(IReadOnlyZetboxContext ctx, string[] moduleNames)
 {
     var moduleList = new List<Zetbox.App.Base.Module>();
     if (moduleNames.Contains("*"))
     {
         moduleList.AddRange(ctx.GetQuery<Zetbox.App.Base.Module>());
     }
     else
     {
         foreach (var name in moduleNames)
         {
             var module = ctx.GetQuery<Zetbox.App.Base.Module>().Where(m => m.Name == name).FirstOrDefault();
             if (module == null)
             {
                 Log.WarnFormat("Module {0} not found, skipping entry", name);
                 continue;
             }
             moduleList.Add(module);
         }
     }
     return moduleList.OrderBy(m => m.Name).ToArray();
 }
Example #28
0
        public static TCacheItem TransientState <TCacheItem, TKey>(this IReadOnlyZetboxContext ctx, string transientCacheKey, TKey key, Func <TCacheItem> getter)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }
            if (string.IsNullOrEmpty(transientCacheKey))
            {
                throw new ArgumentNullException("transientCacheKey");
            }
            if (getter == null)
            {
                throw new ArgumentNullException("getter");
            }

            // Ensure cache
            // Ensure transient cache
            if (!ctx.TransientState.ContainsKey(transientCacheKey))
            {
                ctx.TransientState[transientCacheKey] = new Dictionary <TKey, TCacheItem>();
            }
            Dictionary <TKey, TCacheItem> cache = (Dictionary <TKey, TCacheItem>)ctx.TransientState[transientCacheKey];

            TCacheItem result;

            if (!cache.TryGetValue(key, out result))
            {
                result     = getter();
                cache[key] = result;
                return(result);
            }
            else
            {
                // Cachehit
                // Maybe count it here
                return(result);
            }
        }
Example #29
0
        private static List <Zetbox.App.Base.Module> GetModules(IReadOnlyZetboxContext ctx, string[] moduleNames)
        {
            var moduleList = new List <Zetbox.App.Base.Module>();

            if (moduleNames.Contains("*"))
            {
                moduleList.AddRange(ctx.GetQuery <Zetbox.App.Base.Module>());
            }
            else
            {
                foreach (var name in moduleNames)
                {
                    var module = ctx.GetQuery <Zetbox.App.Base.Module>().Where(m => m.Name == name).FirstOrDefault();
                    if (module == null)
                    {
                        Log.WarnFormat("Module {0} not found, skipping entry", name);
                        continue;
                    }
                    moduleList.Add(module);
                }
            }
            return(moduleList.OrderBy(m => m.Name).ToList());
        }
Example #30
0
        private void ReflectMethods(IReadOnlyZetboxContext metaCtx)
        {
            if (metaCtx == null)
            {
                throw new ArgumentNullException("metaCtx");
            }

            // Load all Implementor Types and Invocations
            foreach (var assembly in metaCtx.GetQuery <Zetbox.App.Base.Assembly>())
            {
                try
                {
                    var restr = assembly.DeploymentRestrictions;
                    if (!_restrictor.IsAcceptableDeploymentRestriction((int)restr))
                    {
                        continue;
                    }

                    System.Reflection.Assembly a;
                    a = System.Reflection.Assembly.Load(assembly.Name);

                    foreach (var t in a.GetTypes())
                    {
                        if (t.GetCustomAttributes(typeof(Implementor), false).Length != 0)
                        {
                            if (!t.Name.EndsWith("Actions"))
                            {
                                Log.Warn(string.Format("Type {0} does not end with 'Actions'. Ignoring this type", t.FullName));
                                continue;
                            }

                            // Found Implementor Type
                            foreach (var m in t.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                            {
                                if (m.GetCustomAttributes(typeof(Invocation), false).Length != 0)
                                {
                                    var key = new MethodKey(t.Namespace, t.Name.Substring(0, t.Name.Length - "Actions".Length), m.Name);
                                    if (_reflectedMethods.ContainsKey(key))
                                    {
                                        _reflectedMethods[key].Add(m);
                                    }
                                    else
                                    {
                                        _reflectedMethods[key] = new List <MethodInfo>()
                                        {
                                            m
                                        };
                                    }
                                }
                                else if (m.GetCustomAttributes(typeof(Zetbox.API.Constraint), false).Length != 0)
                                {
                                    // TODO: Check if Invoking Constraint is valid
                                }
                                else
                                {
                                    Log.Warn(string.Format("Found public method {0}.{1} which has no Invocation attribute. Ignoring this method", t.FullName, m.Name));
                                }
                            }
                        }
                    }
                }
                catch (ReflectionTypeLoadException ex)
                {
                    if (ex.LoaderExceptions.Count() == 1)
                    {
                        Log.Warn(String.Format("Failed to reflect over Assembly [{0}]. Ignoring and continuing.", assembly.Name), ex.LoaderExceptions.Single());
                    }
                    else
                    {
                        foreach (var lex in ex.LoaderExceptions)
                        {
                            Log.Warn(String.Format("Failed to reflect over Assembly [{0}]. Ignoring and continuing. Multiple Errors:", assembly.Name), lex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Warn(String.Format("Error while processing Assembly [{0}]. Ignoring and continuing.", assembly.Name), ex);
                }
            }
        }
        /// <summary>
        /// Initializes caches for the provider of the given Context
        /// </summary>
        /// <param name="metaCtx">the context used to access the meta data</param>
        private void CreateInvokeInfosForDataTypes(IReadOnlyZetboxContext metaCtx)
        {
            if (metaCtx == null) { throw new ArgumentNullException("metaCtx"); }

            foreach (var objClass in metaCtx.GetQuery<CompoundObject>())
            {
                try
                {
                    CreateInvokeInfosForAssembly(objClass);
                }
                catch (Exception ex)
                {
                    Log.Warn("Exception in CreateInvokeInfosForObjectClasses", ex);
                }
            }

            // put this in separate loop to avoid mono bug #701187
            // see https://bugzilla.novell.com/show_bug.cgi?id=701187
            foreach (var objClass in metaCtx.GetQuery<ObjectClass>())
            {
                try
                {
                    CreateInvokeInfosForAssembly(objClass);
                }
                catch (Exception ex)
                {
                    Log.Warn("Exception in CreateInvokeInfosForObjectClasses", ex);
                }
            }
        }
 /// <inheritdoc/>
 public abstract IServerCollectionHandler GetServerCollectionHandler(IReadOnlyZetboxContext ctx, InterfaceType aType, InterfaceType bType, RelationEndRole endRole);
Example #33
0
 public void Disposed(IReadOnlyZetboxContext ctx)
 {
 }
Example #34
0
 public ViewModelDescriptorCache(IReadOnlyZetboxContext ctx)
 {
     _context = ctx;
     FillCache();
 }
Example #35
0
        public static CompoundObject GetCompoundObjectDefinition(this ICompoundObject obj, IReadOnlyZetboxContext ctx)
        {
            if (obj == null)
            {
                throw new ArgumentNullException("obj");
            }
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            return(GetCompoundObjectDefinition(ctx.GetInterfaceType(obj), ctx));
        }
        private void ReflectMethods(IReadOnlyZetboxContext metaCtx)
        {
            if (metaCtx == null) { throw new ArgumentNullException("metaCtx"); }

            // Load all Implementor Types and Invocations
            foreach (var assembly in metaCtx.GetQuery<Zetbox.App.Base.Assembly>())
            {
                try
                {
                    var restr = assembly.DeploymentRestrictions;
                    if (!_restrictor.IsAcceptableDeploymentRestriction((int)restr))
                    {
                        continue;
                    }

                    System.Reflection.Assembly a;
                    a = System.Reflection.Assembly.Load(assembly.Name);

                    foreach (var t in a.GetTypes())
                    {
                        if (t.GetCustomAttributes(typeof(Implementor), false).Length != 0)
                        {
                            if (!t.Name.EndsWith("Actions"))
                            {
                                Log.Warn(string.Format("Type {0} does not end with 'Actions'. Ignoring this type", t.FullName));
                                continue;
                            }

                            // Found Implementor Type
                            foreach (var m in t.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly))
                            {
                                if (m.GetCustomAttributes(typeof(Invocation), false).Length != 0)
                                {
                                    var key = new MethodKey(t.Namespace, t.Name.Substring(0, t.Name.Length - "Actions".Length), m.Name);
                                    if (_reflectedMethods.ContainsKey(key))
                                    {
                                        _reflectedMethods[key].Add(m);
                                    }
                                    else
                                    {
                                        _reflectedMethods[key] = new List<MethodInfo>() { m };
                                    }
                                }
                                else if (m.GetCustomAttributes(typeof(Zetbox.API.Constraint), false).Length != 0)
                                {
                                    // TODO: Check if Invoking Constraint is valid
                                }
                                else
                                {
                                    Log.Warn(string.Format("Found public method {0}.{1} which has no Invocation attribute. Ignoring this method", t.FullName, m.Name));
                                }
                            }
                        }
                    }
                }
                catch (ReflectionTypeLoadException ex)
                {
                    if (ex.LoaderExceptions.Count() == 1)
                    {
                        Log.Warn(String.Format("Failed to reflect over Assembly [{0}]. Ignoring and continuing.", assembly.Name), ex.LoaderExceptions.Single());
                    }
                    else
                    {
                        foreach (var lex in ex.LoaderExceptions)
                        {
                            Log.Warn(String.Format("Failed to reflect over Assembly [{0}]. Ignoring and continuing. Multiple Errors:", assembly.Name), lex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log.Warn(String.Format("Error while processing Assembly [{0}]. Ignoring and continuing.", assembly.Name), ex);
                }
            }
        }
        /// <summary>
        /// Initializes this CustomActionsManager. This method is thread-safe and won't do
        /// anything if the ActionsManager is already initialized.
        /// </summary>
        public virtual void Init(IReadOnlyZetboxContext ctx)
        {
            lock (_initLock)
            {
                var implType = this.GetType();
                if (_initImpls.ContainsKey(implType)) return;
                try
                {
                    Log.InfoFormat("Initializing Actions for [{0}] by [{1}]", ExtraSuffix, implType.Name);
                    Log.TraceTotalMemory("Before BaseCustomActionsManager.Init()");

                    ReflectMethods(ctx);
                    CreateInvokeInfosForDataTypes(ctx);

                    foreach (var key in _reflectedMethods.Where(i => !_attachedMethods.ContainsKey(i.Key)).Select(i => i.Key))
                    {
                        Log.Warn(string.Format("Couldn't find any method for Invocation {0}", key));
                    }

                    Log.TraceTotalMemory("After BaseCustomActionsManager.Init()");
                }
                finally
                {
                    _initImpls[implType] = implType;
                }
            }
        }
Example #38
0
        private static void WriteStartDocument(IPackageProvider s, IReadOnlyZetboxContext ctx, IEnumerable<Zetbox.App.Base.Module> moduleList)
        {
            XmlWriter writer = s.Writer;
            writer.WriteStartDocument();
            if (moduleList.Count() == 1)
            {
                // use exported module as default namespace
                writer.WriteStartElement("ZetboxPackaging", "http://dasz.at/Zetbox");
                foreach (var module in moduleList)
                {
                    writer.WriteAttributeString("xmlns", module.Name, null, module.Namespace);
                }
            }
            else
            {
                writer.WriteStartElement("ZetboxPackaging", "http://dasz.at/Zetbox");
                foreach (var module in moduleList)
                {
                    writer.WriteAttributeString("xmlns", module.Name, null, module.Namespace);
                }
            }

            DateTime? lastChanged = new DateTime?[] {
                ctx.GetQuery<Zetbox.App.Base.Assembly>().Max(d => d.ChangedOn),
                ctx.GetQuery<Zetbox.App.Base.BaseParameter>().Max(d => d.ChangedOn),
                ctx.GetQuery<Zetbox.App.Base.Constraint>().Max(d => d.ChangedOn),
                ctx.GetQuery<Zetbox.App.Base.DataType>().Max(d => d.ChangedOn),
                ctx.GetQuery<Zetbox.App.Base.DefaultPropertyValue>().Max(d => d.ChangedOn),
                ctx.GetQuery<Zetbox.App.Base.EnumerationEntry>().Max(d => d.ChangedOn),
                ctx.GetQuery<Zetbox.App.Base.Method>().Max(d => d.ChangedOn),
                ctx.GetQuery<Zetbox.App.Base.Module>().Max(d => d.ChangedOn),
                ctx.GetQuery<Zetbox.App.Base.Property>().Max(d => d.ChangedOn),
                ctx.GetQuery<Zetbox.App.Base.Relation>().Max(d => d.ChangedOn),
                ctx.GetQuery<Zetbox.App.Base.RelationEnd>().Max(d => d.ChangedOn),
                ctx.GetQuery<Zetbox.App.Base.TypeRef>().Max(d => d.ChangedOn)
            }.Max();

            writer.WriteAttributeString("date", XmlConvert.ToString(lastChanged ?? DateTime.Now, XmlDateTimeSerializationMode.Utc));
        }
Example #39
0
 public void Init(IReadOnlyZetboxContext ctx)
 {
     Reset();
 }
Example #40
0
 public static IZetboxContextInternals Internals(this IReadOnlyZetboxContext ctx)
 {
     return((IZetboxContextInternals)ctx);
 }
Example #41
0
 private static void PrimeCaches(Toolkit? tk, IReadOnlyZetboxContext ctx)
 {
     if (_pmdCache == null)
     {
         _pmdCache = new ViewModelDescriptorCache(ctx);
     }
     if (tk.HasValue && !_viewCaches.ContainsKey(tk.Value))
     {
         _viewCaches[tk.Value] = ViewDescriptorToolkitCache.Content.CreateCache(tk.Value, ctx);
     }
 }
Example #42
0
 public void Init(IReadOnlyZetboxContext ctx)
 {
     // ignore
 }
Example #43
0
 public override void SetUp()
 {
     base.SetUp();
     ctx = GetContext();
 }
Example #44
0
 private static void AddToCache(Type t, TypeRef tr, IReadOnlyZetboxContext ctx)
 {
     if (!ctx.TransientState.ContainsKey(transientCacheKey))
     {
         ctx.TransientState[transientCacheKey] = new Dictionary<Type, TypeRef>();
     }
     var cache = (Dictionary<Type, TypeRef>)ctx.TransientState[transientCacheKey];
     cache[t] = tr;
 }
Example #45
0
        public static CompoundObject GetCompoundObjectDefinition(this InterfaceType ifType, IReadOnlyZetboxContext ctx)
        {
            if (ctx == null)
            {
                throw new ArgumentNullException("ctx");
            }

            Type           type = ifType.Type;
            CompoundObject result;

            result = ctx.TransientState("__CompoundObjectExtensions__GetCompoundObjectDefinition__", type, () => ctx.GetQuery <CompoundObject>().First(o => o.Module.Namespace == type.Namespace && o.Name == type.Name));

            return(result);
        }
Example #46
0
        private static TypeRef LookupByType(IReadOnlyZetboxContext ctx, IQueryable<TypeRef> source, Type t)
        {
            // TODO: think about and implement naked types (i.e. without arguments)
            if (t.IsGenericTypeDefinition) throw new ArgumentOutOfRangeException("t");

            if (t.IsGenericType)
            {
                string fullName = t.GetGenericTypeDefinition().FullName;
                var args = t.GetGenericArguments().Select(arg => arg.ToRef(ctx)).ToArray();
                var argsCount = args.Count();
                foreach (var tRef in source.Where(tRef
                    => tRef.Assembly.Name == t.Assembly.FullName
                    && tRef.FullName == fullName
                    && tRef.GenericArguments.Count == argsCount))
                {
                    bool equal = true;
                    for (int i = 0; i < tRef.GenericArguments.Count; i++)
                    {
                        equal &= args[i] == tRef.GenericArguments[i];
                        if (!equal)
                            break;
                    }
                    if (equal)
                        return tRef;
                }
                return null;
            }
            else
            {
                // ToList: Workaround Case 1212
                return source.FirstOrDefault(tRef
                    => tRef.Assembly.Name == t.Assembly.FullName
                    && tRef.FullName == t.FullName
                    && tRef.GenericArguments.Count == 0);
            }
        }
Example #47
0
        /// <summary>
        /// Exports data from the specified context into the specified package provider. Data is selected by defining
        /// schema and owning module.
        /// </summary>
        /// <remarks>
        /// <para>For example, exporting {"ZetboxBase", "GUI"}/{"*"} will export all schema information to recreate the
        /// current database. Exporting {"Calendar"}/{"MyApplication"} will export all calendar data specific to the
        /// "MyApplication" module.
        /// </para>
        /// </remarks>
        /// <param name="ctx">The data source</param>
        /// <param name="s">The export target</param>
        /// <param name="schemaModules">A list of strings naming the schema-defining modules. This selects which data
        /// (-classes) should be exported. Specify a single asterisk (<code>"*"</code>) to select all available
        /// modules.</param>
        /// <param name="ownerModules">A list of strings naming the data-owning modules. This selects whose data should
        /// be exported.  Specify a single asterisk (<code>"*"</code>) to select all available data, independent of
        /// module-membership. This also includes data that is not member of any module.</param>
        public static void ExportFromContext(IReadOnlyZetboxContext ctx, IPackageProvider s, string[] schemaModules, string[] ownerModules)
        {
            using (Log.DebugTraceMethodCall("ExportFromContext"))
            {
                Log.InfoFormat("Starting Export for Modules [{0}], data owned by [{1}]", string.Join(", ", schemaModules), string.Join(", ", ownerModules));

                var allData = ownerModules.Contains("*");

                var schemaList = GetModules(ctx, schemaModules);
                var schemaNamespaces = schemaList.Select(m => m.Namespace).ToArray();

                WriteStartDocument(s, ctx, schemaList);

                var iexpIf = ctx.GetIExportableInterface();
                foreach (var module in schemaList)
                {
                    Log.InfoFormat("  exporting module {0}", module.Name);
                    foreach (var objClass in ctx.GetQuery<ObjectClass>().Where(o => o.Module == module).OrderBy(o => o.Name).ToList())
                    {
                        if (objClass.SubClasses.Count > 0)
                        {
                            Log.DebugFormat("    skipping {0}: not a leaf class", objClass.Name);
                        }
                        else if (!objClass.AndParents(cls => new[] { cls }, cls => cls.BaseObjectClass).SelectMany(cls => cls.ImplementsInterfaces).Contains(iexpIf))
                        {
                            Log.DebugFormat("    skipping {0}: not exportable", objClass.Name);
                        }
                        else if (allData)
                        {
                            Log.InfoFormat("    exporting class {0}", objClass.Name);
                            foreach (var obj in ctx.Internals().GetAll(objClass.GetDescribedInterfaceType()).OrderBy(obj => ((IExportable)obj).ExportGuid))
                            {
                                ExportObject(s, obj, schemaNamespaces);
                            }
                        }
                        else if (objClass.ImplementsIModuleMember())
                        {
                            Log.InfoFormat("    exporting parts of class {0}", objClass.Name);
                            foreach (var obj in ctx.Internals().GetAll(objClass.GetDescribedInterfaceType())
                                .Cast<IModuleMember>()
                                .Where(mm => mm.Module != null && ownerModules.Contains(mm.Module.Name))
                                .Cast<IExportable>()
                                .OrderBy(obj => obj.ExportGuid)
                                .Cast<IPersistenceObject>())
                            {
                                ExportObject(s, obj, schemaNamespaces);
                            }
                        }
                        else
                        {
                            Log.DebugFormat("    skipping {0}", objClass.Name);
                        }
                    }

                    int moduleID = module.ID; // Dont ask
                    foreach (var rel in ctx.GetQuery<Relation>().Where(r => r.Module.ID == moduleID)
                        .OrderBy(r => r.A.Type.Name).ThenBy(r => r.A.RoleName).ThenBy(r => r.B.Type.Name).ThenBy(r => r.B.RoleName).ThenBy(r => r.ExportGuid))
                    {
                        if (rel.GetRelationType() != RelationType.n_m)
                            continue;
                        if (!rel.A.Type.ImplementsIExportable())
                            continue;
                        if (!rel.B.Type.ImplementsIExportable())
                            continue;

                        try
                        {
                            var ifType = rel.GetEntryInterfaceType();
                            Log.InfoFormat("    {0} ", ifType.Type.Name);

                            MethodInfo mi = ctx.GetType().FindGenericMethod("FetchRelation", new Type[] { ifType.Type }, new Type[] { typeof(Guid), typeof(RelationEndRole), typeof(IDataObject) });
                            var relations = MagicCollectionFactory.WrapAsCollection<IPersistenceObject>(mi.Invoke(ctx, new object[] { rel.ExportGuid, RelationEndRole.A, null }));

                            foreach (var obj in relations.OrderBy(obj => ((IExportable)obj).ExportGuid))
                            {
                                ExportObject(s, obj, schemaNamespaces);
                            }
                        }
                        catch (TypeLoadException ex)
                        {
                            var message = String.Format("Failed to load InterfaceType for entries of {0}", rel);
                            Log.Warn(message, ex);
                        }
                    }
                }
                s.Writer.WriteEndElement();
                s.Writer.WriteEndDocument();

                Log.Info("Export finished");
            }
        }
 public void Init(IReadOnlyZetboxContext ctx)
 {
     // ignore
 }
Example #49
0
 private static TypeRef GetFromCache(Type t, IReadOnlyZetboxContext ctx)
 {
     if (!ctx.TransientState.ContainsKey(transientCacheKey))
     {
         ctx.TransientState[transientCacheKey] = new Dictionary<Type, TypeRef>();
     }
     var cache = (Dictionary<Type, TypeRef>)ctx.TransientState[transientCacheKey];
     if (cache.ContainsKey(t)) return cache[t];
     return null;
 }
Example #50
0
 public override void SetUp()
 {
     base.SetUp();
     ctx = scope.Resolve<IReadOnlyZetboxContext>();
 }
Example #51
0
        /// <summary>
        /// Exports data from the specified context into the specified package provider. Data is selected by defining
        /// schema and owning module.
        /// </summary>
        /// <remarks>
        /// <para>For example, exporting {"ZetboxBase", "GUI"}/{"*"} will export all schema information to recreate the
        /// current database. Exporting {"Calendar"}/{"MyApplication"} will export all calendar data specific to the
        /// "MyApplication" module.
        /// </para>
        /// </remarks>
        /// <param name="ctx">The data source</param>
        /// <param name="s">The export target</param>
        /// <param name="schemaModules">A list of strings naming the schema-defining modules. This selects which data
        /// (-classes) should be exported. Specify a single asterisk (<code>"*"</code>) to select all available
        /// modules.</param>
        /// <param name="ownerModules">A list of strings naming the data-owning modules. This selects whose data should
        /// be exported.  Specify a single asterisk (<code>"*"</code>) to select all available data, independent of
        /// module-membership. This also includes data that is not member of any module.</param>
        public static void ExportFromContext(IReadOnlyZetboxContext ctx, IPackageProvider s, string[] schemaModules, string[] ownerModules)
        {
            using (Log.DebugTraceMethodCall("ExportFromContext"))
            {
                Log.InfoFormat("Starting Export for Modules [{0}], data owned by [{1}]", string.Join(", ", schemaModules), string.Join(", ", ownerModules));

                var allData = ownerModules.Contains("*");

                var schemaList       = GetModules(ctx, schemaModules);
                var schemaNamespaces = schemaList.Select(m => m.Namespace).ToArray();

                WriteStartDocument(s, ctx, schemaList);

                var iexpIf = ctx.GetIExportableInterface();
                foreach (var module in schemaList)
                {
                    Log.InfoFormat("  exporting module {0}", module.Name);
                    foreach (var objClass in ctx.GetQuery <ObjectClass>().Where(o => o.Module == module).OrderBy(o => o.Name).ToList())
                    {
                        if (objClass.SubClasses.Count > 0)
                        {
                            Log.DebugFormat("    skipping {0}: not a leaf class", objClass.Name);
                        }
                        else if (!objClass.AndParents(cls => new[] { cls }, cls => cls.BaseObjectClass).SelectMany(cls => cls.ImplementsInterfaces).Contains(iexpIf))
                        {
                            Log.DebugFormat("    skipping {0}: not exportable", objClass.Name);
                        }
                        else if (allData)
                        {
                            Log.InfoFormat("    exporting class {0}", objClass.Name);
                            foreach (var obj in ctx.Internals().GetAll(objClass.GetDescribedInterfaceType()).OrderBy(obj => ((IExportable)obj).ExportGuid))
                            {
                                ExportObject(s, obj, schemaNamespaces);
                            }
                        }
                        else if (objClass.ImplementsIModuleMember())
                        {
                            Log.InfoFormat("    exporting parts of class {0}", objClass.Name);
                            foreach (var obj in ctx.Internals().GetAll(objClass.GetDescribedInterfaceType())
                                     .Cast <IModuleMember>()
                                     .Where(mm => mm.Module != null && ownerModules.Contains(mm.Module.Name))
                                     .Cast <IExportable>()
                                     .OrderBy(obj => obj.ExportGuid)
                                     .Cast <IPersistenceObject>())
                            {
                                ExportObject(s, obj, schemaNamespaces);
                            }
                        }
                        else
                        {
                            Log.DebugFormat("    skipping {0}", objClass.Name);
                        }
                    }

                    int moduleID = module.ID; // Dont ask
                    foreach (var rel in ctx.GetQuery <Relation>().Where(r => r.Module.ID == moduleID)
                             .OrderBy(r => r.A.Type.Name).ThenBy(r => r.A.RoleName).ThenBy(r => r.B.Type.Name).ThenBy(r => r.B.RoleName).ThenBy(r => r.ExportGuid))
                    {
                        if (rel.GetRelationType() != RelationType.n_m)
                        {
                            continue;
                        }
                        if (!rel.A.Type.ImplementsIExportable())
                        {
                            continue;
                        }
                        if (!rel.B.Type.ImplementsIExportable())
                        {
                            continue;
                        }

                        try
                        {
                            var ifType = rel.GetEntryInterfaceType();
                            Log.InfoFormat("    {0} ", ifType.Type.Name);

                            MethodInfo mi        = ctx.GetType().FindGenericMethod("FetchRelation", new Type[] { ifType.Type }, new Type[] { typeof(Guid), typeof(RelationEndRole), typeof(IDataObject) });
                            var        relations = MagicCollectionFactory.WrapAsCollection <IPersistenceObject>(mi.Invoke(ctx, new object[] { rel.ExportGuid, RelationEndRole.A, null }));

                            foreach (var obj in relations.OrderBy(obj => ((IExportable)obj).ExportGuid))
                            {
                                ExportObject(s, obj, schemaNamespaces);
                            }
                        }
                        catch (TypeLoadException ex)
                        {
                            var message = String.Format("Failed to load InterfaceType for entries of {0}", rel);
                            Log.Warn(message, ex);
                        }
                    }
                }
                s.Writer.WriteEndElement();
                s.Writer.WriteEndDocument();

                Log.Info("Export finished");
            }
        }
Example #52
0
        public static ObjectClass GetObjectClass(this IDataObject obj, IReadOnlyZetboxContext ctx)
        {
            if (obj == null) { throw new ArgumentNullException("obj"); }
            if (ctx == null) { throw new ArgumentNullException("ctx"); }

            return ctx.FindPersistenceObject<ObjectClass>(obj.ObjectClassID);
        }
Example #53
0
 public void Created(IReadOnlyZetboxContext ctx)
 {
 }
Example #54
0
        public static ObjectClass GetObjectClass(this Type type, IReadOnlyZetboxContext ctx)
        {
            if (type == null) { throw new ArgumentNullException("type"); }
            if (ctx == null) { throw new ArgumentNullException("ctx"); }

            ObjectClass result = ctx.TransientState("__ObjectClassExtensions__GetObjectClass__", type.FullName, () => ctx.GetQuery<ObjectClass>().First(o => o.Module.Namespace == type.Namespace && o.Name == type.Name));
            return result;
        }
Example #55
0
 public ViewModelDescriptorCache(IReadOnlyZetboxContext ctx)
 {
     _context = ctx;
     FillCache();
 }
Example #56
0
 public override void SetUp()
 {
     base.SetUp();
     ctx = GetContext();
 }
Example #57
0
            public static Content CreateCache(Toolkit tk, IReadOnlyZetboxContext ctx)
            {
                var result = new Content();

                // All View Descriptors for the given Toolkit
                result._allVDCache = new ReadOnlyCollection<ViewDescriptor>(
                    ctx.GetQuery<ViewDescriptor>().WithEagerLoading().Where(obj => obj.Toolkit == tk).ToList());

                // Dictionary by Kind
                result._vdCache = result._allVDCache.Where(obj => obj.ControlKind != null).GroupBy(obj => obj.ControlKind)
                    .ToDictionary(g => g.Key.ExportGuid, g => new ReadOnlyCollection<ViewDescriptor>(g.ToList()));

                return result;
            }
 public void Init(IReadOnlyZetboxContext ctx)
 {
     Reset();
 }
Example #59
0
 private void CheckScope()
 {
     // for now, clear the cache every hour
     if (_currentScope == null || _clearTime < DateTime.Now)
     {
         Logging.Log.Info("(Re-)Initialising BaseIdentityResolver's cache");
         _cache.Clear();
         if (_currentScope != null) _currentScope.Dispose();
         _currentScope = _parentScope.BeginLifetimeScope();
         _resolverCtx = _currentScope.Resolve<IReadOnlyZetboxContext>();
         _clearTime = DateTime.Now.AddHours(1);
     }
 }
Example #60
0
 public override void SetUp()
 {
     base.SetUp();
     ctx = scope.Resolve <IReadOnlyZetboxContext>();
 }