Beispiel #1
0
        public static void ModifiedClone_Dictionary_ShouldNotBeEqual()
        {
            var original = new DictionaryObject
            {
                Collection =
                {
                    { 1, new BasicObject()
                        {
                            IntValue = 1, LongValue = 10
                        } },
                    { 2, new BasicObject()
                        {
                            IntValue = 2, LongValue = 20
                        } },
                    { 3, new BasicObject()
                        {
                            IntValue = 3, LongValue = 30
                        } },
                }
            };
            DictionaryObject cloned = original.Clone();

            cloned.Collection[2].LongValue = 200;

            cloned.ShouldNotBe(original);
        }
Beispiel #2
0
        private void ExecuteLoadItemsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try {
                using (var dict = _db.GetDocument(CoreApp.DocId)) {
                    var arr = dict.GetArray(CoreApp.ArrKey);
                    for (int i = 0; i < arr.Count; i++)
                    {
                        DictionaryObject d = arr.GetDictionary(i);
                        _items[i].Name           = d.GetString("key");
                        _items[i].Quantity       = d.GetInt("value");
                        _items[i].ImageByteArray = d.GetBlob("image")?.Content;
                    }
                }
            } catch (Exception ex) {
                Debug.WriteLine(ex);
            } finally {
                IsBusy = false;
            }
        }
Beispiel #3
0
 /// <summary>
 /// Creates a new model from the specified Couchbase object.
 /// </summary>
 /// <returns>A new model.</returns>
 /// <param name="dictionaryObject">Dictionary object.</param>
 public PersonObfuscated(DictionaryObject dictionaryObject) :
     this(
         entryGuid : dictionaryObject.ParseGuid(JsonProperties.EntryGuid),
         entryType : dictionaryObject.GetString(JsonProperties.EntryType),
         firstName : dictionaryObject.GetString(JsonProperties.FirstName),
         lastName : dictionaryObject.GetString(JsonProperties.LastName),
         maidenName : dictionaryObject.GetString(JsonProperties.MaidenName),
         displayName : dictionaryObject.GetString(JsonProperties.DisplayName),
         organizationName : dictionaryObject.GetString(JsonProperties.OrganizationName),
         locationGuid : dictionaryObject.ParseGuid(JsonProperties.LocationGuid),
         siteGuid : dictionaryObject.ParseGuid(JsonProperties.SiteGuid),
         siteName : dictionaryObject.GetString(JsonProperties.SiteName),
         userStatus : dictionaryObject.GetString(JsonProperties.UserStatus),
         departmentName : dictionaryObject.GetString(JsonProperties.DepartmentName),
         residenceArea : dictionaryObject.GetString(JsonProperties.ResidenceArea),
         workAreaName : dictionaryObject.GetString(JsonProperties.WorkAreaName),
         teamName : dictionaryObject.GetString(JsonProperties.TeamName),
         contacts : dictionaryObject.ParseDictionaryObjects(JsonProperties.Contacts)
         .Select(Contact.Create)
         .ToList(),
         spouseEntryGuid : dictionaryObject.ParseGuid(JsonProperties.SpouseEntryGuid),
         personPrimaryPhotoGuid : dictionaryObject.ParseGuid(JsonProperties.PersonPrimaryPhotoGuid),
         primaryPhotoUrl : dictionaryObject.GetString(JsonProperties.PrimaryPhotoUrl),
         emergencyContactGuids : dictionaryObject.ParseGuids(JsonProperties.EmergencyContactGuids),
         lastUpdated : dictionaryObject.GetDate(IPerishableDataExtensions.JsonProperties.LastUpdated),
         expirationDate : dictionaryObject.GetDate(IPerishableDataExtensions.JsonProperties.ExpirationDate))
 {
 }
Beispiel #4
0
        public BingoBall(DictionaryObject dictionary)
        {
            Name      = dictionary["Name"].String;
            IsPlayed  = dictionary["IsPlayed"].Boolean;
            IsMatched = dictionary["IsMatched"].Boolean;

            PlayedBy = new List <string>();
            var arrayObject = dictionary["PlayedBy"].Array;

            if (arrayObject != null)
            {
                foreach (IFragment fragment in arrayObject)
                {
                    PlayedBy.Add(fragment.String);
                }
            }

            MatchedBy   = new List <string>();
            arrayObject = dictionary["MatchedBy"].Array;
            if (arrayObject != null)
            {
                foreach (IFragment fragment in arrayObject)
                {
                    MatchedBy.Add(fragment.String);
                }
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="FlateDecode"/> class.
 /// </summary>
 /// <param name="baseStream"></param>
 /// <param name="parameters">The parameters.</param>
 public FlateDecode(Stream baseStream, DictionaryObject parameters)
     : base(baseStream, parameters)
 {
     // NOTE: taking the easy road, decode immediately and store result in memory stream
     // we can do better here, but ZlibStream isn't seekable
     Decode();
 }
Beispiel #6
0
 /// <summary>
 /// Creates a new model from the specified Couchbase object.
 /// </summary>
 /// <returns>A new model.</returns>
 /// <param name="dictionaryObject">Dictionary object.</param>
 public static Contact Create(DictionaryObject dictionaryObject)
 {
     return(new Contact(
                contactType: dictionaryObject.ParseEnum <ContactType>(JsonProperties.Type),
                contactMethod: dictionaryObject.ParseEnum <ContactMethod>(JsonProperties.Method),
                contactValue: dictionaryObject.GetString(JsonProperties.Contact)));
 }
Beispiel #7
0
        public void ThrowError(string fragment)
        {
            // 7.3.7 Dictionary Objects
            byte[]    bytes = System.Text.UTF8Encoding.UTF8.GetBytes(fragment);
            Tokenizer feed  = new Tokenizer(new MemoryStream(bytes));

            Assert.Throws <PdfException>(() => { var dictionaryObject = new DictionaryObject(feed); });
        }
Beispiel #8
0
        public void ReadWithDictionary()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.Converters.Add(new JsonStringEnumConverter());

            const string     json = @"{""IntDictionary"":{""1"":1,""2"":2},""UIntDictionary"":{""1"":{""IntValue"":1},""2"":{""IntValue"":2}},""StringDictionary"":{""1"":[{""IntValue"":11},{""IntValue"":12}],""2"":[{""IntValue"":21},{""IntValue"":22}]},""EnumDictionary"":{""Value1"":{""1"":{""IntValue"":11},""2"":{""IntValue"":12}},""Value2"":{""1"":{""IntValue"":21},""2"":{""IntValue"":22}}}}";
            DictionaryObject obj  = Helper.Read <DictionaryObject>(json, options);

            Assert.NotNull(obj);

            Assert.NotNull(obj.IntDictionary);
            Assert.Equal(2, obj.IntDictionary.Count);
            Assert.True(obj.IntDictionary.ContainsKey(1));
            Assert.Equal(1, obj.IntDictionary[1]);
            Assert.True(obj.IntDictionary.ContainsKey(2));
            Assert.Equal(2, obj.IntDictionary[2]);

            Assert.NotNull(obj.UIntDictionary);
            Assert.Equal(2, obj.UIntDictionary.Count);
            Assert.True(obj.UIntDictionary.ContainsKey(1));
            Assert.NotNull(obj.UIntDictionary[1]);
            Assert.Equal(1, obj.UIntDictionary[1].IntValue);
            Assert.True(obj.UIntDictionary.ContainsKey(2));
            Assert.NotNull(obj.UIntDictionary[2]);
            Assert.Equal(2, obj.UIntDictionary[2].IntValue);

            Assert.NotNull(obj.StringDictionary);
            Assert.Equal(2, obj.StringDictionary.Count);
            Assert.True(obj.StringDictionary.ContainsKey("1"));
            Assert.NotNull(obj.StringDictionary["1"]);
            Assert.Equal(2, obj.StringDictionary["1"].Count);
            Assert.Equal(11, obj.StringDictionary["1"][0].IntValue);
            Assert.Equal(12, obj.StringDictionary["1"][1].IntValue);
            Assert.True(obj.StringDictionary.ContainsKey("2"));
            Assert.NotNull(obj.StringDictionary["2"]);
            Assert.Equal(2, obj.StringDictionary["2"].Count);
            Assert.Equal(21, obj.StringDictionary["2"][0].IntValue);
            Assert.Equal(22, obj.StringDictionary["2"][1].IntValue);

            Assert.NotNull(obj.EnumDictionary);
            Assert.Equal(2, obj.EnumDictionary.Count);
            Assert.True(obj.EnumDictionary.ContainsKey(EnumTest.Value1));
            Assert.NotNull(obj.EnumDictionary[EnumTest.Value1]);
            Assert.Equal(2, obj.EnumDictionary[EnumTest.Value1].Count);
            Assert.Equal(11, obj.EnumDictionary[EnumTest.Value1][1].IntValue);
            Assert.Equal(12, obj.EnumDictionary[EnumTest.Value1][2].IntValue);
            Assert.True(obj.EnumDictionary.ContainsKey(EnumTest.Value2));
            Assert.NotNull(obj.EnumDictionary[EnumTest.Value2]);
            Assert.Equal(2, obj.EnumDictionary[EnumTest.Value2].Count);
            Assert.Equal(21, obj.EnumDictionary[EnumTest.Value2][1].IntValue);
            Assert.Equal(22, obj.EnumDictionary[EnumTest.Value2][2].IntValue);
        }
        public DictionaryObject Predict(DictionaryObject input)
        {
            if (!AllowCalls)
            {
                Error = new InvalidOperationException("Not allowed to be called in this state");
                return(null);
            }

            NumberOfCalls++;
            return(DoPrediction(input));
        }
Beispiel #10
0
        public void ReadDictionary()
        {
            // 7.3.7 Dictionary Objects
            string fragment = @"<< /Type /Example
/Subtype /DictionaryExample
/Version 0.01
/IntegerItem 12
/StringItem (a string)
/Subdictionary << /Item1 0.4
/Item2 true
/LastItem (not!)
/VeryLastItem (OK)
>>
>>";

            byte[]     bytes      = System.Text.UTF8Encoding.UTF8.GetBytes(fragment);
            Tokenizer  feed       = new Tokenizer(new MemoryStream(bytes));
            Objectizer objectizer = new Objectizer(feed);

            DictionaryObject actual = (DictionaryObject)objectizer.NextObject();

            Assert.Equal(12, actual.Childs <PdfObject>().Length);


            Assert.Equal("Type", actual.Child <NameObject>(0).Value);
            Assert.Equal("Example", actual.Child <NameObject>(1).Value);

            Assert.Equal("Subtype", actual.Child <NameObject>(2).Value);
            Assert.Equal("DictionaryExample", actual.Child <NameObject>(3).Value);

            Assert.Equal("Version", actual.Child <NameObject>(4).Value);
            Assert.Equal(0.01f, actual.Child <RealObject>(5).Value);

            Assert.Equal("IntegerItem", actual.Child <NameObject>(6).Value);
            Assert.Equal(12, actual.Child <IntegerObject>(7).IntValue);

            Assert.Equal("StringItem", actual.Child <NameObject>(8).Value);
            Assert.Equal("a string", actual.Child <StringObject>(9).Value);

            Assert.Equal("Subdictionary", actual.Child <NameObject>(10).Value);

            Assert.Equal("Item1", actual.Child <DictionaryObject>(11).Child <NameObject>(0).Value);
            Assert.Equal(0.4f, actual.Child <DictionaryObject>(11).Child <RealObject>(1).Value);

            Assert.Equal("Item2", actual.Child <DictionaryObject>(11).Child <NameObject>(2).Value);
            Assert.True(actual.Child <DictionaryObject>(11).Child <BooleanObject>(3).Value);

            Assert.Equal("LastItem", actual.Child <DictionaryObject>(11).Child <NameObject>(4).Value);
            Assert.Equal("not!", actual.Child <DictionaryObject>(11).Child <StringObject>(5).Value);

            Assert.Equal("VeryLastItem", actual.Child <DictionaryObject>(11).Child <NameObject>(6).Value);
            Assert.Equal("OK", actual.Child <DictionaryObject>(11).Child <StringObject>(7).Value);
        }
Beispiel #11
0
        public unsafe void TestReadOnlyDictionary()
        {
            var now         = DateTimeOffset.UtcNow;
            var nestedArray = new[] { 1L, 2L, 3L };
            var nestedDict  = new Dictionary <string, object> {
                ["foo"] = "bar"
            };
            var masterData = new Dictionary <string, object>
            {
                ["date"]  = now,
                ["array"] = nestedArray,
                ["dict"]  = nestedDict
            };

            var flData = new FLSliceResult();

            Db.InBatch(() =>
            {
                flData = masterData.FLEncode();
            });

            try {
                var context = new DocContext(Db, null);
                using (var mRoot = new MRoot(context)) {
                    mRoot.Context.Should().BeSameAs(context);
                    FLDoc *fleeceDoc = Native.FLDoc_FromResultData(flData,
                                                                   FLTrust.Trusted,
                                                                   Native.c4db_getFLSharedKeys(Db.c4db), FLSlice.Null);
                    var flValue          = Native.FLDoc_GetRoot(fleeceDoc);
                    var mDict            = new MDict(new MValue(flValue), mRoot);
                    var deserializedDict = new DictionaryObject(mDict, false);

                    deserializedDict["bogus"].Blob.Should().BeNull();
                    deserializedDict["date"].Date.Should().Be(now);
                    deserializedDict.GetDate("bogus").Should().Be(DateTimeOffset.MinValue);
                    deserializedDict.GetArray("array").Should().Equal(1L, 2L, 3L);
                    deserializedDict.GetArray("bogus").Should().BeNull();
                    deserializedDict.GetDictionary("dict").Should().BeEquivalentTo(nestedDict);
                    deserializedDict.GetDictionary("bogus").Should().BeNull();

                    var dict = deserializedDict.ToDictionary();
                    dict["array"].As <IList>().Should().Equal(1L, 2L, 3L);
                    dict["dict"].As <IDictionary <string, object> >().Should().BeEquivalentTo(nestedDict);
                    var isContain = mDict.Contains("");
                    isContain.Should().BeFalse();
                    Native.FLDoc_Release(fleeceDoc);
                }
            } finally {
                Native.FLSliceResult_Release(flData);
            }
        }
Beispiel #12
0
        public void ReadAMinimalDictionary(string fragment)
        {
            // 7.3.7 Dictionary Objects
            byte[]    bytes = System.Text.UTF8Encoding.UTF8.GetBytes(fragment);
            Tokenizer feed  = new Tokenizer(new MemoryStream(bytes));

            var actual = new DictionaryObject(feed);

            actual.Childs <PdfObject>().Should().HaveCount(2);
            actual.Childs <PdfObject>()[0].Should().BeOfType <NameObject>();

            Assert.Equal("Type", actual.Child <NameObject>(0).Value);
            Assert.Equal("Example", actual.Child <NameObject>(1).Value);
        }
        public DictionaryObject Predict(DictionaryObject input)
        {
            var blob = input.GetBlob("photo");

            if (blob == null)
            {
                return(null);
            }

            var imageData = blob.Content;
            // `TensorFlowModel` is a fake implementation
            // this would be the implementation of the ml model you have chosen
            var modelOutput = TensorFlowModel.PredictImage(imageData);

            return(new MutableDictionaryObject(modelOutput)); // <1>
        }
        protected override DictionaryObject DoPrediction(DictionaryObject input)
        {
            var numbers = input.GetArray("numbers");

            if (numbers == null)
            {
                return(null);
            }

            var output = new MutableDictionaryObject();

            output.SetLong("sum", numbers.Cast <long>().Sum());
            output.SetLong("min", numbers.Cast <long>().Min());
            output.SetLong("max", numbers.Cast <long>().Max());
            output.SetDouble("avg", numbers.Cast <long>().Average());
            return(output);
        }
Beispiel #15
0
        [InlineData("<</Length 10>>stream\n0123456789endstream")] // is not completely valid, but some writers do
        public void ReadStreams(string fragment)
        {
            // 7.3.8 Stream Objects
            byte[]     bytes      = System.Text.UTF8Encoding.UTF8.GetBytes(fragment);
            Tokenizer  feed       = new Tokenizer(new MemoryStream(bytes));
            Objectizer objectizer = new Objectizer(feed);

            DictionaryObject actual = (DictionaryObject)objectizer.NextObject();

            Assert.Equal(2, actual.Childs <PdfObject>().Length);


            Assert.Equal("Length", actual.Child <NameObject>(0).Value);
            Assert.Equal(10, actual.Child <IntegerObject>(1).IntValue);

            Assert.Equal(System.Text.UTF8Encoding.UTF8.GetBytes("0123456789"), actual.Stream);
        }
Beispiel #16
0
        public unsafe void TestReadOnlyDictionary()
        {
            var now         = DateTimeOffset.UtcNow;
            var nestedArray = new[] { 1L, 2L, 3L };
            var nestedDict  = new Dictionary <string, object> {
                ["foo"] = "bar"
            };
            var masterData = new Dictionary <string, object>
            {
                ["date"]  = now,
                ["array"] = nestedArray,
                ["dict"]  = nestedDict
            };

            var flData = new FLSliceResult();

            Db.InBatch(() =>
            {
                flData = masterData.FLEncode();
            });

            try {
                var context = new DocContext(Db, null);
                using (var mRoot = new MRoot(context)) {
                    mRoot.Context.Should().BeSameAs(context);
                    var flValue          = NativeRaw.FLValue_FromTrustedData((FLSlice)flData);
                    var mDict            = new MDict(new MValue(flValue), mRoot);
                    var deserializedDict = new DictionaryObject(mDict, false);

                    deserializedDict["bogus"].Blob.Should().BeNull();
                    deserializedDict["date"].Date.Should().Be(now);
                    deserializedDict.GetDate("bogus").Should().Be(DateTimeOffset.MinValue);
                    deserializedDict.GetArray("array").Should().Equal(1L, 2L, 3L);
                    deserializedDict.GetArray("bogus").Should().BeNull();
                    deserializedDict.GetDictionary("dict").Should().BeEquivalentTo(nestedDict);
                    deserializedDict.GetDictionary("bogus").Should().BeNull();

                    var dict = deserializedDict.ToDictionary();
                    dict["array"].As <IList>().Should().Equal(1L, 2L, 3L);
                    dict["dict"].As <IDictionary <string, object> >().ShouldBeEquivalentTo(nestedDict);
                }
            } finally {
                Native.FLSliceResult_Free(flData);
            }
        }
        public bool AddDictionaryObject(int i, string name)
        {
            if (String.IsNullOrEmpty(name))
            {
                return(false);
            }

            var dicObj = new DictionaryObject {
                DictionaryId = i, DictionaryObjectName = name, Deactivate = false
            };

            _context.DictionaryObjects.Add(dicObj);
            var saveResult = _context.SaveChanges();

            if (saveResult != null)
            {
                return(true);
            }
            return(false);
        }
Beispiel #18
0
 public static void FinalizeApplication()
 {
     mGlobalStringMap = null;
     mNativeClassNames?.Clear();
     mNativeClassNames = null;
     mConsoleOutput    = null;
     mMessageMapper    = null;
     mStorage          = null;
     mArrayClass       = null;
     mDictionaryClass  = null;
     mVAPool           = null;
     NULL_ARG          = null;
     ArrayObject.FinalizeApplication();
     TjsByteCodeLoader.FinalizeApplication();
     CustomObject.FinalizeApplication();
     DictionaryObject.FinalizeApplication();
     MathClass.FinalizeApplication();
     Variant.FinalizeApplication();
     LexicalAnalyzer.FinalizeApplication();
 }
        protected override DictionaryObject DoPrediction(DictionaryObject input)
        {
            var blob = input.GetBlob("text");

            if (blob == null)
            {
                return(null);
            }

            ContentType = blob.ContentType;

            var text = Encoding.UTF8.GetString(blob.Content);
            var wc   = text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length;
            var sc   = text.Split('.', StringSplitOptions.RemoveEmptyEntries).Length;

            var output = new MutableDictionaryObject();

            output.SetInt("wc", wc);
            output.SetInt("sc", sc);
            return(output);
        }
Beispiel #20
0
 //private static final String TAG ="TJS";
 // プリプロセッサでは未定义の时この值が入る
 // create a member if not exists
 //public static int mCompactVariantArrayMagic;
 //public static VariantArrayStack mVariantArrayStack;
 // static 关系はここで初期化
 public static void Initialize()
 {
     // mStorage = null; // 事前に设定されるので、ここで初期化するのはまずい
     NULL_ARG      = new Variant[0];
     IsTarminating = false;
     mWarnOnNonGlobalEvalOperator    = false;
     mUnaryAsteriskIgnoresPropAccess = false;
     mNativeClassNames = new AList <string>();
     mGlobalStringMap  = new GlobalStringMap();
     //mCompactVariantArrayMagic = 0;
     //mVariantArrayStack = new VariantArrayStack();
     mEvalOperatorIsOnGlobal = false;
     EnableDebugMode         = true;
     mConsoleOutput          = null;
     mMessageMapper          = new MessageMapper();
     RandomGeneratorNI.SetRandomBits128(null);
     //ArrayNI.register();
     mVAPool = new VariantPool();
     CompileState.mEnableDicFuncQuickHack = true;
     Variant.Initialize();
     DictionaryObject.Initialize();
     ArrayObject.Initialize();
     TjsByteCodeLoader.Initialize();
     CustomObject.Initialize();
     MathClass.Initialize();
     LexicalAnalyzer.Initialize();
     try
     {
         mArrayClass      = new ArrayClass();
         mDictionaryClass = new DictionaryClass();
     }
     catch (VariantException)
     {
     }
     catch (TjsException)
     {
     }
 }
Beispiel #21
0
        public static void Should_Clone_DictionaryObject()
        {
            var original = new DictionaryObject
            {
                Collection =
                {
                    { 1, new BasicObject()
                        {
                            IntValue = 1, LongValue = 10
                        } },
                    { 2, new BasicObject()
                        {
                            IntValue = 2, LongValue = 20
                        } },
                    { 3, new BasicObject()
                        {
                            IntValue = 3, LongValue = 30
                        } },
                }
            };
            DictionaryObject cloned = original.Clone();

            cloned.ShouldBe(original);
        }
Beispiel #22
0
        public void Should_Clone_DictionaryObject()
        {
            var original = new DictionaryObject
            {
                Collection =
                {
                    { 1, new BasicObject()
                        {
                            IntValue = 1, LongValue = 10
                        } },
                    { 2, new BasicObject()
                        {
                            IntValue = 2, LongValue = 20
                        } },
                    { 3, new BasicObject()
                        {
                            IntValue = 3, LongValue = 30
                        } },
                }
            };
            var cloned = original.Clone();

            Assert.AreEqual(original, cloned);
        }
Beispiel #23
0
 public void SerializesDictionary()
 {
     var start = new DictionaryObject();
     start.Names.Add("Duncan Idaho", 2);
     var bytes = BsonSerializer.Serialize(start);
     var end = BsonDeserializer.Deserialize<DictionaryObject>(bytes);
     Assert.Equal(1, end.Names.Count);
     Assert.Equal("Duncan Idaho", end.Names.ElementAt(0).Key);
     Assert.Equal(2, end.Names.ElementAt(0).Value);
 }
        private static IEnumerator <RunTimeValueBase> getForEach_IEnumerator(
            Player player,ASBinCode.rtti.Object obj,StackFrame frame,OpStep step,RunTimeScope scope,
            Dictionary <object,object> visited = null
            )
        {
            if (obj is ASBinCode.rtti.DynamicObject)
            {
                ASBinCode.rtti.DynamicObject dobj = (ASBinCode.rtti.DynamicObject)obj;
                {
                    var k = dobj.eachSlot();
                    while (k.MoveNext())
                    {
                        var c = k.Current;
                        DynamicPropertySlot ds = c as DynamicPropertySlot;
                        if (c != null)
                        {
                            yield return(ds.getValue()); //new rtString(ds._propname);
                        }
                    }
                }

                if (obj is DictionaryObject)
                {
                    DictionaryObject dictObj = (DictionaryObject)obj;
                    var k = dictObj.eachDictSlot();
                    while (k.MoveNext())
                    {
                        var            c  = k.Current;
                        DictionarySlot ds = c as DictionarySlot;
                        if (c != null)
                        {
                            yield return(ds.getValue()); //ds._key.key;
                        }
                    }
                }

                if (visited == null)
                {
                    visited = new Dictionary <object,object>();
                }
                //***再到原型链中查找
                if (dobj._prototype_ != null)
                {
                    var protoObj = dobj._prototype_;
                    //****_prototype_的类型,只可能是Function对象或Class对象
                    if (protoObj._class.classid == player.swc.FunctionClass.classid) //Function
                    {
                        dobj = (DynamicObject)((rtObjectBase)protoObj.memberData[1].getValue()).value;

                        if (visited.ContainsKey(dobj))
                        {
                            yield break;
                        }
                        visited.Add(dobj,null);

                        var res = getForEach_IEnumerator(player,dobj,frame,step,scope,visited);
                        while (res.MoveNext())
                        {
                            yield return(res.Current);
                        }
                    }
                    else if (protoObj._class.classid == 1) //搜索到根Object
                    {
                        //***根Object有继承自Class的prototype,再没有就没有了
                        dobj = (DynamicObject)((rtObjectBase)protoObj.memberData[0].getValue()).value;
                        {
                            var k = dobj.eachSlot();
                            while (k.MoveNext())
                            {
                                var c = k.Current;
                                DynamicPropertySlot ds = c as DynamicPropertySlot;
                                if (c != null)
                                {
                                    yield return(ds.getValue()); //new rtString(ds._propname);
                                }
                            }
                        }
                        yield break;
                    }
                    else if (protoObj._class.staticClass == null)
                    {
                        dobj = (DynamicObject)((rtObjectBase)protoObj.memberData[0].getValue()).value;
                        var res = getForEach_IEnumerator(player,dobj,frame,step,scope);
                        while (res.MoveNext())
                        {
                            yield return(res.Current);
                        }
                    }
                    else
                    {
                        frame.throwError((new error.InternalError(frame.player.swc,step.token,
                                                                  "遭遇了异常的_prototype_"
                                                                  )));
                        yield break;
                    }
                }
            }
            else if (obj is ASBinCode.rtti.Object)
            {
                //***处理.net IEnumerable***
                System.Collections.IEnumerator enumerator = null;
                if (obj is LinkSystemObject)
                {
                    var od = ((LinkSystemObject)obj).GetLinkData();
                    if (od is System.Collections.IEnumerable)
                    {
                        enumerator = ((System.Collections.IEnumerable)od).GetEnumerator();
                    }
                    else
                    {
                        enumerator = od as System.Collections.IEnumerator;
                    }
                }

                if (enumerator != null)
                {
                    var e = enumerator;
                    while (e.MoveNext())
                    {
                        int slotidx = frame.baseBottomSlotIndex;
                        if (slotidx >= Player.STACKSLOTLENGTH)
                        {
                            throw new ASRunTimeException("stack overflow",frame.player.stackTrace(0));
                        }
                        var tempslot = frame.stack[slotidx];
                        try
                        {
                            player.linktypemapper.storeLinkObject_ToSlot(e.Current,RunTimeDataType.rt_void,frame._tempSlot2,player.swc,player);
                        }
                        finally
                        {
                            tempslot.clear();
                        }

                        yield return(frame._tempSlot2.getValue());
                    }
                }
                else
                {
                    var dobj = ((ASBinCode.rtti.DynamicObject)
                                frame.player.static_instance[obj._class.staticClass.classid].value);

                    dobj = (ASBinCode.rtti.DynamicObject)((rtObjectBase)dobj.memberData[0].getValue()).value;
                    var res = getForEach_IEnumerator(player,dobj,frame,step,scope);
                    while (res.MoveNext())
                    {
                        yield return(res.Current);
                    }
                }
            }

            yield break;
        }
        private static IEnumerator <RunTimeValueBase> getForinIEnumerator(
            Player player,ASBinCode.rtti.Object obj,StackFrame frame,OpStep step,RunTimeScope scope,
            Dictionary <object,object> visited = null
            )
        {
            if (obj is ASBinCode.rtti.DynamicObject)
            {
                ASBinCode.rtti.DynamicObject dobj = (ASBinCode.rtti.DynamicObject)obj;
                {
                    var k = dobj.eachSlot();
                    while (k.MoveNext())
                    {
                        var c = k.Current;
                        DynamicPropertySlot ds = c as DynamicPropertySlot;
                        if (c != null)
                        {
                            yield return(new rtString(ds._propname));
                        }
                    }
                }

                if (obj is DictionaryObject)
                {
                    DictionaryObject dictObj = (DictionaryObject)obj;
                    var k = dictObj.eachDictSlot();
                    while (k.MoveNext())
                    {
                        var            c  = k.Current;
                        DictionarySlot ds = c as DictionarySlot;
                        if (c != null)
                        {
                            yield return(ds._key.key);
                        }
                    }
                }
                if (visited == null)
                {
                    visited = new Dictionary <object,object>();
                }
                //***再到原型链中查找
                if (dobj._prototype_ != null)
                {
                    var protoObj = dobj._prototype_;
                    //****_prototype_的类型,只可能是Function对象或Class对象
                    if (protoObj._class.classid == player.swc.FunctionClass.classid) //Function
                    {
                        dobj = (DynamicObject)((rtObjectBase)protoObj.memberData[1].getValue()).value;
                        if (visited.ContainsKey(dobj))
                        {
                            yield break;
                        }
                        visited.Add(dobj,null);

                        var res = getForinIEnumerator(player,dobj,frame,step,scope,visited);
                        while (res.MoveNext())
                        {
                            yield return(res.Current);
                        }
                    }
                    else if (protoObj._class.classid == 1) //搜索到根Object
                    {
                        //***根Object有继承自Class的prototype,再没有就没有了
                        dobj = (DynamicObject)((rtObjectBase)protoObj.memberData[0].getValue()).value;
                        {
                            var k = dobj.eachSlot();
                            while (k.MoveNext())
                            {
                                var c = k.Current;
                                DynamicPropertySlot ds = c as DynamicPropertySlot;
                                if (c != null)
                                {
                                    yield return(new rtString(ds._propname));
                                }
                            }
                        }
                        yield break;
                    }
                    else if (protoObj._class.staticClass == null)
                    {
                        dobj = (DynamicObject)((rtObjectBase)protoObj.memberData[0].getValue()).value;
                        var res = getForinIEnumerator(player,dobj,frame,step,scope);
                        while (res.MoveNext())
                        {
                            yield return(res.Current);
                        }
                    }
                    else
                    {
                        frame.throwError((new error.InternalError(frame.player.swc,step.token,
                                                                  "遭遇了异常的_prototype_"
                                                                  )));
                        yield break;
                    }
                }
            }
            else if (obj is ASBinCode.rtti.Object)
            {
                var dobj = ((ASBinCode.rtti.DynamicObject)
                            frame.player.static_instance[obj._class.staticClass.classid].value);

                dobj = (ASBinCode.rtti.DynamicObject)((rtObjectBase)dobj.memberData[0].getValue()).value;
                var res = getForinIEnumerator(player,dobj,frame,step,scope);
                while (res.MoveNext())
                {
                    yield return(res.Current);
                }
            }

            yield break;
        }
        private static ASBinCode.rtti.Object createObject(CSWC swc,Class cls,InstanceCreator creator,
                                                          out ASBinCode.rtData.rtObjectBase rtObjectBase,
                                                          out ASBinCode.rtData.rtObjectBase linkrtobj,
                                                          out string errinfo
                                                          )
        {
            ASBinCode.rtti.Object obj = null;// = new ASBinCode.rtti.Object(cls);
            rtObjectBase = null; linkrtobj = null; errinfo = null;
            if (cls.isLink_System)
            {
                if (creator != null)
                {
                    StackSlot stackSlot = creator.objectStoreToSlot as StackSlot;
                    if (stackSlot != null)
                    {
                        rtObjectBase = stackSlot.getStackCacheObject(cls);
                        return(rtObjectBase.value);
                    }
                }


                var func = (NativeFunctionBase)swc.class_Creator[cls];

                string err; int no;
                ASBinCode.rtData.rtObjectBase rtObj =
                    func.execute(null,null,cls,out err,out no) as ASBinCode.rtData.rtObjectBase;
                linkrtobj = rtObj;
                if (rtObj == null)
                {
                    errinfo = cls.ToString() + " create linksystem object failed";
                    return(null);
                }
                else
                {
                    return(rtObj.value);
                }
            }
            else if (cls.isCrossExtend)
            {
                var scls = cls.super;
                while (!scls.isLink_System)
                {
                    scls = scls.super;
                }

                var cextend = scls.staticClass.linkObjCreator;
                var func    = swc.getNativeFunction(((ClassMethodGetter)cextend.bindField).functionId);

                if (func == null)
                {
                    errinfo = cls.ToString() + " create crossextend object failed, creator function not found";
                    return(null);
                }

                string err; int no;
                ASBinCode.rtData.rtObjectBase rtObj =
                    func.execute(null,null,cls,out err,out no) as ASBinCode.rtData.rtObjectBase;
                linkrtobj = rtObj;
                if (rtObj == null)
                {
                    errinfo = cls.ToString() + " create crossextend object failed";
                    return(null);
                }
                else
                {
                    LinkSystemObject lo = (LinkSystemObject)rtObj.value;
                    return(lo);
                }
            }
            else if (
                swc.DictionaryClass != null
                &&
                ClassMemberFinder.isInherits(cls,swc.DictionaryClass))
            {
                obj = new DictionaryObject(cls);
            }
            else if (cls.dynamic)
            {
                if (cls.isUnmanaged)
                {
                    obj = new HostedDynamicObject(cls);
                }
                else
                {
                    obj = new DynamicObject(cls);
                }
            }
            else if (cls.isUnmanaged)
            {
                obj = new HostedObject(cls);
            }
            else
            {
                obj = new ASBinCode.rtti.Object(cls);
            }

            return(obj);
        }
Beispiel #27
0
 public IMutableDictionary SetDictionary(string key, DictionaryObject value)
 {
     SetObject(key, value);
     return(this);
 }
Beispiel #28
0
        private bool WriteObject(StreamObject obj)
        {
            if (obj == null)
                return false;

            var options = new DictionaryObject()
                .Set("Length", obj.Length)
                /*
                .Set("Filters", new ArrayObject()
                     .Add(new NameObject("ASCII85Decode"))
                     .Add(new NameObject("LZWDecode")))
                */
                ;
            WriteObject(options);
            WriteLine().WriteLine("stream");

            /*
            StringWriter w = new StringWriter();
            PdfOutput inner = new PdfOutput(w);
            inner.WriteStream(obj.Value);
            string raw = w.ToString();

            // byte[] compressed = LZW.Encode(raw);
            var lzwByteStream = LZW.ToByteStream(raw);

            w = new StringWriter();

            Ascii85.Encode(lzwByteStream, w);

            int start = _writer.Position;
            _writer.Write(w);
            _writer.WriteLine();
            int length = _writer.Position - start;
            // */

            // /*
            int start = _writer.Position;
            WriteStream(obj.Value);
            int length = _writer.Position - start;
            // */

            Write("endstream");

            obj.Length.Get<IntegerNumberObject>().Value = length;

            return true;
        }
 protected abstract DictionaryObject DoPrediction(DictionaryObject input);
Beispiel #30
0
        private DocumentCatalog ReadXRef(Tokenizer tokenizer)
        {
            long xrefPosition = XrefPosition(tokenizer);

            tokenizer.MoveToPosition(xrefPosition);

            Token token = tokenizer.Token();

            if (!TokenValidator.Validate(token, CharacterSetType.Regular, "xref"))
            {
                throw new PdfException(PdfExceptionCodes.INVALID_XREF, "Expected xref");
            }

            token = tokenizer.Token();
            if (!TokenValidator.IsWhiteSpace(token))
            {
                throw new PdfException(PdfExceptionCodes.INVALID_XREF, "after xref must be a whitspace");
            }

            tokenizer.GetInteger();                         // objectNumber
            tokenizer.TokenExcludedComments();
            int numberOfEntries = tokenizer.GetInteger();

            tokenizer.TokenExcludedComments();

            PDFObjects pdfObjects = new PDFObjects();

            for (int i = 0; i < numberOfEntries; i++)
            {
                int pos = tokenizer.GetInteger();           // position
                tokenizer.TokenExcludedComments();          // whitespace
                tokenizer.GetInteger();                     // generation
                tokenizer.TokenExcludedComments();          // whitespace
                string type = tokenizer.Token().ToString(); // f or n
                tokenizer.TokenExcludedComments();          // whitespace

                if (type != "f" && type != "n")
                {
                    throw new PdfException(PdfExceptionCodes.INVALID_XREF, "only xref f or n entries allowed");
                }

                if (type == "f")      // free element
                {
                    continue;
                }

                tokenizer.SavePosition();
                tokenizer.MoveToPosition(pos);

                IndirectObject obj = new IndirectObject(tokenizer);
                pdfObjects.AddObject(obj);
                tokenizer.RestorePosition();
            }

            if (tokenizer.Token().ToString() != "trailer")
            {
                throw new PdfException(PdfExceptionCodes.INVALID_TRAILER, "expected trailer");
            }

            var trailer      = new DictionaryObject(tokenizer);
            var rootIndirect = (IndirectReferenceObject)trailer.Dictionary["Root"];

            return(pdfObjects.GetDocument <DocumentCatalog>(rootIndirect));
        }
 protected override DictionaryObject DoPrediction(DictionaryObject input)
 {
     return(input);
 }
Beispiel #32
0
        public void WriteWithDictionary()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();

            options.SetupExtensions();
            options.Converters.Add(new JsonStringEnumConverter());

            const string json = @"{""IntDictionary"":{""1"":1,""2"":2},""UIntDictionary"":{""1"":{""IntValue"":1},""2"":{""IntValue"":2}},""StringDictionary"":{""1"":[{""IntValue"":11},{""IntValue"":12}],""2"":[{""IntValue"":21},{""IntValue"":22}]},""EnumDictionary"":{""Value1"":{""1"":{""IntValue"":11},""2"":{""IntValue"":12}},""Value2"":{""1"":{""IntValue"":21},""2"":{""IntValue"":22}}}}";

            DictionaryObject obj = new DictionaryObject
            {
                IntDictionary = new Dictionary <int, int>
                {
                    { 1, 1 },
                    { 2, 2 }
                },
                UIntDictionary = new Dictionary <uint, IntObject>
                {
                    { 1, new IntObject {
                          IntValue = 1
                      } },
                    { 2, new IntObject {
                          IntValue = 2
                      } }
                },
                StringDictionary = new Dictionary <string, List <IntObject> >
                {
                    { "1", new List <IntObject> {
                          new IntObject {
                              IntValue = 11
                          }, new IntObject {
                              IntValue = 12
                          }
                      } },
                    { "2", new List <IntObject> {
                          new IntObject {
                              IntValue = 21
                          }, new IntObject {
                              IntValue = 22
                          }
                      } }
                },
                EnumDictionary = new Dictionary <EnumTest, Dictionary <int, IntObject> >
                {
                    {
                        EnumTest.Value1, new Dictionary <int, IntObject>
                        {
                            { 1, new IntObject {
                                  IntValue = 11
                              } },
                            { 2, new IntObject {
                                  IntValue = 12
                              } }
                        }
                    },
                    {
                        EnumTest.Value2, new Dictionary <int, IntObject>
                        {
                            { 1, new IntObject {
                                  IntValue = 21
                              } },
                            { 2, new IntObject {
                                  IntValue = 22
                              } }
                        }
                    }
                }
            };

            Helper.TestWrite(obj, json, options);
        }
Beispiel #33
0
        private bool WriteObject(DictionaryObject obj)
        {
            if (obj == null)
                return false;

            WriteLine("<<").Indent();
            foreach (var baseObject in obj.Objects) {
                WriteIndent();
                WriteObject(baseObject.Key);
                Write(" ");
                WriteObject(baseObject.Value);
                WriteLine();
            }

            Outdent().WriteIndent().Write(">>");
            return true;
        }