public MouseKeyboardEvents(CompendiumMapDepthMap _caller, MapDepthViewManager viewManager, TypeManager typeManager, MapDepthNavigator navigator, DatabaseMappingService nodeService, ScaleTransform _scaleTransform, TranslateTransform _translateTransform)
 {
     caller = _caller;
     ViewManager = viewManager;
     _typeManager = typeManager;
     _navigator = navigator;
     _nodeService = nodeService;
     scaleTransform = _scaleTransform;
     translateTransform = _translateTransform;
 }
 /// <summary>
 /// Get all types that can be assigned to type rootType.
 /// </summary>
 /// <param name="rootType">The class type to use as the base class or interface for all found types.</param>
 /// <returns>A list of types that are assignable to type T.  The results are not cached.</returns>
 public static List <Type> GetTypes(Type rootType)
 {
     return(TypeManager.GetManagerTypes(rootType));
 }
Example #3
0
        private PackageFragmentValidationResult DoInstall()
        {
            using (var transactionScope = TransactionsFacade.Create(true, TimeSpan.FromMinutes(30.0)))
            {
                string uninstallFilename = Path.Combine(this.PackageInstallDirectory,
                                                        PackageSystemSettings.UninstallFilename);

                Exception installException  = null;
                XElement  uninstallElements =
                    new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace,
                                                   PackageSystemSettings.PackageFragmentUninstallersElementName));
                try
                {
                    foreach (var kvp in _packageFramentInstallers)
                    {
                        List <XElement> uninstallInformation = kvp.Key.Install().ToList();

                        if (this.CanBeUninstalled)
                        {
                            XElement uninstallElement =
                                new XElement(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace,
                                                               PackageSystemSettings.
                                                               PackageFragmentUninstallersAddElementName));
                            uninstallElement.Add(new XAttribute(PackageSystemSettings.UninstallerTypeAttributeName,
                                                                TypeManager.SerializeType(kvp.Value)));
                            uninstallElement.Add(uninstallInformation);

                            uninstallElements.Add(uninstallElement);
                        }
                    }
                }
                catch (Exception ex)
                {
                    installException = ex;
                    LoggingService.LogError("Package installation failed", ex);
                }
                finally
                {
                    if (this.CanBeUninstalled)
                    {
                        XDocument doc =
                            new XDocument(
                                new XElement(
                                    XmlUtils.GetXName(PackageSystemSettings.XmlNamespace,
                                                      PackageSystemSettings.PackageInstallerElementName),
                                    uninstallElements));
                        doc.SaveToFile(uninstallFilename);
                    }
                }


                if (installException != null)
                {
                    if (this.CanBeUninstalled)
                    {
                        IPackageUninstaller packageUninstaller =
                            this.PackageInstallerUninstallerFactory.CreateUninstaller(
                                this.ZipFilename, uninstallFilename,
                                this.PackageInstallDirectory,
                                TempDirectoryFacade.
                                CreateTempDirectory(),
                                this.FlushOnCompletion,
                                this.ReloadConsoleOnCompletion,
                                false,
                                this.PackageInformation);

                        List <PackageFragmentValidationResult> validationResult = null;
                        try
                        {
                            validationResult = packageUninstaller.Validate().ToList();
                        }
                        catch (Exception ex)
                        {
                            return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex));
                        }


                        if (validationResult.Count == 0)
                        {
                            try
                            {
                                packageUninstaller.Uninstall(SystemLockingType.None);
                            }
                            catch (Exception ex)
                            {
                                return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex));
                            }
                        }
                        else
                        {
                            LoggingService.LogError(LogTitle, "Failed to perform installation rollback.");
                            foreach (var valResult in validationResult)
                            {
                                if (valResult.Exception != null)
                                {
                                    LoggingService.LogError(LogTitle, new InvalidOperationException(valResult.Message ?? string.Empty, valResult.Exception));
                                }
                                else
                                {
                                    LoggingService.LogWarning(LogTitle, valResult.Message);
                                }
                            }

                            return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal,
                                                                       "Could not perform installation rollback. The details are in the log.")
                            {
                                InnerResult = validationResult
                            });
                        }
                    }

                    return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal,
                                                               installException));
                }
                transactionScope.Complete();
            }
            return(null);
        }
Example #4
0
        public IValue ReadXML(XmlReaderImpl xmlReader, IValue valueType = null)
        {
            TypeTypeValue typeValue = null;

            if (valueType is TypeTypeValue typeTypeValue)
            {
                typeValue = typeTypeValue;
            }

            else if (xmlReader.NodeType == xmlNodeEnum.FromNativeValue(XmlNodeType.Element))
            {
                IValue xsiType = xmlReader.GetAttribute(ValueFactory.Create("type"), XmlSchema.InstanceNamespace);
                IValue xsiNil  = xmlReader.GetAttribute(ValueFactory.Create("nil"), XmlSchema.InstanceNamespace);

                if (xsiType.DataType == DataType.String)
                {
                    switch (xsiType.AsString())
                    {
                    case "string":
                        typeValue = new TypeTypeValue("String");
                        break;

                    case "decimal":
                        typeValue = new TypeTypeValue("Number");
                        break;

                    case "boolean":
                        typeValue = new TypeTypeValue("Boolean");
                        break;

                    case "dateTime":
                        typeValue = new TypeTypeValue("Date");
                        break;

                    default:
                        break;
                    }
                }
                else if (xsiNil.DataType == DataType.String)
                {
                    typeValue = new TypeTypeValue("Undefined");
                }
            }
            ;

            if (typeValue == null)
            {
                throw RuntimeException.InvalidArgumentValue();
            }

            Type implType = TypeManager.GetImplementingClass(typeValue.Value.ID);

            IValue result = ValueFactory.Create();

            if (typeValue.Equals(new TypeTypeValue("Undefined")))
            {
                result = ValueFactory.Create();
                xmlReader.Skip();
            }
            else if (implType == typeof(DataType))
            {
                xmlReader.Read();
                if (xmlReader.NodeType == xmlNodeEnum.FromNativeValue(XmlNodeType.Text))
                {
                    result = XMLValue(typeValue, xmlReader.Value);
                    xmlReader.Read();
                }
                else
                {
                    throw RuntimeException.InvalidArgumentValue();
                }
            }
            else if (typeof(IXDTOSerializableXML).IsAssignableFrom(implType))
            {
                result = Activator.CreateInstance(implType, new object[] { xmlReader, this }) as IValue;
            }

            xmlReader.Read();
            return(result);
        }
    // caller already:
    //	- setup the header and namespace
    //	- call/emit PrintPlatformAttributes on the type
    void GenerateEnum(Type type)
    {
        if (AttributeManager.HasAttribute <FlagsAttribute> (type))
        {
            print("[Flags]");
        }

        var native = AttributeManager.GetCustomAttribute <NativeAttribute> (type);

        if (native != null)
        {
            var sb = new StringBuilder();
            sb.Append("[Native");
            var hasNativeName       = !string.IsNullOrEmpty(native.NativeName);
            var hasConvertToManaged = !string.IsNullOrEmpty(native.ConvertToManaged);
            var hasConvertToNative  = !string.IsNullOrEmpty(native.ConvertToNative);
            if (hasNativeName || hasConvertToManaged || hasConvertToNative)
            {
                sb.Append(" (");
                if (hasNativeName)
                {
                    sb.Append('"').Append(native.NativeName).Append('"');
                }
                if (hasConvertToManaged)
                {
                    if (hasNativeName)
                    {
                        sb.Append(", ");
                    }
                    sb.Append("ConvertToManaged = \"");
                    sb.Append(native.ConvertToManaged);
                    sb.Append('"');
                }
                if (hasConvertToNative)
                {
                    if (hasNativeName || hasConvertToManaged)
                    {
                        sb.Append(", ");
                    }
                    sb.Append("ConvertToNative = \"");
                    sb.Append(native.ConvertToNative);
                    sb.Append('"');
                }
                sb.Append(")");
            }
            sb.Append("]");
            print(sb.ToString());
        }
        CopyObsolete(type);

        var unique_constants = new HashSet <string> ();
        var fields           = new Dictionary <FieldInfo, FieldAttribute> ();
        Tuple <FieldInfo, FieldAttribute> null_field     = null;
        Tuple <FieldInfo, FieldAttribute> default_symbol = null;
        var underlying_type = GetCSharpTypeName(TypeManager.GetUnderlyingEnumType(type));

        print("{0} enum {1} : {2} {{", AttributeManager.HasAttribute <InternalAttribute> (type) ? "internal" : "public", type.Name, underlying_type);
        indent++;
        foreach (var f in type.GetFields())
        {
            // skip value__ field
            if (f.IsSpecialName)
            {
                continue;
            }
            PrintPlatformAttributes(f);
            CopyObsolete(f);
            print("{0} = {1},", f.Name, f.GetRawConstantValue());
            var fa = AttributeManager.GetCustomAttribute <FieldAttribute> (f);
            if (fa == null)
            {
                continue;
            }
            if (f.IsUnavailable(this))
            {
                continue;
            }
            if (fa.SymbolName == null)
            {
                null_field = new Tuple <FieldInfo, FieldAttribute> (f, fa);
            }
            else if (unique_constants.Contains(fa.SymbolName))
            {
                throw new BindingException(1046, true, fa.SymbolName, type.Name);
            }
            else
            {
                fields.Add(f, fa);
                unique_constants.Add(fa.SymbolName);
            }
            if (AttributeManager.GetCustomAttribute <DefaultEnumValueAttribute> (f) != null)
            {
                if (default_symbol != null)
                {
                    throw new BindingException(1045, true, type.Name);
                }
                default_symbol = new Tuple <FieldInfo, FieldAttribute> (f, fa);
            }
        }
        indent--;
        print("}");
        unique_constants.Clear();

        var library_name = type.Namespace;
        var error        = AttributeManager.GetCustomAttribute <ErrorDomainAttribute> (type);

        if ((fields.Count > 0) || (error != null) || (null_field != null))
        {
            print("");
            // the *Extensions has the same version requirement as the enum itself
            PrintPlatformAttributes(type);
            print_generated_code();
            print("static public partial class {0}Extensions {{", type.Name);
            indent++;

            var field     = fields.FirstOrDefault();
            var fieldAttr = field.Value;

            ComputeLibraryName(fieldAttr, type, field.Key?.Name, out library_name, out string library_path);
        }

        if (error != null)
        {
            // this attribute is important for our tests
            print("[Field (\"{0}\", \"{1}\")]", error.ErrorDomain, library_name);
            print("static NSString? _domain;");
            print("");
            print("public static NSString? GetDomain (this {0} self)", type.Name);
            print("{");
            indent++;
            print("if (_domain is null)");
            indent++;
            print("_domain = Dlfcn.GetStringConstant (Libraries.{0}.Handle, \"{1}\");", library_name, error.ErrorDomain);
            indent--;
            print("return _domain;");
            indent--;
            print("}");
        }

        if ((fields.Count > 0) || (null_field != null))
        {
            print("static IntPtr[] values = new IntPtr [{0}];", fields.Count);
            print("");

            int n = 0;
            foreach (var kvp in fields)
            {
                var f  = kvp.Key;
                var fa = kvp.Value;
                // the attributes (availability and field) are important for our tests
                PrintPlatformAttributes(f);
                libraries.TryGetValue(library_name, out var libPath);
                var libname = fa.LibraryName?.Replace("+", string.Empty);
                // We need to check for special cases inside FieldAttributes
                // fa.LibraryName could contain a different framework i.e UITrackingRunLoopMode (UIKit) inside NSRunLoopMode enum (Foundation).
                // libPath could have a custom path i.e. CoreImage which in macOS is inside Quartz
                // library_name contains the Framework constant name the Field is inside of, used as fallback.
                bool useFieldAttrLibName = libname != null && !string.Equals(libname, library_name, StringComparison.OrdinalIgnoreCase);
                print("[Field (\"{0}\", \"{1}\")]", fa.SymbolName, useFieldAttrLibName ? libname : libPath ?? library_name);
                print("internal unsafe static IntPtr {0} {{", fa.SymbolName);
                indent++;
                print("get {");
                indent++;
                print("fixed (IntPtr *storage = &values [{0}])", n++);
                indent++;
                print("return Dlfcn.CachePointer (Libraries.{0}.Handle, \"{1}\", storage);", useFieldAttrLibName ? libname : library_name, fa.SymbolName);
                indent--;
                indent--;
                print("}");
                indent--;
                print("}");
                print("");
            }

            print("public static NSString? GetConstant (this {0} self)", type.Name);
            print("{");
            indent++;
            print("IntPtr ptr = IntPtr.Zero;");
            // can be empty - and the C# compiler emit `warning CS1522: Empty switch block`
            if (fields.Count > 0)
            {
                print("switch (({0}) self) {{", underlying_type);
                var default_symbol_name = default_symbol?.Item2.SymbolName;
                // more than one enum member can share the same numeric value - ref: #46285
                foreach (var kvp in fields)
                {
                    print("case {0}: // {1}.{2}", Convert.ToInt64(kvp.Key.GetRawConstantValue()), type.Name, kvp.Key.Name);
                    var sn = kvp.Value.SymbolName;
                    if (sn == default_symbol_name)
                    {
                        print("default:");
                    }
                    indent++;
                    print("ptr = {0};", sn);
                    print("break;");
                    indent--;
                }
                print("}");
            }
            print("return (NSString?) Runtime.GetNSObject (ptr);");
            indent--;
            print("}");

            print("");

            var nullable = null_field != null;
            print("public static {0} GetValue (NSString{1} constant)", type.Name, nullable ? "?" : "");
            print("{");
            indent++;
            print("if (constant is null)");
            indent++;
            // if we do not have a enum value that maps to a null field then we throw
            if (!nullable)
            {
                print("throw new ArgumentNullException (nameof (constant));");
            }
            else
            {
                print("return {0}.{1};", type.Name, null_field.Item1.Name);
            }
            indent--;
            foreach (var kvp in fields)
            {
                print("if (constant.IsEqualTo ({0}))", kvp.Value.SymbolName);
                indent++;
                print("return {0}.{1};", type.Name, kvp.Key.Name);
                indent--;
            }
            // if there's no default then we throw on unknown constants
            if (default_symbol == null)
            {
                print("throw new NotSupportedException ($\"{constant} has no associated enum value on this platform.\");");
            }
            else
            {
                print("return {0}.{1};", type.Name, default_symbol.Item1.Name);
            }
            indent--;
            print("}");
        }

        if ((fields.Count > 0) || (error != null) || (null_field != null))
        {
            indent--;
            print("}");
        }

        // namespace closing (it's optional to use namespaces even if it's a bad practice, ref #35283)
        if (indent > 0)
        {
            indent--;
            print("}");
        }
    }
 public COMWrapperContext()
     : base(TypeManager.GetTypeByFrameworkType(typeof(COMWrapperContext)))
 {
 }
 public MessageReceiverHandler(INodeNavigator navigator, MapDepthViewManager viewManager, TypeManager typeManager)
 {
     Navigator = navigator;
     ViewManager = viewManager;
     TypeManager = typeManager;
 }
Example #8
0
 public CharacterDB(DatabaseConnection db, ItemDB itemDB, TypeManager typeManager) : base(db)
 {
     this.TypeManager = typeManager;
     this.ItemDB      = itemDB;
 }
Example #9
0
        private void ValidateDynamicAddedType(DataType dataType)
        {
            DataTypeDescriptor dataTypeDescriptor = this.InstallerContext.GetPendingDataTypeDescriptor(dataType.InterfaceTypeName);

            if (dataTypeDescriptor == null)
            {
                _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingTypeDescriptor").FormatWith(dataType.InterfaceTypeName));
                return;
            }

            bool dataTypeLocalized = dataTypeDescriptor.SuperInterfaces.Contains(typeof(ILocalizedControlled));

            if (!ValidateTargetLocaleInfo(dataType, dataTypeLocalized))
            {
                return;
            }

            foreach (XElement addElement in dataType.Dataset)
            {
                var  dataKeyPropertyCollection = new DataKeyPropertyCollection();
                bool propertyValidationPassed  = true;
                var  fieldValues = new Dictionary <string, object>();

                foreach (XAttribute attribute in addElement.Attributes())
                {
                    string fieldName = attribute.Name.LocalName;

                    // A compatibility fix
                    if (IsObsoleteField(dataTypeDescriptor, fieldName))
                    {
                        continue;
                    }

                    DataFieldDescriptor dataFieldDescriptor = dataTypeDescriptor.Fields[fieldName];

                    if (dataFieldDescriptor == null)
                    {
                        _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_MissingProperty(dataTypeDescriptor, fieldName));
                        propertyValidationPassed = false;
                        continue;
                    }

                    object fieldValue;
                    try
                    {
                        fieldValue = ValueTypeConverter.Convert(attribute.Value, dataFieldDescriptor.InstanceType);
                    }
                    catch (Exception)
                    {
                        _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_ConversionFailed(attribute.Value, dataFieldDescriptor.InstanceType));
                        propertyValidationPassed = false;
                        continue;
                    }

                    if (dataTypeDescriptor.KeyPropertyNames.Contains(fieldName))
                    {
                        dataKeyPropertyCollection.AddKeyProperty(fieldName, fieldValue);
                    }

                    fieldValues.Add(fieldName, fieldValue);
                }

                if (!propertyValidationPassed)
                {
                    continue;
                }

                if (!dataType.AllowOverwrite && !dataType.OnlyUpdate)
                {
                    // TODO: implement check if the same key has already been added
                }

                RegisterKeyToBeAdded(dataType, dataTypeDescriptor, dataKeyPropertyCollection);

                // Checking foreign key references
                foreach (var referenceField in dataTypeDescriptor.Fields.Where(f => f.ForeignKeyReferenceTypeName != null))
                {
                    if (!fieldValues.TryGetValue(referenceField.Name, out object propertyValue) ||
                        propertyValue == null ||
                        (propertyValue is Guid guid && guid == Guid.Empty) ||
                        (propertyValue is string str && str == ""))
                    {
                        continue;
                    }

                    string referredTypeName = referenceField.ForeignKeyReferenceTypeName;
                    var    referredType     = TypeManager.TryGetType(referredTypeName);
                    if (referredType == null)
                    {
                        // TODO: implement reference check for dynamic types as well
                        continue;
                    }

                    string targetKeyPropertyName = referredType.GetKeyPropertyNames().SingleOrDefault();

                    CheckForBrokenReference(dataType, referredType, targetKeyPropertyName, propertyValue);
                }
            }
        }
Example #10
0
        private void ValidateAndLoadConfiguration()
        {
            XElement typesElement = this.Configuration.SingleOrDefault(f => f.Name == "Types");

            if (typesElement == null)
            {
                _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingElement"));
            }

            if (typesElement == null)
            {
                return;
            }

            foreach (XElement typeElement in typesElement.Elements("Type"))
            {
                var typeAttribute = typeElement.Attribute("type");
                if (typeAttribute == null)
                {
                    _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_MissingAttribute("type"), typeElement);
                    continue;
                }

                XAttribute allowOverwriteAttribute = typeElement.Attribute("allowOverwrite");
                XAttribute onlyUpdateAttribute     = typeElement.Attribute("onlyUpdate");

                bool allowOverwrite = allowOverwriteAttribute != null && (bool)allowOverwriteAttribute;
                bool onlyUpdate     = onlyUpdateAttribute != null && (bool)onlyUpdateAttribute;

                string interfaceTypeName = typeAttribute.Value;

                interfaceTypeName = TypeManager.FixLegasyTypeName(interfaceTypeName);

                foreach (XElement dataElement in typeElement.Elements("Data"))
                {
                    XAttribute dataScopeIdentifierAttribute = dataElement.Attribute("dataScopeIdentifier");
                    if (dataScopeIdentifierAttribute == null)
                    {
                        _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_MissingAttribute("dataScopeIdentifier"), typeElement);
                        continue;
                    }

                    DataScopeIdentifier dataScopeIdentifier;
                    try
                    {
                        dataScopeIdentifier = DataScopeIdentifier.Deserialize(dataScopeIdentifierAttribute.Value);
                    }
                    catch (Exception)
                    {
                        _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.WrongDataScopeIdentifier").FormatWith(dataScopeIdentifierAttribute.Value), dataScopeIdentifierAttribute);
                        continue;
                    }



                    CultureInfo locale          = null; // null => do not use localization
                    bool        allLocales      = false;
                    bool        currentLocale   = false;
                    XAttribute  localeAttribute = dataElement.Attribute("locale");
                    if (localeAttribute != null)
                    {
                        if (localeAttribute.Value == "*")
                        {
                            allLocales = true;
                        }
                        else if (localeAttribute.Value == "?")
                        {
                            currentLocale = true;
                        }
                        else
                        {
                            try
                            {
                                locale = CultureInfo.CreateSpecificCulture(localeAttribute.Value);
                            }
                            catch (Exception)
                            {
                                _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.WrongLocale").FormatWith(localeAttribute.Value), localeAttribute);
                                continue;
                            }
                        }
                    }


                    XAttribute dataFilenameAttribute = dataElement.Attribute("dataFilename");
                    if (dataFilenameAttribute == null)
                    {
                        _validationResult.AddFatal(Texts.DataPackageFragmentInstaller_MissingAttribute("dataFilename"), typeElement);
                        continue;
                    }


                    if (!this.InstallerContext.ZipFileSystem.ContainsFile(dataFilenameAttribute.Value))
                    {
                        _validationResult.AddFatal(GetText("DataPackageFragmentInstaller.MissingFile").FormatWith(dataFilenameAttribute.Value), dataFilenameAttribute);
                        continue;
                    }


                    XDocument doc;
                    try
                    {
                        using (var stream = this.InstallerContext.ZipFileSystem.GetFileStream(dataFilenameAttribute.Value))
                            using (var reader = new C1StreamReader(stream))
                            {
                                doc = XDocument.Load(reader);
                            }
                    }
                    catch (Exception ex)
                    {
                        _validationResult.Add(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex));
                        continue;
                    }


                    XAttribute isDynamicAddedAttribute = typeElement.Attribute("isDynamicAdded");

                    bool isDynamicAdded = isDynamicAddedAttribute != null && (bool)isDynamicAddedAttribute;

                    var dataType = new DataType
                    {
                        InterfaceTypeName   = interfaceTypeName,
                        DataScopeIdentifier = dataScopeIdentifier,
                        Locale             = locale,
                        AddToAllLocales    = allLocales,
                        AddToCurrentLocale = currentLocale,
                        IsDynamicAdded     = isDynamicAdded,
                        AllowOverwrite     = allowOverwrite,
                        OnlyUpdate         = onlyUpdate,
                        Dataset            = doc.Root.Elements("Add")
                    };

                    _dataTypes.Add(dataType);
                }
            }
        }
Example #11
0
        private ConstantExpression TryReduce(Type targetType)
        {
            if (Type == targetType)
            {
                var thisType = GetType();

                if (!thisType.IsGenericType && !TypeManager.IsEnumType(targetType))
                {
                    switch (Type.GetTypeCode(targetType))
                    {
                    case TypeCode.Boolean:
                        return(new ConstantExpression <bool>((bool)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.Char:
                        return(new ConstantExpression <char>((char)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.SByte:
                        return(new ConstantExpression <sbyte>((sbyte)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.Byte:
                        return(new ConstantExpression <byte>((byte)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.Int16:
                        return(new ConstantExpression <short>((short)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.UInt16:
                        return(new ConstantExpression <ushort>((ushort)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.Int32:
                        return(new ConstantExpression <int>((int)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.UInt32:
                        return(new ConstantExpression <uint>((uint)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.Int64:
                        return(new ConstantExpression <long>((long)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.UInt64:
                        return(new ConstantExpression <ulong>((ulong)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.Single:
                        return(new ConstantExpression <float>((float)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.Double:
                        return(new ConstantExpression <double>((double)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.Decimal:
                        return(new ConstantExpression <decimal>((decimal)_value)
                        {
                            Span = Span
                        });

                    case TypeCode.String:
                        return(new ConstantExpression <string>((string)_value)
                        {
                            Span = Span
                        });
                    }
                }
                return(this);
            }

            if (TypeManager.IsEnumType(targetType))
            {
                var c = TryReduce(Enum.GetUnderlyingType(targetType));
                if (c == null)
                {
                    return(null);
                }

                return(new EnumConstantExpression(c, targetType));
            }

            return(ConvertExplicitly(false, targetType));
        }
Example #12
0
        private TypeConverter HandleGetTypeConverter(IElement container, NamedObjectSave instance, TypedMemberBase typedMember)
        {
            Type   memberType = typedMember.MemberType;
            string memberName = typedMember.MemberName;

            TypeConverter typeConverter = null;

            // If the NOS references a FRB type, we need to adjust the type appropriately

            bool wasTypeModified = false;
            Type oldType         = memberType;

            bool handled = false;



            if (instance.SourceType == SourceType.FlatRedBallType)
            {
                Type type = TypeManager.GetTypeFromString(instance.SourceClassType);

                if (type == typeof(Sprite) && memberName == "CurrentChainName")
                {
                    // special case handling for CurrentChainName
                    typeConverter = new AvailableAnimationChainsStringConverter(container, instance);

                    handled = true;
                }
                else if (typedMember.MemberType?.Name == "Sprite")
                {
                    var nosTypeConverter = new AvailableNamedObjectsAndFiles(container);
                    nosTypeConverter.NamedObjectTypeRestriction = "FlatRedBall.Sprite";
                    typeConverter = nosTypeConverter;
                    handled       = true;
                }
            }
            else if (instance.SourceType == SourceType.File)
            {
                if (instance.ClassType == "Sprite" && memberName == "CurrentChainName")
                {
                    // special case handling for CurrentChainName
                    typeConverter = new AvailableAnimationChainsStringConverter(container, instance);

                    handled = true;
                }
            }

            if (!handled)
            {
                if (instance.DoesMemberNeedToBeSetByContainer(memberName))
                {
                    var availableNamedObjectsAndFiles = new AvailableNamedObjectsAndFiles(container);
                    availableNamedObjectsAndFiles.NamedObjectTypeRestriction = typedMember.MemberType.FullName;
                    typeConverter = availableNamedObjectsAndFiles;
                }
                else if (memberType.IsEnum)
                {
                    typeConverter = new EnumConverter(memberType);
                }
                else if (memberType == typeof(Microsoft.Xna.Framework.Color))
                {
                    typeConverter = new AvailableColorTypeConverter();
                    memberType    = typeof(string);
                }
                else if (IsTypeFile(typedMember))
                {
                    AvailableFileStringConverter availableFileStringConverter = new AvailableFileStringConverter(container);
                    availableFileStringConverter.QualifiedRuntimeTypeName = memberType.FullName;
                    if (!string.IsNullOrEmpty(typedMember.CustomTypeName))
                    {
                        availableFileStringConverter.QualifiedRuntimeTypeName = typedMember.CustomTypeName;
                    }
                    availableFileStringConverter.RemovePathAndExtension = true;
                    typeConverter = availableFileStringConverter;

                    memberType = typeof(string);
                }
                else if (instance.SourceType == SourceType.Entity && !string.IsNullOrEmpty(instance.SourceClassType))
                {
                    EntitySave entity = ObjectFinder.Self.GetEntitySave(instance.SourceClassType);

                    if (entity != null)
                    {
                        CustomVariable customVariable = entity.GetCustomVariable(memberName);

                        if (customVariable != null)
                        {
                            typeConverter = customVariable.GetTypeConverter(entity);
                        }
                    }
                }
            }
            //else if (this.SourceType == SaveClasses.SourceType.FlatRedBallType &&
            //    typedMember != null && typedMember.MemberType != null)
            //{

            //}

            if (wasTypeModified)
            {
                memberType = oldType;
            }

            return(typeConverter);
        }
        /// <summary>
        /// This method finds the callers tree node own entity token by searching up/down using filters.
        /// In some cases this can be expensive.
        /// </summary>
        /// <param name="treeNode"></param>
        /// <param name="entityToken"></param>
        /// <param name="dynamicContext"></param>
        /// <returns></returns>
        private EntityToken FindOwnEntityToken(TreeNode treeNode, EntityToken entityToken, TreeNodeDynamicContext dynamicContext)
        {
            DataElementsTreeNode dataElementsTreeNode = treeNode as DataElementsTreeNode;

            if (dataElementsTreeNode != null)
            {
                if (dataElementsTreeNode.InterfaceType == this.OwnerNode.InterfaceType) // We found it :)
                {
                    return(entityToken);
                }
            }


            TreeDataFieldGroupingElementEntityToken dataFieldGroupingElementEntityToken = entityToken as TreeDataFieldGroupingElementEntityToken;

            if (dataFieldGroupingElementEntityToken != null) // Search 'downwards'
            {
                ParameterExpression parameterExpression = Expression.Parameter(this.OwnerNode.InterfaceType, "data");

                DataKeyPropertyCollection dataKeyPropertyCollection = new DataKeyPropertyCollection();
                dataKeyPropertyCollection.AddKeyProperty("Id", dataFieldGroupingElementEntityToken.ChildGeneratingDataElementsReferenceValue);

                Type dataType = dataFieldGroupingElementEntityToken.ChildGeneratingDataElementsReferenceType;

                IData parentData = DataFacade.GetDataByUniqueKey(dataType, dataKeyPropertyCollection);

                TreeNodeDynamicContext dummyContext = new TreeNodeDynamicContext(TreeNodeDynamicContextDirection.Down);
                dummyContext.CustomData.Add("ParentData", parentData);

                IData resultData;
                if (this.OwnerNode.InterfaceType == TypeManager.GetType(dataFieldGroupingElementEntityToken.Type))
                {
                    Expression filterExpression = this.CreateDownwardsFilterExpression(parameterExpression, dummyContext);

                    Expression whereExpression = ExpressionHelper.CreateWhereExpression(DataFacade.GetData(this.OwnerNode.InterfaceType).Expression, parameterExpression, filterExpression);

                    resultData = (IData)DataFacade.GetData(this.OwnerNode.InterfaceType).Provider.CreateQuery(whereExpression).ToEnumerableOfObjects().First();
                }
                else
                {
                    resultData = parentData;
                }

                return(resultData.GetDataEntityToken());
            }


            AncestorResult ancestorResult = treeNode.GetParentEntityToken(entityToken, this.ParentFilterType, dynamicContext);

            if ((this.OwnerNode.Id == ancestorResult.TreeNode.Id) || (this.OwnerNode.IsDescendant(ancestorResult.TreeNode))) // Search upwards
            {
                return(FindOwnEntityToken(ancestorResult.TreeNode, ancestorResult.EntityToken, dynamicContext));
            }


            // Search 'downwards' by using the parent datas key value to get
            DataElementsTreeNode parentDataElementsTreeNode = (DataElementsTreeNode)ancestorResult.TreeNode;

            if (this.ParentFilterType == parentDataElementsTreeNode.InterfaceType)
            {
                DataEntityToken dataEntityToken = (DataEntityToken)ancestorResult.EntityToken;

                ParameterExpression parameterExpression = Expression.Parameter(this.OwnerNode.InterfaceType, "data");

                TreeNodeDynamicContext dummyContext = new TreeNodeDynamicContext(TreeNodeDynamicContextDirection.Down);
                dummyContext.CustomData.Add("ParentData", dataEntityToken.Data);

                Expression filterExpression = this.CreateDownwardsFilterExpression(parameterExpression, dummyContext);

                Expression whereExpression = ExpressionHelper.CreateWhereExpression(DataFacade.GetData(this.OwnerNode.InterfaceType).Expression, parameterExpression, filterExpression);

                IData resultData = (IData)DataFacade.GetData(this.OwnerNode.InterfaceType).Provider.CreateQuery(whereExpression).ToEnumerableOfObjects().First();

                return(resultData.GetDataEntityToken());
            }


            throw new InvalidOperationException("Missing parent id filtering or try to simplify the parent id filterings (Unable to find own entity token)");
        }
        public string GenerateAdditionalLinkXmlFile(BuildReport report, UnityLinkerBuildPipelineData data)
        {
            // Let's build a dictionary of Assemblies as key and all their ComponentSystem as value (in a list)
            var typesByAssemblies = new Dictionary <Assembly, List <Type> >();

            var csb = typeof(ComponentSystemBase);

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                if (!TypeManager.IsAssemblyReferencingEntities(assembly))
                {
                    continue;
                }

                try
                {
                    var allTypes = assembly.GetTypes();
                    var types    = allTypes.Where(type => type.IsSubclassOf(csb)).ToList();

                    if (types.Count > 0)
                    {
                        typesByAssemblies.Add(assembly, types);
                    }
                }
                catch (ReflectionTypeLoadException)
                {
                    Debug.LogWarning($"Couldn't load types from assembly: {assembly.FullName}");
                }
            }

            // Create the XML file
            var sb = new StringBuilder();

            // Header
            sb.AppendLine("<linker>");

            // For each assembly, add an <assembly> element that will contains <type> elements nested for all the type to include
            foreach (var assembly in typesByAssemblies.Keys)
            {
                // Add the assembly element
                sb.AppendLine($"  <assembly fullname=\"{assembly.GetName().Name}\">");

                // Add the type element
                var types = typesByAssemblies[assembly];
                foreach (var type in types)
                {
                    sb.AppendLine($"    <type fullname=\"{FormatForXml(ToCecilName(type.FullName))}\" preserve=\"all\"/>");
                }

                // Close assembly element
                sb.AppendLine("  </assembly>");
            }

            // Close linker element
            sb.AppendLine("</linker>");

            // Create a file with the content
            var filePathName = Path.Combine(data.inputDirectory, "DotsStripping.xml");

            File.WriteAllText(filePathName, sb.ToString());

            // Return the file path & name
            return(filePathName);
        }
        protected override void OnUpdate()
        {
            var mgr = EntityManager;

            // cleanup native and internal components in case the thing component was removed (this also covers entity deletion)
            // remove Native and Loading if Thing is gone
            EntityCommandBuffer ecb = new EntityCommandBuffer(Allocator.Temp);

            using (var entities = m_CleanupQuery.ToEntityArray(Allocator.TempJob))
            {
                foreach (var e in entities)
                {
                    var n = TypeManager.IsZeroSized(m_TN_TypeIndex) ? default : EntityManager.GetComponentData <TN>(e);
                            c.FreeNative(mgr, e, ref n);
                            ecb.RemoveComponent <TN>(e);
                            if (mgr.HasComponent <L>(e))
                            {
                                ecb.RemoveComponent <L>(e);
                            }
                }
            }
            ecb.Playback(mgr);
            ecb.Dispose();

            // add the Native component for Things that want to load and do not have one yet
            ecb = new EntityCommandBuffer(Allocator.Temp);
            using (var entities = m_PrepareLoadQuery.ToEntityArray(Allocator.TempJob))
            {
                foreach (var e in entities)
                {
                    ecb.AddComponent(e, default(TN)); // +TN
                }
            }
            ecb.Playback(mgr);
            ecb.Dispose();

            // start loading!
            ecb = new EntityCommandBuffer(Allocator.Temp);
            using (var entities = m_StartLoadQuery.ToEntityArray(Allocator.TempJob))
            {
                foreach (var e in entities)
                {
                    var t = TypeManager.IsZeroSized(m_T_TypeIndex)  ? default : EntityManager.GetComponentData <T>(e);

                            var n = TypeManager.IsZeroSized(m_TN_TypeIndex) ? default : EntityManager.GetComponentData <TN>(e);

                                    var s = TypeManager.IsZeroSized(m_TS_TypeIndex) ? default : EntityManager.GetComponentData <TS>(e);

                                            L l = default;
                                            c.StartLoad(mgr, e, ref t, ref n, ref s, ref l);
                                            ecb.AddComponent(e, l);

                                            ecb.SetComponent(e, t);
                                            ecb.SetComponent(e, n);
                                            ecb.SetComponent(e, s);
                }
            }
            ecb.Playback(mgr);
            ecb.Dispose();

            // check on all things that are in flight, and finish when done
            ecb = new EntityCommandBuffer(Allocator.Temp);
            using (var entities = m_InProgressLoadQuery.ToEntityArray(Allocator.TempJob))
            {
                foreach (var e in entities)
                {
                    var t = TypeManager.IsZeroSized(m_T_TypeIndex)  ? default : EntityManager.GetComponentData <T>(e);

                            var n = TypeManager.IsZeroSized(m_TN_TypeIndex) ? default : EntityManager.GetComponentData <TN>(e);

                                    var s = TypeManager.IsZeroSized(m_TS_TypeIndex) ? default : EntityManager.GetComponentData <TS>(e);

                                            var l = TypeManager.IsZeroSized(m_L_TypeIndex)  ? default : EntityManager.GetComponentData <L>(e);

                                                    LoadResult lr = c.CheckLoading(wrapper, mgr, e, ref t, ref n, ref s, ref l);
                                                    if (lr == LoadResult.stillWorking)
                                                    {
                                                        ecb.SetComponent(e, t);
                                                        ecb.SetComponent(e, n);
                                                        ecb.SetComponent(e, s);
                                                        ecb.SetComponent(e, l);
                                                        continue;
                                                    }

                                                    // remove load state
                                                    ecb.RemoveComponent <L>(e);
                                                    ecb.RemoveComponent <TS>(e);
                                                    if (lr == LoadResult.failed)
                                                    {
                                                        c.FreeNative(mgr, e, ref n);

                                                        // should we remove native here?
                                                        ecb.SetComponent(e, t);
                                                        ecb.SetComponent(e, n);
                                                        continue;
                                                    }
                                                    // success!
                                                    c.FinishLoading(mgr, e, ref t, ref n, ref l);

                                                    ecb.SetComponent(e, t);
                                                    ecb.SetComponent(e, n);
                }
            }
            ecb.Playback(mgr);
            ecb.Dispose();
        }
Example #16
0
 public override string GetSignatureForError()
 {
     return(TypeManager.GetCSharpName(Type));
 }
Example #17
0
        /// <exclude />
        public override IEnumerable <XElement> Install()
        {
            Verify.IsNotNull(_dataTypes, "DataPackageFragmentInstaller has not been validated");

            List <XElement> typeElements = new List <XElement>();

            foreach (DataType dataType in _dataTypes)
            {
                Log.LogVerbose(LogTitle, $"Installing data for the type '{dataType.InterfaceType}'");

                if (dataType.IsDynamicAdded || dataType.InterfaceType == null)
                {
                    dataType.InterfaceType = this.InstallerContext.IsDataTypePending(dataType.InterfaceTypeName)
                        ? this.InstallerContext.GetPendingDataType(dataType.InterfaceTypeName)
                        : TypeManager.GetType(dataType.InterfaceTypeName);

                    Verify.IsNotNull(dataType.InterfaceType, "Failed to get interface type by name: '{0}'", dataType.InterfaceTypeName);
                }

                XElement typeElement = new XElement("Type",
                                                    new XAttribute("type", TypeManager.SerializeType(dataType.InterfaceType)),
                                                    new XAttribute("dataScopeIdentifier", dataType.DataScopeIdentifier));


                using (new DataScope(dataType.DataScopeIdentifier))
                {
                    if (dataType.AddToAllLocales)
                    {
                        foreach (CultureInfo locale in DataLocalizationFacade.ActiveLocalizationCultures)
                        {
                            using (new DataScope(locale))
                            {
                                XElement element = AddData(dataType, locale);
                                typeElement.Add(element);
                            }
                        }
                    }
                    else if (dataType.AddToCurrentLocale)
                    {
                        var currentLocale = DataLocalizationFacade.DefaultLocalizationCulture;
                        if (UserValidationFacade.IsLoggedIn())
                        {
                            currentLocale = UserSettings.ActiveLocaleCultureInfo;
                        }

                        using (new DataScope(currentLocale))
                        {
                            XElement element = AddData(dataType, currentLocale);
                            typeElement.Add(element);
                        }
                    }
                    else if (dataType.Locale != null)
                    {
                        if (DataLocalizationFacade.ActiveLocalizationCultures.Contains(dataType.Locale))
                        {
                            using (new DataScope(dataType.Locale))
                            {
                                XElement element = AddData(dataType, dataType.Locale);
                                typeElement.Add(element);
                            }
                        }
                    }
                    else
                    {
                        var locale = UserValidationFacade.IsLoggedIn()
                            ? UserSettings.ActiveLocaleCultureInfo
                            : DataLocalizationFacade.DefaultLocalizationCulture;

                        using (new DataScope(locale))
                        {
                            XElement element = AddData(dataType, null);
                            typeElement.Add(element);
                        }
                    }
                }

                typeElements.Add(typeElement);
            }

            yield return(new XElement("Types", typeElements));
        }
Example #18
0
        private static DynamicBufferUnsafe <T> ToDynamicBufferUnsafe <T>(this IntPtr ptr) where T : struct, IBufferElementData
        {
            var internalCapacity = TypeManager.GetTypeInfo <T>().BufferCapacity;

            return(new DynamicBufferUnsafe <T>(ptr, internalCapacity));
        }
Example #19
0
            private static bool Get(
                ref EntityContainer container,
                int index,
                HashSet <Type> primitiveTypes,
                out StructProxy p)
            {
                var typeIndex    = container.m_Manager.GetComponentTypeIndex(container.m_Entity, index);
                var propertyType = TypeManager.GetType(typeIndex);

                p = new StructProxy();

                if (typeof(ISharedComponentData).IsAssignableFrom(propertyType))
                {
                    try
                    {
                        var o = container.m_Manager.GetSharedComponentData(container.m_Entity, typeIndex);

                        // TODO: skip the StructObjectProxyProperty adapter and have the Accept()
                        // TODO:    handle Struct & Object proxies
                        p = new StructProxy
                        {
                            bag = new StructPropertyBag <StructProxy>(
                                new StructObjectProxyProperty(propertyType, o, primitiveTypes)
                                ),
                            data = default(byte *),
                            type = propertyType
                        };

                        return(true);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }

                if (typeof(IBufferElementData).IsAssignableFrom(propertyType))
                {
                    IPropertyBag bag = TypeInformation.GetOrCreate(propertyType, primitiveTypes);

                    p = new StructProxy
                    {
                        bag = new StructPropertyBag <StructProxy>(
                            new BufferListProxyProperty(
                                bag,
                                propertyType,
                                container.m_Manager.GetBufferLength(container.m_Entity, typeIndex)
                                )
                            ),
                        data = (byte *)container.m_Manager.GetBufferRawRW(container.m_Entity, typeIndex),
                        type = propertyType
                    };

                    return(true);
                }

                {
                    IPropertyBag bag = TypeInformation.GetOrCreate(propertyType, primitiveTypes);

                    // We skip the property bag & proxy creation for zero sized types (e.g. MonoBehaviors, etc).
                    // They wont get displayed at all in the inspector since we dont know
                    byte *data = null;
                    if (!TypeManager.GetTypeInfo(typeIndex).IsZeroSized)
                    {
                        data = (byte *)container.m_Manager.GetComponentDataRawRW(container.m_Entity, typeIndex);
                    }

                    p = new StructProxy
                    {
                        bag  = bag,
                        data = data,
                        type = propertyType
                    };

                    return(true);
                }
            }
Example #20
0
        void EmitFieldSize(int buffer_size)
        {
            int type_size = BuiltinTypeSpec.GetSize(MemberType);

            if (buffer_size > int.MaxValue / type_size)
            {
                Report.Error(1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
                             GetSignatureForError(), buffer_size.ToString(), TypeManager.CSharpName(MemberType));
                return;
            }

            AttributeEncoder encoder;

            var ctor = Module.PredefinedMembers.StructLayoutAttributeCtor.Resolve(Location);

            if (ctor == null)
            {
                return;
            }

            var field_size    = Module.PredefinedMembers.StructLayoutSize.Resolve(Location);
            var field_charset = Module.PredefinedMembers.StructLayoutCharSet.Resolve(Location);

            if (field_size == null || field_charset == null)
            {
                return;
            }

            var char_set = CharSet ?? Module.DefaultCharSet ?? 0;

            encoder = new AttributeEncoder();
            encoder.Encode((short)LayoutKind.Sequential);
            encoder.EncodeNamedArguments(
                new [] { field_size, field_charset },
                new Constant [] {
                new IntConstant(Compiler.BuiltinTypes, buffer_size * type_size, Location),
                new IntConstant(Compiler.BuiltinTypes, (int)char_set, Location)
            }
                );

            fixed_buffer_type.SetCustomAttribute((ConstructorInfo)ctor.GetMetaInfo(), encoder.ToArray());

            //
            // Don't emit FixedBufferAttribute attribute for private types
            //
            if ((ModFlags & Modifiers.PRIVATE) != 0)
            {
                return;
            }

            ctor = Module.PredefinedMembers.FixedBufferAttributeCtor.Resolve(Location);
            if (ctor == null)
            {
                return;
            }

            encoder = new AttributeEncoder();
            encoder.EncodeTypeName(MemberType);
            encoder.Encode(buffer_size);
            encoder.EncodeEmptyNamedArguments();

            FieldBuilder.SetCustomAttribute((ConstructorInfo)ctor.GetMetaInfo(), encoder.ToArray());
        }
Example #21
0
        public static int SyncIndex()
        {
            _index = TypeManager <IEvent> .IndexOf(typeof(T));

            return(_index);
        }
Example #22
0
        public void SIZ_TagComponentZeroSize()
        {
            var entity0 = m_Manager.CreateEntity(typeof(EcsTestTag));

            unsafe {
                // a system ran, the version should match the global
                var chunk0           = m_Manager.Entities->GetComponentChunk(entity0);
                var archetype0       = chunk0->Archetype;
                var indexInTypeArray = ChunkDataUtility.GetIndexInTypeArray(chunk0->Archetype, TypeManager.GetTypeIndex <EcsTestTag>());

                Assert.AreEqual(0, archetype0->SizeOfs[indexInTypeArray]);
            }
        }
Example #23
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        protected override void ExecuteTask()
        {
            String baseFolder = this.CreateBaseDir();
            DocSet docSet     = this.CreateDocSet();
            IEnumerable <Framework> frameworks = this.CreateFrameworks(docSet);

            this.typeManager = new TypeManager();
            this.typeManager.SetMappings(this.MappingFile.ToString());
            Func <FrameworkEntity, bool> selector = delegate(FrameworkEntity e) {
                return(e.type == FrameworkEntityType.C || e.type == FrameworkEntityType.P);
            };
            var names = frameworks.SelectMany(f => f.GetEntities().Where(selector).Select(e => e.name));

            this.typeManager.SetClasses(names);

            // Prepare the settings
            this.settings = this.CreateSettings();

            TextWriter writer = null;

            if (this.Report != null)
            {
                writer = new StreamWriter(this.Report.ToString());
            }

            foreach (var f in frameworks)
            {
                if (writer != null)
                {
                    writer.WriteLine("Framework " + f.name);
                }
                foreach (var e in f.GetEntities())
                {
                    if (writer != null)
                    {
                        writer.WriteLine("Entity " + e.name);
                    }
                    this.Log(Level.Verbose, String.Format("Processing '{0}'...", e.name));

                    String sourcePath      = e.GetPath(baseFolder, DocumentType.Xhtml);
                    String destinationPath = e.GetPath(baseFolder, DocumentType.Model);

                    if (sourcePath == null || !File.Exists(sourcePath))
                    {
                        continue;
                    }

                    if (sourcePath.IsYoungerThan(destinationPath))
                    {
                        this.Log(Level.Info, String.Format("Converting '{0}'...", e.name));
                        Convert(f, e, sourcePath, destinationPath, writer);
                    }
                    else
                    {
                        this.Log(Level.Debug, String.Format("Skipping '{0}'...", e.name));
                    }
                }
            }

            if (this.Report != null)
            {
                writer.Close();
                writer.Dispose();
            }

            if (this.MappingReport != null)
            {
                using (writer = new StreamWriter(this.MappingReport.ToString())) {
                    IDictionary <String, String> samples = this.typeManager.Samples;
                    List <String> keys = new List <String>(samples.Keys);
                    keys.Sort();
                    foreach (var key in keys)
                    {
                        writer.WriteLine("{0}={1}", key, samples[key]);
                    }
                    writer.Close();
                }
            }
        }
        public static unsafe void SerializeWorld(EntityManager entityManager, BinaryWriter writer, out int[] sharedComponentsToSerialize, NativeArray <EntityRemapUtility.EntityRemapInfo> entityRemapInfos)
        {
            writer.Write(CurrentFileFormatVersion);
            var entityComponentStore = entityManager.EntityComponentStore;

            NativeHashMap <EntityArchetype, int> archetypeToIndex;

            EntityArchetype[] archetypeArray;
            GetAllArchetypes(entityComponentStore, out archetypeToIndex, out archetypeArray);

            var typeHashes = new NativeHashMap <ulong, int>(1024, Allocator.Temp);

            foreach (var archetype in archetypeArray)
            {
                for (int iType = 0; iType < archetype.Archetype->TypesCount; ++iType)
                {
                    var typeIndex = archetype.Archetype->Types[iType].TypeIndex;
                    var typeInfo  = TypeManager.GetTypeInfo(typeIndex);
                    var hash      = typeInfo.StableTypeHash;
                    ValidateTypeForSerialization(typeInfo);
                    typeHashes.TryAdd(hash, 0);
                }
            }
            var typeHashSet = typeHashes.GetKeyArray(Allocator.Temp);

            writer.Write(typeHashSet.Length);
            foreach (ulong hash in typeHashSet)
            {
                writer.Write(hash);
            }

            var typeHashToIndexMap = new NativeHashMap <ulong, int>(typeHashSet.Length, Allocator.Temp);

            for (int i = 0; i < typeHashes.Length; ++i)
            {
                typeHashToIndexMap.TryAdd(typeHashSet[i], i);
            }

            WriteArchetypes(writer, archetypeArray, typeHashToIndexMap);
            var sharedComponentMapping = GatherSharedComponents(archetypeArray, out var sharedComponentArraysTotalCount);
            var sharedComponentArrays  = new NativeArray <int>(sharedComponentArraysTotalCount, Allocator.Temp);

            FillSharedComponentArrays(sharedComponentArrays, archetypeArray, sharedComponentMapping);
            writer.Write(sharedComponentArrays.Length);
            writer.WriteArray(sharedComponentArrays);
            sharedComponentArrays.Dispose();

            //TODO: ensure chunks are defragged?

            var bufferPatches   = new NativeList <BufferPatchRecord>(128, Allocator.Temp);
            var totalChunkCount = GenerateRemapInfo(entityManager, archetypeArray, entityRemapInfos);

            writer.Write(totalChunkCount);

            GatherAllUsedBlobAssets(archetypeArray, out var blobAssetRefs, out var blobAssets);

            var blobAssetOffsets   = new NativeArray <int>(blobAssets.Length, Allocator.Temp);
            int totalBlobAssetSize = sizeof(BlobAssetBatch);

            for (int i = 0; i < blobAssets.Length; ++i)
            {
                totalBlobAssetSize += sizeof(BlobAssetHeader);
                blobAssetOffsets[i] = totalBlobAssetSize;
                totalBlobAssetSize += Align16(blobAssets[i].header->Length);
            }

            writer.Write(totalBlobAssetSize);
            var blobAssetBatch = BlobAssetBatch.CreateForSerialize(blobAssets.Length, totalBlobAssetSize);

            writer.WriteBytes(&blobAssetBatch, sizeof(BlobAssetBatch));
            var zeroBytes = int4.zero;

            for (int i = 0; i < blobAssets.Length; ++i)
            {
                var blobAssetLength = blobAssets[i].header->Length;
                var header          = BlobAssetHeader.CreateForSerialize(Align16(blobAssetLength));
                writer.WriteBytes(&header, sizeof(BlobAssetHeader));
                writer.WriteBytes(blobAssets[i].header + 1, blobAssetLength);
                writer.WriteBytes(&zeroBytes, header.Length - blobAssetLength);
            }

            var tempChunk = (Chunk *)UnsafeUtility.Malloc(Chunk.kChunkSize, 16, Allocator.Temp);

            for (int archetypeIndex = 0; archetypeIndex < archetypeArray.Length; ++archetypeIndex)
            {
                var archetype = archetypeArray[archetypeIndex].Archetype;
                for (var ci = 0; ci < archetype->Chunks.Count; ++ci)
                {
                    var chunk = archetype->Chunks.p[ci];
                    bufferPatches.Clear();

                    UnsafeUtility.MemCpy(tempChunk, chunk, Chunk.kChunkSize);
                    tempChunk->metaChunkEntity = EntityRemapUtility.RemapEntity(ref entityRemapInfos, tempChunk->metaChunkEntity);

                    // Prevent patching from touching buffers allocated memory
                    BufferHeader.PatchAfterCloningChunk(tempChunk);

                    byte *tempChunkBuffer = tempChunk->Buffer;
                    EntityRemapUtility.PatchEntities(archetype->ScalarEntityPatches, archetype->ScalarEntityPatchCount, archetype->BufferEntityPatches, archetype->BufferEntityPatchCount, tempChunkBuffer, tempChunk->Count, ref entityRemapInfos);
                    if (archetype->ContainsBlobAssetRefs)
                    {
                        PatchBlobAssetsInChunkBeforeSave(tempChunk, chunk, blobAssetOffsets, blobAssetRefs);
                    }

                    FillPatchRecordsForChunk(chunk, bufferPatches);

                    ClearChunkHeaderComponents(tempChunk);
                    ChunkDataUtility.MemsetUnusedChunkData(tempChunk, 0);
                    tempChunk->Archetype = (Archetype *)archetypeIndex;

                    if (archetype->NumManagedArrays != 0)
                    {
                        throw new ArgumentException("Serialization of GameObject components is not supported for pure entity scenes");
                    }

                    writer.WriteBytes(tempChunk, Chunk.kChunkSize);

                    writer.Write(bufferPatches.Length);

                    if (bufferPatches.Length > 0)
                    {
                        writer.WriteList(bufferPatches);

                        // Write heap backed data for each required patch.
                        // TODO: PERF: Investigate static-only deserialization could manage one block and mark in pointers somehow that they are not indiviual
                        for (int i = 0; i < bufferPatches.Length; ++i)
                        {
                            var patch  = bufferPatches[i];
                            var header = (BufferHeader *)OffsetFromPointer(tempChunk->Buffer, patch.ChunkOffset);
                            writer.WriteBytes(header->Pointer, patch.AllocSizeBytes);
                            BufferHeader.Destroy(header);
                        }
                    }
                }
            }

            blobAssetRefs.Dispose();
            blobAssets.Dispose();

            bufferPatches.Dispose();
            UnsafeUtility.Free(tempChunk, Allocator.Temp);

            sharedComponentsToSerialize = new int[sharedComponentMapping.Length - 1];

            using (var keyArray = sharedComponentMapping.GetKeyArray(Allocator.Temp))
                foreach (var key in keyArray)
                {
                    if (key == 0)
                    {
                        continue;
                    }

                    if (sharedComponentMapping.TryGetValue(key, out var val))
                    {
                        sharedComponentsToSerialize[val - 1] = key;
                    }
                }

            archetypeToIndex.Dispose();
            typeHashes.Dispose();
            typeHashSet.Dispose();
            typeHashToIndexMap.Dispose();
        }
	public BindAsAttribute (Type type)
	{
		Type = type;
#if BGENERATOR
		var nullable = type.IsArray ? TypeManager.GetUnderlyingNullableType (type.GetElementType ()) : TypeManager.GetUnderlyingNullableType (type);
		IsNullable = nullable != null;
		IsValueType = IsNullable ? nullable.IsValueType : type.IsValueType;
#endif
	}
Example #26
0
        public static FilterNode CreateFilterNode(XElement filterElement, Tree tree)
        {
            if (filterElement.Name == TreeMarkupConstants.Namespace + "ParentIdFilter")
            {
                XAttribute parentTypeAttribute         = filterElement.Attribute("ParentType");
                XAttribute referenceFieldNameAttribute = filterElement.Attribute("ReferenceFieldName");

                if (parentTypeAttribute == null)
                {
                    tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.Common.MissingAttribute", "ParentType");
                    return(null);
                }

                if (referenceFieldNameAttribute == null)
                {
                    tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.Common.MissingAttribute", "ReferenceFieldName");
                    return(null);
                }


                Type parentInterfaceType = TypeManager.TryGetType(parentTypeAttribute.Value);
                if (parentInterfaceType == null)
                {
                    tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.Common.UnknownInterfaceType", parentTypeAttribute.Value);
                    return(null);
                }

                return(new ParentIdFilterNode
                {
                    XPath = filterElement.GetXPath(),
                    Id = tree.BuildProcessContext.FilterIdCounter++,
                    ParentFilterType = parentInterfaceType,
                    ReferenceFieldName = referenceFieldNameAttribute.Value
                });
            }

            if (filterElement.Name == TreeMarkupConstants.Namespace + "FieldFilter")
            {
                XAttribute fieldNameAttribute     = filterElement.Attribute("FieldName");
                XAttribute fieldValueAttribute    = filterElement.Attribute("FieldValue");
                XAttribute operatorValueAttribute = filterElement.Attribute("Operator");

                if (fieldNameAttribute == null)
                {
                    tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.Common.MissingAttribute", "FieldName");
                    return(null);
                }

                if (fieldValueAttribute == null)
                {
                    tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.Common.MissingAttribute", "FieldValue");
                    return(null);
                }

                FieldFilterNodeOperator filterOperator;
                string operatorValue = operatorValueAttribute.GetValueOrDefault("equal");
                switch (operatorValue)
                {
                case "equal":
                    filterOperator = FieldFilterNodeOperator.Equal;
                    break;

                case "inequal":
                    filterOperator = FieldFilterNodeOperator.Inequal;
                    break;

                case "lesser":
                    filterOperator = FieldFilterNodeOperator.Lesser;
                    break;

                case "greater":
                    filterOperator = FieldFilterNodeOperator.Greater;
                    break;

                case "lesserequal":
                    filterOperator = FieldFilterNodeOperator.LesserEqual;
                    break;

                case "greaterequal":
                    filterOperator = FieldFilterNodeOperator.GreaterEqual;
                    break;

                default:
                    tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.FieldFilter.UnknownOperatorName", operatorValue);
                    return(null);
                }

                return(new FieldFilterNode
                {
                    XPath = filterElement.GetXPath(),
                    Id = tree.BuildProcessContext.FilterIdCounter++,
                    FieldName = fieldNameAttribute.Value,
                    FieldValue = fieldValueAttribute.Value,
                    Operator = filterOperator
                });
            }

            if (filterElement.Name == TreeMarkupConstants.Namespace + "FunctionFilter")
            {
                XElement functionMarkupElement = filterElement.Element((XNamespace)FunctionTreeConfigurationNames.NamespaceName + FunctionTreeConfigurationNames.FunctionTagName);

                if (functionMarkupElement == null)
                {
                    tree.AddValidationError(filterElement.GetXPath(), "TreeValidationError.FunctionFilter.MissingFunctionMarkup");
                    return(null);
                }

                return(new FunctionFilterNode()
                {
                    XPath = filterElement.GetXPath(),
                    Id = tree.BuildProcessContext.FilterIdCounter++,
                    FunctionMarkup = functionMarkupElement
                });
            }

            throw new NotImplementedException("ValidationError");
        }
Example #27
0
        public void ReactToNamedObjectChangedValue(string changedMember, string parent, object oldValue)
        {
            string combinedMember;

            if (string.IsNullOrEmpty(parent))
            {
                combinedMember = changedMember;
            }
            else
            {
                combinedMember = parent + "." + changedMember;
            }

            NamedObjectSave namedObjectSave = EditorLogic.CurrentNamedObject;
            IElement        element         = EditorLogic.CurrentElement;

            if (PropertiesToMethods.ContainsKey(changedMember))
            {
                PropertiesToMethods[changedMember](namedObjectSave, oldValue);
            }

            #region SourceType changed
            else if (changedMember == "SourceType")
            {
                bool didErrorOccur = false;

                if (didErrorOccur)
                {
                    namedObjectSave.SourceType = (SourceType)oldValue;
                }
                else
                {
                    if (namedObjectSave.SourceType == SourceType.Entity)
                    {
                        namedObjectSave.AddToManagers = true;
                    }
                    else if (namedObjectSave.SourceType == SourceType.File &&
                             namedObjectSave.GetContainerType() == ContainerType.Screen)
                    {
                        namedObjectSave.AddToManagers = false;
                    }
                }
            }
            #endregion

            #region SourceClassType changed

            else if (changedMember == "SourceClassType")
            {
                ReactToChangedSourceClassType(namedObjectSave, oldValue);
            }

            #endregion

            #region SourceFile changed
            else if (changedMember == "SourceFile")
            {
                if (namedObjectSave.SourceFile != (string)oldValue)
                {
                    // See if the current SourceName is valid or not
                    List <string> availableSourceNames =
                        AvailableNameablesStringConverter.GetAvailableNamedObjectSourceNames(namedObjectSave);


                    bool isSourceNameValid = availableSourceNames.Contains(namedObjectSave.SourceName);

                    if (!isSourceNameValid)
                    {
                        namedObjectSave.SourceName = "<NONE>";
                    }
                }
            }

            #endregion

            #region SourceName

            else if (changedMember == "SourceName")
            {
                // This needs to happen before we update custom properties
                ReactToChangedNosSourceName(namedObjectSave, oldValue as string);


                namedObjectSave.UpdateCustomProperties();
            }

            #endregion

            #region InstanceName changed

            else if (changedMember == "InstanceName")
            {
                ReactToNamedObjectChangedInstanceName(namedObjectSave, oldValue);
            }

            #endregion

            #region SetByDerived Changed

            else if (changedMember == "SetByDerived")
            {
                if (namedObjectSave.SourceType == SourceType.Entity &&
                    !string.IsNullOrEmpty(namedObjectSave.SourceClassType))
                {
                    if (ProjectManager.VerifyReferenceGraph(ObjectFinder.Self.GetEntitySave(namedObjectSave.SourceClassType)) == ProjectManager.CheckResult.Failed)
                    {
                        namedObjectSave.SetByDerived = !namedObjectSave.SetByDerived;
                    }
                }


                if (namedObjectSave.SetByDerived && namedObjectSave.ExposedInDerived)
                {
                    // The user has just set SetByDerived to true, but ExposedInDerived means that
                    // the derived expects that the base instantiates.  We need to tell the user that
                    // both values can't be true at the same time, and that ExposedInDerived will be set
                    // to false.
                    MessageBox.Show("You have set SetByDerived to true, but ExposedInDerived is also true.  Both cannot be true at the same time " +
                                    "so Glue will set ExposedInDerived to false.");
                    namedObjectSave.ExposedInDerived = false;
                }


                if (namedObjectSave.SourceType == SourceType.FlatRedBallType &&
                    namedObjectSave.IsList &&
                    namedObjectSave.SetByDerived == true &&
                    namedObjectSave.ContainedObjects.Count != 0)
                {
                    MessageBox.Show("This list is not empty, so it can't be set to \"Set By Derived\".  You must first empty the list", "Invalid Setting");

                    namedObjectSave.SetByDerived = false;
                }
                else
                {
                    ProjectManager.UpdateAllDerivedElementFromBaseValues(false, true);
                }
            }

            #endregion

            #region ExposedInDerived Changed

            else if (changedMember == "ExposedInDerived")
            {
                if (namedObjectSave.SetByDerived && namedObjectSave.ExposedInDerived)
                {
                    // See comment in ExposedByDerived block on why this occurs
                    MessageBox.Show("You have set ExposedInDerived to true, but SetByDerived is also true.  Both cannot be true at the same time " +
                                    "so Glue will set SetByDerived to false.");
                    namedObjectSave.SetByDerived = false;
                }


                SetExposedByDerivedRecursively(namedObjectSave, oldValue);

                ProjectManager.UpdateAllDerivedElementFromBaseValues(false, true);
            }


            #endregion

            #region SourceClassGenericType

            else if (changedMember == "SourceClassGenericType")
            {
                ReactToSourceClassGenericType(namedObjectSave, oldValue);
            }

            #endregion

            #region IsDisabled

            else if (changedMember == "IsDisabled")
            {
                GlueState.Self.Find.ElementTreeNode(EditorLogic.CurrentElement).UpdateReferencedTreeNodes();
            }

            #endregion

            #region SetByContainer Changed
            else if (changedMember == "SetByContainer")
            {
                if (namedObjectSave.SourceType == SourceType.Entity &&
                    !string.IsNullOrEmpty(namedObjectSave.SourceClassType))
                {
                    if (ProjectManager.VerifyReferenceGraph(ObjectFinder.Self.GetEntitySave(namedObjectSave.SourceClassType)) == ProjectManager.CheckResult.Failed)
                    {
                        namedObjectSave.SetByContainer = !namedObjectSave.SetByContainer;
                    }
                }

                List <IElement> derivedElements = ObjectFinder.Self.GetAllElementsThatInheritFrom(
                    EditorLogic.CurrentElement.Name);

                foreach (IElement derived in derivedElements)
                {
                    foreach (NamedObjectSave nos in derived.NamedObjects)
                    {
                        if (nos.InstanceName == namedObjectSave.InstanceName)
                        {
                            nos.SetByContainer = namedObjectSave.SetByContainer;
                        }
                    }
                }

                if (EditorLogic.CurrentEntitySave != null)
                {
                    List <NamedObjectSave> entityNamedObjects = ObjectFinder.Self.GetAllNamedObjectsThatUseEntity(EditorLogic.CurrentEntitySave.Name);

                    foreach (NamedObjectSave nos in entityNamedObjects)
                    {
                        nos.UpdateCustomProperties();
                    }
                }
            }

            #endregion

            #region AddToManagers Changed

            else if (changedMember == "AddToManagers")
            {
                if (namedObjectSave.AddToManagers &&
                    namedObjectSave.GetContainerType() == ContainerType.Screen && namedObjectSave.SourceType == SourceType.File)
                {
                    ScreenSave screenSave = namedObjectSave.GetContainer() as ScreenSave;

                    ReferencedFileSave rfs = screenSave.GetReferencedFileSave(namedObjectSave.SourceFile);

                    if (rfs != null && !rfs.IsSharedStatic)
                    {
                        System.Windows.Forms.MessageBox.Show("This object comes from a file.  Files which are part of Screens " +
                                                             "are automatically added to the engine managers.  " +
                                                             "Adding this object would result in double-membership in the engine which may cause unexpected results.  " +
                                                             "\n\nGlue will now set this value back to false.");
                        namedObjectSave.AddToManagers = false;
                    }
                }
            }

            #endregion


            #region LayerOn

            else if (changedMember == "LayerOn")
            {
                if (namedObjectSave.IsList)
                {
                    DialogResult result = DialogResult.No;
                    if (string.IsNullOrEmpty(namedObjectSave.LayerOn))
                    {
                        result = MessageBox.Show("Do you want to remove every object in the List " + namedObjectSave.InstanceName +
                                                 " from its Layer?",
                                                 "Remove all from Layer?",
                                                 MessageBoxButtons.YesNo);
                    }
                    else
                    {
                        result = MessageBox.Show("Do you want to add every object contained in the List " + namedObjectSave.InstanceName +
                                                 " to the Layer " + namedObjectSave.LayerOn + "?",
                                                 "Add all to Layer?",
                                                 MessageBoxButtons.YesNo);
                    }

                    if (result == DialogResult.Yes)
                    {
                        namedObjectSave.SetLayerRecursively(namedObjectSave.LayerOn);
                    }
                }
            }

            #endregion

            #region IsContainer

            else if (changedMember == "IsContainer")
            {
                HandleChangedIsContainer(namedObjectSave, element);
            }

            #endregion


            #region AttachToCamera

            else if (changedMember == "AttachToCamera")
            {
                if (namedObjectSave.IsList)
                {
                    DialogResult result = DialogResult.No;

                    if (namedObjectSave.AttachToCamera)
                    {
                        result = MessageBox.Show("Do you want to attach every object contained in the list " + namedObjectSave.InstanceName +
                                                 " to the Camera?", "Attach all to Camera?",
                                                 MessageBoxButtons.YesNo);
                    }
                    else
                    {
                        result = MessageBox.Show("Do you want to detach every object contained in the list " + namedObjectSave.InstanceName +
                                                 " from the Camera?", "Detach all from the Camera?",
                                                 MessageBoxButtons.YesNo);
                    }

                    if (result == DialogResult.Yes)
                    {
                        namedObjectSave.SetAttachToCameraRecursively(namedObjectSave.AttachToCamera);
                    }
                }
            }


            #endregion

            #region DestinationRectangle.Y (for Layers)
            else if (parent == "DestinationRectangle" && changedMember == "Y")
            {
                // If the Y is odd, we should warn the user that it should be even
                // or else text will draw incorrectly
                if (namedObjectSave.DestinationRectangle.HasValue && namedObjectSave.DestinationRectangle.Value.Y % 2 == 1)
                {
                    MessageBox.Show("Setting an odd value to the DestinationRectangle's Y may cause text to render improperly.  An " +
                                    "even value is recommended");
                }
            }

            #endregion

            #region RemoveFromManagersWhenInvisible

            else if (changedMember == "RemoveFromManagersWhenInvisible")
            {
                // is this an Entity instance?
                if (namedObjectSave.SourceType == SourceType.Entity && namedObjectSave.RemoveFromManagersWhenInvisible)
                {
                    var entitySave = ObjectFinder.Self.GetEntitySave(namedObjectSave.SourceClassType);

                    if (entitySave != null)
                    {
                        // Is this CreatedByOtherEntities?
                        if (!entitySave.CreatedByOtherEntities)
                        {
                            MessageBox.Show("The Entity " + entitySave + " should have its CreatedByOtherEntities set to true to enable " +
                                            "visibility-based removal to work properly");
                        }
                    }
                }
            }
            #endregion


            else if (namedObjectSave?.GetCustomVariable(changedMember) != null)
            {
                // See if this variable is tunneled into in this element.
                // If so, set that value too.
                CustomVariableInNamedObject cvino = namedObjectSave.GetCustomVariable(changedMember);
                object value = cvino.Value;

                foreach (CustomVariable customVariable in EditorLogic.CurrentElement.CustomVariables)
                {
                    if (customVariable.SourceObject == namedObjectSave.InstanceName &&
                        customVariable.SourceObjectProperty == changedMember)
                    {
                        // The custom variable may have a different type:
                        if (!string.IsNullOrEmpty(customVariable.OverridingPropertyType))
                        {
                            // it does, so convert
                            Type overridingType = TypeManager.GetTypeFromString(customVariable.OverridingPropertyType);

                            customVariable.DefaultValue = System.Convert.ChangeType(value, overridingType);
                        }
                        else
                        {
                            customVariable.DefaultValue = value;
                        }
                        break;
                    }
                }
            }

            // If we changed BitmapFont and if the NOS is marked as PixelPerfect
            // and if it's a Text object, then we should set the Scale, Spacing, and
            // NewLineDistance according to the set BitmapFont
            // We don't do an else because there could be a CustomVariable by the name
            // of BitmapFont as well, and we dont' want to eliminate that.
            if (changedMember == "Font" && namedObjectSave.SourceType == SourceType.FlatRedBallType &&
                namedObjectSave.SourceClassType == "Text" && namedObjectSave.IsPixelPerfect)
            {
                ReactToFontSet(namedObjectSave, oldValue);
            }

            PropertyGridHelper.UpdateNamedObjectDisplay();

            PluginManager.ReactToNamedObjectChangedValue(changedMember, oldValue);
        }
Example #28
0
        private IList <PackageFragmentValidationResult> LoadPackageFragmentInstallers(XElement packageFragmentInstallersElement)
        {
            var result = new List <PackageFragmentValidationResult>();

            XName packageInstallerXName = XmlUtils.GetXName(PackageSystemSettings.XmlNamespace, PackageSystemSettings.PackageFragmentInstallersAddElementName);

            foreach (XElement element in packageFragmentInstallersElement.Elements(packageInstallerXName))
            {
                XAttribute installerTypeAttribute = element.Attribute(PackageSystemSettings.InstallerTypeAttributeName);
                if (installerTypeAttribute == null)
                {
                    result.AddFatal($"Missing attribute '{PackageSystemSettings.InstallerTypeAttributeName}'", element);
                    continue;
                }

                Type installerType = TypeManager.TryGetType(installerTypeAttribute.Value);
                if (installerType == null)
                {
                    result.AddFatal($"Could not find install fragment type '{installerTypeAttribute.Value}'", installerTypeAttribute);
                    continue;
                }

                IPackageFragmentInstaller packageFragmentInstaller;
                try
                {
                    packageFragmentInstaller = Activator.CreateInstance(installerType) as IPackageFragmentInstaller;
                }
                catch (Exception ex)
                {
                    result.AddFatal(ex);
                    continue;
                }

                if (packageFragmentInstaller == null)
                {
                    result.AddFatal($"The type '{installerTypeAttribute.Value}' does not implement {typeof (IPackageFragmentInstaller)}", installerTypeAttribute);
                    continue;
                }

                Type uninstallerType = null;
                if (this.CanBeUninstalled)
                {
                    XAttribute uninstallerTypeAttribute = element.Attribute(PackageSystemSettings.UninstallerTypeAttributeName);
                    if (uninstallerTypeAttribute == null)
                    {
                        result.AddFatal($"Missing attribute '{PackageSystemSettings.UninstallerTypeAttributeName}'", element);
                        continue;
                    }

                    uninstallerType = TypeManager.TryGetType(uninstallerTypeAttribute.Value);
                    if (uninstallerType == null)
                    {
                        result.AddFatal($"Could not find uninstall fragment type '{uninstallerTypeAttribute.Value}'", uninstallerTypeAttribute);
                        continue;
                    }

                    IPackageFragmentUninstaller packageFragmentUninstaller;
                    try
                    {
                        packageFragmentUninstaller = Activator.CreateInstance(uninstallerType) as IPackageFragmentUninstaller;
                    }
                    catch (Exception ex)
                    {
                        result.AddFatal(ex);
                        continue;
                    }

                    if (packageFragmentUninstaller == null)
                    {
                        result.AddFatal($"The type '{uninstallerTypeAttribute.Value}' does not implement {typeof (IPackageFragmentUninstaller)}", uninstallerTypeAttribute);
                        continue;
                    }
                }

                try
                {
                    packageFragmentInstaller.Initialize(_packageInstallerContex, element.Descendants(), element);
                }
                catch (Exception ex)
                {
                    result.AddFatal(ex);
                    continue;
                }

                _packageFramentInstallers.Add(packageFragmentInstaller, uninstallerType);
            }

            return(result);
        }
Example #29
0
 public PageTeaserInstanceEntityToken(IPage page, IPageTeaser teaser)
 {
     _source = page.Id.ToString();
     _type   = TypeManager.SerializeType(teaser.DataSourceId.InterfaceType);
     _id     = teaser.Id.ToString();
 }
Example #30
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "XhtmlBaseParser" /> class.
 /// </summary>
 /// <param name = "settings">The settings.</param>
 /// <param name = "typeManager">The type manager.</param>
 protected XhtmlBaseParser(NameValueCollection settings, TypeManager typeManager, TextWriter logger) : base(settings, typeManager, logger)
 {
 }
 public void RegisterUnityEngineComponentType_WithWrongType_ThrowsArgumentException(Type type)
 {
     Assert.Throws <ArgumentException>(() => TypeManager.RegisterUnityEngineComponentType(type));
 }
        private void initializeCodeActivity_Copy_ExecuteCode(object sender, EventArgs e)
        {
            var castedEntityToken = (DataEntityToken)this.EntityToken;

            IPage newPage;

            using (var transactionScope = TransactionsFacade.CreateNewScope())
            {
                CultureInfo sourceCultureInfo = UserSettings.ForeignLocaleCultureInfo;

                IPage sourcePage;
                List <IPagePlaceholderContent> sourcePagePlaceholders;
                List <IData> sourceMetaDataSet;

                using (new DataScope(sourceCultureInfo))
                {
                    var  pageFromEntityToken = (IPage)castedEntityToken.Data;
                    Guid sourcePageId        = pageFromEntityToken.Id;
                    Guid sourcePageVersionId = pageFromEntityToken.VersionId;

                    using (new DataScope(DataScopeIdentifier.Administrated))
                    {
                        sourcePage = DataFacade.GetData <IPage>(f => f.Id == sourcePageId && f.VersionId == sourcePageVersionId).Single();
                        sourcePage = sourcePage.GetTranslationSource();

                        using (new DataScope(sourcePage.DataSourceId.DataScopeIdentifier))
                        {
                            sourcePagePlaceholders = DataFacade
                                                     .GetData <IPagePlaceholderContent>(f => f.PageId == sourcePageId && f.VersionId == sourcePageVersionId)
                                                     .ToList();
                            sourceMetaDataSet = sourcePage.GetMetaData().ToList();
                        }
                    }
                }


                CultureInfo targetCultureInfo = UserSettings.ActiveLocaleCultureInfo;

                using (new DataScope(targetCultureInfo))
                {
                    newPage = DataFacade.BuildNew <IPage>();
                    sourcePage.ProjectedCopyTo(newPage);

                    newPage.SourceCultureName = targetCultureInfo.Name;
                    newPage.PublicationStatus = GenericPublishProcessController.Draft;
                    newPage = DataFacade.AddNew <IPage>(newPage);

                    foreach (IPagePlaceholderContent sourcePagePlaceholderContent in sourcePagePlaceholders)
                    {
                        IPagePlaceholderContent newPagePlaceholderContent = DataFacade.BuildNew <IPagePlaceholderContent>();
                        sourcePagePlaceholderContent.ProjectedCopyTo(newPagePlaceholderContent);

                        newPagePlaceholderContent.SourceCultureName = targetCultureInfo.Name;
                        newPagePlaceholderContent.PublicationStatus = GenericPublishProcessController.Draft;
                        DataFacade.AddNew <IPagePlaceholderContent>(newPagePlaceholderContent);
                    }

                    foreach (IData metaData in sourceMetaDataSet)
                    {
                        ILocalizedControlled localizedData = metaData as ILocalizedControlled;

                        if (localizedData == null)
                        {
                            continue;
                        }

                        IEnumerable <ReferenceFailingPropertyInfo> referenceFailingPropertyInfos = DataLocalizationFacade.GetReferencingLocalizeFailingProperties(localizedData).Evaluate();

                        if (!referenceFailingPropertyInfos.Any())
                        {
                            IData newMetaData = DataFacade.BuildNew(metaData.DataSourceId.InterfaceType);
                            metaData.ProjectedCopyTo(newMetaData);

                            ILocalizedControlled localizedControlled = newMetaData as ILocalizedControlled;
                            localizedControlled.SourceCultureName = targetCultureInfo.Name;

                            IPublishControlled publishControlled = newMetaData as IPublishControlled;
                            publishControlled.PublicationStatus = GenericPublishProcessController.Draft;

                            DataFacade.AddNew(newMetaData);
                        }
                        else
                        {
                            foreach (ReferenceFailingPropertyInfo referenceFailingPropertyInfo in referenceFailingPropertyInfos)
                            {
                                Log.LogVerbose("LocalizePageWorkflow",
                                               "Meta data of type '{0}' is not localized because the field '{1}' is referring some not yet localzed data"
                                               .FormatWith(metaData.DataSourceId.InterfaceType, referenceFailingPropertyInfo.DataFieldDescriptor.Name));
                            }
                        }
                    }
                }

                EntityTokenCacheFacade.ClearCache(sourcePage.GetDataEntityToken());
                EntityTokenCacheFacade.ClearCache(newPage.GetDataEntityToken());

                foreach (var folderType in PageFolderFacade.GetDefinedFolderTypes(newPage))
                {
                    EntityTokenCacheFacade.ClearCache(new AssociatedDataElementProviderHelperEntityToken(
                                                          TypeManager.SerializeType(typeof(IPage)),
                                                          PageElementProvider.DefaultConfigurationName,
                                                          newPage.Id.ToString(),
                                                          TypeManager.SerializeType(folderType)));
                }


                transactionScope.Complete();
            }

            ParentTreeRefresher parentTreeRefresher = this.CreateParentTreeRefresher();

            parentTreeRefresher.PostRefreshMesseges(newPage.GetDataEntityToken(), 2);

            this.ExecuteWorklow(newPage.GetDataEntityToken(), typeof(EditPageWorkflow));
        }
        public CompendiumFirstDepthMap()
        {
            InitializeComponent();

            if (!IsInDesignMode)
            {
                _nodeService = new DatabaseMappingService();

                _typeManager = new TypeManager(_nodeService);
                IoC.IoCContainer.GetInjectionInstance().RegisterComponent<TypeManager>(_typeManager);

                _typeManager.InitialiseNodeTypeManagerCompleted += new EventHandler(InitialiseNodeTypeManagerCompleted);
                _typeManager.InitialiseNodeTypeManager();
            }
        }