Beispiel #1
0
        void describe_prototype_to_json()
        {
            before = () =>
            {
                objectToConvert = new Prototype();
                objectToConvert.Id = 15;
                objectToConvert.String = "hello";
                objectToConvert.Char = 'a';
                objectToConvert.DateTime = DateTime.Today;
                objectToConvert.Double = (double)100;
                objectToConvert.Guid = Guid.Empty;
                objectToConvert.Decimal = (decimal)15;
                objectToConvert.StringAsNull = null as string;
                objectToConvert.Long = (long)100;
                objectToConvert.S = "property with single character";
            };

            act = () =>
            {
                jsonString = DynamicToJson.Convert(objectToConvert);
            };

            it["converts prototype"] = () =>
            {
                var expected = @"{{ ""id"": {0}, ""string"": ""{1}"", ""char"": ""{2}"", ""dateTime"": ""{3}"", ""double"": {4}, ""guid"": ""{5}"", ""decimal"": {6}, ""stringAsNull"": {7}, ""long"": 100, ""s"": ""property with single character"" }}"
                    .With(15, "hello", 'a', DateTime.Today, (double)100, Guid.Empty, (decimal)15, "null");

                jsonString.should_be(expected);
            };
        }
Beispiel #2
0
        void gemini_constructor_that_takes_in_dto()
        {
            before = () =>
            {
                blog = new Prototype();
                blog.Title = "Working With Oak";
                blog.Body = "Oak is tight, yo.";
                blog.Author = "Amir";
            };

            context["given that the dynamic blog is wrapped with a gemini"] = () =>
            {
                before = () =>
                    gemini = new BlogEntry(blog);

                it["base properties are still accessible"] = () =>
                    (gemini.Title as string).should_be("Working With Oak");

                it["base properties are still settable"] = () =>
                {
                    gemini.Title = "Another Title";
                    (blog.Title as string).should_be("Another Title");
                };

                it["new properites provided by BlogEntry gemini are available"] = () =>
                    ((bool)gemini.IsValid()).should_be_true();

                it["properites defined in the gemini override base properties"] = () =>
                    (gemini.Body as string).should_be("");

                it["auto property is assigned as opposed to creating a new prop on the fly"] = () =>
                    (gemini.Author as string).should_be("Amir");
            };
        }
Beispiel #3
0
 public Prototype definePrototype(string name, Types parameter_types, Types return_types)
 {
     if (null == name) name = ".P"+m_code.prototypes.Count;
     Prototype proto = new Prototype(name, parameter_types, return_types);
     m_code.prototypes.Add(proto);
     return proto;
 }
Beispiel #4
0
 public MethodReference(CompositeType owner, string name, Prototype prototype)
     : this()
 {
     Owner = owner;
     Name = name;
     Prototype = prototype;
 }
Beispiel #5
0
 public MethodDefinition(ClassDefinition owner, string name, Prototype prototype)
     : this()
 {
     Owner = owner;
     Name = name;
     Prototype = prototype;
 }
Beispiel #6
0
        void describe_Any()
        {
            before = () => models = new DynamicModels(new List<Prototype>());

            context["matching single property"] = () =>
            {
                act = () => resultForAny = models.Any(new { Name = "Jane" });

                context["no items in list"] = () =>
                {
                    it["any returns false"] = () => resultForAny.should_be_false();
                };

                context["items exist in list that match"] = () =>
                {
                    before = () =>
                    {
                        dynamic prototype = new Prototype();
                        prototype.Name = "Jane";
                        models.Models.Add(prototype);
                    };

                    it["any returns true"] = () => resultForAny.should_be_true();
                };
            };

            context["item exists in list that match multiple properties"] = () =>
            {
                act = () => resultForAny = models.Any(new { Name = "Jane", Age = 15 });

                context["entry exists where all properties match"] = () =>
                {
                    before = () =>
                    {
                        dynamic prototype = new Prototype();
                        prototype.Name = "Jane";
                        prototype.Age = 15;
                        models.Models.Add(prototype);
                    };

                    it["any returns true"] = () => resultForAny.should_be_true();
                };

                context["entry exists where all properties do not match"] = () =>
                {
                    before = () =>
                    {
                        dynamic prototype = new Prototype();
                        prototype.Name = "Jane";
                        prototype.Age = 10;
                        models.Models.Add(prototype);
                    };

                    it["any returns false"] = () => resultForAny.should_be_false();
                };
            };
        }
Beispiel #7
0
        public static string Encode(Prototype prototype)
        {
            var result = new StringBuilder();
            result.Append(Encode(prototype.ReturnType,true));

            foreach (var parameter in prototype.Parameters)
                result.Append(Encode(parameter.Type, true));

            return result.ToString();
        }
Beispiel #8
0
        private dynamic BeforeAfter(dynamic before, dynamic after)
        {
            dynamic prototype = new Prototype();

            prototype.Original = before;

            prototype.New = after;

            return prototype;
        }
Beispiel #9
0
 public static Prototype SetFindType(Symbol name, Prototype type)
 {
     if (Keywordp(name))
     {
         throw new LispException("Type name cannot be a keyword");
     }
     Types[name] = type;
     type.ClassName = name;
     return type;
 }
Beispiel #10
0
        public dynamic GetChanges(dynamic property)
        {
            if (property != null) return ChangesFor(property);

            var dictionary = new Prototype() as IDictionary<string, object>;

            var keys = CurrentValues().Keys.Union(OriginalValues.Keys).Distinct();

            foreach (var key in keys) if (HasPropertyChanged(key)) dictionary.Add(key, ChangesFor(key));

            return dictionary;
        }
Beispiel #11
0
 /// <summary>
 /// Create a prototype for the given methods signature
 /// </summary>
 internal static Prototype BuildPrototype(AssemblyCompiler compiler, DexTargetPackage targetPackage, ClassDefinition declaringClass, MethodDefinition method)
 {
     var result = new Prototype();
     var module = compiler.Module;
     result.ReturnType = method.ReturnType.GetReference(XTypeUsageFlags.ReturnType, targetPackage, module);
     var paramIndex = 0;
     foreach (var p in method.Parameters)
     {
         var dparameter = new Parameter(p.GetReference(XTypeUsageFlags.ParameterType, targetPackage, module), "p" + paramIndex++);
         result.Parameters.Add(dparameter);
     }
     return result;
 }
Beispiel #12
0
        public void Reset()
        {
            _currentMeshGeometry = null;
            _currentClump = null;
            _currentPrototype = null;
            _currentPrelight = default(Color);
            _currentTransform = new Matrix4();
            _currentMaterial = new Material();

            _clumpStack.Clear();
            _materialStack.Clear();
            _transformStack.Clear();

            _model = new Model();
        }
 /// <summary>
 /// Create the current type as class definition.
 /// </summary>
 internal DelegateInstanceTypeBuilder(
     ISourceLocation sequencePoint,
     AssemblyCompiler compiler, DexTargetPackage targetPackage,
     ClassDefinition delegateClass,
     XMethodDefinition invokeMethod, Prototype invokePrototype,
     XMethodDefinition calledMethod)
 {
     this.sequencePoint = sequencePoint;
     this.compiler = compiler;
     this.targetPackage = targetPackage;
     this.delegateClass = delegateClass;
     this.invokeMethod = invokeMethod;
     this.invokePrototype = invokePrototype;
     this.calledMethod = calledMethod;
     this.multicastDelegateClass = compiler.GetDot42InternalType("System", "MulticastDelegate").GetClassReference(targetPackage);
 }
Beispiel #14
0
        public MainWindow()
        {
            InitializeComponent();

            //zum Beispiel:
            proto = new Prototype();
            proto.VideoFrameReady += new VideoFrameReadyDelegate(proto_VideoFrameReady);
            proto.AddComponent<PostureRecognition>();
            proto.AddComponent<GestureRecognition>();
            proto.AddComponent<ButtonRecognition>();

            ButtonRecognition br = proto.GetComponent<ButtonRecognition>();
            /*br.AddButton(new Triangle(0.5f, 0, 2, 0, 0.5f, 2, -0.5f, 0, 2));
            br.AddButton(new Triangle(0.5f, 1, 2, 0.5f, 1, 3, 0.5f, -1, 3));
            br.AddButton(new Triangle(0.5f, 1, 2, 0.5f, -1, 2, 0.5f, -1, 3));
            br.AddButton(new Triangle(-0.5f, 1, 2, -0.5f, 1, 3, -0.5f, -1, 3));
            br.AddButton(new Triangle(-0.5f, 1, 2, -0.5f, -1, 2, -0.5f, -1, 3));*/
            //br.AddSavedButtons("TestButtons.but");

            // Get notification if gesture was recognized by posture recognition component:
            // 1. Get posture recognition component
            PostureRecognition pr = proto.GetComponent<PostureRecognition>();
            // 2. Define which postures we want to listen for
            //some postures are hard coded...
            String[] postures = {"BothArmsUpPosture","BothHandsTogetherPosture","XPosture"};
            pr.setRecognizablePostures(postures, false);
            //...some are not
            String[] xmlPostures = { "TPosture", "LouderVolumePosture", "LowerVolumePosture" };
            pr.setRecognizablePostures(xmlPostures, true);
            // 3. Add new delegate with link to own method to the "postureRecognized" event
            // NOTE: By specifying the recognizable postures in the above step, we tell the system
            // to raise the "postureRecognized" Event only if any of the specified postures are recognized.
            pr.PostureRecognized += new PostureRecognizedDelegate(pr_postureRecognized);

            GestureRecognition gr = proto.GetComponent<GestureRecognition>();
            String[] gestures = { "ZoomOutGesture", "LeftHandSwipeRightGesture", "ZoomInGesture", "RightHandSwipeLeftGesture", "PushGesture" };
            gr.setRecognizableGestures(gestures, false);
            gr.GestureRecognized += new GestureRecognizedDelegate(gr_gestureRecognized);

            VideoImage.Width = 640;
            VideoImage.Height = 480;

            this.WindowState = WindowState.Minimized;
        }
Beispiel #15
0
 /// <summary>
 /// Add generic parameters to the prototype based on the given XMethodDefinition
 /// </summary>
 public static void AddGenericParameters(AssemblyCompiler compiler, DexTargetPackage targetPackage, XMethodDefinition method, Prototype result)
 {
     if (method.NeedsGenericInstanceTypeParameter)
     {
         var annType = compiler.GetDot42InternalType(InternalConstants.GenericTypeParameterAnnotation).GetClassReference(targetPackage);
         int numParameters = method.DeclaringType.GenericParameters.Count;
         var buildAsArray = numParameters > InternalConstants.GenericTypeParametersAsArrayThreshold;
         var parameterArray = result.GenericInstanceTypeParameters;
         AddGenericParameterArguments(result, buildAsArray, numParameters, "__$$git", annType, parameterArray);
     }
     if (method.NeedsGenericInstanceMethodParameter)
     {
         // Add GenericInstance parameter
         var annType = compiler.GetDot42InternalType(InternalConstants.GenericMethodParameterAnnotation).GetClassReference(targetPackage);
         int numParameters = method.GenericParameters.Count;
         var buildAsArray = numParameters > InternalConstants.GenericMethodParametersAsArrayThreshold;
         var parameterArray = result.GenericInstanceMethodParameters;
         AddGenericParameterArguments(result, buildAsArray, numParameters, "__$$gim", annType, parameterArray);
     }
 }
Beispiel #16
0
        /// <summary>
        /// Gets the instance type that calls the given method.
        /// Create if needed.
        /// </summary>
        public DelegateInstanceType GetOrCreateInstance(ISourceLocation sequencePoint, DexTargetPackage targetPackage, XMethodDefinition calledMethod)
        {
            DelegateInstanceType result;
            if (instances.TryGetValue(calledMethod, out result))
                return result;

            // Ensure prototype exists
            if (invokePrototype == null)
            {
                invokePrototype = PrototypeBuilder.BuildPrototype(compiler, targetPackage, interfaceClass, invokeMethod);
            }

            

            // Not found, build it.
            var builder = new DelegateInstanceTypeBuilder(sequencePoint, compiler, targetPackage, InterfaceClass, 
                                                          invokeMethod, invokePrototype, calledMethod);
            result = builder.Create();
            instances.Add(calledMethod, result);
            return result;
        }
Beispiel #17
0
        /// <summary>
        /// Create a prototype for the given methods signature
        /// </summary>
        internal static Prototype BuildPrototype(AssemblyCompiler compiler, DexTargetPackage targetPackage, ClassDefinition declaringClass, XMethodDefinition method)
        {
            var result = new Prototype();
            result.ReturnType = method.ReturnType.GetReference(targetPackage);
            if (method.IsAndroidExtension && !method.IsStatic)
            {
                // Add "this" parameter
                var dparameter = new Parameter(method.DeclaringType.GetReference(targetPackage), "this");
                result.Parameters.Add(dparameter);
            }
            
            foreach (var p in method.Parameters)
            {
                var dparameter = new Parameter(p.ParameterType.GetReference(targetPackage), p.Name);
                result.Parameters.Add(dparameter);
            }
            
            AddGenericParameters(compiler, targetPackage, method, result);

            result.Freeze();
            return result;
        }
Beispiel #18
0
 private static void AddGenericParameterArguments(Prototype result, bool buildAsArray, int numParameters, string parameterBaseName, ClassReference annType, IList<Parameter> parameterArray)
 {
     if (buildAsArray)
     {
         // Add GenericInstance parameter (to pass the generic instance array of the declaring type)
         var paramType = FrameworkReferences.ClassArray;
         var dparameter = new Parameter(paramType, parameterBaseName);
         dparameter.Annotations.Add(new Annotation(annType, AnnotationVisibility.Runtime));
         result.Parameters.Add(dparameter);
         parameterArray.Add(dparameter);
     }
     else
     {
         for (int i = 0; i < numParameters; ++i)
         {
             var dparameter = new Parameter(FrameworkReferences.Class, parameterBaseName + (i + 1));
             dparameter.Annotations.Add(new Annotation(annType, AnnotationVisibility.Runtime));
             result.Parameters.Add(dparameter);
             parameterArray.Add(dparameter);
         }
     }
 }
Beispiel #19
0
 /// <summary>
 /// Create a prototype for the given methods signature
 /// </summary>
 internal static Prototype BuildPrototype(AssemblyCompiler compiler, DexTargetPackage targetPackage, ClassDefinition declaringClass, XMethodDefinition method)
 {
     var result = new Prototype();
     result.ReturnType = method.ReturnType.GetReference(targetPackage);
     if (method.IsAndroidExtension && !method.IsStatic)
     {
         // Add "this" parameter
         var dparameter = new Parameter(method.DeclaringType.GetReference(targetPackage), "this");
         result.Parameters.Add(dparameter);
     }
     foreach (var p in method.Parameters)
     {
         var dparameter = new Parameter(p.ParameterType.GetReference(targetPackage), p.Name);
         result.Parameters.Add(dparameter);
     }
     if (method.NeedsGenericInstanceTypeParameter)
     {
         // Add GenericInstance parameter (to pass the generic instance array of the declaring type)
         var paramType = FrameworkReferences.ClassArray;
         var dparameter = new Parameter(paramType, "__$$git");
         var annType = compiler.GetDot42InternalType(InternalConstants.GenericTypeParameterAnnotation).GetClassReference(targetPackage);
         dparameter.Annotations.Add(new Annotation(annType, AnnotationVisibility.Runtime));
         result.Parameters.Add(dparameter);
         result.GenericInstanceTypeParameter = dparameter;
     }
     if (method.NeedsGenericInstanceMethodParameter)
     {
         // Add GenericInstance parameter
         var paramType = FrameworkReferences.ClassArray;
         var dparameter = new Parameter(paramType, "__$$gim");
         var annType = compiler.GetDot42InternalType(InternalConstants.GenericMethodParameterAnnotation).GetClassReference(targetPackage);
         dparameter.Annotations.Add(new Annotation(annType, AnnotationVisibility.Runtime));
         result.Parameters.Add(dparameter);
         result.GenericInstanceMethodParameter = dparameter;
     }
     return result;
 }
Beispiel #20
0
 /// <summary>
 /// Finds an open slot in Prototypes and adds the requested prototype to it. Returns
 /// an ObjectReference Value pointing to the Prototype.
 /// </summary>
 /// <param name="p"></param>
 /// <returns></returns>
 public Value AddObject(Prototype p)
 {
     Value v = new Value();
     v.Type = ValueTypes.OBJECT;
     v.ObjectReference_Value = new ObjectReference();
     int protLoc = -1;
     for (int x = 0; x < Prototypes.Count(); x++) {
         if (Prototypes[x] == null) {
             Prototypes[x] = p;
             protLoc = x;
             break;
         }
     }
     if (protLoc == -1) {
         Prototypes.Add(p);
         protLoc = Prototypes.Count() - 1;
         Memory = Memory + 2;
     }
     Objects.Add(protLoc);
     v.ObjectReference_Value.Home = this;
     v.ObjectReference_Value.Index = Objects.Count() - 1;
     Memory++;
     return v;
 }
Beispiel #21
0
 private void ReadParameters(BinaryReader reader, Prototype prototype, uint parametersOffset)
 {
     reader.PreserveCurrentPosition(parametersOffset, () =>
     {
         var typecount = reader.ReadUInt32();
         for (var j = 0; j < typecount; j++)
         {
             var parameter = new Parameter();
             var typeIndex = reader.ReadUInt16();
             parameter.Type = Dex.TypeReferences[typeIndex];
             prototype.Parameters.Add(parameter);
         }
     });
 }
Beispiel #22
0
 /// <summary>
 /// (A op B)
 /// Example: (A == 2)
 /// </summary>
 /// <param name="a"></param>
 /// <param name="b"></param>
 /// <param name="op"></param>
 public Condition(Prototype pt, BytecodeInstruction condi)
 {
     //this.a = a;
     //this.b = b;
     op = map[condi.opcode];
 }
 public override CodeBlock CreateCodeBlock(Prototype _Prototype)
 {
     return (CodeBlock)Activator.CreateInstance(_Prototype.BlockType);
 }
        public DelegateInstanceType Create()
        {
            instanceField = null; // actually at the momennt, we are not called multiple times...
            genericMethodTypeFields.Clear();
            genericInstanceTypeFields.Clear();

            // Prepare called method
            var target = targetPackage.DexFile;
            var owner  = target.GetClass(calledMethod.DeclaringType.GetClassReference(targetPackage).Fullname)
                         ?? targetPackage.GetOrCreateGeneratedCodeClass();
            var calledMethodPrototype = PrototypeBuilder.BuildPrototype(compiler, targetPackage, owner, calledMethod);
            var calledMethodRef       = calledMethod.GetReference(targetPackage);

            if (calledMethod.DeclaringType.HasDexImportAttribute())
            {
                // Delegate method is a Dex import method
            }
            else
            {
                // Delegate method is a .NET method
                var calledDexMethod = owner.Methods.Single(x => (x.Name == calledMethodRef.Name) && (x.Prototype.Equals(calledMethodRef.Prototype)));
                if (calledDexMethod.IsPrivate)
                {
                    calledDexMethod.IsPrivate   = false;
                    calledDexMethod.IsProtected = true;
                }
            }

            var @class = new ClassDefinition
            {
                Name        = CreateInstanceTypeName(owner),
                Namespace   = owner.Namespace,
                AccessFlags = AccessFlags.Public | AccessFlags.Final,
                MapFileId   = compiler.GetNextMapFileId(),
            };

            owner.AddInnerClass(@class);

            // Set super class
            @class.SuperClass = delegateClass;

            // Implement delegate interface
            //@class.Interfaces.Add(delegateInterface);

            // Get type of instance
            XTypeDefinition instanceType    = calledMethod.DeclaringType;
            TypeReference   instanceTypeRef = instanceType.GetReference(targetPackage);

            // Add ctor
            var ctor = new MethodDefinition
            {
                Owner       = @class,
                Name        = "<init>",
                AccessFlags = AccessFlags.Public | AccessFlags.Constructor,
                Prototype   = new Prototype(PrimitiveType.Void),
            };

            ctor.Prototype.Unfreeze();
            if (!calledMethod.IsStatic)
            {
                ctor.Prototype.Parameters.Add(new Parameter(instanceTypeRef, "this"));
            }

            PrototypeBuilder.AddGenericParameters(compiler, targetPackage, calledMethod, ctor.Prototype);
            ctor.Prototype.Freeze();
            @class.Methods.Add(ctor);

            // Add methodInfo field
            methodInfoField             = new FieldDefinition();
            methodInfoField.Name        = "methodInfo";
            methodInfoField.Owner       = @class;
            methodInfoField.Type        = compiler.GetDot42InternalType("System.Reflection", "MethodInfo").GetReference(targetPackage);
            methodInfoField.AccessFlags = AccessFlags.Private | AccessFlags.Final | AccessFlags.Static;
            @class.Fields.Add(methodInfoField);

            // Add instance field & getTargetImpl method
            if (!calledMethod.IsStatic)
            {
                instanceField             = new FieldDefinition();
                instanceField.Name        = "instance";
                instanceField.Owner       = @class;
                instanceField.Type        = instanceTypeRef;
                instanceField.AccessFlags = AccessFlags.Private | AccessFlags.Final;
                @class.Fields.Add(instanceField);

                AddMethod(@class, "GetTargetImpl", new Prototype(FrameworkReferences.Object), AccessFlags.Protected,
                          CreateGetTargetImplBody());
            }

            // Add generic instance type and method fields
            var gtpa = compiler.GetDot42InternalType(InternalConstants.GenericTypeParameterAnnotation).GetClassReference(targetPackage);
            var gmpa = compiler.GetDot42InternalType(InternalConstants.GenericMethodParameterAnnotation).GetClassReference(targetPackage);

            foreach (var parameter in ctor.Prototype.Parameters)
            {
                bool isGtpa = parameter.Annotations.Any(a => a.Type.Equals(gtpa));
                bool isGmpa = parameter.Annotations.Any(a => a.Type.Equals(gmpa));
                if (isGmpa || isGtpa)
                {
                    var list  = isGtpa ? genericInstanceTypeFields : genericMethodTypeFields;
                    var field = new FieldDefinition();
                    field.Name = isGtpa ? "$git" : "$gmt";
                    if (parameter.Type.Equals(FrameworkReferences.Class))
                    {
                        field.Name += list.Count + 1;
                    }
                    field.Owner       = @class;
                    field.Type        = parameter.Type;
                    field.AccessFlags = AccessFlags.Private | AccessFlags.Final;
                    @class.Fields.Add(field);
                    list.Add(field);
                }
            }

            // Create ctor body
            var ctorBody = CreateCtorBody();

            targetPackage.Record(new CompiledMethod()
            {
                DexMethod = ctor, RLBody = ctorBody
            });

            // add class static ctor
            AddMethod(@class, "<clinit>", new Prototype(PrimitiveType.Void),
                      AccessFlags.Public | AccessFlags.Constructor | AccessFlags.Static,
                      CreateCctorBody());

            // Add Invoke method
            AddMethod(@class, "Invoke", invokePrototype, AccessFlags.Public, CreateInvokeBody(calledMethodPrototype));

            // Add Equals method
            var typeOnlyEqualsSuffices = calledMethod.IsStatic && !calledMethod.NeedsGenericInstanceTypeParameter && !calledMethod.NeedsGenericInstanceMethodParameter;
            var equalsBody             = typeOnlyEqualsSuffices ? CreateEqualsCheckTypeOnlyBody(@class) : CreateEqualsBody(@class);

            var equalsPrototype = new Prototype(PrimitiveType.Boolean, new Parameter(multicastDelegateClass, "other"));

            AddMethod(@class, "EqualsWithoutInvocationList", equalsPrototype, AccessFlags.Protected, equalsBody);

            if (!typeOnlyEqualsSuffices)
            {
                var hashCodePrototype = new Prototype(PrimitiveType.Int);
                AddMethod(@class, "HashCodeWithoutInvocationList", hashCodePrototype, AccessFlags.Protected, CreateHashCodeBody(@class));
            }

            var clonePrototype = new Prototype(multicastDelegateClass, new Parameter(new ArrayType(multicastDelegateClass), "invocationList"), new Parameter(PrimitiveType.Int, "invocationListLength"));

            AddMethod(@class, "CloneWithNewInvocationList", clonePrototype, AccessFlags.Protected,
                      CreateCloneBody(ctor, @class));

            AddMethod(@class, "GetMethodInfoImpl", new Prototype(methodInfoField.Type), AccessFlags.Protected,
                      CreateGetMethodInfoImplBody());

            return(new DelegateInstanceType(calledMethod, @class, ctor));
        }
Beispiel #25
0
 public static Prototype AsPrototype(IEnumerable seq, IApply keyFunc, IApply valueFunc)
 {
     var dict = new Prototype();
     foreach (var item in ToIter(seq))
     {
         var k = Funcall(keyFunc, item);
         var v = Funcall(valueFunc, item);
         dict.SetValue(k, v);
     }
     return dict;
 }
Beispiel #26
0
        public static void DumpDictionary(object stream, Prototype prototype)
        {
            if (prototype == null)
            {
                return;
            }

            var dict = prototype.Dict;

            foreach (string key in ToIter(SeqBase.Sort(dict.Keys, CompareApply, IdentityApply)))
            {
                object val = dict[key];
                string line = string.Format("{0} => ", key);
                Write(line, Symbols.Escape, false, Symbols.Stream, stream);
                PrettyPrintLine(stream, line.Length, null, val);
            }
        }
Beispiel #27
0
 static void Report(string s, Prototype prototype, Prototype clone)
 {
     Console.WriteLine("\n" + s);
     Console.WriteLine("Prototype\t" + prototype + "\nClone\t\t" + clone);
 }
Beispiel #28
0
        private ProcessResult FillContent(XElement contentControl, IContentItem item)
        {
            var processResult = ProcessResult.NotHandledResult;

            if (!(item is RepeatContent))
            {
                return(ProcessResult.NotHandledResult);
            }

            var repeat = item as RepeatContent;

            // If there isn't a list with that name, add an error to the error string.
            if (contentControl == null)
            {
                processResult.AddError(new ContentControlNotFoundError(repeat));

                return(processResult);
            }

            // If the list doesn't contain content controls in items, then error.
            var itemsContentControl = contentControl
                                      .Descendants(W.sdt)
                                      .FirstOrDefault();

            if (itemsContentControl == null)
            {
                processResult.AddError(
                    new CustomContentItemError(repeat, "doesn't contain content controls in items"));

                return(processResult);
            }

            var fieldNames = repeat.FieldNames.ToList();

            // Create a prototype of new items to be inserted into the document.
            var prototype = new Prototype(_context, contentControl, fieldNames);

            if (!prototype.IsValid)
            {
                processResult.AddError(
                    new CustomContentItemError(repeat,
                                               String.Format("doesn't contain items with content controls {0}",
                                                             string.Join(", ", fieldNames))));

                return(processResult);
            }

            // Propagates a prototype.
            var propagationResult = PropagatePrototype(prototype, repeat.Items);

            processResult.Merge(propagationResult);

            // Remove the prototype row and add all of the newly constructed rows.
            if (!item.IsHidden)
            {
                prototype.PrototypeItems.Last().AddAfterSelf(propagationResult.Result);
            }
            prototype.PrototypeItems.Remove();

            processResult.AddItemToHandled(repeat);

            return(processResult);
        }
Beispiel #29
0
        /// <summary>
        /// Returns a dynamic PagedResult. Result properties are Items, TotalPages, and TotalRecords.
        /// </summary>
        public virtual dynamic PagedQuery(string sql, string where = "", string orderBy = "", string columns = "*", int pageSize = 20, int currentPage = 1, params object[] args)
        {
            dynamic result = new Prototype();
            var countSQL = string.Format("SELECT COUNT({0}) FROM ({1}) as result", PrimaryKeyField, sql);
            if (String.IsNullOrEmpty(orderBy))
                orderBy = PrimaryKeyField;

            if (!string.IsNullOrEmpty(where))
            {
                if (!where.Trim().StartsWith("where", StringComparison.CurrentCultureIgnoreCase))
                {
                    where = " WHERE " + where;
                }
            }
            var sql2 = string.Format("SELECT {0} FROM (SELECT ROW_NUMBER() OVER (ORDER BY {2}) AS Row, {0} FROM ({3}) as result {4}) AS Paged ", columns, pageSize, orderBy, sql, where);
            var pageStart = (currentPage - 1) * pageSize;
            sql2 += string.Format(" WHERE Row > {0} AND Row <={1}", pageStart, (pageStart + pageSize));
            countSQL += where;
            result.TotalRecords = Scalar(countSQL, args);
            result.TotalPages = result.TotalRecords / pageSize;
            if (result.TotalRecords % pageSize > 0)
                result.TotalPages += 1;
            result.Items = new DynamicModels(Query(string.Format(sql2, columns, TableName), args));
            return result;
        }
Beispiel #30
0
        /// <summary>
        /// Spawns an instance of the area from prototype and adds it to the cache.
        /// </summary>
        /// <param name="withEntities">Whether to also spawn contained rooms.</param>
        /// <param name="parent">The parent instance ID</param>
        /// <returns>The instance ID of the spawned area. Will return null if the method is called from an instanced object.</returns>
        /// <remarks>Does not fix spawned instance rooms' exits.</remarks>
        public override uint?Spawn(bool withEntities, uint parent)
        {
            if (CacheType != CacheType.Prototype)
            {
                return(null);
            }

            var parentContainer = DataAccess.Get <EntityContainer>(parent, CacheType.Instance);
            var parentWorld     = DataAccess.Get <World>(parentContainer.InstanceParent, CacheType.Instance);

            if (parentContainer == null || parentWorld == null)
            {
                throw new LocaleException("Parent cannot be null when spawning an area.");
            }

            // Create new instance area and add to parent container
            var newArea = DataAccess.Get <Area>(DataAccess.Add <Area>(new Area(), CacheType.Instance), CacheType.Instance);

            parentWorld.Areas.AddEntity(newArea.Instance, newArea, false);

            Logger.Info(nameof(Area), nameof(Spawn), "Spawning area: " + Name + ": ProtoID=" + Prototype.ToString());

            // Set remaining properties
            newArea.Prototype = Prototype;
            CopyTo(newArea);

            // Spawn contained entities
            if (withEntities)
            {
                newArea.Rooms = Rooms.SpawnAsObject <EntityContainer>(!withEntities, (uint)newArea.Instance);
                foreach (var room in Rooms.GetAllEntitiesAsObjects <Room>())
                {
                    room.Spawn(withEntities, (uint)newArea.Rooms.Instance);
                }
            }
            else
            {
                newArea.Rooms = Rooms.SpawnAsObject <EntityContainer>(!withEntities, (uint)newArea.Instance);
            }

            Logger.Info(nameof(Area), nameof(Spawn), "Finished spawning area.");

            return(newArea.Instance);
        }
Beispiel #31
0
 public void LoadUser(Prototype _prototype)
 {
     prototypeId = _prototype.PrototypeId;
 }
Beispiel #32
0
        private void ReadPrototypes(BinaryReader reader)
        {
            reader.PreserveCurrentPosition(Header.PrototypesOffset, () =>
            {
                for (var i = 0; i < Header.PrototypesSize; i++)
                {
                    //var thisOffset = reader.BaseStream.Position;
                    /*var shortyIndex =*/ reader.ReadInt32();
                    var returnTypeIndex = reader.ReadInt32();
                    var parametersOffset = reader.ReadUInt32();

                    var prototype = new Prototype {ReturnType = Dex.TypeReferences[returnTypeIndex]};

                    if (parametersOffset > 0)
                    {
                        ReadParameters(reader, prototype, parametersOffset);
                    }

                    Dex.Prototypes.Add(prototype);
                }
            });
        }
Beispiel #33
0
				public _IProcedure4_130(Prototype _enclosing, List4 parentPath, IReflectClass claxx
					, object @object, int depth)
				{
					this._enclosing = _enclosing;
					this.parentPath = parentPath;
					this.claxx = claxx;
					this.@object = @object;
					this.depth = depth;
				}
        // Fills prototype with values recursive.
        private PropagationProcessResult PropagatePrototype(Prototype prototype,
                                                            IEnumerable <ListItemContent> content)
        {
            var processResult = new PropagationProcessResult();
            var newRows       = new List <XElement>();

            foreach (var contentItem in content)
            {
                var currentLevelPrototype = prototype.CurrentLevelPrototype(contentItem.FieldNames);

                if (currentLevelPrototype == null || !currentLevelPrototype.IsValid)
                {
                    processResult.AddError(new CustomError(
                                               string.Format("Prototype for list item '{0}' not found",
                                                             string.Join(", ", contentItem.FieldNames.ToArray()))));

                    continue;
                }

                // Create new item from the prototype.
                var newItemEntry = currentLevelPrototype.Clone();

                foreach (var xElement in newItemEntry.PrototypeItems)
                {
                    var newElement = new XElement(xElement);
                    if (!newElement.DescendantsAndSelf(W.sdt).Any())
                    {
                        newRows.Add(newElement);
                        continue;
                    }

                    foreach (var sdt in newElement.FirstLevelDescendantsAndSelf(W.sdt).ToList())
                    {
                        var fieldContent = contentItem.GetContentItem(sdt.SdtTagName());
                        if (fieldContent == null)
                        {
                            processResult.AddError(new CustomError(
                                                       string.Format("Field content for field '{0}' not found",
                                                                     sdt.SdtTagName())));

                            continue;
                        }

                        var contentProcessResult = new ContentProcessor(_context)
                                                   .SetRemoveContentControls(_isNeedToRemoveContentControls)
                                                   .FillContent(sdt, fieldContent);

                        processResult.Merge(contentProcessResult);
                    }
                    newRows.Add(newElement);
                }

                // If there are nested items fill prototype for them.
                if (contentItem.NestedFields != null)
                {
                    var filledNestedFields = PropagatePrototype(
                        prototype.Exclude(currentLevelPrototype),
                        contentItem.NestedFields);

                    newRows.AddRange(filledNestedFields.Result);
                }
            }
            processResult.Result = newRows;
            return(processResult);
        }
Beispiel #35
0
        public static Prototype GetDescription(object obj, bool showNonPublic)
        {
            var result = new Prototype();
            var z = result.Dict;
            var sym = obj as Symbol;
            var isVariable = false;
            object runtimeValue;

            if (sym == null)
            {
                runtimeValue = obj;
            }
            else {
                runtimeValue = sym.Value;

                z["symbol"] = sym;
                z["name"] = sym.Name;
                z["package"] = sym.Package == null ? null : sym.Package.Name;

                switch (sym.CompilerUsage)
                {
                    case SymbolUsage.CompilerMacro:
                        {
                            z["compiler-usage"] = Symbols.CompilerMacro;
                            z["compiler-value"] = sym.MacroValue;
                            var b = ((ISyntax)sym.MacroValue).GetSyntax(sym);
                            if (b != null)
                            {
                                z["compiler-syntax"] = b;
                            }
                            break;
                        }
                    case SymbolUsage.Macro:
                        {
                            z["compiler-usage"] = Symbols.Macro;
                            z["compiler-value"] = sym.MacroValue;
                            var b = ((ISyntax)sym.MacroValue).GetSyntax(sym);
                            if (b != null)
                            {
                                z["compiler-syntax"] = b;
                            }
                            break;
                        }
                    case SymbolUsage.SymbolMacro:
                        {
                            z["compiler-usage"] = Symbols.SymbolMacro;
                            z["compiler-value"] = sym.SymbolMacroValue;
                            break;
                        }
                    case SymbolUsage.SpecialForm:
                        {
                            z["compiler-usage"] = Symbols.SpecialForm;
                            z["compiler-value"] = sym.SpecialFormValue;
                            break;
                        }
                }

                if (!string.IsNullOrWhiteSpace(sym.CompilerDocumentation))
                {
                    z["compiler-documentation"] = sym.CompilerDocumentation;
                }

                switch (sym.Usage)
                {
                    case SymbolUsage.None:
                        {
                            z["usage"] = Symbols.Undefined;
                            return result;
                        }
                    case SymbolUsage.Constant:
                        {
                            if (sym.IsDynamic)
                            {
                                z["usage"] = Symbols.SpecialConstant;
                                isVariable = true;
                            }
                            else {
                                z["usage"] = Symbols.Constant;
                                isVariable = true;
                            }
                            break;
                        }
                    case SymbolUsage.ReadonlyVariable:
                        {
                            if (sym.IsDynamic)
                            {
                                z["usage"] = Symbols.SpecialReadonlyVariable;
                                isVariable = true;
                            }
                            else {
                                z["usage"] = Symbols.ReadonlyVariable;
                                isVariable = true;
                            }
                            break;
                        }
                    case SymbolUsage.Variable:
                        {
                            if (sym.IsDynamic)
                            {
                                z["usage"] = Symbols.SpecialVariable;
                                isVariable = true;
                            }
                            else {
                                z["usage"] = Symbols.Variable;
                                isVariable = true;
                            }
                            break;
                        }
                    case SymbolUsage.Function:
                        {
                            z["usage"] = Symbols.Function;
                            break;
                        }
                }

                if (!string.IsNullOrWhiteSpace(sym.Documentation))
                {
                    z["documentation"] = sym.Documentation;
                }

            }

            if (!(runtimeValue is ICollection) || (runtimeValue is IList))
            {
                z["value"] = runtimeValue;
            }

            if (Nullp(runtimeValue))
            {
                return result;
            }
            else if (!(runtimeValue is ICollection) || (runtimeValue is IList))
            {
                z["type"] = runtimeValue.GetType().ToString();
            }

            Symbol usage = null;

            if (!isVariable)
            {
                if (runtimeValue is ISyntax)
                {
                    var b = ((ISyntax)runtimeValue).GetSyntax(obj as Symbol);
                    if (b != null)
                    {
                        z["function-syntax"] = b;
                    }
                }

                if (runtimeValue is MultiMethod)
                {
                    usage = Symbols.GenericFunction;
                }
                else if (runtimeValue is ImportedConstructor)
                {
                    var kiezel = ((ImportedConstructor)runtimeValue).HasKiezelMethods;
                    usage = kiezel ? Symbols.BuiltinConstructor : Symbols.ImportedConstructor;
                }
                else if (runtimeValue is ImportedFunction)
                {
                    var kiezel = ((ImportedFunction)runtimeValue).HasKiezelMethods;
                    usage = kiezel ? Symbols.BuiltinFunction : Symbols.ImportedFunction;
                }
                else if (runtimeValue is LambdaClosure)
                {
                    var l = (LambdaClosure)runtimeValue;

                    //z[ "function-source" ] = l.Definition.Source;

                    switch (l.Kind)
                    {
                        case LambdaKind.Method:
                            {
                                usage = Symbols.Method;
                                break;
                            }
                        default:
                            {
                                usage = Symbols.Function;
                                break;
                            }
                    }
                }
            }

            if (obj is Symbol && usage != null)
            {
                z["usage"] = usage;
            }

            if (runtimeValue is Prototype)
            {
                var p = (Prototype)runtimeValue;
                z["type-specifier"] = p.GetTypeSpecifier();
            }
            else {
                var dict = AsPrototype(runtimeValue);

                if (dict.Dict.Count != 0)
                {
                    z["members"] = dict;
                }
            }

            return result;
        }
        private ProcessResult FillContent(XElement contentControl, IContentItem item)
        {
            var processResult = ProcessResult.NotHandledResult;

            if (!(item is ListContent))
            {
                return(ProcessResult.NotHandledResult);
            }

            var list = item as ListContent;

            // If there isn't a list with that name, add an error to the error string.
            if (contentControl == null)
            {
                processResult.AddError(new ContentControlNotFoundError(list));

                return(processResult);
            }

            // If the list doesn't contain content controls in items, then error.
            var itemsContentControl = contentControl
                                      .Descendants(W.sdt)
                                      .FirstOrDefault();

            if (itemsContentControl == null)
            {
                processResult.AddError(
                    new CustomContentItemError(list, "doesn't contain content controls in items"));

                return(processResult);
            }

            if (list.IsHidden || list.FieldNames == null)
            {
                contentControl.Descendants(W.tr).Remove();
            }
            else
            {
                var fieldNames = list.FieldNames.ToList();

                // Create a prototype of new items to be inserted into the document.
                var prototype = new Prototype(_context, contentControl, fieldNames);

                if (!prototype.IsValid)
                {
                    processResult.AddError(
                        new CustomContentItemError(list,
                                                   string.Format("doesn't contain items with content controls {0}",
                                                                 string.Join(", ", fieldNames.ToArray()))));

                    return(processResult);
                }

                new NumberingAccessor(_context.Document.NumberingPart, _context.LastNumIds)
                .ResetNumbering(prototype.PrototypeItems);

                // Propagates a prototype.
                if (list.Items != null)

                {
                    var propagationResult = PropagatePrototype(prototype, list.Items);
                    processResult.Merge(propagationResult);
                    // add all of the newly constructed rows.
                    if (!item.IsHidden)
                    {
                        prototype.PrototypeItems.Last().AddAfterSelf(propagationResult.Result);
                    }
                }

                prototype.PrototypeItems.Remove();
            }

            processResult.AddItemToHandled(list);

            return(processResult);
        }
 public ComponentWithBackReference(Prototype p)
 {
     Prototype = p;
 }
Beispiel #38
0
        public IEnumerable <Object> FetchDependencies(ISerializedFile file, bool isLog = false)
        {
            yield return(Prototype.FetchDependency(file, isLog, () => nameof(DetailPrototype), "prototype"));

            yield return(PrototypeTexture.FetchDependency(file, isLog, () => nameof(DetailPrototype), "prototypeTexture"));
        }
        /// <summary>
        /// Create the body of the invoke method.
        /// </summary>
        /// <param name="calledMethodPrototype"></param>
        private MethodBody CreateInvokeBody(Prototype calledMethodPrototype)
        {
            var body  = new MethodBody(null);
            var rthis = body.AllocateRegister(RCategory.Argument, RType.Object);

            foreach (var p in invokePrototype.Parameters)
            {
                if (p.Type.IsWide())
                {
                    body.AllocateWideRegister(RCategory.Argument);
                }
                else
                {
                    var type = (p.Type is PrimitiveType) ? RType.Value : RType.Object;
                    body.AllocateRegister(RCategory.Argument, type);
                }
            }
            var incomingMethodArgs = body.Registers.ToArray();

            // Create code
            var      ins         = body.Instructions;
            Register instanceReg = null;

            if (!calledMethod.IsStatic)
            {
                // load instance
                instanceReg = body.AllocateRegister(RCategory.Temp, RType.Object);
                ins.Add(new Instruction(RCode.Iget_object, instanceReg, rthis)
                {
                    Operand = instanceField
                });
            }

            List <Register> genericTypeParameterRegs = new List <Register>();

            foreach (var field in GenericTypeFields)
            {
                var r = body.AllocateRegister(RCategory.Temp, RType.Object);
                ins.Add(new Instruction(RCode.Iget_object, r, rthis)
                {
                    Operand = field
                });
                genericTypeParameterRegs.Add(r);
            }

            // Invoke
            var calledMethodRef = calledMethod.GetReference(targetPackage);
            var inputArgs       = calledMethod.IsStatic ? incomingMethodArgs.Skip(1).ToArray() : incomingMethodArgs;

            // Cast arguments (if needed)
            var outputArgs = new List <Register>();

            if (!calledMethod.IsStatic)
            {
                outputArgs.Add(instanceReg);
            }
            var parameterIndex = 0;

            for (var i = calledMethod.IsStatic ? 0 : 1; i < inputArgs.Length;)
            {
                var invokeType  = invokePrototype.Parameters[parameterIndex].Type;
                var inputIsWide = invokeType.IsWide();
                var calledType  = calledMethodPrototype.Parameters[parameterIndex].Type;
                if (!invokeType.Equals(calledType))
                {
                    // Add cast / unbox
                    var source = inputIsWide
                                     ? new RegisterSpec(inputArgs[i], inputArgs[i + 1], invokeType)
                                     : new RegisterSpec(inputArgs[i], null, invokeType);
                    var tmp = ins.Unbox(sequencePoint, source, calledMethod.Parameters[parameterIndex].ParameterType, compiler, targetPackage, body);
                    outputArgs.Add(tmp.Result.Register);
                    if (calledType.IsWide())
                    {
                        outputArgs.Add(tmp.Result.Register2);
                    }
                }
                else
                {
                    outputArgs.Add(inputArgs[i]);
                    if (calledType.IsWide())
                    {
                        outputArgs.Add(inputArgs[i + 1]);
                    }
                }
                i += inputIsWide ? 2 : 1;
                parameterIndex++;
            }

            outputArgs.AddRange(genericTypeParameterRegs);

            // Actual call
            ins.Add(new Instruction(calledMethod.Invoke(calledMethod, null), calledMethodRef, outputArgs.ToArray()));

            // Collect return value
            var         invokeReturnType = invokePrototype.ReturnType;
            var         calledReturnType = calledMethodPrototype.ReturnType;
            var         needsBoxing      = !invokeReturnType.Equals(calledReturnType);
            Instruction returnInstruction;
            Instruction nextMoveResultInstruction = null;

            if (calledReturnType.IsWide())
            {
                var r = body.AllocateWideRegister(RCategory.Temp);
                ins.Add(new Instruction(RCode.Move_result_wide, r.Item1));
                if (needsBoxing)
                {
                    // Box
                    var source = new RegisterSpec(r.Item1, r.Item2, calledReturnType);
                    var tmp    = ins.Box(sequencePoint, source, calledMethod.ReturnType, targetPackage, body);
                    returnInstruction         = new Instruction(RCode.Return_object, tmp.Result.Register);
                    nextMoveResultInstruction = new Instruction(RCode.Move_result_object, tmp.Result.Register);
                }
                else
                {
                    // Return wide
                    returnInstruction         = new Instruction(RCode.Return_wide, r.Item1);
                    nextMoveResultInstruction = new Instruction(RCode.Move_result_wide, r.Item1);
                }
            }
            else if (calledMethod.ReturnType.IsVoid())
            {
                // Void return
                returnInstruction = new Instruction(RCode.Return_void);
            }
            else if (calledReturnType is PrimitiveType)
            {
                // Single register return
                var r = body.AllocateRegister(RCategory.Temp, RType.Value);
                ins.Add(new Instruction(RCode.Move_result, r));
                if (needsBoxing)
                {
                    // Box
                    var source = new RegisterSpec(r, null, invokeReturnType);
                    var tmp    = ins.Box(sequencePoint, source, calledMethod.ReturnType, targetPackage, body);
                    returnInstruction         = new Instruction(RCode.Return_object, tmp.Result.Register);
                    nextMoveResultInstruction = new Instruction(RCode.Move_result_object, tmp.Result.Register);
                }
                else
                {
                    // Return
                    returnInstruction         = new Instruction(RCode.Return, r);
                    nextMoveResultInstruction = new Instruction(RCode.Move_result, r);
                }
            }
            else
            {
                var r = body.AllocateRegister(RCategory.Temp, RType.Object);
                ins.Add(new Instruction(RCode.Move_result_object, r));
                if (needsBoxing)
                {
                    // Box
                    var source = new RegisterSpec(r, null, invokeReturnType);
                    var tmp    = ins.Box(sequencePoint, source, invokeMethod.ReturnType, targetPackage, body);
                    returnInstruction         = new Instruction(RCode.Return_object, tmp.Result.Register);
                    nextMoveResultInstruction = new Instruction(RCode.Move_result_object, tmp.Result.Register);
                }
                else
                {
                    // Return
                    returnInstruction         = new Instruction(RCode.Return_object, r);
                    nextMoveResultInstruction = new Instruction(RCode.Move_result_object, r);
                }
            }

            // Call delegate list
            var multicastDelegateType  = new ClassReference(targetPackage.NameConverter.GetConvertedFullName("System.MulticastDelegate"));
            var invListLengthReference = new FieldReference(multicastDelegateType, "InvocationListLength", PrimitiveType.Int);
            var multicastDelegateArray = new ArrayType(multicastDelegateType);
            var invListReference       = new FieldReference(multicastDelegateType, "InvocationList", multicastDelegateArray);

            var index   = body.AllocateRegister(RCategory.Temp, RType.Value);
            var count   = body.AllocateRegister(RCategory.Temp, RType.Value);
            var next    = body.AllocateRegister(RCategory.Temp, RType.Object);
            var invList = body.AllocateRegister(RCategory.Temp, RType.Object);

            var done = new Instruction(RCode.Nop);

            var nextInvokeMethod = new MethodReference(delegateClass, "Invoke", invokePrototype);
            var nextInvokeArgs = new[] { next }.Concat(incomingMethodArgs.Skip(1)).ToArray();

            ins.Add(new Instruction(RCode.Iget, invListLengthReference, new[] { count, rthis }));
            ins.Add(new Instruction(RCode.If_eqz, done, new[] { count }));
            ins.Add(new Instruction(RCode.Const, 0, new[] { index }));
            ins.Add(new Instruction(RCode.Iget_object, invListReference, new[] { invList, rthis }));

            var getNext = new Instruction(RCode.Aget_object, null, new[] { next, invList, index });

            ins.Add(getNext);
            ins.Add(new Instruction(RCode.Check_cast, delegateClass, new [] { next }));
            ins.Add(new Instruction(RCode.Invoke_virtual, nextInvokeMethod, nextInvokeArgs));

            if (nextMoveResultInstruction != null)
            {
                ins.Add(nextMoveResultInstruction);
            }

            ins.Add(new Instruction(RCode.Add_int_lit8, 1, new[] { index, index }));
            ins.Add(new Instruction(RCode.If_lt, getNext, new[] { index, count }));

            ins.Add(done);

            // Add return instructions
            ins.Add(returnInstruction);

            return(body);
        }
Beispiel #40
0
 private void AddPrototype(Prototype proto)
 {
     ReplacePrototype(selectedModule, null, proto);
 }
        void describe_collection()
        {
            before = () =>
            {
                dynamic prototype = new Prototype();
                prototype.Id = 1;

                objectToConvert = new List<dynamic>
                {
                    prototype,
                    new DynamicModel(new { Id = 2 }),
                    new Gemini(new { Id = 3 }),
                };
            };

            act = () => jsonString = DynamicToJson.Convert(objectToConvert);

            it["converts collection"] = () =>
                {
                    string expected = @"[ { ""Id"": 1 }, { ""Id"": 2 }, { ""Id"": 3 } ]";

                    jsonString.should_be(expected);
                };
        }
Beispiel #42
0
        /// <summary>
        /// Создаёт устройство на основе типа устройства
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static DeviceBase Create(DeviceType type)
        {
            IProfile profile = Prototype.Create(type);

            return(new DeviceBase(profile));
        }
Beispiel #43
0
 public static dynamic RecordToGemini(this IDataReader rdr, Func<dynamic, dynamic> projection)
 {
     if (projection == null)
     {
         var e = new Prototype() as IDictionary<string, object>;;
         PopluateDynamicDictionary(rdr, e);
         return e;
     }
     else
     {
         dynamic e = new Gemini();
         PopluateDynamicDictionary(rdr, e.Prototype);
         return projection(e);
     }
 }
 static void Report(string s, Prototype a, Prototype b)
 {
     Console.WriteLine("\n" + s);
     Console.WriteLine("Prototype: \n" + a + "\nClone: \n" + b);
 }