public void SetUp()
 {
     var registry = new ValidationRegistry();
     var resolver = new TypeResolver();
     _query = new ValidationQuery(resolver, registry.GetConfiguredSources());
     _provider = new ValidationProvider(resolver, _query);
 }
Exemple #2
0
 public new void ResolveTypes(TypeResolver typeResolver)
 {
     foreach (var methodParameter in Parameters)
     {
         methodParameter.ResolveTypes(typeResolver);
     }
 }
 public FlexiPlainTextSerializationContext(
     IFlexiPlainTextSerializer serializer,
     ITypeDescriptor typeDescriptor,
     TypeResolver typeResolver,
     Func<Type, CreateInstanceContext, object> createInstanceWith = null)
     : base(serializer, typeDescriptor, typeResolver, createInstanceWith)
 { }
Exemple #4
0
    public void Execute()
    {
        var freezableTypeFinder = new FreezableTypeFinder(ModuleDefinition, AssemblyResolver);
        freezableTypeFinder.Execute();

        var exceptionFinder = new ExceptionFinder(ModuleDefinition, AssemblyResolver);
        exceptionFinder.Execute();

        var volatileFinder = new VolatileTypeFinder(ModuleDefinition, AssemblyResolver);
        volatileFinder.Execute();

        var volatileFieldFixer = new VolatileFieldFixer(volatileFinder);
        var fieldInjector = new FieldInjector(volatileFinder, ModuleDefinition.TypeSystem, volatileFieldFixer);
        var checkIsFrozenBuilder = new CheckIsFrozenBuilder(ModuleDefinition.TypeSystem, exceptionFinder);
        var freezeCheckerInjector = new FreezeCheckerInjector(ModuleDefinition, fieldInjector, checkIsFrozenBuilder);

        var typeResolver = new TypeResolver();
        var implementsInterfaceFinder = new ImplementsInterfaceFinder(typeResolver);

        var classes = ModuleDefinition.GetTypes()
            .Where(x => x.IsClass)
            .ToList();
        var assemblyProcessor = new AssemblyProcessor(freezeCheckerInjector, implementsInterfaceFinder, LogInfo);
        assemblyProcessor.Execute(classes);

        volatileFieldFixer.Execute(classes);
    }
Exemple #5
0
 public static IEnumerable<ITypeDescription> Read(IObjectContainer database,
     TypeResolver typeResolver)
 {
     new {database, typeResolver}.CheckNotNull();
     var reader = new MetaDataReader(typeResolver, ExtractStoredClasses(database.Ext().StoredClasses()));
     return reader.CreateTypes(database.Ext()).ToList();
 }
 public static DatabaseMetaInfo Create(IObjectContainer db,
     TypeResolver typeResolver,
     AssemblyName intoAssembly)
 {
     var metaInfo = MetaDataReader.Read(db, typeResolver);
     var dynamicRepresentaton = CodeGenerator.Create(metaInfo, intoAssembly);
     return new DatabaseMetaInfo(metaInfo, dynamicRepresentaton.Types, dynamicRepresentaton.DataContext);
 }
    public TypeEqualityFinder(ModuleReader moduleReader, MsCoreReferenceFinder msCoreReferenceFinder, TypeResolver typeResolver)
    {
        methodCache = new Dictionary<string, MethodReference>();

        this.moduleReader = moduleReader;
        this.msCoreReferenceFinder = msCoreReferenceFinder;
        this.typeResolver = typeResolver;
    }
Exemple #8
0
 internal static void WithTestContext(IObjectContainer db,TypeResolver resolver, Action action)
 {
     using (var ctx = DatabaseContext.Create(db, NewName(), resolver))
         {
             CurrentContext.NewContext(ctx);
             action();
         }
 }
        public void WeWillSkipAllComponentsIfExcludeByDefaultIsTrue()
        {
            Assert.Ignore("We have changed the wayt that this works, so the tests need to be rewritten");

            resolver = new TypeResolver() { ExcludeByDefault = true };
            Assert.That(resolver.SkipComponent("Test"), Is.True);
            Assert.That(resolver.SkipComponent(1), Is.True);
        }
        public void WeWillNotSkipAnyComponentIfExcludeByDefaultIsFalse()
        {
            Assert.Ignore("We have changed the wayt that this works, so the tests need to be rewritten");

            resolver = new TypeResolver() { ExcludeByDefault = false };
            Assert.That(resolver.SkipComponent("Test"), Is.False);
            Assert.That(resolver.SkipComponent(1), Is.False);
        }
 public IsChangedMethodFinder(MethodGenerifier methodGenerifier, Logger logger, MsCoreReferenceFinder msCoreReferenceFinder, TypeNodeBuilder typeNodeBuilder, ModuleReader moduleReader, TypeResolver typeResolver)
 {
     this.methodGenerifier = methodGenerifier;
     this.logger = logger;
     this.msCoreReferenceFinder = msCoreReferenceFinder;
     this.typeNodeBuilder = typeNodeBuilder;
     this.moduleReader = moduleReader;
     this.typeResolver = typeResolver;
 }
        public static XElement SerializeQuery(this IQueryable query)
        {
			var resolver = new TypeResolver(assemblies: null,knownTypes: new Type[] { query.ElementType });
            ExpressionSerializer serializer = new ExpressionSerializer(resolver) 
			{ 
				Converters = { new DLinqCustomExpressionXmlConverter(null, resolver)} 
			};
            return serializer.Serialize(query.Expression);
        }
 public MethodFinder(MethodGenerifier methodGenerifier, MethodInjector methodInjector, TypeNodeBuilder typeNodeBuilder, ModuleReader moduleReader, Logger logger, TypeResolver typeResolver, EventInvokerNameResolver eventInvokerNameResolver)
 {
     this.methodGenerifier = methodGenerifier;
     this.methodInjector = methodInjector;
     this.typeNodeBuilder = typeNodeBuilder;
     this.moduleReader = moduleReader;
     this.logger = logger;
     this.typeResolver = typeResolver;
     this.eventInvokerNameResolver = eventInvokerNameResolver;
 }
 public FlexiXmlSerializationContext(
     IFlexiSerializer serializer, 
     ITypeDescriptor typeDescriptor, 
     TypeResolver typeResolver,
     FlexiXmlSerializationOptions options,
     Func<Type, CreateInstanceContext, object> createInstanceWith = null)
     : base(serializer, typeDescriptor, typeResolver, createInstanceWith)
 {
     this.Options = options;
 }
        public static IQueryable DeserializeQuery(this DataContext dc, XElement rootXml)
        {
			var resolver = new TypeResolver(assemblies: null, knownTypes: GetKnownTypesFromTables(dc) );
            DLinqCustomExpressionXmlConverter customConverter = new DLinqCustomExpressionXmlConverter(dc, resolver);
			ExpressionSerializer serializer = new ExpressionSerializer(resolver, new List<CustomExpressionXmlConverter> { customConverter });
            Expression queryExpr = serializer.Deserialize(rootXml);
            // Query kind is populated by the ResolveXmlFromExpression method
            if (customConverter.QueryKind == null)
                throw new Exception(string.Format("CAnnot deserialize into DLinq query for datacontext {0} - no Table found", dc));
            return customConverter.QueryKind.Provider.CreateQuery(queryExpr);
        }
 public SerializationContext(
     IFlexiSerializer serializer,
     ITypeDescriptor typeDescriptor,
     TypeResolver typeResolver,
     Func<Type, CreateInstanceContext, object> createInstanceWith = null)
 {
     this.Serializer = serializer;
     this.TypeDescriptor = typeDescriptor;
     this.TypeResolver = typeResolver;
     this.CustomCreateInstanceWith = createInstanceWith;
 }
        public void ResolveAllOfT_GivenICopIntercept_ReturnsRegisteredInterceptorAspects()
        {
            // arrange
            var sut = new TypeResolver();

            // act
            var registeredAspects = sut.ResolveAll<ICopIntercept>();

            // assert
            Assert.That(registeredAspects.Count(), Is.EqualTo(1));
        }
        public void ResolveAllOfT_GivenICache_ReturnsRegisteredCacheImplementation()
        {
            // arrange
            var sut = new TypeResolver();

            // act
            var registeredCaches = sut.ResolveAll<ICache>();

            // assert
            Assert.That(registeredCaches.Count(), Is.EqualTo(1));
        }
        public void Dispose_WhenCalledTwice_ShouldNotThrow()
        {
            // arrange
            var sut = new TypeResolver();

            // act
            sut.Dispose();

            // assert
            Assert.DoesNotThrow(() => sut.Dispose());
        }
Exemple #20
0
        public override void ResolveTypes(TypeResolver typeResolver)
        {
            foreach (var module in Modules)
            {
                module.ResolveTypes(typeResolver);
            }

            foreach (var tsType in Types)
            {
                tsType.ResolveTypes(typeResolver);
            }
        }
        public void register_a_service_by_value()
        {
            var myContainer = new Container();
            var myFacility = new StructureMapContainerFacility(myContainer);

            var registry = new TypeResolver();

            myFacility.Register(typeof (ITypeResolver), new ObjectDef{
                Value = registry
            });

            myFacility.BuildFactory();

            myContainer.GetInstance<ITypeResolver>().ShouldBeTheSameAs(registry);
        }
Exemple #22
0
		static ExpressionSerializer CreateSerializer()
		{
			var assemblies = new Assembly[] { typeof(Customer).Assembly, typeof(ExpressionType).Assembly, typeof(IQueryable).Assembly };
			var resolver = new TypeResolver(assemblies, new Type[] 
			{ 
				typeof(Customer), typeof(Order), typeof(Product), 
				typeof(Supplier), typeof(Shipper) 
			});
			//var creator = new QueryCreator();
			CustomExpressionXmlConverter queryconverter = new QueryExpressionXmlConverter(creator: null, resolver: resolver);
			CustomExpressionXmlConverter knowntypeconverter = new KnownTypeExpressionXmlConverter(resolver);
			ExpressionSerializer serializer = new ExpressionSerializer(resolver, new CustomExpressionXmlConverter[] { queryconverter, knowntypeconverter });
			return serializer;
			//ExpressionSerializer serializer = new ExpressionSerializer()
		}
Exemple #23
0
        public void ResolveTypes(TypeResolver typeResolver)
        {
            foreach (var generic in Generics)
            {
                generic.ResolveTypes(typeResolver);
            }
            foreach (var methodParameter in Parameters)
            {
                methodParameter.ResolveTypes(typeResolver);
            }

            if (Return != null)
            {
                Return = typeResolver.GetType(Return.UnderlyingType, Parent);
            }
        }
        public override RtClass GenerateNode(Type element, RtClass result, TypeResolver resolver)
        {
            result = base.GenerateNode(element, result, resolver);
            if (result == null) return null;

            // We add some docs to keep you oriented
            result.Documentation = new RtJsdocNode(){Description = "Result of AngularControllerGenerator activity"};

            // Here we just create ng.IHttpService type name because it is used several times
            var httpServiceType = new RtSimpleTypeName("IHttpService") { Namespace = "angular" };

            // Here we are declaring constructor for our angular service using $http as parameter
            // It is quite simple so no more details
            RtConstructor constructor = new RtConstructor();
            constructor.Arguments.Add(new RtArgument(){Type = httpServiceType,Identifier = new RtIdentifier("$http")});
            constructor.Body = new RtRaw("this.http = $http;");

            // Here we declaring class field for storing $http instance
            RtField httpServiceField = new RtField()
            {
                Type = httpServiceType,
                Identifier = new RtIdentifier("http"),
                AccessModifier = AccessModifier.Private,
                Documentation = new RtJsdocNode() { Description = "Keeps $http instance received on construction"}
            };

            // Here we are adding our constructor and field to resulting class
            result.Members.Add(httpServiceField);
            result.Members.Add(constructor);

            // Also we will add controller registration to our app instance
            // To automatically get it registered in Angular's IoC
            const string initializerFormat =
                "if (window['app']) window['app'].factory('Api.{0}', ['$http', ($http: angular.IHttpService) => new {1}($http)]);";

            RtRaw registration = new RtRaw(String.Format(initializerFormat,element.Name,result.Name));
            
            // Since RtModule.compilationUnits is not typed and could contain any type then we 
            // simply add RtRaw node here with registration glue code
            // app variable is declared in /Scripts/ReinforcedTypings/App.ts since it is used in 
            // corresponding client script
            Context.Location.CurrentModule.CompilationUnits.Add(registration);

            // That's all. here we return node that will be written to target file.
            // Check result in /Scripts/ReinforcedTypings/GeneratedTypings.ts
            return result;
        }
Exemple #25
0
        /// <summary>
        /// The get service.
        /// </summary>
        /// <param name="name">
        /// The name.
        /// </param>
        /// <param name="logger">
        /// The logger.
        /// </param>
        /// <returns>
        /// The <see cref="IServiceRunner"/>.
        /// </returns>
        private static IServiceRunner GetService(string name, ILogger logger)
        {
            var targetType = Type.GetType(name);
            if (targetType == null)
            {
                return null;
            }

            var typeResolver = new TypeResolver(logger);
            if (targetType.IsClass && !targetType.IsAbstract && typeof(IServiceRunner).IsAssignableFrom(targetType))
            {
                var result = typeResolver.CreateInstance<IServiceRunner>(targetType);
                result.Logger = logger;
                return result;
            }

            return null;
        }
        public void SetUp()
        {
            var validationRegistry = new ValidationRegistry(registry =>
                                                                {
                                                                    registry
                                                                        .Rules
                                                                        .IfPropertyIs<int>()
                                                                        .ApplyStrategy<GreaterThanZeroFieldStrategy>();

                                                                    registry
                                                                        .Rules
                                                                        .If(a => a.Name.ToLower().Contains("required"))
                                                                        .ApplyStrategy<RequiredFieldStrategy>();
                                                                });
            var resolver = new TypeResolver();
            _query = new ValidationQuery(resolver, validationRegistry.GetConfiguredSources());
            _provider = new ValidationProvider(resolver, _query);
        }
        public override RtFuncion GenerateNode(MethodInfo element, RtFuncion result, TypeResolver resolver)
        {
            result = base.GenerateNode(element, result, resolver);
            if (result == null) return null;

            // here we are overriding return type to corresponding promise
            var retType = result.ReturnType;
            bool isVoid = (retType is RtSimpleTypeName) && (((RtSimpleTypeName)retType).TypeName == "void");

            // we use TypeResolver to get "any" type to avoid redundant type name construction
            // (or because I'm too lazy to manually construct "any" type)
            if (isVoid) retType = resolver.ResolveTypeName(typeof(object));

            // Here we override TS method return type to make it angular.IPromise
            // We are using RtSimpleType with generig parameter of existing method type
            result.ReturnType = new RtSimpleTypeName(new[] { retType }, "angular", "IPromise");

            // Here we retrieve method parameters
            // We are using .GetName() extension method to retrieve parameter name
            // It is supplied within Reinforced.Typings and retrieves parameter name 
            // including possible name override with Fluent configuration or 
            // [TsParameter] attribute
            var p = element.GetParameters().Select(c => string.Format("'{0}': {0}", c.GetName()));

            // Joining parameters for method body code
            var dataParameters = string.Join(", ", p);

            // Here we get path to controller
            // It is quite simple solution requiring /{controller}/{action} route
            string controller = element.DeclaringType.Name.Replace("Controller", String.Empty);
            string path = String.Format("/{0}/{1}", controller, element.Name);

            const string code = @"var params = {{ {1} }};
return this.http.post('{0}', params)
    .then((response) => {{ response.data['requestParams'] = params; return response.data; }});";

            RtRaw body = new RtRaw(String.Format(code, path, dataParameters));
            result.Body = body;

            // That's all. here we return node that will be written to target file.
            // Check result in /Scripts/ReinforcedTypings/GeneratedTypings.ts
            return result;
        }
        public void register_a_service_by_value()
        {
            var builder = new ContainerBuilder();
            var myContext = builder.Build();
            var myFacility = new AutofacContainerFacility(myContext);

            var registry = new TypeResolver();

            myFacility.Register(
                typeof(ITypeResolver),
                new ObjectDef
                {
                    Value = registry
                });

            myFacility.BuildFactory();

            myContext.Resolve<ITypeResolver>().ShouldBeTheSameAs(registry);
        }
        /// <summary>
        ///     Generates namespace source code
        /// </summary>
        /// <param name="types">Types list</param>
        /// <param name="namespaceName">Namespace name</param>
        /// <param name="resolver">Type resolver</param>
        public virtual RtModule Generate(IEnumerable<Type> types, string namespaceName, TypeResolver resolver)
        {
            RtModule module = new RtModule();
            if (string.IsNullOrEmpty(namespaceName)) module.IsAbstractModule = true;
            module.ModuleName = namespaceName;

            Context.CurrentNamespace = namespaceName;
            Context.Location.SetLocation(module);
            foreach (var type in types)
            {
                var converter = resolver.GeneratorFor(type, Context);
                var member = converter.Generate(type, resolver);
                module.CompilationUnits.Add(member);
                Console.WriteLine("Exported {0}", type);
            }

            Context.CurrentNamespace = null;
            Context.Location.ResetLocation(module);
            return module;
        }
Exemple #30
0
        /// <summary>
        ///     Main code generator method. This method should write corresponding TypeScript code for element (1st argument) to
        ///     WriterWrapper (3rd argument) using TypeResolver if necessary
        /// </summary>
        /// <param name="element">Element code to be generated to output</param>
        /// <param name="result">Resulting node</param>
        /// <param name="resolver">Type resolver</param>
        public override RtArgument GenerateNode(ParameterInfo element, RtArgument result, TypeResolver resolver)
        {
            if (Context.CurrentBlueprint.IsIgnored(element))
            {
                return(null);
            }
            var        name = element.Name;
            RtTypeName type;
            var        isNullable = false;

            var fa           = Context.CurrentBlueprint.ForMember(element);
            var defaultValue = GetDefaultValue(element, fa);

            if (fa != null)
            {
                if (!string.IsNullOrEmpty(fa.Name))
                {
                    name = fa.Name;
                }

                if (!string.IsNullOrEmpty(fa.Type))
                {
                    type = new RtSimpleTypeName(fa.Type);
                }
                else if (fa.StrongType != null)
                {
                    type       = resolver.ResolveTypeName(fa.StrongType);
                    isNullable = element.IsOptional;
                }
                else
                {
                    type = resolver.ResolveTypeName(element.ParameterType);
                }
                type = fa.TypeInferers.Infer(element, resolver) ?? type;
            }
            else
            {
                type       = resolver.ResolveTypeName(element.ParameterType);
                isNullable = element.IsOptional;
            }
            if (element.GetCustomAttribute <ParamArrayAttribute>() != null)
            {
                result.IsVariableParameters = true;
            }
            result.Identifier = new RtIdentifier(name);
            result.Type       = type;
            if (isNullable && defaultValue == null)
            {
                result.Identifier.IsNullable = true;
            }
            if (defaultValue != null)
            {
                //if parameter is having enum type then simple string value assignment is now right
                //so for Enum type result.DefaultValue should be equal to ENUME_NAME+"."+DefaultValue
                if (element.ParameterType.IsEnum)
                {
                    result.DefaultValue = result.Type + "." + defaultValue;
                }
                else
                {
                    result.DefaultValue = defaultValue;
                }
            }
            AddDecorators(result, Context.CurrentBlueprint.DecoratorsFor(element));
            return(result);
        }
Exemple #31
0
        public static DragAndDropVisualMode HandleHierarchyPaneDragAndDrop(IEnumerable <UnityObject> objectsBeingDropped, TrackAsset targetTrack, bool perform, TimelineAsset timeline, PlayableDirector director, TypeResolver typeResolver, TrackAsset insertBefore = null)
        {
            if (timeline == null)
            {
                return(DragAndDropVisualMode.Rejected);
            }

            // if we are over a target track, defer to track binding system (implemented in TrackGUIs), unless we are a groupTrack
            if (targetTrack != null && (targetTrack as GroupTrack) == null)
            {
                return(DragAndDropVisualMode.None);
            }

            if (targetTrack != null && targetTrack.lockedInHierarchy)
            {
                return(DragAndDropVisualMode.Rejected);
            }

            var tracksWithBinding = objectsBeingDropped.SelectMany(TypeUtility.GetTracksCreatableFromObject).Distinct();

            if (!tracksWithBinding.Any())
            {
                return(DragAndDropVisualMode.None);
            }

            if (perform)
            {
                System.Action <Type> onResolve = trackType =>
                {
                    foreach (var obj in objectsBeingDropped)
                    {
                        if (!obj.IsPrefab() && TypeUtility.IsTrackCreatableFromObject(obj, trackType))
                        {
                            var newTrack = TimelineHelpers.CreateTrack(timeline, trackType, targetTrack, string.Empty);
                            if (insertBefore != null)
                            {
                                if (targetTrack != null)
                                {
                                    targetTrack.MoveLastTrackBefore(insertBefore);
                                }
                                else
                                {
                                    timeline.MoveLastTrackBefore(insertBefore);
                                }
                            }

                            TimelineHelpers.Bind(newTrack, obj, director);
                        }
                    }
                    TimelineEditor.Refresh(RefreshReason.ContentsAddedOrRemoved);
                };
                typeResolver(tracksWithBinding, onResolve, k_SelectTrackWithBinding);
            }

            return(DragAndDropVisualMode.Copy);
        }
 public RtTypeName PropertyInfer(MemberInfo member, TypeResolver typeResolver)
 {
     return(InferNullable((member as PropertyInfo).PropertyType, typeResolver));
 }
 public RtTypeName MethodInfer(MethodInfo method, TypeResolver typeResolver)
 {
     return(InferNullable(method.ReturnType, typeResolver));
 }
Exemple #34
0
        private bool IsApplication(NodeHead appNode)
        {
            var type = TypeResolver.GetType(appNode.GetNodeType().ClassName, false);

            return(type != null && typeof(Application).IsAssignableFrom(type));
        }
Exemple #35
0
 internal override void ResolveSignatureTypes(ParserContext parser, TypeResolver typeResolver)
 {
     // Nothing to do.
 }
Exemple #36
0
        private void BuildClientClass(string typeName, SignalRGenerationOptions options, Type element, RtInterface result, TypeResolver resolver)
        {
            RtClass clientImpl = new RtClass
            {
                Name       = new RtSimpleTypeName(typeName),
                Export     = true,
                Decorators = { },
                Members    =
                {
                    new RtConstructor
                    {
                        Arguments =   { new RtArgument
                                        {
                                            Type       = new RtSimpleTypeName(options.HubConnectionProviderType),
                                            Identifier = new RtIdentifier("hubConnectionProvider")
                                        } },
                        Body      = new RtRaw($"this.hubConnection = hubConnectionProvider.getHubConnection(\"{options.HubPath}\");"),
                        LineAfter = " "
                    }
                }
            };

            clientImpl.Members.AddRange(GetImplementationMembers(result, options.HubPath));

            Context.Location.CurrentNamespace.CompilationUnits.Add(clientImpl);
            Context.AddNewLine();
        }
Exemple #37
0
        internal override Expression ResolveTypes(ParserContext parser, TypeResolver typeResolver)
        {
            this.Root.ResolveTypes(parser, typeResolver);

            string field = this.FieldToken.Value;

            if (this.Root is EnumReference)
            {
                throw new System.NotImplementedException();
            }

            ResolvedType rootType = this.Root.ResolvedType;

            // TODO: all of this needs to be localized.
            switch (rootType.Category)
            {
            case ResolvedTypeCategory.NULL:
                throw new ParserException(this.DotToken, "Cannot dereference a field from null.");

            case ResolvedTypeCategory.ANY:
                // ¯\_(ツ)_/¯
                this.ResolvedType = ResolvedType.ANY;
                return(this);

            case ResolvedTypeCategory.INTEGER:
                throw new ParserException(this.DotToken, "Integers do not have any fields.");

            case ResolvedTypeCategory.FLOAT:
                throw new ParserException(this.DotToken, "Floating point decimals do not have any fields.");

            case ResolvedTypeCategory.BOOLEAN:
                throw new ParserException(this.DotToken, "Booleans do not have any fields.");

            case ResolvedTypeCategory.STRING:
                switch (field)
                {
                case "length":
                    this.ResolvedType = ResolvedType.INTEGER;
                    if (this.Root is StringConstant)
                    {
                        return(new IntegerConstant(this.FirstToken, ((StringConstant)this.Root).Value.Length, this.Owner));
                    }
                    return(this);

                case "contains": return(BuildPrimitiveMethod(ResolvedType.BOOLEAN, ResolvedType.STRING));

                case "endsWith": return(BuildPrimitiveMethod(ResolvedType.BOOLEAN, ResolvedType.STRING));

                case "indexOf": return(BuildPrimitiveMethod(ResolvedType.INTEGER, ResolvedType.STRING));

                case "lower": return(BuildPrimitiveMethod(ResolvedType.STRING));

                case "ltrim": return(BuildPrimitiveMethod(ResolvedType.STRING));

                case "replace": return(BuildPrimitiveMethod(ResolvedType.STRING, ResolvedType.STRING, ResolvedType.STRING));

                case "reverse": return(BuildPrimitiveMethod(ResolvedType.STRING));

                case "rtrim": return(BuildPrimitiveMethod(ResolvedType.STRING));

                case "split": return(BuildPrimitiveMethod(ResolvedType.ListOrArrayOf(ResolvedType.STRING), ResolvedType.STRING));

                case "startsWith": return(BuildPrimitiveMethod(ResolvedType.BOOLEAN, ResolvedType.STRING));

                case "trim": return(BuildPrimitiveMethod(ResolvedType.STRING));

                case "upper": return(BuildPrimitiveMethod(ResolvedType.STRING));

                // common mistakes
                case "join":
                    throw new ParserException(this.DotToken, "Strings do not have a .join(list) method. Did you mean to do list.join(string)?");

                case "size":
                    throw new ParserException(this.DotToken, "Strings do not have a .size() method. Did you mean to use .length?");

                default:
                    throw new ParserException(this.DotToken, "Strings do not have that method.");
                }

            case ResolvedTypeCategory.LIST:
                ResolvedType itemType = rootType.ListItemType;
                switch (field)
                {
                case "length":
                    this.ResolvedType = ResolvedType.INTEGER;
                    return(this);

                case "filter":
                case "map":
                    if (this.CompilationScope.IsStaticallyTyped)
                    {
                        // TODO: for Acrylic, this needs to have a way to indicate that resolution should be attempted
                        // again once the function return type is known.
                        throw new System.NotImplementedException();
                    }
                    this.ResolvedType = ResolvedType.ANY;
                    return(this);

                case "add": return(BuildPrimitiveMethod(ResolvedType.VOID, itemType));

                case "choice": return(BuildPrimitiveMethod(ResolvedType.VOID));

                case "clear": return(BuildPrimitiveMethod(ResolvedType.VOID));

                case "clone": return(BuildPrimitiveMethod(rootType));

                case "concat": return(BuildPrimitiveMethod(rootType, rootType));

                case "contains": return(BuildPrimitiveMethod(ResolvedType.BOOLEAN, itemType));

                case "insert": return(BuildPrimitiveMethod(ResolvedType.VOID, ResolvedType.INTEGER, itemType));

                case "join": return(BuildPrimitiveMethodWithOptionalArgs(ResolvedType.STRING, 1, ResolvedType.STRING));

                case "pop": return(BuildPrimitiveMethod(itemType));

                case "remove": return(BuildPrimitiveMethod(ResolvedType.VOID, ResolvedType.INTEGER));

                case "reverse": return(BuildPrimitiveMethod(ResolvedType.VOID));

                case "shuffle": return(BuildPrimitiveMethod(ResolvedType.VOID));

                case "sort": return(BuildPrimitiveMethod(ResolvedType.VOID));

                // common mistakes
                case "count":
                case "size":
                    throw new ParserException(this.DotToken, "Lists do not have a ." + this.FieldToken.Value + "() method. Did you mean to use .length?");

                default:
                    throw new ParserException(this.DotToken, "Lists do not have that method.");
                }

            case ResolvedTypeCategory.DICTIONARY:
                ResolvedType keyType   = rootType.DictionaryKeyType;
                ResolvedType valueType = rootType.DictionaryValueType;
                switch (field)
                {
                case "length":
                    this.ResolvedType = ResolvedType.INTEGER;
                    return(this);

                case "clear": return(BuildPrimitiveMethod(ResolvedType.VOID));

                case "clone": return(BuildPrimitiveMethod(rootType));

                case "contains": return(BuildPrimitiveMethod(ResolvedType.BOOLEAN, keyType));

                case "get": return(BuildPrimitiveMethodWithOptionalArgs(valueType, 1, keyType, valueType));

                case "keys": return(BuildPrimitiveMethod(ResolvedType.ListOrArrayOf(keyType)));

                case "merge": return(BuildPrimitiveMethod(ResolvedType.VOID, rootType));

                case "remove": return(BuildPrimitiveMethod(ResolvedType.VOID, keyType));

                case "values": return(BuildPrimitiveMethod(ResolvedType.ListOrArrayOf(valueType)));

                default:
                    throw new ParserException(this.DotToken, "Dictionaries do not have that field.");
                }

            case ResolvedTypeCategory.CLASS_DEFINITION:
                throw new ParserException(this.DotToken, "Class definitions do not have that field.");

            case ResolvedTypeCategory.FUNCTION_POINTER:
                switch (field)
                {
                case "invoke":
                    return(BuildPrimitiveMethod(ResolvedType.ANY, ResolvedType.ListOrArrayOf(ResolvedType.ANY)));

                default:
                    throw new ParserException(this.DotToken, "Fucntions do not have that field.");
                }

            case ResolvedTypeCategory.INSTANCE:
                FieldDefinition fieldDef = rootType.ClassTypeOrReference.GetField(field, true);
                if (fieldDef != null)
                {
                    if (!Node.IsAccessAllowed(this, fieldDef))
                    {
                        ClassDefinition cd = fieldDef.ClassOwner;
                        throw new ParserException(FieldToken, "The field '" + cd.NameToken.Value + "." + this.FieldToken.Value + "' is not accessible from here due to its access scope.");
                    }

                    this.ResolvedType = fieldDef.ResolvedFieldType;
                    return(this);
                }
                FunctionDefinition funcDef = rootType.ClassTypeOrReference.GetMethod(field, true);
                if (funcDef != null)
                {
                    this.ResolvedType = ResolvedType.GetFunctionType(funcDef);
                    return(this);
                }
                throw new ParserException(this.DotToken, "The class '" + rootType.ClassTypeOrReference.NameToken.Value + "' does not have a field called '" + field + "'.");

            default:
                throw new ParserException(this.DotToken, "This field does not exist.");
            }
        }
Exemple #38
0
        /// <summary>
        ///     Main code generator method. This method should write corresponding TypeScript code for element (1st argument) to
        ///     WriterWrapper (3rd argument) using TypeResolver if necessary
        /// </summary>
        /// <param name="element">Element code to be generated to output</param>
        /// <param name="result">Resulting node</param>
        /// <param name="resolver">Type resolver</param>
        public override RtField GenerateNode(MemberInfo element, RtField result, TypeResolver resolver)
        {
            if (Context.CurrentBlueprint.IsIgnored(element))
            {
                return(null);
            }
            result.IsStatic = element.IsStatic();
            result.Order    = Context.CurrentBlueprint.GetOrder(element);

            var doc = Context.Documentation.GetDocumentationMember(element);

            if (doc != null)
            {
                RtJsdocNode jsdoc = new RtJsdocNode();
                if (doc.HasInheritDoc())
                {
                    jsdoc.AddTag(DocTag.Inheritdoc);
                }
                if (doc.HasSummary())
                {
                    jsdoc.Description = doc.Summary.Text;
                }
                result.Documentation = jsdoc;
            }

            var        t                = GetType(element);
            RtTypeName type             = null;
            var        propName         = new RtIdentifier(element.Name);
            bool       isNameOverridden = false;
            var        tp               = Context.CurrentBlueprint.ForMember <TsPropertyAttribute>(element);

            if (tp != null)
            {
                if (tp.StrongType != null)
                {
                    type = resolver.ResolveTypeName(tp.StrongType);
                }
                else if (!string.IsNullOrEmpty(tp.Type))
                {
                    type = new RtSimpleTypeName(tp.Type);
                }

                type = tp.TypeInferers.Infer(element, resolver) ?? type;

                if (!string.IsNullOrEmpty(tp.Name))
                {
                    propName.IdentifierName = tp.Name;
                    isNameOverridden        = true;
                }
            }

            if (!Context.SpecialCase)
            {
                propName.IsNullable = HasToBeNullable(tp, t);
            }

            if (type == null)
            {
                type = resolver.ResolveTypeName(t);
            }

            if (!isNameOverridden)
            {
                if (element is PropertyInfo)
                {
                    propName.IdentifierName =
                        Context.ConditionallyConvertPropertyNameToCamelCase(propName.IdentifierName);
                }
                propName.IdentifierName = Context.CurrentBlueprint.CamelCaseFromAttribute(element, propName.IdentifierName);
                propName.IdentifierName = Context.CurrentBlueprint.PascalCaseFromAttribute(element, propName.IdentifierName);
            }

            if (this.Context.Location.CurrentClass != null)
            {
                this.FillInitialization(element, result, resolver, t, tp);
            }
            result.Identifier     = propName;
            result.AccessModifier = Context.SpecialCase ? AccessModifier.Public : element.GetModifier();
            result.Type           = type;
            AddDecorators(result, Context.CurrentBlueprint.DecoratorsFor(element));
            return(result);
        }
Exemple #39
0
        public override void Process(PreprocessRequestArgs arguments)
        {
            Assert.ArgumentNotNull(arguments, "arguments");
            try
            {
                var url       = TypeResolver.Resolve <IObsoletor>().GetRequestUrl(arguments);
                var localPath = url.LocalPath;

                if (localPath.StartsWith("/-/script/v1", StringComparison.OrdinalIgnoreCase))
                {
                    var sourceArray = url.LocalPath.TrimStart('/').Split('/');
                    if (sourceArray.Length < 3)
                    {
                        return;
                    }
                    var length           = sourceArray.Length - 3;
                    var destinationArray = new string[length];
                    Array.Copy(sourceArray, 3, destinationArray, 0, length);
                    var scriptPath = $"/{string.Join("/", destinationArray)}";
                    var query      = url.Query.TrimStart('?');
                    query += $"{(string.IsNullOrEmpty(query) ? "?" : "&")}script={scriptPath}&apiVersion=1";
                    WebUtil.RewriteUrl(
                        new UrlString
                    {
                        Path  = "/sitecore modules/PowerShell/Services/RemoteScriptCall.ashx",
                        Query = query
                    }.ToString());
                }
                if (localPath.StartsWith("/-/script/v2", StringComparison.OrdinalIgnoreCase) ||
                    localPath.StartsWith("/-/script/media", StringComparison.OrdinalIgnoreCase) ||
                    localPath.StartsWith("/-/script/file", StringComparison.OrdinalIgnoreCase) ||
                    localPath.StartsWith("/-/script/handle", StringComparison.OrdinalIgnoreCase) ||
                    localPath.StartsWith("/-/script/script", StringComparison.OrdinalIgnoreCase)
                    )
                {
                    var sourceArray = url.LocalPath.TrimStart('/').Split('/');
                    if (sourceArray.Length < 4)
                    {
                        return;
                    }
                    var apiVersion       = sourceArray[2].Is("v2") ? "2": sourceArray[2];
                    var length           = sourceArray.Length - 4;
                    var destinationArray = new string[length];
                    var origin           = sourceArray[3].ToLowerInvariant();
                    var database         = apiVersion.Is("file") || apiVersion.Is("handle") ? string.Empty : origin;
                    Array.Copy(sourceArray, 4, destinationArray, 0, length);
                    var scriptPath = $"/{string.Join("/", destinationArray)}";
                    var query      = url.Query.TrimStart('?');
                    query += $"{(string.IsNullOrEmpty(query) ? "" : "&")}script={scriptPath}&sc_database={database}&scriptDb={origin}&apiVersion={apiVersion}";
                    WebUtil.RewriteUrl(
                        new UrlString
                    {
                        Path  = "/sitecore modules/PowerShell/Services/RemoteScriptCall.ashx",
                        Query = query
                    }.ToString());
                }
            }
            catch (Exception exception)
            {
                PowerShellLog.Error("Error during the SPE API call", exception);
            }
        }
Exemple #40
0
        static void HandleItemCreation(IEnumerable <UnityEngine.Object> objectsBeingDropped, TrackAsset targetTrack, double candidateTime, TypeResolver typeResolver, bool allowMenu)
        {
            var assetTypes = objectsBeingDropped.Select(o =>
                                                        TypeUtility.GetAssetTypesForObject(targetTrack.GetType(), o)
                                                        .Union(TypeUtility.MarkerTypesWithFieldForObject(o))).ToList();
            Action <Type> onCreateItem = assetType =>
            {
                if (typeof(PlayableAsset).IsAssignableFrom(assetType))
                {
                    TimelineHelpers.CreateClipsFromObjects(assetType, targetTrack, candidateTime,
                                                           objectsBeingDropped);
                }
                else
                {
                    TimelineHelpers.CreateMarkersFromObjects(assetType, targetTrack, candidateTime, objectsBeingDropped);
                }
            };

            var flatAssetTypes = assetTypes.SelectMany(x => x).Distinct();

            // If there is a one to one mapping between assets and timeline types, no need to go through the type resolution, not ambiguous.
            if (assetTypes.All(x => x.Count() <= 1))
            {
                foreach (var type in flatAssetTypes)
                {
                    onCreateItem(type);
                }
            }
            else
            {
                if (!allowMenu) // If we already popped a menu, and are presented with an ambiguous choice, take the first entry
                {
                    flatAssetTypes = new[] { flatAssetTypes.First() };
                }

                typeResolver(flatAssetTypes, onCreateItem, k_SelectClip);
            }
        }
Exemple #41
0
        public static DragAndDropVisualMode HandleClipPanePlayableAssetDragAndDrop(IEnumerable <IPlayableAsset> assetsBeingDropped, TrackAsset targetTrack, bool perform, TimelineAsset timeline, TrackAsset parent, PlayableDirector director, double candidateTime, TypeResolver typeResolver)
        {
            // get the list of supported track types
            var assetTypes = assetsBeingDropped.Select(x => x.GetType()).Distinct();
            IEnumerable <Type> supportedTypes = null;

            if (targetTrack == null)
            {
                supportedTypes = TypeUtility.AllTrackTypes().Where(t => TypeUtility.GetPlayableAssetsHandledByTrack(t).Intersect(assetTypes).Any()).ToList();
            }
            else
            {
                supportedTypes = Enumerable.Empty <Type>();
                var trackAssetTypes = TypeUtility.GetPlayableAssetsHandledByTrack(targetTrack.GetType());
                if (trackAssetTypes.Intersect(assetTypes).Any())
                {
                    supportedTypes = new[] { targetTrack.GetType() }
                }
                ;
            }

            if (!supportedTypes.Any())
            {
                return(DragAndDropVisualMode.Rejected);
            }

            if (perform)
            {
                Action <Type> onResolved = (t) =>
                {
                    if (targetTrack == null)
                    {
                        targetTrack = TimelineHelpers.CreateTrack(timeline, t, parent, string.Empty);
                    }

                    var clipTypes = TypeUtility.GetPlayableAssetsHandledByTrack(targetTrack.GetType());
                    foreach (var asset in assetsBeingDropped)
                    {
                        if (clipTypes.Contains(asset.GetType()))
                        {
                            TimelineHelpers.CreateClipOnTrackFromPlayableAsset(asset, targetTrack, candidateTime);
                        }
                    }
                };

                typeResolver(supportedTypes, onResolved, k_SelectTrackWithClip);
            }


            return(DragAndDropVisualMode.Copy);
        }
Exemple #42
0
 public TypeNodeBuilder(ModuleReader moduleReader, NotifyInterfaceFinder notifyInterfaceFinder, TypeResolver typeResolver)
 {
     this.moduleReader          = moduleReader;
     this.notifyInterfaceFinder = notifyInterfaceFinder;
     this.typeResolver          = typeResolver;
 }
Exemple #43
0
        internal static void ApplyChangesInEditor(ContentType contentType, SchemaEditor editor)
        {
            // Find ContentHandler
            var handlerType = TypeResolver.GetType(contentType.HandlerName, false);

            if (handlerType == null)
            {
                throw new RegistrationException(string.Concat(
                                                    SR.Exceptions.Registration.Msg_ContentHandlerNotFound, ": ", contentType.HandlerName));
            }

            // parent type
            NodeType parentNodeType = null;

            if (contentType.ParentTypeName != null)
            {
                parentNodeType = editor.NodeTypes[contentType.ParentTypeName];
                if (parentNodeType == null)
                {
                    throw new ContentRegistrationException(SR.Exceptions.Registration.Msg_UnknownParentContentType, contentType.Name);
                }
            }

            // handler type
            NodeType nodeType = editor.NodeTypes[contentType.Name];

            if (nodeType == null)
            {
                nodeType = editor.CreateNodeType(parentNodeType, contentType.Name, contentType.HandlerName);
            }
            if (nodeType.ClassName != contentType.HandlerName)
            {
                editor.ModifyNodeType(nodeType, contentType.HandlerName);
            }
            if (nodeType.Parent != parentNodeType)
            {
                editor.ModifyNodeType(nodeType, parentNodeType);
            }

            // 1: ContentHandler properties
            NodeTypeRegistration ntReg = ParseAttributes(handlerType);

            if (ntReg == null)
            {
                throw new ContentRegistrationException(
                          SR.Exceptions.Registration.Msg_DefinedHandlerIsNotAContentHandler, contentType.Name);
            }

            // 2: Field properties
            foreach (FieldSetting fieldSetting in contentType.FieldSettings)
            {
                Type[][] slots          = fieldSetting.HandlerSlots;
                int      fieldSlotCount = slots.GetLength(0);

                if (fieldSetting.Bindings.Count != fieldSlotCount)
                {
                    throw new ContentRegistrationException(String.Format(CultureInfo.InvariantCulture,
                                                                         SR.Exceptions.Registration.Msg_FieldBindingsCount_1, fieldSlotCount), contentType.Name, fieldSetting.Name);
                }
                for (int i = 0; i < fieldSetting.Bindings.Count; i++)
                {
                    string propName = fieldSetting.Bindings[i];
                    var    dataType = fieldSetting.DataTypes[i];
                    CheckDataType(propName, dataType, contentType.Name, editor);
                    PropertyInfo propInfo = handlerType.GetProperty(propName);
                    if (propInfo != null)
                    {
                        // #1: there is a property under the slot:
                        bool ok = false;
                        for (int j = 0; j < slots[i].Length; j++)
                        {
                            if (slots[i][j].IsAssignableFrom(propInfo.PropertyType))
                            {
                                PropertyTypeRegistration propReg = ntReg.PropertyTypeRegistrationByName(propName);
                                if (propInfo.DeclaringType != handlerType)
                                {
                                    if (propReg == null)
                                    {
                                        object[] attrs = propInfo.GetCustomAttributes(typeof(RepositoryPropertyAttribute), false);
                                        if (attrs.Length > 0)
                                        {
                                            propReg = new PropertyTypeRegistration(propInfo, (RepositoryPropertyAttribute)attrs[0]);
                                            ntReg.PropertyTypeRegistrations.Add(propReg);
                                        }
                                    }
                                }
                                if (propReg != null && propReg.DataType != fieldSetting.DataTypes[i])
                                {
                                    throw new ContentRegistrationException(String.Concat(
                                                                               "The data type of the field in the content type definition does not match the data type of its content handler's property. ",
                                                                               "Please modify the field type in the content type definition. ",
                                                                               "ContentTypeDefinition: '", contentType.Name,
                                                                               "', FieldName: '", fieldSetting.Name,
                                                                               "', DataType of Field's binding: '", fieldSetting.DataTypes[i],
                                                                               "', ContentHandler: '", handlerType.FullName,
                                                                               "', PropertyName: '", propReg.Name,
                                                                               "', DataType of property: '", propReg.DataType,
                                                                               "'"));
                                }

                                ok = true;
                                fieldSetting.HandlerSlotIndices[i] = j;
                                fieldSetting.PropertyIsReadOnly    = !PropertyHasPublicSetter(propInfo);
                                break;
                            }
                        }
                        if (!ok)
                        {
                            if (fieldSetting.ShortName == "Reference" || fieldSetting.DataTypes[i] == RepositoryDataType.Reference)
                            {
                                CheckReference(propInfo, slots[i], contentType, fieldSetting);
                            }
                            else
                            {
                                throw new ContentRegistrationException(SR.Exceptions.Registration.Msg_PropertyAndFieldAreNotConnectable,
                                                                       contentType.Name, fieldSetting.Name);
                            }
                        }
                    }
                    else
                    {
                        // #2: there is not a property under the slot:
                        PropertyTypeRegistration propReg = new PropertyTypeRegistration(propName, dataType);
                        ntReg.PropertyTypeRegistrations.Add(propReg);
                    }
                }
            }

            // Collect deletables. Check equals
            foreach (PropertyType propType in nodeType.PropertyTypes.ToArray())
            {
                PropertyTypeRegistration propReg = ntReg.PropertyTypeRegistrationByName(propType.Name);
                if (propReg == null)
                {
                    editor.RemovePropertyTypeFromPropertySet(propType, nodeType);
                }
            }


            // Register
            foreach (PropertyTypeRegistration ptReg in ntReg.PropertyTypeRegistrations)
            {
                PropertyType propType = nodeType.PropertyTypes[ptReg.Name];
                if (propType == null)
                {
                    propType = editor.PropertyTypes[ptReg.Name];
                    if (propType == null)
                    {
                        propType = editor.CreatePropertyType(ptReg.Name, ConvertDataType(ptReg.DataType));
                    }
                    editor.AddPropertyTypeToPropertySet(propType, nodeType);
                }
            }
        }
Exemple #44
0
        public override void OnInspectorGUI()
        {
            ShowEventMenu(
                UnityEventWatcher.GetBindableEvents(targetScript.gameObject)
                .OrderBy(evt => evt.Name)
                .ToArray(),
                updatedValue => targetScript.uiEventName = updatedValue,
                targetScript.uiEventName
                );

            Type viewPropertyType;

            ShowViewPropertyMenu(
                new GUIContent("View property", "Property on the view to bind to"),
                PropertyFinder.GetBindableProperties(targetScript.gameObject)
                .OrderBy(property => property.ReflectedType.Name)
                .ThenBy(property => property.Name)
                .ToArray(),
                updatedValue => targetScript.uiPropertyName = updatedValue,
                targetScript.uiPropertyName,
                out viewPropertyType
                );

            // Don't let the user set other options until they've set the event and view property.
            var guiPreviouslyEnabled = GUI.enabled;

            if (string.IsNullOrEmpty(targetScript.uiEventName) || string.IsNullOrEmpty(targetScript.uiPropertyName))
            {
                GUI.enabled = false;
            }

            var viewAdapterTypeNames = GetAdapterTypeNames(
                type => viewPropertyType == null ||
                TypeResolver.FindAdapterAttribute(type).OutputType == viewPropertyType
                );

            ShowAdapterMenu(
                new GUIContent("View adapter", "Adapter that converts values sent from the view-model to the view."),
                viewAdapterTypeNames,
                targetScript.viewAdapterTypeName,
                newValue =>
            {
                // Get rid of old adapter options if we changed the type of the adapter.
                if (newValue != targetScript.viewAdapterTypeName)
                {
                    Undo.RecordObject(targetScript, "Set view adapter options");
                    targetScript.viewAdapterOptions = null;
                }

                UpdateProperty(
                    updatedValue => targetScript.viewAdapterTypeName = updatedValue,
                    targetScript.viewAdapterTypeName,
                    newValue,
                    "Set view adapter"
                    );
            }
                );

            Type viewAdapterType;

            viewAdapterOptionsFade.target = ShouldShowAdapterOptions(targetScript.viewAdapterTypeName, out viewAdapterType);
            ShowAdapterOptionsMenu(
                "View adapter options",
                viewAdapterType,
                options => targetScript.viewAdapterOptions = options,
                targetScript.viewAdapterOptions,
                viewAdapterOptionsFade.faded
                );

            EditorGUILayout.Space();

            var adaptedViewPropertyType = AdaptTypeBackward(viewPropertyType, targetScript.viewAdapterTypeName);

            ShowViewModelPropertyMenu(
                new GUIContent("View-model property", "Property on the view-model to bind to."),
                TypeResolver.FindBindableProperties(targetScript),
                updatedValue => targetScript.viewModelPropertyName = updatedValue,
                targetScript.viewModelPropertyName,
                property => property.PropertyType == adaptedViewPropertyType
                );

            var viewModelAdapterTypeNames = GetAdapterTypeNames(
                type => adaptedViewPropertyType == null ||
                TypeResolver.FindAdapterAttribute(type).OutputType == adaptedViewPropertyType
                );

            ShowAdapterMenu(
                new GUIContent("View-model adapter", "Adapter that converts from the view back to the view-model"),
                viewModelAdapterTypeNames,
                targetScript.viewModelAdapterTypeName,
                newValue =>
            {
                if (newValue != targetScript.viewModelAdapterTypeName)
                {
                    Undo.RecordObject(targetScript, "Set view-model adapter options");
                    targetScript.viewModelAdapterOptions = null;
                }

                UpdateProperty(
                    updatedValue => targetScript.viewModelAdapterTypeName = updatedValue,
                    targetScript.viewModelAdapterTypeName,
                    newValue,
                    "Set view-model adapter"
                    );
            }
                );

            Type viewModelAdapterType;

            viewModelAdapterOptionsFade.target = ShouldShowAdapterOptions(targetScript.viewModelAdapterTypeName, out viewModelAdapterType);
            ShowAdapterOptionsMenu(
                "View-model adapter options",
                viewModelAdapterType,
                options => targetScript.viewModelAdapterOptions = options,
                targetScript.viewModelAdapterOptions,
                viewModelAdapterOptionsFade.faded
                );

            EditorGUILayout.Space();

            var expectionAdapterTypeNames = GetAdapterTypeNames(
                type => TypeResolver.FindAdapterAttribute(type).InputType == typeof(Exception)
                );

            var adaptedExceptionPropertyType = AdaptTypeForward(typeof(Exception), targetScript.exceptionAdapterTypeName);

            ShowViewModelPropertyMenu(
                new GUIContent("Exception property", "Property on the view-model to bind the exception to."),
                TypeResolver.FindBindableProperties(targetScript),
                updatedValue => targetScript.exceptionPropertyName = updatedValue,
                targetScript.exceptionPropertyName,
                property => property.PropertyType == adaptedExceptionPropertyType
                );

            ShowAdapterMenu(
                new GUIContent("Exception adapter", "Adapter that handles exceptions thrown by the view-model adapter"),
                expectionAdapterTypeNames,
                targetScript.exceptionAdapterTypeName,
                newValue =>
            {
                if (newValue != targetScript.exceptionAdapterTypeName)
                {
                    Undo.RecordObject(targetScript, "Set exception adapter options");
                    targetScript.exceptionAdapterOptions = null;
                }

                UpdateProperty(
                    updatedValue => targetScript.exceptionAdapterTypeName = updatedValue,
                    targetScript.exceptionAdapterTypeName,
                    newValue,
                    "Set exception adapter"
                    );
            }
                );

            Type exceptionAdapterType;

            exceptionAdapterOptionsFade.target = ShouldShowAdapterOptions(targetScript.exceptionAdapterTypeName, out exceptionAdapterType);
            ShowAdapterOptionsMenu(
                "Exception adapter options",
                exceptionAdapterType,
                options => targetScript.exceptionAdapterOptions = options,
                targetScript.exceptionAdapterOptions,
                exceptionAdapterOptionsFade.faded
                );

            GUI.enabled = guiPreviouslyEnabled;
        }
 private Type GetLifetimeType()
 {
     return(TypeResolver.ResolveTypeWithDefault(this.TypeName,
                                                typeof(TransientLifetimeManager)));
 }
        private void ValidateBeforeProceeding(IInvocation invocation)
        {
            //le invocation vas être destiné (target) a un IBaseValidatedAppService, car dans le ValidationRegistrar dans la méthode Kernel_ComponentRegistered
            //seulement les IBaseRestApplicationService sont handle par l'Interceptor.
            IBaseValidatedAppService appService = invocation.InvocationTarget as IBaseValidatedAppService;

            string assemblyName = invocation.InvocationTarget.GetType().BaseType.Assembly.ManifestModule.Name.Replace(".dll", ".");

            string validatorName = "I" + appService.GetType().BaseType.Name + "Validator";

            TypeResolver typeResolver = _iocResolver.Resolve <TypeResolver>();

            Type validatorInterfaceType = typeResolver[assemblyName + validatorName];

            if (validatorInterfaceType is null)
            {
                return;
            }

            IBaseValidator baseValidator = _iocResolver.Resolve(validatorInterfaceType) as IBaseValidator;

            Type validatorType = baseValidator.GetType();

            //IocManager.Instance.IocContainer.Resolve("");
            //on vas essayer d'aller chercher par réflection les méthode de validation
            //on vas devoir avoir un standard que les méthode dans les Validator qui hérite de IBaseValidation
            //doivent avoir le même nom que la méthode du app service qu'elle valide plus le terme Validation
            string methodName = invocation.MethodInvocationTarget.Name + "Validation";

            MethodInfo method = validatorType.GetMethod(methodName);

            if (method != null)
            {
                //on invoke la méthode du validator
                //on doit faire le try catch et le re-throw ici sinon on perdait le type de l'exception
                try
                {
                    if (InternalAsyncHelper.IsAsyncMethod(method))
                    {
                        var returnValue = method.Invoke(baseValidator, invocation.Arguments);
                        ////Wait task execution and modify return value
                        if (method.ReturnType == typeof(Task))
                        {
                            returnValue = InternalAsyncHelper.AwaitTaskWithFinally(
                                (Task)returnValue,
                                ex =>
                            {
                                invocation.Proceed();
                            });
                        }
                        else //Task<TResult>
                        {
                            returnValue = InternalAsyncHelper.CallAwaitTaskWithFinallyAndGetResult(
                                method.ReturnType.GenericTypeArguments[0],
                                returnValue,
                                ex =>
                            {
                                invocation.Proceed();
                            });
                        }
                    }
                    else
                    {
                        invocation.Proceed();
                    }
                }
                catch (Exception ex)
                {
                    throw ex.InnerException;
                }
            }
            else
            {
            }
        }
Exemple #47
0
        public void ProcessRequest(HttpContext context)
        {
            var request           = context.Request;
            var requestParameters = request.Params;

            var apiVersion        = requestParameters.Get("apiVersion");
            var serviceMappingKey = request.HttpMethod + "/" + apiVersion;
            var serviceName       = ApiVersionToServiceMapping.ContainsKey(serviceMappingKey)
                ? ApiVersionToServiceMapping[serviceMappingKey]
                : string.Empty;

            PowerShellLog.Info($"A request to the {serviceName} service was made from IP {GetIp(request)}");
            PowerShellLog.Debug($"'{request.Url}'");

            // verify that the service is enabled
            if (!CheckServiceEnabled(context, serviceName))
            {
                return;
            }

            var authenticationManager = TypeResolver.ResolveFromCache <IAuthenticationManager>();
            var username   = requestParameters.Get("user");
            var password   = requestParameters.Get("password");
            var authHeader = request.Headers["Authorization"];

            if (string.IsNullOrEmpty(username) && string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(authHeader))
            {
                if (authHeader.StartsWith("Basic"))
                {
                    var encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
                    var encoding         = Encoding.GetEncoding("iso-8859-1");
                    var usernamePassword = encoding.GetString(System.Convert.FromBase64String(encodedUsernamePassword));

                    var separatorIndex = usernamePassword.IndexOf(':');

                    username = usernamePassword.Substring(0, separatorIndex);
                    password = usernamePassword.Substring(separatorIndex + 1);
                }

                if (authHeader.StartsWith("Bearer"))
                {
                    var token = authHeader.Substring("Bearer ".Length).Trim();
                    try
                    {
                        if (ServiceAuthenticationManager.AuthenticationProvider.Validate(token, request.Url.GetLeftPart(UriPartial.Authority), out username))
                        {
                            authenticationManager.SwitchToUser(username, true);
                        }
                        else
                        {
                            RejectAuthenticationMethod(context, serviceName);
                            return;
                        }
                    }
                    catch (SecurityException ex)
                    {
                        RejectAuthenticationMethod(context, serviceName, ex);
                        return;
                    }
                }
            }

            var authUserName = string.IsNullOrEmpty(username) ? authenticationManager.CurrentUsername : username;

            if (string.IsNullOrEmpty(authUserName))
            {
                RejectAuthenticationMethod(context, serviceName);
                return;
            }

            var identity = new AccountIdentity(authUserName);

            if (!string.IsNullOrEmpty(password))
            {
                try
                {
                    if (authenticationManager.ValidateUser(identity.Name, password))
                    {
                        authenticationManager.SwitchToUser(identity.Name, true);
                    }
                    else
                    {
                        RejectAuthenticationMethod(context, serviceName);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    RejectAuthenticationMethod(context, serviceName, ex);
                    return;
                }
            }

            // verify that the user is authorized to access the end point
            if (!CheckIsUserAuthorized(context, identity.Name, serviceName))
            {
                return;
            }

            var isAuthenticated = authenticationManager.IsAuthenticated;

            if (identity.Name != authenticationManager.CurrentUsername && !CheckServiceAuthentication(context, serviceName, isAuthenticated))
            {
                return;
            }

            var itemParam         = requestParameters.Get("script");
            var pathParam         = requestParameters.Get("path");
            var originParam       = requestParameters.Get("scriptDb");
            var sessionId         = requestParameters.Get("sessionId");
            var persistentSession = requestParameters.Get("persistentSession").Is("true");
            var rawOutput         = requestParameters.Get("rawOutput").Is("true");
            var isUpload          = request.HttpMethod.Is("POST") && request.InputStream.Length > 0;
            var unpackZip         = requestParameters.Get("skipunpack").IsNot("true");
            var skipExisting      = requestParameters.Get("skipexisting").Is("true");
            var scDb = requestParameters.Get("sc_database");

            var useContextDatabase = apiVersion.Is("file") || apiVersion.Is("handle") || !isAuthenticated ||
                                     string.IsNullOrEmpty(originParam) || originParam.Is("current");

            // in some cases we need to set the database as it's still set to web after authentication
            if (!scDb.IsNullOrEmpty())
            {
                Context.Database = Database.GetDatabase(scDb);
            }

            var scriptDb = useContextDatabase ? Context.Database : Database.GetDatabase(originParam);
            var dbName   = scriptDb?.Name;

            if (scriptDb == null && !apiVersion.Is("file") && !apiVersion.Is("handle"))
            {
                PowerShellLog.Error($"The '{serviceMappingKey}' service requires a database but none was found in parameters or Context.");
                return;
            }

            Item scriptItem = null;

            switch (apiVersion)
            {
            case "1":
                scriptItem = scriptDb.GetItem(itemParam) ??
                             scriptDb.GetItem(ApplicationSettings.ScriptLibraryPath + itemParam);
                break;

            case "media":
                ProcessMedia(context, isUpload, scriptDb, itemParam, unpackZip, skipExisting);
                return;

            case "file":
                ProcessFile(context, isUpload, originParam, pathParam);
                return;

            case "handle":
                ProcessHandle(context, originParam);
                return;

            case "2":
                var apiScripts = GetApiScripts(dbName);
                if (apiScripts.ContainsKey(dbName))
                {
                    var dbScripts = apiScripts[dbName];
                    if (dbScripts.ContainsKey(itemParam))
                    {
                        scriptItem = scriptDb.GetItem(dbScripts[itemParam].Id);
                    }
                }

                if (scriptItem == null)
                {
                    context.Response.StatusCode        = 404;
                    context.Response.StatusDescription = "The specified script is invalid.";
                    return;
                }
                break;

            case "script":
                ProcessScript(context, request, rawOutput, sessionId, persistentSession);
                return;

            default:
                PowerShellLog.Error($"Requested API/Version ({serviceMappingKey}) is not supported.");
                return;
            }

            ProcessScript(context, scriptItem);
        }
        public override void OnInspectorGUI()
        {
            if (CannotModifyInPlayMode())
            {
                GUI.enabled = false;
            }

            UpdatePrefabModifiedProperties();

            var defaultLabelStyle = EditorStyles.label.fontStyle;

            var viewPropertyType = typeof(bool);

            var viewAdapterTypeNames = GetAdapterTypeNames(
                type => TypeResolver.FindAdapterAttribute(type).OutputType == viewPropertyType
                );

            EditorStyles.label.fontStyle = viewAdapterPrefabModified
                ? FontStyle.Bold
                : defaultLabelStyle;

            ShowAdapterMenu(
                new GUIContent(
                    "View adapter",
                    "Adapter that converts values sent from the view-model to the view."
                    ),
                viewAdapterTypeNames,
                targetScript.ViewAdapterTypeName,
                newValue =>
            {
                // Get rid of old adapter options if we changed the type of the adapter.
                if (newValue != targetScript.ViewAdapterTypeName)
                {
                    Undo.RecordObject(targetScript, "Set view adapter options");
                    targetScript.ViewAdapterOptions = null;
                }

                UpdateProperty(
                    updatedValue => targetScript.ViewAdapterTypeName = updatedValue,
                    targetScript.ViewAdapterTypeName,
                    newValue,
                    "Set view adapter"
                    );
            }
                );

            Type adapterType;

            viewAdapterOptionsFade.target = ShouldShowAdapterOptions(
                targetScript.ViewAdapterTypeName,
                out adapterType
                );

            EditorStyles.label.fontStyle = viewAdapterOptionsPrefabModified
                ? FontStyle.Bold
                : defaultLabelStyle;

            ShowAdapterOptionsMenu(
                "View adapter options",
                adapterType,
                options => targetScript.ViewAdapterOptions = options,
                targetScript.ViewAdapterOptions,
                viewAdapterOptionsFade.faded
                );

            EditorGUILayout.Space();

            EditorStyles.label.fontStyle = viewModelPropertyPrefabModified
                ? FontStyle.Bold
                : defaultLabelStyle;

            var adaptedViewPropertyType = AdaptTypeBackward(
                viewPropertyType,
                targetScript.ViewAdapterTypeName
                );

            ShowViewModelPropertyMenu(
                new GUIContent(
                    "View-model property",
                    "Property on the view-model to bind to."
                    ),
                TypeResolver.FindBindableProperties(targetScript),
                updatedValue => targetScript.ViewModelPropertyName = updatedValue,
                targetScript.ViewModelPropertyName,
                property => property.PropertyType == adaptedViewPropertyType
                );

            EditorStyles.label.fontStyle = defaultLabelStyle;
        }
Exemple #49
0
        private Control GetVariableEditor(IDictionary variable)
        {
            var value  = variable["Value"];
            var name   = (string)variable["Name"];
            var editor = variable["Editor"] as string;
            var type   = value.GetType();

            if (type == typeof(DateTime) ||
                (!string.IsNullOrEmpty(editor) &&
                 (editor.IndexOf("date", StringComparison.OrdinalIgnoreCase) > -1 ||
                  editor.IndexOf("time", StringComparison.OrdinalIgnoreCase) > -1)))
            {
                var dateTimePicker = new DateTimePicker
                {
                    ID       = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_"),
                    ShowTime = (variable["ShowTime"] != null && (bool)variable["ShowTime"]) ||
                               (!string.IsNullOrEmpty(editor) &&
                                editor.IndexOf("time", StringComparison.OrdinalIgnoreCase) > -1)
                };
                if (value is DateTime)
                {
                    var date = (DateTime)value;
                    if (date != DateTime.MinValue && date != DateTime.MaxValue)
                    {
                        dateTimePicker.Value = date.Kind != DateTimeKind.Utc
                            ? DateUtil.ToIsoDate(TypeResolver.Resolve <IDateConverter>().ToServerTime(date))
                            : DateUtil.ToIsoDate(date);
                    }
                }
                else
                {
                    dateTimePicker.Value = value as string ?? string.Empty;
                }
                return(dateTimePicker);
            }

            if (!string.IsNullOrEmpty(editor) && editor.IndexOf("rule", StringComparison.OrdinalIgnoreCase) > -1)
            {
                var editorId = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_");
                Sitecore.Context.ClientPage.ServerProperties[editorId] = value;

                var rulesBorder = new Border
                {
                    Class = "rulesWrapper",
                    ID    = editorId
                };

                var rulesEditButton = new Button
                {
                    Header = Texts.PowerShellMultiValuePrompt_GetVariableEditor_Edit_rule,
                    Class  = "scButton edit-button rules-edit-button",
                    Click  = "EditConditionClick(\\\"" + editorId + "\\\")"
                };

                rulesBorder.Controls.Add(rulesEditButton);
                var rulesRender = new Literal
                {
                    ID   = editorId + "_renderer",
                    Text = GetRuleConditionsHtml(
                        string.IsNullOrEmpty(value as string) ? "<ruleset />" : value as string)
                };
                rulesRender.Class = rulesRender.Class + " varRule";
                rulesBorder.Controls.Add(rulesRender);
                return(rulesBorder);
            }

            if (!string.IsNullOrEmpty(editor) &&
                (editor.IndexOf("treelist", StringComparison.OrdinalIgnoreCase) > -1 ||
                 (editor.IndexOf("multilist", StringComparison.OrdinalIgnoreCase) > -1) ||
                 (editor.IndexOf("droplist", StringComparison.OrdinalIgnoreCase) > -1) ||
                 (editor.IndexOf("droptree", StringComparison.OrdinalIgnoreCase) > -1)))
            {
                Item item     = null;
                var  strValue = string.Empty;
                if (value is Item)
                {
                    item     = (Item)value;
                    strValue = item.ID.ToString();
                }
                else if (value is IEnumerable <object> )
                {
                    var items = (value as IEnumerable <object>).Cast <Item>().ToList();
                    item     = items.FirstOrDefault();
                    strValue = string.Join("|", items.Select(i => i.ID.ToString()).ToArray());
                }

                var dbName = item == null ? Sitecore.Context.ContentDatabase.Name : item.Database.Name;
                if (editor.IndexOf("multilist", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    var multiList = new MultilistExtended
                    {
                        ID       = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_"),
                        Value    = strValue,
                        Database = dbName,
                        ItemID   = ItemIDs.RootID.ToString(),
                        Source   = variable["Source"] as string ?? "/sitecore",
                    };
                    multiList.SetLanguage(Sitecore.Context.Language.Name);

                    multiList.Class += "  treePicker";
                    return(multiList);
                }

                if (editor.IndexOf("droplist", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    if (Sitecore.Context.ContentDatabase?.Name != dbName)
                    {
                        // this control will crash if if content database is different than the items fed to it.
                        return(new Literal
                        {
                            Text = "<span style='color: red'>" +
                                   Translate.Text(
                                Texts
                                .PowerShellMultiValuePrompt_GetVariableEditor_DropList_control_cannot_render_items_from_the_database___0___because_it_its_not_the_same_as___1___which_is_the_current_content_database__,
                                dbName, Sitecore.Context.ContentDatabase?.Name) + "</span>",
                            Class = "varHint"
                        });
                    }
                    var lookup = new LookupEx
                    {
                        ID           = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_"),
                        Database     = dbName,
                        ItemID       = item?.ID.ToString() ?? ItemIDs.RootID.ToString(),
                        Source       = variable["Source"] as string ?? "/sitecore",
                        ItemLanguage = Sitecore.Context.Language.Name,
                        Value        = item?.ID.ToString() ?? ItemIDs.RootID.ToString()
                    };
                    lookup.Class += " textEdit";
                    return(lookup);
                }

                if (editor.IndexOf("droptree", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    var tree = new Tree
                    {
                        ID           = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_"),
                        Database     = dbName,
                        ItemID       = item?.ID.ToString() ?? ItemIDs.Null.ToString(),
                        Source       = variable["Source"] as string ?? "",
                        ItemLanguage = Sitecore.Context.Language.Name,
                        Value        = item?.ID.ToString() ?? ""
                    };
                    tree.Class += " textEdit";
                    return(tree);
                }
                var treeList = new TreeList
                {
                    ID    = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_"),
                    Value = strValue,
                    AllowMultipleSelection = true,
                    DatabaseName           = dbName,
                    Database         = dbName,
                    Source           = variable["Source"] as string ?? "/sitecore",
                    DisplayFieldName = variable["DisplayFieldName"] as string ?? "__DisplayName"
                };
                treeList.Class += " treePicker";
                return(treeList);
            }
            if (type == typeof(Item) ||
                (!string.IsNullOrEmpty(editor) && (editor.IndexOf("item", StringComparison.OrdinalIgnoreCase) > -1)))
            {
                var item       = value as Item;
                var source     = variable["Source"] as string;
                var root       = variable["Root"] as string;
                var sourceRoot = string.IsNullOrEmpty(source)
                    ? "/sitecore"
                    : StringUtil.ExtractParameter("DataSource", source);
                var dataContext = item != null
                    ? new DataContext
                {
                    DefaultItem  = item.Paths.Path,
                    ID           = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("dataContext"),
                    Parameters   = string.IsNullOrEmpty(source) ? "databasename=" + item.Database.Name : source,
                    DataViewName = "Master",
                    Root         = string.IsNullOrEmpty(root) ? sourceRoot : root,
                    Database     = item.Database.Name,
                    Selected     = new[] { new DataUri(item.ID, item.Language, item.Version) },
                    Folder       = item.ID.ToString(),
                    Language     = item.Language,
                    Version      = item.Version
                }
                    : new DataContext
                {
                    ID           = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("dataContext"),
                    Parameters   = string.IsNullOrEmpty(source) ? "databasename=master" : source,
                    DataViewName = "Master",
                    Root         = string.IsNullOrEmpty(root) ? sourceRoot : root
                };

                DataContextPanel.Controls.Add(dataContext);

                var treePicker = new TreePicker
                {
                    ID    = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_"),
                    Value = item != null?item.ID.ToString() : string.Empty,
                                DataContext = dataContext.ID,
                                AllowNone   =
                                    !string.IsNullOrEmpty(editor) &&
                                    (editor.IndexOf("allownone", StringComparison.OrdinalIgnoreCase) > -1)
                };
                treePicker.Class += " treePicker";
                return(treePicker);
            }

            if (type == typeof(bool) ||
                (!string.IsNullOrEmpty(editor) && (editor.IndexOf("bool", StringComparison.OrdinalIgnoreCase) > -1)))
            {
                var checkboxBorder = new Border
                {
                    Class = "checkBoxWrapper",
                    ID    = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_")
                };
                var checkBox = new Checkbox
                {
                    ID          = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_"),
                    Header      = (string)variable["Title"],
                    HeaderStyle = "display:inline-block;",
                    Checked     = (bool)value,
                    Class       = "varCheckbox"
                };
                checkboxBorder.Controls.Add(checkBox);
                return(checkboxBorder);
            }

            if (!string.IsNullOrEmpty(editor))
            {
                var showRoles = editor.IndexOf("role", StringComparison.OrdinalIgnoreCase) > -1;
                var showUsers = editor.IndexOf("user", StringComparison.OrdinalIgnoreCase) > -1;
                var multiple  = editor.IndexOf("multiple", StringComparison.OrdinalIgnoreCase) > -1;
                if (showRoles || showUsers)
                {
                    var picker = new UserPicker();
                    picker.Style.Add("float", "left");
                    picker.ID     = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_");
                    picker.Class += " scContentControl textEdit clr" + value.GetType().Name;
                    picker.Value  = value is IEnumerable <object>
                                    ?string.Join("|", ((IEnumerable <object>)value).Select(x => x.ToString()).ToArray())
                                        : value.ToString();

                    picker.ExcludeRoles = !showRoles;
                    picker.ExcludeUsers = !showUsers;
                    picker.DomainName   = variable["Domain"] as string ?? variable["DomainName"] as string;
                    picker.Multiple     = multiple;
                    picker.Click        = "UserPickerClick(" + picker.ID + ")";
                    return(picker);
                }
            }

            Sitecore.Web.UI.HtmlControls.Control edit;
            if (!string.IsNullOrEmpty(editor) && editor.IndexOf("info", StringComparison.OrdinalIgnoreCase) > -1)
            {
                return(new Literal {
                    Text = value.ToString(), Class = "varHint"
                });
            }

            if (variable["lines"] != null && ((int)variable["lines"] > 1))
            {
                edit = new Memo();
                edit.Attributes.Add("rows", variable["lines"].ToString());
                var placeholder = variable["Placeholder"];
                if (placeholder is string)
                {
                    edit.Attributes.Add("Placeholder", placeholder.ToString());
                }
            }
            else if (variable["Options"] != null)
            {
                var psOptions = variable["Options"].BaseObject();
                var options   = new OrderedDictionary();
                if (psOptions is OrderedDictionary)
                {
                    options = psOptions as OrderedDictionary;
                }
                else if (psOptions is string)
                {
                    var strOptions = ((string)variable["Options"]).Split('|');
                    var i          = 0;
                    while (i < strOptions.Length)
                    {
                        options.Add(strOptions[i++], strOptions[i++]);
                    }
                }
                else if (psOptions is Hashtable)
                {
                    var hashOptions = variable["Options"] as Hashtable;
                    foreach (var key in hashOptions.Keys)
                    {
                        options.Add(key, hashOptions[key]);
                    }
                }
                else
                {
                    throw new Exception("Checklist options format unrecognized.");
                }

                if (!string.IsNullOrEmpty(editor))
                {
                    if (editor.IndexOf("radio", StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        var radioList = new Groupbox
                        {
                            ID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_"),
                            // Header = (string) variable["Title"],
                            Class = "scRadioGroup"
                        };

                        foreach (var option in options.Keys)
                        {
                            var optionName  = option.ToString();
                            var optionValue = options[optionName].ToString();
                            var item        = new Radiobutton
                            {
                                Header  = optionName,
                                Value   = optionValue,
                                ID      = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID(radioList.ID),
                                Name    = radioList.ID,
                                Checked = optionValue == value.ToString()
                            };
                            radioList.Controls.Add(item);
                            radioList.Controls.Add(new Literal("<br/>"));
                        }

                        return(radioList);
                    }

                    if (editor.IndexOf("check", StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        var checkBorder = new Border
                        {
                            Class = "checkListWrapper",
                            ID    = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_")
                        };
                        var editorId = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_");
                        var link     =
                            new Literal(
                                @"<div class='checkListActions'>" +
                                @"<a href='#' class='scContentButton' onclick=""javascript:return scForm.postEvent(this,event,'checklist:checkall(id=" +
                                editorId + @")')"">" + Translate.Text("Select all") + "</a> &nbsp;|&nbsp; " +
                                @"<a href='#' class='scContentButton' onclick=""javascript:return scForm.postEvent(this,event,'checklist:uncheckall(id=" +
                                editorId + @")')"">" + Translate.Text("Unselect all") + "</a> &nbsp;|&nbsp;" +
                                @"<a href='#' class='scContentButton' onclick=""javascript:return scForm.postEvent(this,event,'checklist:invert(id=" +
                                editorId + @")')"">" + Translate.Text("Invert selection") + "</a>" +
                                @"</div>");
                        checkBorder.Controls.Add(link);
                        var checkList = new PSCheckList
                        {
                            ID          = editorId,
                            HeaderStyle = "margin-top:20px; display:inline-block;",
                            ItemID      = ItemIDs.RootID.ToString()
                        };
                        checkList.SetItemLanguage(Sitecore.Context.Language.Name);
                        string[] values;
                        if (value is string)
                        {
                            values = value.ToString().Split('|');
                        }
                        else if (value is IEnumerable)
                        {
                            values =
                                (value as IEnumerable).Cast <object>()
                                .Select(s => s == null ? "" : s.ToString())
                                .ToArray();
                        }
                        else
                        {
                            values = new[] { value.ToString() };
                        }
                        foreach (var item in from object option in options.Keys
                                 select option.ToString()
                                 into optionName
                                 let optionValue = options[optionName].ToString()
                                                   select new ChecklistItem
                        {
                            ID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID(checkList.ID),
                            Header = optionName,
                            Value = optionValue,
                            Checked = values.Contains(optionValue, StringComparer.OrdinalIgnoreCase)
                        })
                        {
                            checkList.Controls.Add(item);
                        }

                        checkList.TrackModified = false;
                        checkList.Disabled      = false;
                        checkBorder.Controls.Add(checkList);
                        return(checkBorder);
                    }
                }

                edit = new Combobox();
                var placeholder = variable["Placeholder"];
                if (placeholder is string)
                {
                    var option = new ListItem
                    {
                        Header   = placeholder.ToString(),
                        Value    = "",
                        Selected = true
                    };
                    edit.Controls.Add(option);
                }

                foreach (var option in options.Keys)
                {
                    var optionName  = option.ToString();
                    var optionValue = options[optionName].ToString();
                    var item        = new ListItem
                    {
                        Header = optionName,
                        Value  = optionValue
                    };
                    edit.Controls.Add(item);
                }
            }
            else
            {
                var placeholder = variable["Placeholder"];
                if (!string.IsNullOrEmpty(editor) && editor.IndexOf("pass", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    edit = new PasswordExtended();
                    if (placeholder is string)
                    {
                        ((PasswordExtended)edit).PlaceholderText = placeholder.ToString();
                    }
                }
                else
                {
                    edit = new EditExtended();
                    if (placeholder is string)
                    {
                        ((EditExtended)edit).PlaceholderText = placeholder.ToString();
                    }
                }
            }
            var tip = variable["Tooltip"] as string;

            if (!string.IsNullOrEmpty(tip))
            {
                edit.ToolTip = tip.RemoveHtmlTags();
            }
            edit.Style.Add("float", "left");
            edit.ID     = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("variable_" + name + "_");
            edit.Class += " scContentControl textEdit clr" + value.GetType().Name;
            edit.Value  = value.ToString();

            return(edit);
        }
Exemple #50
0
 internal override Expression ResolveTypes(ParserContext parser, TypeResolver typeResolver)
 {
     throw new NotImplementedException();
 }
Exemple #51
0
 // Signature types are implicitly declared by the contents for dynamically typed language (Crayon)
 // or set in the outer loop in the resolver pipeline in statically typed languages (Acrylic)
 internal override void ResolveSignatureTypes(ParserContext parser, TypeResolver typeResolver)
 {
     throw new System.NotImplementedException();
 }
Exemple #52
0
        static bool HandleTrackAndItemCreation(IEnumerable <UnityEngine.Object> objectsBeingDropped, double candidateTime, TypeResolver typeResolver, TimelineAsset timeline, TrackAsset parent, IEnumerable <Type> validTrackTypes, TrackAsset insertBefore = null)
        {
            Action <Type> onResolved = t =>
            {
                var newTrack = TimelineHelpers.CreateTrack(timeline, t, parent, string.Empty);
                if (insertBefore != null)
                {
                    if (parent != null)
                    {
                        parent.MoveLastTrackBefore(insertBefore);
                    }
                    else
                    {
                        timeline.MoveLastTrackBefore(insertBefore);
                    }
                }
                HandleItemCreation(objectsBeingDropped, newTrack, candidateTime, typeResolver, validTrackTypes.Count() == 1); // menu is popped if ambiguous clip choice and unambiguous track choice
            };

            return(typeResolver(validTrackTypes, t => onResolved(t), k_SelectTrackWithClip)); // Did it create a track
        }
 public RtTypeName ParameterInfer(ParameterInfo parameter, TypeResolver typeResolver)
 {
     return(InferNullable(parameter.ParameterType, typeResolver));
 }
Exemple #54
0
        public static DragAndDropVisualMode HandleClipPaneObjectDragAndDrop(IEnumerable <UnityObject> objectsBeingDropped, TrackAsset targetTrack, bool perform, TimelineAsset timeline, TrackAsset parent, PlayableDirector director, double candidateTime, TypeResolver typeResolver, TrackAsset insertBefore = null)
        {
            if (timeline == null)
            {
                return(DragAndDropVisualMode.Rejected);
            }

            // locked tracks always reject
            if (targetTrack != null && targetTrack.lockedInHierarchy)
            {
                return(DragAndDropVisualMode.Rejected);
            }

            // treat group tracks as having no track
            if (targetTrack is GroupTrack)
            {
                parent      = targetTrack;
                targetTrack = null;
            }

            // Special case for monoscripts, since they describe the type
            if (objectsBeingDropped.Any(o => o is MonoScript))
            {
                return(HandleClipPaneMonoScriptDragAndDrop(objectsBeingDropped.OfType <MonoScript>(), targetTrack, perform, timeline, parent, director, candidateTime));
            }

            // no unity objects, or explicit exceptions
            if (!objectsBeingDropped.Any() || objectsBeingDropped.Any(o => !ValidateObjectDrop(o)))
            {
                return(DragAndDropVisualMode.Rejected);
            }

            // reject scene references if we have no context
            if (director == null && objectsBeingDropped.Any(o => o.IsSceneObject()))
            {
                return(DragAndDropVisualMode.Rejected);
            }

            var validTrackTypes = objectsBeingDropped.SelectMany(o => TypeUtility.GetTrackTypesForObject(o)).Distinct().ToList();

            // special case for playable assets
            if (objectsBeingDropped.Any(o => TypeUtility.IsConcretePlayableAsset(o.GetType())))
            {
                var playableAssets = objectsBeingDropped.OfType <IPlayableAsset>().Where(o => TypeUtility.IsConcretePlayableAsset(o.GetType()));
                return(HandleClipPanePlayableAssetDragAndDrop(playableAssets, targetTrack, perform, timeline, parent, director, candidateTime, typeResolver));
            }

            var markerTypes = objectsBeingDropped.SelectMany(o => TypeUtility.MarkerTypesWithFieldForObject(o)).Distinct();

            // Markers support all tracks
            if (!markerTypes.Any())
            {
                // No tracks support this object
                if (!validTrackTypes.Any())
                {
                    return(DragAndDropVisualMode.Rejected);
                }

                // no tracks for this object
                if (targetTrack != null && !validTrackTypes.Contains(targetTrack.GetType()))
                {
                    return(DragAndDropVisualMode.Rejected);
                }
            }

            // there is no target track, dropping to empty space, or onto a group
            if (perform)
            {
                // choose track and then clip
                if (targetTrack == null)
                {
                    var createdTrack = HandleTrackAndItemCreation(objectsBeingDropped, candidateTime, typeResolver, timeline, parent, validTrackTypes, insertBefore);
                    if (!createdTrack)
                    {
                        timeline.CreateMarkerTrack();
                        HandleItemCreation(objectsBeingDropped, timeline.markerTrack, candidateTime, typeResolver, true); // menu is always popped if ambiguous choice
                    }
                }
                // just choose clip/marker
                else
                {
                    HandleItemCreation(objectsBeingDropped, targetTrack, candidateTime, typeResolver, true); // menu is always popped if ambiguous choice
                }
            }

            return(DragAndDropVisualMode.Copy);
        }
Exemple #55
0
 /// <summary>
 /// Applies a protocol-buffer stream to an existing instance (or null), using length-prefixed
 /// data - useful with network IO.
 /// </summary>
 /// <param name="value">The existing instance to be modified (can be null).</param>
 /// <param name="source">The binary stream to apply to the instance (cannot be null).</param>
 /// <param name="style">How to encode the length prefix.</param>
 /// <param name="resolver">Used to resolve types on a per-field basis.</param>
 /// <returns>The updated instance; this may be different to the instance argument if
 /// either the original instance was null, or the stream defines a known sub-type of the
 /// original instance.</returns>
 public static bool TryDeserializeWithLengthPrefix(Stream source, PrefixStyle style, TypeResolver resolver, out object value)
 {
     value = RuntimeTypeModel.Default.DeserializeWithLengthPrefix(source, null, null, style, 0, resolver);
     return(value != null);
 }
Exemple #56
0
        private static void UpdateLocalReferences(Node templateRoot, Node targetRoot)
        {
            if (templateRoot == null)
            {
                throw new ArgumentNullException("templateRoot");
            }
            if (targetRoot == null)
            {
                throw new ArgumentNullException("targetRoot");
            }

            using (new SystemAccount())
            {
                IEnumerable <Content> targetContentList;

                if (SearchManager.ContentQueryIsAllowed)
                {
                    targetContentList = Content.All.DisableAutofilters().DisableLifespan().Where(c => c.InTree(targetRoot)).OrderBy(c => c.Path).ToList();
                }
                else
                {
                    var targetCts = NodeQuery.QueryNodesByPath(targetRoot.Path, true).Nodes.Select(Content.Create).ToList();
                    var first     = targetCts.FirstOrDefault();

                    // we have to add the tenplate node manually because the query above does not return the root itself
                    if (first == null || first.Id != targetRoot.Id)
                    {
                        targetCts.Insert(0, Content.Create(targetRoot));
                    }

                    targetContentList = targetCts;
                }

                // iterate through the newly created content
                foreach (var content in targetContentList)
                {
                    var needToSave = false;

                    // iterate through all writable reference fields
                    foreach (var field in content.Fields.Values.Where(f => f is ReferenceField && !f.ReadOnly && content.ContentHandler.HasProperty(f.Name)))
                    {
                        var refData  = field.GetData();
                        var refNodes = refData as IEnumerable <Node>;
                        if (refNodes == null)
                        {
                            var refNode = refData as Node;
                            if (refNode != null)
                            {
                                refNodes = new List <Node> {
                                    refNode
                                }
                            }
                            ;
                        }

                        if (refNodes == null)
                        {
                            continue;
                        }

                        var targetRefIds = new List <int>();

                        // iterate through all referenced content and choose
                        // the ones that point to the template subtree
                        foreach (var refNode in refNodes.Where(rn => rn.InTree(templateRoot)))
                        {
                            // remove the reference to the template sub element
                            content.ContentHandler.RemoveReference(field.Name, refNode);

                            // find the corresponding new content in the target tree (e.g. a local group)
                            var targetHead = NodeHead.Get(refNode.Path.Replace(templateRoot.Path, targetRoot.Path));
                            if (targetHead != null)
                            {
                                targetRefIds.Add(targetHead.Id);
                            }
                        }

                        if (targetRefIds.Count <= 0)
                        {
                            continue;
                        }

                        // add the new references to the property
                        content.ContentHandler.AddReferences(field.Name, Node.LoadNodes(targetRefIds));
                        needToSave = true;
                    }

                    if (!needToSave)
                    {
                        continue;
                    }

                    content.ContentHandler.NodeOperation = NodeOperation.TemplateCreation;
                    content.ContentHandler.DisableObserver(TypeResolver.GetType(NodeObserverNames.DOCUMENTPREVIEW, false));
                    content.ContentHandler.DisableObserver(TypeResolver.GetType(NodeObserverNames.WORKFLOWNOTIFICATION, false));
                    content.ContentHandler.DisableObserver(TypeResolver.GetType(NodeObserverNames.NOTIFICATION, false));

                    content.SaveSameVersion();
                }
            }
        }
    }
		public KnownTypeExpressionXmlConverter(TypeResolver @resolver)
		{
			this.resolver = @resolver;
		}
 internal override void ResolveSignatureTypes(ParserContext parser, TypeResolver typeResolver)
 {
     this.ResolvedArgTypes = typeResolver.ResolveTypes(this.ArgTypes);
 }
        protected override void OnInspector()
        {
            UpdatePrefabModifiedProperties();

            var defaultLabelStyle = EditorStyles.label.fontStyle;

            EditorStyles.label.fontStyle = viewPropertyPrefabModified
                ? FontStyle.Bold
                : defaultLabelStyle;

            Type viewPropertyType;

            ShowViewPropertyMenu(
                new GUIContent("View Property", "Property on the view to bind to."),
                PropertyFinder.GetBindableProperties(targetScript.gameObject)
                .OrderBy(prop => prop.ViewModelTypeName)
                .ThenBy(prop => prop.MemberName)
                .ToArray(),
                updatedValue => targetScript.ViewPropertyName = updatedValue,
                targetScript.ViewPropertyName,
                out viewPropertyType
                );

            // Don't let the user set anything else until they've chosen a view property.
            var guiPreviouslyEnabled = GUI.enabled;

            if (string.IsNullOrEmpty(targetScript.ViewPropertyName))
            {
                GUI.enabled = false;
            }

            var viewAdapterTypeNames = TypeResolver.GetAdapterIds(
                o => viewPropertyType == null || o.OutType == viewPropertyType);

            EditorStyles.label.fontStyle = viewAdapterPrefabModified
                ? FontStyle.Bold
                : defaultLabelStyle;

            ShowAdapterMenu(
                new GUIContent(
                    "View Adapter",
                    "Adapter that converts values sent from the view-model to the view."
                    ),
                viewAdapterTypeNames,
                targetScript.ViewAdapterId,
                newValue =>
            {
                // Get rid of old adapter options if we changed the type of the adapter.
                if (newValue != targetScript.ViewAdapterId)
                {
                    Undo.RecordObject(targetScript, "Set View Adapter Options");
                    targetScript.ViewAdapterOptions = null;
                }

                UpdateProperty(
                    updatedValue => targetScript.ViewAdapterId = updatedValue,
                    targetScript.ViewAdapterId,
                    newValue,
                    "Set View Adapter"
                    );
            }
                );

            Type adapterType;

            viewAdapterOptionsFade.target = ShouldShowAdapterOptions(
                targetScript.ViewAdapterId,
                out adapterType
                );

            EditorStyles.label.fontStyle = viewAdapterOptionsPrefabModified
                ? FontStyle.Bold
                : defaultLabelStyle;

            ShowAdapterOptionsMenu(
                "View Adapter Options",
                adapterType,
                options => targetScript.ViewAdapterOptions = options,
                targetScript.ViewAdapterOptions,
                viewAdapterOptionsFade.faded
                );

            EditorGUILayout.Space();

            EditorStyles.label.fontStyle = viewModelPropertyPrefabModified
                ? FontStyle.Bold
                : defaultLabelStyle;

            var adaptedViewPropertyType = AdaptTypeBackward(
                viewPropertyType,
                targetScript.ViewAdapterId
                );

            ShowViewModelPropertyMenu(
                new GUIContent(
                    "View-Model Property",
                    "Property on the view-model to bind to."
                    ),
                TypeResolver.FindBindableProperties(targetScript),
                updatedValue => targetScript.ViewModelPropertyName = updatedValue,
                targetScript.ViewModelPropertyName,
                property => property.PropertyType == adaptedViewPropertyType
                );

            GUI.enabled = guiPreviouslyEnabled;

            EditorStyles.label.fontStyle = defaultLabelStyle;
        }
Exemple #60
0
        /// <summary>
        /// Fills in initialization expression
        /// </summary>
        /// <param name="element">Class member</param>
        /// <param name="result">Resulting AST</param>
        /// <param name="resolver">Type resolver</param>
        /// <param name="memberType">Field/property type</param>
        /// <param name="attr">Attribute</param>
        protected virtual void FillInitialization(MemberInfo element, RtField result, TypeResolver resolver, Type memberType, TsPropertyAttribute attr)
        {
            bool exportConstant = true;

            if (attr != null)
            {
                exportConstant = attr.Constant;
            }
            if (element.IsStatic() && exportConstant)
            {
                if (TypeResolver.NumericTypes.Contains(memberType))
                {
                    var val = GetStaticValue(element);
                    if (val == null)
                    {
                        result.InitializationExpression = "null";
                    }
                    else if (TypeResolver.IntegerTypes.Contains(memberType))
                    {
                        result.InitializationExpression = val.ToString();
                    }
                    else
                    {
                        double dVal = (double)val;
                        result.InitializationExpression = dVal.ToString(JsNumberFormat);
                    }
                }

                if (memberType == typeof(bool))
                {
                    var val = GetStaticValue(element);
                    if (val == null)
                    {
                        result.InitializationExpression = "null";
                    }
                    else
                    {
                        result.InitializationExpression = (bool)val ? "true" : "false";
                    }
                }

                if (memberType == typeof(string))
                {
                    var val = GetStaticValue(element);
                    if (val == null)
                    {
                        result.InitializationExpression = "null";
                    }
                    else
                    {
                        var sv = string.Format("`{0}`", val.ToString().Replace("'", "\\'"));
                        result.InitializationExpression = sv;
                    }
                }

                if (memberType._IsEnum())
                {
                    var val = GetStaticValue(element);
                    if (val == null)
                    {
                        result.InitializationExpression = "null";
                    }
                    else
                    {
                        var bp = Context.Project.Blueprint(memberType, false);
                        if (bp != null)
                        {
                            var tn   = resolver.ResolveTypeName(memberType);
                            var name = Enum.GetName(memberType, val);
                            result.InitializationExpression = string.Format("{0}.{1}", tn, name);
                        }
                        else
                        {
                            var v = (int)val;
                            result.InitializationExpression = v.ToString();
                        }
                    }
                }
            }

            if (attr?.InitializerEvaluator != null)
            {
                var val = element.IsStatic() ? GetStaticValue(element) : null;
                result.InitializationExpression = attr.InitializerEvaluator(element, resolver, val);
            }
        }