Example #1
0
 bool DoesFragmentTypeApply(__Type objectType, __Type fragmentType, ParserRuleContext ctx)
 {
     if (fragmentType.kind == __TypeKind.OBJECT || fragmentType.kind == __TypeKind.INTERFACE)
     {
         if (objectType.kind == __TypeKind.UNION || objectType.kind == __TypeKind.INTERFACE)
         {
             return(objectType.possibleTypes.Contains(fragmentType));
         }
         else
         {
             if (fragmentType.kind != objectType.kind)
             {
                 return(false);
             }
         }
     }
     else if (fragmentType.kind == __TypeKind.UNION)
     {
         if (objectType != fragmentType)
         {
             return(false);
         }
     }
     else
     {
         Error($"Unexpected fragment type found - {fragmentType.kind}", ctx);
     }
     return(true);
 }
Example #2
0
 void OperationSelectionMatch()
 {
     foreach (GraphQLParser.OperationDefinitionContext c in GetOperations(x => true))
     {
         __Type type = null;
         if (c.operationType().GetText() == "mutation")
         {
             type = schema.__schema.mutationType;
         }
         else if (c.operationType().GetText() == "query")
         {
             type = schema.__schema.queryType;
         }
         else
         {
             Error($"Unexpected operation type - expected query/mutation received {c.operationType().GetText()}", c);
         }
         if (c.selectionSet() != null)
         {
             ValidateTypeAgainstSelectionSet(type.name, c.selectionSet());
         }
         else
         {
             Error($"unexpected state - no selection set in operation", c);
         }
     }
 }
        public void Read_QueryType()
        {
            /* Given */
            var query = new __Type
            {
                Kind = __TypeKind.OBJECT,
                Name = "Q"
            };

            var schema = new __Schema
            {
                QueryType = query,
                Types     = new List <__Type>
                {
                    query
                }
            };

            var builder = new SchemaBuilder();
            var reader  = new IntrospectionSchemaReader(
                builder,
                new IntrospectionResult
            {
                Schema = schema
            });

            /* When */
            reader.Read();

            /* Then */
            builder.TryGetType <ObjectType>("Query", out var queryType);
            Assert.NotNull(queryType);
        }
Example #4
0
        // Edit And Continue, while on pause, can add a new type to the assembly.
        public virtual __Type[] GetTypes()
        {
            // how would it help if we were to add a new type during debug?
            // the server would need to notify the client of a new type!

            // X:\jsc.svn\examples\javascript\test\TestEditAndContinueWithColor\TestEditAndContinueWithColor\Application.cs

            // would a sub application, running in an iframe
            // be able to merge with the host applicationa and switch to it?
            // only if the corelib is the same?
            // its like downloading a secondary app from the server
            // like chrome extension tab injection?

            var t = this.__Value.Types;
            var x = new __Type[t.Length];

            for (int i = 0; i < t.Length; i++)
            {
                var constructor = global::ScriptCoreLib.JavaScript.Runtime.Expando.Of(t[i]);

                var p = new __RuntimeTypeHandle
                {
                    Value = (IntPtr)(object)constructor.prototype
                };

                x[i] = new __Type
                {
                    TypeHandle = p
                };
            }

            return(x);
        }
Example #5
0
        private InputObjectType InputObject(__Type type)
        {
            if (_builder.TryGetType <InputObjectType>(type.Name, out var owner))
            {
                return(owner);
            }

            _builder.InputObject(type.Name, out owner, type.Description);

            if (type.InputFields != null && type.InputFields.Any())
            {
                _builder.Connections(connect =>
                {
                    foreach (var field in type.InputFields)
                    {
                        connect.InputField(
                            owner,
                            field.Name,
                            InputType(field.Type),
                            field.DefaultValue,
                            field.Description);
                    }
                });
            }

            return(owner);
        }
        public void Read_SubscriptionType()
        {
            /* Given */
            var subscription = new __Type
            {
                Kind = __TypeKind.OBJECT,
                Name = "S"
            };

            var schema = new __Schema
            {
                SubscriptionType = subscription,
                Types            = new List <__Type>
                {
                    subscription
                }
            };

            var builder = new SchemaBuilder();
            var reader  = new IntrospectionSchemaReader(
                builder,
                new IntrospectionResult
            {
                Schema = schema
            });

            /* When */
            reader.Read();

            /* Then */
            builder.TryGetType <ObjectType>("Subscription", out var subscriptionType);
            Assert.NotNull(subscriptionType);
        }
Example #7
0
        public static __SchemaContainer InitializeSchema(Type root, GraphQlCustomiseSchema custom)
        {
            if (cached.ContainsKey(root) == false)
            {
                var queryAttribute = root.GetProperties()
                                     .FirstOrDefault(x => x.GetCustomAttribute(typeof(GraphQlTopLevelQueryAttribute)) != null);

                if (queryAttribute == null)
                {
                    throw new Exception(
                              $"Top Level query - {root.Name} - must contain a public property with '[GRaphQlQuery]' as attribute - to indicate top level query ... if mutations are required then must include [GraphQlMutations] attribute on a different property");
                }

                var queryType = root.GetProperties().Where(x => x.GetCustomAttribute <GraphQlTopLevelQueryAttribute>() != null)
                                .Select(x => x.PropertyType).First();

                var mutationAttribute = root.GetProperties()
                                        .FirstOrDefault(x => x.GetCustomAttribute(typeof(GraphQlMutationsAttribute)) != null);

                Type mutationType = null;

                if (mutationAttribute == null)
                {
                    L.Trace($"[GraphQlMutation] attribute on {root.Name} not found ... continuing");
                }
                else
                {
                    mutationType = root.GetProperties()
                                   .Where(x => x.GetCustomAttribute <GraphQlMutationsAttribute>() != null)
                                   .Select(x => x.PropertyType).First();
                }


                var types = new Dictionary <Type, __Type>();

                var __queryType = new __Type(queryType, types, custom);

                __SchemaContainer schemaContainer = null;
                if (mutationType == null)
                {
                    schemaContainer = new __SchemaContainer(new __Schema(__queryType));
                }
                else
                {
                    var __mutationType = new __Type(mutationType, types, custom);
                    schemaContainer = new __SchemaContainer(new __Schema(__queryType, __mutationType));
                }

                var foo =
                    new[]
                {
                    typeof(__SchemaContainer)
                }.Select(x => new __Type(x, types, custom))
                .ToArray();
                schemaContainer.__schema.types = types.Values.Where(SchemaTypeFilter).ToList();
                cached[root] = schemaContainer;
            }
            return(cached[root]);
        }
Example #8
0
 static bool SchemaTypeFilter(__Type t)
 {
     if (t.kind == __TypeKind.SCALAR || t.kind == __TypeKind.LIST)
     {
         return(false);
     }
     return(true);
 }
Example #9
0
        internal static Type GetTypeFromValue(object x)
        {
            var e = new __Type
            {
                InternalTypeDescription = describeType(x)
            };

            return (Type)(object)e;
        }
Example #10
0
        public static Type GetTypeFromHandle(RuntimeTypeHandle TypeHandle)
        {
            var e = new __Type
            {
                _TypeHandle = TypeHandle
            };

            return (Type)(object)e;
        }
Example #11
0
        public Dictionary <__Type, GraphQLParser.SelectionSetContext> GetTypedSelectionSetContextFromUnionType(
            __Type unionType, GraphQLParser.SelectionSetContext ss)
        {
            Dictionary <__Type, GraphQLParser.SelectionSetContext> ret =
                new Dictionary <__Type, GraphQLParser.SelectionSetContext>();

            foreach (var s in ss.selection())
            {
                if (s.field() != null)
                {
                    Error($"Not expecting field under Union type - {unionType.name}", ss);
                }
                else if (s.fragmentSpread() != null)
                {
                    var fragmentSpreadName = s.fragmentSpread().fragmentName().GetText();

                    var fragment = GetFragments(x => x.fragmentName().GetText() == fragmentSpreadName).FirstOrDefault();
                    if (fragment == null)
                    {
                        continue;
                    }

                    var fragmentTypeName = fragment.typeCondition().typeName().GetText();

                    var fragmentType = schema.GetType(fragmentTypeName);

                    if (!DoesFragmentTypeApply(unionType, fragmentType, fragment))
                    {
                        continue;
                    }

                    if (fragmentType.kind == __TypeKind.UNION)
                    {
                        var z = GetTypedSelectionSetContextFromUnionType(fragmentType, fragment.selectionSet());
                        foreach (var c in z.Keys)
                        {
                            ret[c] = z[c];
                        }
                    }
                    else
                    {
                        ret[fragmentType] = fragment.selectionSet();
                    }
                }
                else if (s.inlineFragment() != null)
                {
                    var fragmentType = schema.GetType(s.inlineFragment().typeCondition().GetText());
                    if (fragmentType != null && !DoesFragmentTypeApply(unionType, fragmentType, s.inlineFragment()))
                    {
                        continue;
                    }
                    ret[fragmentType] = s.inlineFragment().selectionSet();
                }
            }
            return(ret);
        }
Example #12
0
 public static SchemaBuilder Add(this SchemaBuilder builder, __Type type)
 {
     return(type.Kind switch
     {
         __TypeKind.SCALAR => builder.AddScalarDefinition(type),
         __TypeKind.OBJECT => builder.AddObjectDefinition(type),
         __TypeKind.INTERFACE => builder.AddInterfaceDefinition(type),
         __TypeKind.UNION => builder.AddUnionDefinition(type),
         __TypeKind.ENUM => builder.AddEnumDefinition(type),
         __TypeKind.INPUT_OBJECT => builder.AddInputObjectDefinition(type),
         _ => throw new ArgumentOutOfRangeException(nameof(type), type.Kind, "Cannot add as schema type")
     });
Example #13
0
        public static Type GetType(string x)
        {
            // tested by?
            // X:\jsc.svn\examples\actionscript\Test\TestThreadStart\TestThreadStart\ApplicationSprite.cs


            var e = new __Type
            {
                InternalTypeDescription = describeType(getDefinitionByName(x))
            };

            return (Type)(object)e;
        }
        public void Read_UnionType()
        {
            /* Given */
            var object1 = new __Type
            {
                Kind = __TypeKind.OBJECT,
                Name = "object1"
            };
            var object2 = new __Type
            {
                Kind = __TypeKind.OBJECT,
                Name = "object2"
            };
            var introspectedType = new __Type
            {
                Kind          = __TypeKind.UNION,
                Name          = "U",
                PossibleTypes = new List <__Type>
                {
                    object1,
                    object2
                }
            };

            var schema = new __Schema
            {
                Types = new List <__Type>
                {
                    object1,
                    introspectedType,
                    object2
                }
            };

            var builder = new SchemaBuilder();
            var reader  = new IntrospectionSchemaReader(
                builder,
                new IntrospectionResult
            {
                Schema = schema
            });

            /* When */
            reader.Read();

            /* Then */
            Assert.True(builder.TryGetType <UnionType>(introspectedType.Name, out var type));
            Assert.Single(type.PossibleTypes, possibleType => possibleType.Key == "object1");
            Assert.Single(type.PossibleTypes, possibleType => possibleType.Key == "object2");
        }
Example #15
0
        void ExecuteSelectionSet(ModifiableSelectionSet ss, __Type objectType, Object objectValue,
                                 Dictionary <string, Object> variableValues)
        {
            var visitedFragments = new Dictionary <string, GraphQLParser.FragmentDefinitionContext>();
            var groupedFieldSet  = CollectFields(objectType, ss, variableValues, visitedFragments);
            var resultMap        = new OrderedDictionary <string, object>();

            foreach (string responseKey in groupedFieldSet.Keys)
            {
                var fields    = groupedFieldSet[responseKey] as List <GraphQLParser.FieldContext>;
                var fieldName = fields.First().fieldName().GetText();

                var field = objectType.GetField((x) => x.name == fieldName);

                if (field == null)
                {
                    if (fieldName == "__schema")
                    {
                        IsSchemaQuery = true;
                        field         = schema.GetType("__SchemaContainer").GetField((x) => x.name == "__schema");
                        objectValue   = schema;
                        objectType    = schema.GetType("__SchemaContainer");
                    }
                    else
                    {
                        continue;
                    }
                }

                var fieldType = field.type;


                if (objectType.kind == __TypeKind.UNION)
                {
                    if (field.parentType.dotNetType != objectValue.GetType())
                    {
                        continue;
                    }

                    ExecuteField(fields.First(), field.parentType, objectValue, fieldType, fields, variableValues,
                                 visitedFragments);
                }
                else
                {
                    ExecuteField(fields.First(), objectType, objectValue, fieldType, fields, variableValues,
                                 visitedFragments);
                }
            }
        }
        public void Read_InputObjectType_with_field()
        {
            /* Given */
            var type = new __Type
            {
                Kind        = __TypeKind.INPUT_OBJECT,
                Name        = "object",
                InputFields = new List <__InputValue>
                {
                    new __InputValue
                    {
                        Name = "field1",
                        Type = new __Type
                        {
                            Kind = __TypeKind.SCALAR,
                            Name = "Int"
                        }
                    }
                }
            };

            var schema = new __Schema
            {
                Types = new List <__Type>
                {
                    type
                }
            };

            var builder = new SchemaBuilder();
            var reader  = new IntrospectionSchemaReader(
                builder,
                new IntrospectionResult
            {
                Schema = schema
            });

            /* When */
            reader.Read();

            /* Then */
            builder.TryGetType <InputObjectType>(type.Name, out var inputObjectType);
            Assert.NotNull(inputObjectType);
            builder.Connections(connections =>
            {
                Assert.True(connections.TryGetInputField(inputObjectType, "field1", out var field1));
                Assert.Equal(ScalarType.Int, field1.Type);
            });
        }
Example #17
0
        void ExecuteField(GraphQLParser.FieldContext parentField, __Type objectType, Object objectValue,
                          __Type fieldType,
                          List <GraphQLParser.FieldContext> fields,
                          Dictionary <string, Object> variableValues,
                          Dictionary <string, GraphQLParser.FragmentDefinitionContext> visitedFragments)
        {
            var field = fields.First();

            var argumentValues = CoerceArgumentValues(objectType, field, variableValues);

            var resolvedValue =
                ResolveFieldValue(objectType, objectValue, field.fieldName().GetText(), argumentValues, field);

            CompleteValue(fieldType, field, fields, resolvedValue, variableValues);
        }
Example #18
0
        protected IType OutputType(__Type typeReference)
        {
            if (typeReference.Kind == __TypeKind.NON_NULL)
            {
                var innerType = OutputType(typeReference.OfType);
                return(innerType != null ? new NonNull(innerType) : null);
            }

            if (typeReference.Kind == __TypeKind.LIST)
            {
                var innerType = OutputType(typeReference.OfType);
                return(innerType != null ? new List(innerType) : null);
            }

            var typeName = typeReference.Name;

            // is type already known by the builder?
            if (_builder.TryGetType <INamedType>(typeName, out var knownType))
            {
                return(knownType);
            }

            // get the actual type
            var typeDefinition = _schema.Types.Single(t => t.Name == typeReference.Name);

            // type is not known so we need to build it
            switch (typeDefinition.Kind)
            {
            case __TypeKind.SCALAR:
                return(Scalar(typeDefinition));

            case __TypeKind.ENUM:
                return(Enum(typeDefinition));

            case __TypeKind.OBJECT:
                return(Object(typeDefinition));

            case __TypeKind.INTERFACE:
                return(Interface(typeDefinition));

            case __TypeKind.UNION:
                return(Union(typeDefinition));
            }

            return(null);
        }
Example #19
0
        public static void Main(string[] args)
        {
            // jsc needs to see args to make Main into main for javac..


            // see also>
            // X:\jsc.svn\examples\javascript\android\AndroidBroadcastLogger\AndroidBroadcastLogger\ApplicationWebService.cs

            System.Console.WriteLine(
                typeof(object).AssemblyQualifiedName
                );

            var t = typeof(Program);

            var f = t.GetField("field1");

            //{ FieldType = boolean, ElementType =  }
            //{ Tbool = java.lang.Boolean, ElementType =  }

            Console.WriteLine(new { f.FieldType, isBoolean = f.FieldType == typeof(bool) });

            __Type TBoolean           = typeof(java.lang.Boolean);
            __Type TBoolean_primitive = java.lang.Boolean.TYPE;
            __Type Tbool = typeof(bool);

            // { TBoolean = java.lang.Boolean, TBoolean_primitive = boolean, Tbool = java.lang.Boolean, isPrimitive = false }

            //{ FieldType = boolean }
            //{ Tbool = java.lang.Boolean }

            // http://www.thecodingforums.com/threads/difference-between-boolean-and-java-lang-boolean.585702/
            // Boolean is a boolean
            //primitive wrapped up in an Object.

            //{ FieldType = boolean, ElementType =  }
            //{ TBoolean = java.lang.Boolean, Tbool = java.lang.Boolean, isPrimitive = false }

            // Each wrapper class contains a field named TYPE which is equal to the Class for the primitive type being wrapped.
            // The value of Double.TYPE is identical to that of double.class.
            // { Tbool = java.lang.Boolean, isPrimitive = false }
            Console.WriteLine(new { TBoolean, TBoolean_primitive, Tbool, isPrimitive = Tbool.InternalTypeDescription.isPrimitive() });


            CLRProgram.CLRMain();
        }
Example #20
0
        private UnionType Union(__Type type)
        {
            if (_builder.TryGetType <UnionType>(type.Name, out var unionType))
            {
                return(unionType);
            }

            var possibleTypes = type.PossibleTypes?
                                .Select(possibleType => (ObjectType)OutputType(possibleType))
                                .ToArray();

            _builder.Union(
                type.Name,
                out unionType,
                type.Description,
                possibleTypes: possibleTypes);

            return(unionType);
        }
Example #21
0
 void CoerceDotNetValue(__Type fieldType, GraphQLParser.FieldContext field, Object value,
                        Context context = Context.Object)
 {
     try
     {
         if (value == null)
         {
             if (context == Context.List)
             {
                 output.AddScalarValue(null);
             }
             else
             {
                 output.AddScalarProperty(field.fieldName().GetText(), null);
             }
         }
         else if (fieldType.dotNetType == value.GetType() || (fieldType.dotNetType.IsEnum && value is String))
         {
             if (context == Context.List)
             {
                 output.AddScalarValue(value);
             }
             else
             {
                 output.AddScalarProperty(field.fieldName().GetText(), value);
             }
         }
         else
         {
             Error(
                 $"Error trying to coerce '{field.fieldName().GetText()}' of type '{value.GetType().Name}' to '{fieldType.kind}' with DotNetType: '{fieldType.dotNetType.Name}' ",
                 field);
         }
     }
     catch (Exception e)
     {
         Error(
             $"Error - '{e.Message}' trying to coerce '{field.fieldName().GetText()}' of type '{value.GetType().Name}' to '{fieldType.kind}' with DotNetType: '{fieldType.dotNetType.Name}' ",
             field);
     }
 }
Example #22
0
        private EnumType Enum(__Type type)
        {
            if (_builder.TryGetType <EnumType>(type.Name, out var enumType))
            {
                return(enumType);
            }

            _builder.Enum(
                type.Name,
                out enumType,
                type.Description,
                values => type.EnumValues
                .ForEach(v => values.Value(
                             v.Name,
                             v.Description,
                             Enumerable.Empty <DirectiveInstance>(),
                             v.DeprecationReason))
                );

            return(enumType);
        }
        public void Read_Enum_with_values()
        {
            /* Given */
            var introspectedType = new __Type
            {
                Kind       = __TypeKind.ENUM,
                Name       = "T",
                EnumValues = new List <__EnumValue>
                {
                    new __EnumValue
                    {
                        Name        = "VALUE1",
                        Description = "description"
                    }
                }
            };

            var schema = new __Schema
            {
                Types = new List <__Type>
                {
                    introspectedType
                }
            };

            var builder = new SchemaBuilder();
            var reader  = new IntrospectionSchemaReader(
                builder,
                new IntrospectionResult
            {
                Schema = schema
            });

            /* When */
            reader.Read();

            /* Then */
            Assert.True(builder.TryGetType <EnumType>(introspectedType.Name, out var type));
            Assert.Single(type.Values, value => value.Key == "VALUE1");
        }
Example #24
0
        public virtual __Type[] GetTypes()
        {
            var t = this.__Value.Types;
            var x = new __Type[t.Length];

            for (int i = 0; i < t.Length; i++)
            {
                var constructor = global::ScriptCoreLibAppJet.JavaScript.Runtime.Expando.Of(t[i]);

                var p = new __RuntimeTypeHandle
                {
                    Value = (IntPtr)(object)constructor.prototype
                };

                x[i] = new __Type
                {
                    TypeHandle = p
                };
            }

            return(x);
        }
Example #25
0
        Object ResolveFieldValue(__Type objectType, Object objectValue, String fieldName,
                                 Dictionary <string, Object> argumentValues, GraphQLParser.FieldContext field)
        {
            if (objectValue == null)
            {
                return(null);
            }

            if (fieldName == "__typename")
            {
                return(objectType.name);
            }

            var fieldObj = objectType.GetField(x => x.name == fieldName);

            if (fieldObj == null)
            {
                Error($"Could not resolve property type - {fieldName} in context of {objectType.name}", field);
            }

            if (fieldObj.FieldType == __Field.FieldTypeEnum.Property && argumentValues.Any())
            {
                Error($"Found a property type - {fieldName} - but are presented with set of argumentValues, indicating it should be a method type ", field);
            }

            if (fieldObj.ResolveProperty == null && fieldObj.ResolveMethod == null)
            {
                Error($"Found a property type - {fieldName} from {objectType.name} which has no method or property resolver", field);
            }

            if (fieldObj.ResolveProperty != null)
            {
                return(fieldObj.ResolveProperty(objectValue));
            }
            else
            {
                return(fieldObj.ResolveMethod(objectValue, argumentValues));
            }
        }
Example #26
0
        private void CreateTypeObject(TypeDefBase typeDef)
        {
            var type_ = new __Type()
            {
                Name = typeDef.Name, Kind = typeDef.Kind, Description = typeDef.Description, DisplayName = typeDef.Name,
            };

            typeDef.Intro_ = type_;
            _schema.Types.Add(type_);

            // Initialize lists - we do this for all types upfront to allow Build methods to access other type's lists
            //  without worrying if it is created or not. For ex, BuildObjectType finds interfaces and adds itself
            //  to PossibleTypes list of each interface it implements
            switch (type_.Kind)
            {
            case TypeKind.Object:
                type_.Fields     = new List <__Field>();
                type_.Interfaces = new List <__Type>();
                break;

            case TypeKind.Interface:
                type_.Fields        = new List <__Field>();
                type_.PossibleTypes = new List <__Type>();
                break;

            case TypeKind.InputObject:
                type_.InputFields = new List <__InputValue>();
                break;

            case TypeKind.Enum:
                type_.EnumValues = new List <__EnumValue>();
                break;

            case TypeKind.Union:
                type_.PossibleTypes = new List <__Type>();
                break;
            }
        }
Example #27
0
        private InterfaceType Interface(__Type type)
        {
            if (_builder.TryGetType <InterfaceType>(type.Name, out var owner))
            {
                return(owner);
            }

            _builder.Interface(type.Name, out owner, type.Description);
            if (type.Fields != null && type.Fields.Any())
            {
                _delayedActions.Enqueue(() =>
                {
                    _builder.Connections(connect =>
                    {
                        foreach (var field in type.Fields)
                        {
                            connect.Field(
                                owner,
                                field.Name,
                                OutputType(field.Type),
                                field.Description,
                                args: args => field.Args
                                .ForEach(a => args.Arg(
                                             a.Name,
                                             InputType(a.Type),
                                             a.DefaultValue,
                                             a.Description
                                             )
                                         )
                                );
                        }
                    });
                });
            }

            return(owner);
        }
Example #28
0
 private static bool InternalEquals(__Type x, __Type e)
 {
     return x.InternalFullName == e.InternalFullName;
 }
Example #29
0
        public static global::System.Type GetTypeFromHandle(RuntimeTypeHandle TypeHandle)
        {
            var e = new __Type
            {
                _TypeHandle = TypeHandle
            };

            return (global::System.Type)(object)e;
        }
Example #30
0
        private static bool InternalEquals(__Type e, __Type k)
        {
            // X:\jsc.svn\examples\java\hybrid\Test\JVMCLRTypeOfBool\JVMCLRTypeOfBool\Program.cs

            #region null checks
            var oleft = (object)e;
            var oright = (object)k;

            if (oleft == null)
            {
                if (oright == null)
                    return true;

                return false;
            }
            else
            {
                if (oright == null)
                    return false;
            }
            #endregion

            // c# typeof is not using primitves, so upgrade for check
            if (e.InternalTypeDescription == java.lang.Boolean.TYPE)
                e = typeof(bool);
            if (k.InternalTypeDescription == java.lang.Boolean.TYPE)
                k = typeof(bool);


            // Z:\jsc.svn\core\ScriptCoreLibJava\BCLImplementation\System\ServiceModel\ClientBase.cs
            if (e.InternalTypeDescription == java.lang.Integer.TYPE)
                e = typeof(int);
            if (k.InternalTypeDescription == java.lang.Integer.TYPE)
                k = typeof(int);


            if (e.InternalTypeDescription == java.lang.Long.TYPE)
                e = typeof(long);
            if (k.InternalTypeDescription == java.lang.Long.TYPE)
                k = typeof(long);


            if (e.InternalTypeDescription == java.lang.Double.TYPE)
                e = typeof(double);
            if (k.InternalTypeDescription == java.lang.Double.TYPE)
                k = typeof(double);



            // .net 4.0 seems to also add == operator. jsc should choose equals until then?
            if (k.InternalTypeDescription.isAssignableFrom(e.InternalTypeDescription))
                return k.FullName == e.FullName;

            return false;
        }
Example #31
0
        private static bool InternalEquals(__Type x, __Type e)
        {
            var x_ClassTokenName = ((__IntPtr)(object)(x._TypeHandle.Value)).ClassTokenName;
            var e_ClassTokenName = ((__IntPtr)(object)(e._TypeHandle.Value)).ClassTokenName;

            return x_ClassTokenName == e_ClassTokenName;
        }
        public void Read_ObjectType_with_field()
        {
            /* Given */
            var type = new __Type
            {
                Kind   = __TypeKind.OBJECT,
                Name   = "object",
                Fields = new List <__Field>
                {
                    new __Field
                    {
                        Name = "field1",
                        Type = new __Type
                        {
                            Kind = __TypeKind.SCALAR,
                            Name = "Int"
                        },
                        Args = new List <__InputValue>
                        {
                            new __InputValue
                            {
                                Name = "arg1",
                                Type = new __Type
                                {
                                    Kind = __TypeKind.SCALAR,
                                    Name = "String"
                                }
                            }
                        }
                    }
                }
            };

            var schema = new __Schema
            {
                Types = new List <__Type>
                {
                    type
                }
            };

            var builder = new SchemaBuilder();
            var reader  = new IntrospectionSchemaReader(
                builder,
                new IntrospectionResult
            {
                Schema = schema
            });

            /* When */
            reader.Read();

            /* Then */
            builder.TryGetType <ObjectType>(type.Name, out var objectType);
            Assert.NotNull(objectType);
            builder.Connections(connections =>
            {
                Assert.True(connections.TryGetField(objectType, "field1", out var field1));
                Assert.Equal(ScalarType.Int, field1.Type);
                Assert.Single(field1.Arguments, arg => arg.Key == "arg1" &&
                              ScalarType.String.Equals(arg.Value.Type));
            });
        }
Example #33
0
        Object CoerceDocumentValue(__Type argumentType, String argumentName, GraphQLParser.ValueContext val)
        {
            try
            {
                if (val is GraphQLParser.StringValueContext)
                {
                    var typedVal = Trim(((GraphQLParser.StringValueContext)val).GetText());
                    if (argumentType.kind == __TypeKind.ENUM)
                    {
                        return(Enum.Parse(argumentType.dotNetType, typedVal));
                    }
                    else if (argumentType.kind == __TypeKind.SCALAR)
                    {
                        if (TypeCheck.IsNumeric(argumentType.dotNetType))
                        {
                            Error($"Cannot convert string to numeric value", val);
                        }
                        else if (TypeCheck.IsString(argumentType.dotNetType))
                        {
                            return(typedVal);
                        }
                        else if (TypeCheck.IsDateTime(argumentType.dotNetType))
                        {
                            return(DateTime.Parse(typedVal));
                        }
                    }
                }
                else if (val is GraphQLParser.BooleanValueContext)
                {
                    var typedVal = (val.GetText() == "true") ? true : false;
                    if (argumentType.kind == __TypeKind.SCALAR)
                    {
                        if (TypeCheck.IsBoolean(argumentType.dotNetType))
                        {
                            return(typedVal);
                        }
                        else if (TypeCheck.IsNumeric(argumentType.dotNetType))
                        {
                            if (typedVal)
                            {
                                return(1);
                            }
                            return(0);
                        }
                        else if (TypeCheck.IsString(argumentType.dotNetType))
                        {
                            if (typedVal)
                            {
                                return("true");
                            }
                            return(false);
                        }
                    }
                }
                else if (val is GraphQLParser.NumberValueContext)
                {
                    var typedValue = Convert.ToDouble(val.GetText());

                    if (TypeCheck.IsNumeric(argumentType.dotNetType))
                    {
                        if (argumentType.dotNetType == typeof(int))
                        {
                            return((int)typedValue);
                        }
                        else if (argumentType.dotNetType == typeof(short))
                        {
                            return((short)typedValue);
                        }
                        else if (argumentType.dotNetType == typeof(uint))
                        {
                            return((uint)typedValue);
                        }
                        else if (argumentType.dotNetType == typeof(uint))
                        {
                            return((uint)typedValue);
                        }
                        else if (argumentType.dotNetType == typeof(float))
                        {
                            return((float)typedValue);
                        }
                        else
                        {
                            return(typedValue);
                        }
                    }
                    else if (TypeCheck.IsString(argumentType.dotNetType))
                    {
                        return(typedValue.ToString());
                    }
                    else if (TypeCheck.IsBoolean(argumentType.dotNetType))
                    {
                        if (typedValue == 0.0)
                        {
                            return(false);
                        }
                        return(true);
                    }
                }
                else if (val is GraphQLParser.ObjectValueContext)
                {
                    var jsonObj = GraphQlJson.FromJSonString(val.GetText(), argumentType.dotNetType, true);
                    return(jsonObj);
                }
                else if (val is GraphQLParser.EnumValueContext)
                {
                    return(Enum.Parse(argumentType.dotNetType, val.GetText()));
                }
                else if (val is GraphQLParser.ArrayValueContext)
                {
                    List <Object> objects = new List <object>();
                    foreach (var c in ((GraphQLParser.ArrayValueContext)val).array().value())
                    {
                        objects.Add(CoerceDocumentValue(argumentType.ofType, argumentName, c));
                    }
                    return(objects);
                }
                Error(
                    $"Encountered unexpected DotNetType when coercing value - {argumentName} - {argumentType.dotNetType.Name}",
                    val);
                return(0);
            }
            catch (Exception e)
            {
                Error(
                    $"Error - '{e.Message}' trying to coerce '{argumentName}' of type '{val.GetType().Name}' to '{argumentType.kind}' with DotNetType: '{argumentType.dotNetType.Name}' ",
                    val);
                return(0);
            }
        }
        // JVM load the .so and calls this native function
        static long Java_OVROculus360Photos_Activities_xMarshal_nativeSetAppInterface(
             JNIEnv env,
            jclass clazz,


            // ApplicationActivity : com.oculus.vrappframework.VrActivity
            jobject activity,

            jstring fromPackageNameString,
            jstring commandString,
            jstring uriString
            )
        {
            // can we do typeof() yet and have our env from there?

            // Error	3	No overload for method '__android_log_print' takes 3 arguments	X:\jsc.svn\examples\java\android\synergy\OVROculus360PhotosNDK\OVROculus360PhotosNDK\xNativeActivity.cs	39	13	OVROculus360PhotosNDK

            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20150721/ovroculus360photoshud
            ScriptCoreLibAndroidNDK.Library.ConsoleExtensions.trace("enter Java_OVROculus360Photos_Activities_xMarshal_nativeSetAppInterface");


            //Oculus360Photos_h.AtStartBackgroundPanoLoad = new object();
            xNativeAtStartBackgroundPanoLoad = xNativeAtStartBackgroundPanoLoadInvoke;

            //xNativeAtStartBackgroundPanoLoad("not yet loaded", null);


            var loctype = env.GetObjectClass(env, activity);
            var gtype = (jclass)env.NewGlobalRef(env, loctype);
            //var gtype = (jclass)env.NewGlobalRef<jclass>(env, loctype);

            var typeof_this = new __Type { arg0_env = env, arg1_type = gtype };

            //var setDefaultLocale = typeof_this.GetMethodID("setDefaultLocale", "()V");
            var setDefaultLocale = typeof_this.GetMethod("setDefaultLocale", "()V");

            //var setDefaultLocale = env.GetMethodID(env, loctype, "setDefaultLocale", "()V");

            //Type.GetMethod();



            ConsoleExtensions.tracei64("setDefaultLocale: ", (int)(object)setDefaultLocale);


            //            I/xNativeActivity(24350): [3194400] \xNativeActivity.cs:202 enter Java_OVROculus360Photos_Activities_xMarshal_nativeSetAppInterface
            //I/xNativeActivity(24350): [3194400] \xNativeActivity.cs:222 setDefaultLocale:  -2012160456

            //  public virtual void setDefaultLocale()
            //env.NewStringUTF(env, "en");


            //  error: undefined reference to '__new_jvalue'
            // env.CallVoidMethodA(env, activity, setDefaultLocale, args: default(jvalue[]));

            setDefaultLocale.Invoke(activity);

            return Oculus360Photos_h.Java_com_oculus_oculus360photossdk_MainActivity_nativeSetAppInterface(
                 env,
                //clazz,
                gtype,
                activity,
                fromPackageNameString,
                commandString,
                uriString,


                arg_AtStartBackgroundPanoLoad: xNativeAtStartBackgroundPanoLoad
            );
        }
Example #35
0
        private static bool InternalEquals(__Type x, __Type e)
        {
            // X:\jsc.svn\core\ScriptCoreLib.Windows.Forms\ScriptCoreLib.Windows.Forms\JavaScript\BCLImplementation\System\Windows\Forms\DataGridView\DataGridView.DataSource.cs

            object xx = x;
            object ee = e;

            if (xx == null)
            {
                if (ee == null)
                    return true;

                return false;
            }

            if (ee == null)
            {
                return false;
            }

            object a = x.TypeHandle.Value;
            object b = e.TypeHandle.Value;

            return a == b;
        }
Example #36
0
        public OrderedDictionary <string, List <GraphQLParser.FieldContext> > CollectFields(__Type objectType,
                                                                                            ModifiableSelectionSet ss,
                                                                                            Dictionary <string, Object> variableValues,
                                                                                            Dictionary <string, GraphQLParser.FragmentDefinitionContext> visitedFragments)
        {
            var groupedFields = new OrderedDictionary <string, List <GraphQLParser.FieldContext> >();

            foreach (var s in ss.selections)
            {
                if (s.field() != null)
                {
                    if (skipDirective(s.field()))
                    {
                        continue;
                    }

                    if (!includeDirective(s.field()))
                    {
                        continue;
                    }

                    var responseKey = s.field().fieldName().GetText();
                    if (groupedFields.ContainsKey(responseKey) == false)
                    {
                        groupedFields[responseKey] = new List <GraphQLParser.FieldContext>();
                    }
                    groupedFields[responseKey].Add(s.field());
                }
                else if (s.fragmentSpread() != null)
                {
                    var fragmentSpreadName = s.fragmentSpread().fragmentName().GetText();
                    if (visitedFragments.ContainsKey(fragmentSpreadName))
                    {
                        continue;
                    }

                    var fragment = GetFragments(x => x.fragmentName().GetText() == fragmentSpreadName).FirstOrDefault();
                    if (fragment == null)
                    {
                        continue;
                    }

                    var fragmentTypeName = fragment.typeCondition().typeName().GetText();

                    var fragmentType = schema.GetType(fragmentTypeName);

                    if (!DoesFragmentTypeApply(objectType, fragmentType, fragment))
                    {
                        continue;
                    }

                    var fragmentSelectionSet    = new ModifiableSelectionSet(fragment.selectionSet());
                    var fragmentGroupedFieldSet = CollectFields(objectType, fragmentSelectionSet, variableValues,
                                                                visitedFragments);

                    foreach (string responseKey in fragmentGroupedFieldSet.Keys)
                    {
                        if (groupedFields.ContainsKey(responseKey) == false)
                        {
                            groupedFields[responseKey] = new List <GraphQLParser.FieldContext>();
                        }
                        groupedFields[responseKey].AddRange(fragmentGroupedFieldSet[responseKey]);
                    }
                }
                else if (s.inlineFragment() != null)
                {
                    var fragmentType = schema.GetType(s.inlineFragment().typeCondition().GetText());
                    if (fragmentType != null && !DoesFragmentTypeApply(objectType, fragmentType, s.inlineFragment()))
                    {
                        continue;
                    }
                    var fragmentSelectionSet    = new ModifiableSelectionSet(s.inlineFragment().selectionSet());
                    var fragmentGroupedFieldSet = CollectFields(objectType, fragmentSelectionSet, variableValues,
                                                                visitedFragments);

                    foreach (string responseKey in fragmentGroupedFieldSet.Keys)
                    {
                        if (groupedFields.ContainsKey(responseKey) == false)
                        {
                            groupedFields[responseKey] = new List <GraphQLParser.FieldContext>();
                        }
                        groupedFields[responseKey].AddRange(fragmentGroupedFieldSet[responseKey]);
                    }
                }
            }
            return(groupedFields);
        }
Example #37
0
        public Dictionary <string, Object> CoerceArgumentValues(__Type objectType, GraphQLParser.FieldContext field,
                                                                Dictionary <string, Object> variableValues)
        {
            if (field.arguments() == null)
            {
                return(emptyArgs);
            }

            var coercedValues = new Dictionary <string, Object>();

            var argumentValues = field.arguments().argument();

            var fieldName = field.fieldName().GetText();

            var objectField = objectType.GetField((x) => x.name == fieldName);

            if (objectField == null)
            {
                Error(
                    $"Could not find field with name - {fieldName} in objecttype with name: {objectType.name} and underlying type:{objectType.dotNetType.Name}",
                    field);
            }

            foreach (var argumentDefinition in objectField.args)
            {
                var argumentName = argumentDefinition.name;
                var argumentType = argumentDefinition.type;
                var defaultValue = argumentDefinition.defaultValue;
                var value        =
                    argumentValues.Where(x => x.NAME().GetText() == argumentName)
                    .Select(x => x.valueOrVariable())
                    .FirstOrDefault();
                if (value?.variable() != null)
                {
                    var    variableName  = value.variable().NAME().GetText();
                    Object variableValue = null;
                    if (variableValues.ContainsKey(variableName))
                    {
                        variableValue = variableValues[variableName];
                    }

                    if (variableValue != null)
                    {
                        coercedValues[argumentName] = variableValue;
                    }
                    else if (defaultValue != null)
                    {
                        coercedValues[argumentName] = defaultValue;
                    }
                    else if (argumentType.kind == __TypeKind.NON_NULL)
                    {
                        Error(
                            $"Required field '{argumentName}' refered by variable '{variableName}' is not present in document",
                            field);
                    }
                    else
                    {
                        continue;
                    }
                }
                else if (value?.value() == null)
                {
                    if (defaultValue != null)
                    {
                        coercedValues[argumentName] = defaultValue;
                    }
                    else if (argumentType.kind == __TypeKind.NON_NULL)
                    {
                        Error($"Required field '{argumentName}' is not present in document", field);
                    }
                    else
                    {
                        continue;
                    }
                }
                else
                {
                    coercedValues[argumentName] = CoerceDocumentValue(argumentType, argumentName, value.value());
                }
            }
            return(coercedValues);
        }
Example #38
0
        void CompleteValue(__Type fieldType, GraphQLParser.FieldContext field, List <GraphQLParser.FieldContext> fields,
                           Object result,
                           Dictionary <string, Object> variableValues, bool assertNotNull = false, Context context = Context.Object)
        {
            if (fieldType.kind == __TypeKind.NON_NULL)
            {
                var innerType = fieldType.ofType;
                CompleteValue(innerType, field, fields, result, variableValues, true);
            }
            else if (result == null && assertNotNull)
            {
                Error($"Null or empty value was found on non null field", field);
            }
            else if (fieldType.kind == __TypeKind.LIST)
            {
                if (result != null && TypeCheck.IsEnumerableType(result.GetType()) == false)
                {
                    Error($"Did not find list type for {field.fieldName().GetText()} - found {result.GetType().Name}",
                          field);
                }
                var innerType = fieldType.ofType;

                output.PushArray(field.fieldName().GetText());
                if (result != null)
                {
                    foreach (var c in (IEnumerable)result)
                    {
                        if (field.fieldName().GetText() == "types" && IsSchemaQuery && c is __Type &&
                            ((__Type)c).name.StartsWith("__"))
                        {
                            continue;
                        }
                        CompleteValue(innerType, field, fields, c, variableValues, false, Context.List);
                    }
                }
                output.Pop();
            }
            else if (fieldType.kind == __TypeKind.SCALAR || fieldType.kind == __TypeKind.ENUM)
            {
                CoerceDotNetValue(fieldType, field, result, context);
            }
            else if (fieldType.kind == __TypeKind.OBJECT || fieldType.kind == __TypeKind.UNION ||
                     fieldType.kind == __TypeKind.INTERFACE)
            {
                if (fieldType.kind == __TypeKind.OBJECT || fieldType.kind == __TypeKind.UNION)
                {
                    var objectType      = fieldType;
                    var subSelectionSet = MergeSelectionSets(fields);

                    if (context == Context.Object)
                    {
                        if (result == null)
                        {
                            output.AddScalarProperty(field.fieldName().GetText(), null);
                        }
                        else
                        {
                            output.PushObject(field.fieldName().GetText());
                            ExecuteSelectionSet(subSelectionSet, objectType, result, variableValues);
                        }
                    }
                    else if (context == Context.List)
                    {
                        if (result != null)
                        {
                            output.PushObject();
                            ExecuteSelectionSet(subSelectionSet, objectType, result, variableValues);
                        }
                    }

                    if (result != null)
                    {
                        output.Pop();
                    }
                }
                else
                {
                    Error($"Interface and Union not yet supported", field);
                }
            }
            else
            {
                Error($"Unexpected fieldType - {fieldType.kind}", field);
            }
        }
        // JVM load the .so and calls this native function
        static void Java_x360video_Activities_xMarshal_startMovieFromUDP(JNIEnv env, jobject thiz, jobject args)
        {
            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20160103/x360videoui
            // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20160103/startmoviefromudp

            // this needs to be done so that we get to play movie from paused state.
            ConsoleExtensions.trace("enter Java_x360video_Activities_xMarshal_startMovieFromUDP");

            // list all menu items.
            // if one has the filename we need. activate it?

            //var menu = this.menuitems[0];


            //var __ptr = args.__ptr;
            //var pathName = args.pathName;

            var t = new __Type { arg0_env = env, arg1_type = (jclass)env.NewGlobalRef(env, env.GetObjectClass(env, args)) };

            //sage: 'sart/runtime/check_jni.cc:65] JNI DETECTED ERROR IN APPLICATION: JNI GetFieldID called with pending exception 
            // 'java.lang.NoSuchFieldError' thrown in void x360video.Activities.xMarshal.startMovieFromUDP(java.lang.Obje


            var field__ptr = env.GetFieldID(env, t.arg1_type, "__ptr", "J");
            var __ptr = env.GetLongField(env, args, field__ptr);

            ConsoleExtensions.tracei64("__ptr", __ptr);

            ///xNativeActivity(16201): [14349792] \xNativeActivity.cs:138 fieldpathName -2012062200
            ///xNativeActivity(16201): [14349792] \xNativeActivity.cs:139 field__ptr -2012062232

            // http://journals.ecs.soton.ac.uk/java/tutorial/native1.1/implementing/example-1.1/FieldAccess.c


            var fieldpathName = env.GetFieldID(env, t.arg1_type, "pathName", "Ljava/lang/String;");
            ConsoleExtensions.tracei64("fieldpathName", (long)(object)fieldpathName);
            var jstr = (jstring)env.GetObjectField(env, args, fieldpathName);

            var isCopy = default(bool);
            var str = env.GetStringUTFChars(env, jstr, out isCopy);
            ConsoleExtensions.traces("pathName: ", str);


            //I/xNativeActivity(19611): [13566168] \xNativeActivity.cs:118 enter Java_x360video_Activities_xMarshal_startMovieFromUDP
            //I/xNativeActivity(19611): [13566168] \xNativeActivity.cs:138 fieldpathName -2012064080
            //I/xNativeActivity(19611): [13566168] \xNativeActivity.cs:139 field__ptr -2012064112
            //I/xNativeActivity(19611): \xNativeActivity.cs:153 pathName:  /storage/emulated/0/Oculus/360Videos/360 3D 3D  VR Timelapse Hanriver TB by ___________________.mp3._TB.mp4

            // looky. 
            // we jumped from UI to NDK. and we have the string.

            // now we need to jump into C++

            // C:\Windows\system32>x:\util\android-sdk-windows\platform-tools\adb.exe logcat -s "xNativeActivity" "System.Console" "DEBUG" "PlatformActivity" "Oculus360Videos"

            // Matrix4f Oculus360Videos::Frame( const VrFrame & vrFrame ) ??
            Oculus360Videos_h.startMovieFromUDP(env, __ptr, str);



            ConsoleExtensions.trace("exit Java_x360video_Activities_xMarshal_startMovieFromUDP");
        }
Example #40
0
        public static Class ToClassToken(this Type e)
        {
            __Type c = e;

            return((Class)__Type.getDefinitionByName(c.InternalFullName));
        }
Example #41
0
 public bool Equals(__Type e)
 {
     return InternalEquals(this, e);
 }