Ejemplo n.º 1
0
 public void GetKeys()
 {
     DObject
     .Create(new { Array = new[] { 1, 2, 3 }, Object = new object(), String = "string" })
     .GetKeys()
     .ShouldBe(new[] { "Array", "Object", "String" });
 }
Ejemplo n.º 2
0
 public void CreateFromDictionary()
 {
     DObject.Create(new Dictionary <string, object> {
         { "key", "value" }
     })
     .Contains("key");
 }
Ejemplo n.º 3
0
 public void CreateFromUnsupportedType()
 {
     Should.Throw <InvalidCastException>(() => DObject.Create(null));
     Should.Throw <InvalidCastException>(() => DObject.Create(""));
     Should.Throw <InvalidCastException>(() => DObject.Create(0));
     Should.Throw <InvalidCastException>(() => DObject.Create(new object[] { }));
 }
Ejemplo n.º 4
0
        public void GetObjectData(object /*!*/ obj, SerializationInfo /*!*/ info, StreamingContext context)
        {
            DObject instance = (DObject)obj;

            if ((context.State & StreamingContextStates.Persistence) != StreamingContextStates.Persistence)
            {
                Serialization.DebugInstanceSerialized(instance, false);

                // serialization is requested by Remoting -> serialize everything and do not change type
                MemberInfo[] members = FormatterServices.GetSerializableMembers(instance.GetType());
                info.AddValue(MembersSerializationInfoKey, FormatterServices.GetObjectData(instance, members));
            }
            else
            {
                Serialization.DebugInstanceSerialized(instance, true);

                // Serialization was requested by the user via the serialize() PHP function so it is possible that
                // the type of this instance will be undefined at deserialization time.

                if (instance.RealObject is Library.SPL.Serializable)
                {
                    // the instance is PHP5.1 serializable -> reroute the deserialization to SPLDeserializer
                    SPLDeserializer.GetObjectData(instance, info, context);
                }
                else
                {
                    // otherwise reroute the deserialization to Deserializer, which handles __sleep
                    Deserializer.GetObjectData(instance, info, context);
                }
            }
        }
Ejemplo n.º 5
0
        new public static void GetObjectData(DObject /*!*/ instance, SerializationInfo /*!*/ info, StreamingContext strctx)
        {
            info.SetType(typeof(SPLDeserializer));

            SerializationContext context = SerializationContext.CreateFromStreamingContext(strctx);

            object res = PhpVariable.Dereference(instance.InvokeMethod("serialize", null, context.ScriptContext));

            if (res == null)
            {
                // serialize returned NULL -> this instance will deserialize as NULL
                info.AddValue(__PHP_Incomplete_Class.ClassNameFieldName, String.Empty);
            }
            else
            {
                string res_str = PhpVariable.AsString(res);
                if (res_str == null)
                {
                    // serialize did not return NULL nor a string -> throw an exception
                    Library.SPL.Exception.ThrowSplException(
                        _ctx => new Library.SPL.Exception(_ctx, true),
                        context.ScriptContext,
                        string.Format(CoreResources.serialize_must_return_null_or_string, instance.TypeName), 0, null);
                }

                info.AddValue(SerializedDataFieldName, res_str);
                info.AddValue(__PHP_Incomplete_Class.ClassNameFieldName, instance.TypeName);
            }
        }
Ejemplo n.º 6
0
        public DChunk ChunkByAddress(uint aAddress)
        {
            DObjectCon con = ContainerByType(DObject.TObjectType.EChunk);
            DObject    ret = con[aAddress];

            return((ret != null) ? ret as DChunk : null);
        }
Ejemplo n.º 7
0
        public DLibrary LibraryByAddress(uint aAddress)
        {
            DObjectCon con = ContainerByType(DObject.TObjectType.ELibrary);
            DObject    ret = con[aAddress];

            return((ret != null) ? ret as DLibrary : null);
        }
Ejemplo n.º 8
0
        public DProcess ProcessByAddress(uint aAddress)
        {
            DObjectCon con = ContainerByType(DObject.TObjectType.EProcess);
            DObject    ret = con[aAddress];

            return((ret != null) ? ret as DProcess : null);
        }
Ejemplo n.º 9
0
        public DThread ThreadByAddress(uint aAddress)
        {
            DObjectCon con = ContainerByType(DObject.TObjectType.EThread);
            DObject    ret = con[aAddress];

            return((ret != null)? ret as DThread : null);
        }
Ejemplo n.º 10
0
        private static string GetObjectTitle(DObject obj, MType type)
        {
            if (type.Id == MType.SMART_FOLDER_ID && obj.Attributes.ContainsKey(SystemAttributes.SMART_FOLDER_TITLE))
            {
                return(obj.Attributes[SystemAttributes.SMART_FOLDER_TITLE].ToString());
            }

            if (obj.Id == DObject.RootId)
            {
                return(type.Title);
            }

            var sb        = new StringBuilder();
            var attibutes = AttributeFormatter.Format(type, obj.Attributes);

            foreach (var displayableAttr in type.GetDisplayAttributes())
            {
                var attributeText = GetAttributeText(obj, attibutes, displayableAttr);
                if (sb.Length != 0 && !string.IsNullOrEmpty(attributeText))
                {
                    sb.Append(Constants.PROJECT_TITLE_ATTRIBUTES_DELIMITER);
                }
                sb.Append(attributeText);
            }
            return(sb.ToString());
        }
Ejemplo n.º 11
0
        public DObject ExecuteFunction(InterpreterLocation functionLocation)
        {
            int originalDepth = depth;

            Eat("l curly");

            returnValue = null;

            while (depth != originalDepth)
            {
                if (returnValue != null || shouldBreak)
                {
                    while (depth > originalDepth + 1)
                    {
                        Eat();
                    }

                    break;
                }

                evaluator.Evaluate();
            }

            var v = returnValue == null ? DVoid.instance : returnValue;

            returnValue = null;

            return(v);
        }
Ejemplo n.º 12
0
        static PhpReference GetRefMemberNotFound(DObject self, string name, DTypeDesc caller)
        {
            PhpReference reference;
            bool         getter_exists;

            // search in RT fields
            if (self.RuntimeFields != null && self.RuntimeFields.ContainsKey(name))
            {
                var namekey = new IntStringKey(name);
                return(self.RuntimeFields.table._ensure_item_ref(ref namekey, self.RuntimeFields));
            }

            // property is not present -> try to invoke __get
            reference = self.InvokeGetterRef(name, caller, out getter_exists);
            if (getter_exists)
            {
                return((reference == null) ? new PhpReference() : reference);
            }

            // (no notice/warning/error thrown by PHP)

            // add the field
            reference = new PhpReference();
            if (self.RuntimeFields == null)
            {
                self.RuntimeFields = new PhpArray();
            }
            self.RuntimeFields[name] = reference;

            return(reference);
        }
Ejemplo n.º 13
0
        private DFile GetFile(long version, DObject obj)
        {
            var versionUniversalTime = new DateTime(version);

            if (obj.ActualFileSnapshot.Created.Equals(versionUniversalTime) || version == 0)
            {
                var file = obj.ActualFileSnapshot.Files.FirstOrDefault();
                if (file != null)
                {
                    VersionTime = obj.ActualFileSnapshot.Created;
                    Author      = _repository.GetPerson(obj.ActualFileSnapshot.CreatorId).DisplayName;
                }
                return(file);
            }
            var snapshot = obj.PreviousFileSnapshots.FirstOrDefault(o => o.Created.Equals(versionUniversalTime));

            if (snapshot != null)
            {
                IsActual = false;
                var file = snapshot.Files.FirstOrDefault();
                if (file != null)
                {
                    if (!string.IsNullOrEmpty(snapshot.Reason))
                    {
                        VersionReason = string.Format("\"{0}\"", snapshot.Reason);
                    }
                    VersionTime = snapshot.Created;
                    Author      = GetPersonDisplayName(snapshot.CreatorId);
                }
                return(file);
            }
            return(null);
        }
Ejemplo n.º 14
0
        protected StateContainerBase(CrashDebuggerParser aParser)
            : base(aParser)
        {
            DObject temp = CreateNewObject();

            iObjectType = temp.Type;
        }
Ejemplo n.º 15
0
        public JsonResult InsertChangeOrder(ECO _param)
        {
            int resultOid = 0;

            try
            {
                DaoFactory.BeginTransaction();
                //       DObjectRepository.UdtLatestDObject(new DObject { OID = _param.OID });

                DObject dobj = new DObject();
                dobj.Type        = EoConstant.TYPE_CHANGE_ORDER;
                dobj.TableNm     = EoConstant.TABLE_CHANGE_ORDER;
                dobj.Name        = _param.Name;
                dobj.Description = _param.Description;
                //dobj.TdmxOID = DObjectRepository.SelTdmxOID(new DObject { Type = DocumentContant.TYPE_DOCUMENT });
                resultOid = DObjectRepository.InsDObject(dobj);

                _param.OID = resultOid;
                //_param.DocType = _param.DocType;
                //_param.Title = _param.Title;
                //_param.Eo_No = _param.Eo_No;
                DaoFactory.SetInsert("ChangeOrder.InsChangeOrder", _param);

                DaoFactory.Commit();
            }
            catch (Exception ex)
            {
                DaoFactory.Rollback();
                return(Json(new ResultJsonModel {
                    isError = true, resultMessage = ex.Message, resultDescription = ex.ToString()
                }));
            }
            return(Json(resultOid));
        }
Ejemplo n.º 16
0
        internal static object GetUserArrayItem(DObject /*!*/ arrayAccess, object index, Operators.GetItemKinds kind)
        {
            PhpStack stack = ScriptContext.CurrentContext.Stack;

            switch (kind)
            {
            case Operators.GetItemKinds.Isset:
                // pass isset() ""/null to say true/false depending on the value returned from "offsetExists":
                stack.AddFrame(index);
                return(Core.Convert.ObjectToBoolean(arrayAccess.InvokeMethod(offsetExists, null, stack.Context)) ? "" : null);

            case Operators.GetItemKinds.Empty:
                // if "offsetExists" returns false, the empty()/isset() returns false (pass null to say true/false):
                // otherwise, "offsetGet" is called to retrieve the value, which is passed to isset():
                stack.AddFrame(index);
                if (!Core.Convert.ObjectToBoolean(arrayAccess.InvokeMethod(offsetExists, null, stack.Context)))
                {
                    return(null);
                }
                else
                {
                    goto default;
                }

            default:
                // regular getter:
                stack.AddFrame(index);
                return(PhpVariable.Dereference(arrayAccess.InvokeMethod(offsetGet, null, stack.Context)));
            }
        }
Ejemplo n.º 17
0
        private void SimpleGetTest(string path, DObject expected)
        {
            DObjectNavigator nav = new DObjectNavigator(_root);
            DObjectNavigator selector = nav.Select(path);

            Assert.AreEqual(expected, selector.Get());
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Переподключиться к БД
        /// </summary>
        /// <returns>возвращает NULL в случае успешного подключения или ошибку</returns>
        public static Exception Reconnect()
        {
            try
            {
                // Проверка необходимости переподключения
                DObject rootObj = DALContext.Repository.GetObjects(new[] { DObject.RootId }).First();

                return(null);
            }
            catch
            {
                if (DALContext == null)
                {
                    throw new Exception("Не определен класс \'DALContext\'");
                }
                else if (Credentials == null)
                {
                    throw new Exception("Не определен класс \'Credentials\'");
                }

                // Переподключение к БД
                Exception except = DALContext.Connect(Credentials);
                return(except);
            }
        }
Ejemplo n.º 19
0
        public JsonResult InsProblemsLibrary(ProblemsLibrary _param)
        {
            int resultOid = 0;

            try
            {
                DaoFactory.BeginTransaction();

                DObject dobj = new DObject();
                dobj.Type        = EcontentsConstant.TYPE_ECONTENTS;
                dobj.TableNm     = EcontentsConstant.TABLE_PROBLEMS_LIBRARY;
                dobj.Name        = _param.Name;
                dobj.Description = _param.Description;

                resultOid = DObjectRepository.InsDObject(dobj);

                _param.OID = resultOid;
                DaoFactory.SetInsert("Econtents.InsProblemsLibrary", _param);

                DaoFactory.Commit();
            }
            catch (Exception ex)
            {
                DaoFactory.Rollback();
                return(Json(new ResultJsonModel {
                    isError = true, resultMessage = ex.Message, resultDescription = ex.ToString()
                }));
            }
            return(Json(resultOid));
        }
Ejemplo n.º 20
0
 // Use this for initialization
 void Start()
 {
     active = this;
     DObject.addListener(this);
     Respawn.addListener(this);
     startEngine();
 }
Ejemplo n.º 21
0
        private Guid[] GetChildrenByType(DObject obj, ChildrenType type)
        {
            var childIds = new Guid[0];

            switch (type)
            {
            case ChildrenType.All:
                childIds = obj.Children.Select(c => c.ObjectId).ToArray();
                break;

            case ChildrenType.ListView:
                childIds = obj.GetChildrenForListView(this).ToArray();
                break;

            case ChildrenType.TreeView:
                break;

            case ChildrenType.Storage:
                childIds = obj.GetChildrenForPilotStorage(this).ToArray();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(type), type, null);
            }

            return(childIds);
        }
Ejemplo n.º 22
0
            /// <summary>
            /// Serializes a <see cref="DObject"/>.
            /// </summary>
            /// <param name="value">The object.</param>
            private void WriteDObject(DObject value)
            {
                __PHP_Incomplete_Class pic;

                // write out properties
                WriteJsonObject(JsonObjectProperties(value, (pic = value as __PHP_Incomplete_Class) != null && pic.__PHP_Incomplete_Class_Name.IsSet));
            }
Ejemplo n.º 23
0
        public static void GetInheritFieldUsingIC(DObject obj, int fieldId, ref DValue v, int mapId, int fieldIndex, int inheritObjectCacheIndex)
        {
#if __STAT__PD
            if (mdr.Runtime.Instance.Configuration.ProfileStats)
            {
                mdr.Runtime.Instance.Counters.GetCounter("Inh IC calls").Count++;
            }
#endif
            if (mapId == obj.MapId)
            {
                DObject patentObj = JSRuntime._inheritPropertyObjectCache[inheritObjectCacheIndex];
                if (patentObj != null)
                {
                    v = patentObj.Fields[fieldIndex];
#if __STAT__PD
                    if (mdr.Runtime.Instance.Configuration.ProfileStats)
                    {
                        mdr.Runtime.Instance.Counters.GetCounter("Inh IC hits").Count++;
                        mdr.Runtime.Instance.Counters.GetCounter("Inh IC hit oindex_" + inheritObjectCacheIndex).Count++;
                        mdr.Runtime.Instance.Counters.GetCounter("Inh IC hit findex_" + fieldIndex).Count++;
                    }
#endif
                }
            }
            else
            {
                obj.GetPropertyDescriptorByFieldId(fieldId).Get(obj, ref v);
#if __STAT__PD
                if (mdr.Runtime.Instance.Configuration.ProfileStats)
                {
                    mdr.Runtime.Instance.Counters.GetCounter("Inh IC misses").Count++;
                }
#endif
            }
        }
Ejemplo n.º 24
0
        private object BindObject(DObject obj, Type targetType)
        {
            object instance = Activator.CreateInstance(targetType);// no ctor parameters

            FieldInfo[] fi = targetType.GetFields(BindingFlags.Public | BindingFlags.Instance);
            object      value;

            foreach (var field in fi)
            {
                if (SetSpecifiedField(instance, field))
                {
                    continue;
                }

                value = obj.GetProperty(field.Name, null, true);

                if (value != null)
                {
                    field.SetValue(instance, Bind(value, field.FieldType));
                }
            }

            lastPrimitive = false;

            return(instance);
        }
Ejemplo n.º 25
0
        public static void GetFieldUsingIC(DObject obj, int fieldId, ref DValue v, int mapId, int fieldIndex)
        {
#if __STAT__PD
            if (mdr.Runtime.Instance.Configuration.ProfileStats)
            {
                mdr.Runtime.Instance.Counters.GetCounter("IC calls").Count++;
            }
#endif
            if (mapId == obj.MapId)
            {
                v = obj.Fields[fieldIndex];
#if __STAT__PD
                if (mdr.Runtime.Instance.Configuration.ProfileStats)
                {
                    mdr.Runtime.Instance.Counters.GetCounter("IC hit").Count++;
                    mdr.Runtime.Instance.Counters.GetCounter("IC hit findex_" + fieldIndex).Count++;
                }
#endif
            }
            else
            {
                obj.GetPropertyDescriptorByFieldId(fieldId).Get(obj, ref v);
#if __STAT__PD
                if (mdr.Runtime.Instance.Configuration.ProfileStats)
                {
                    mdr.Runtime.Instance.Counters.GetCounter("IC miss").Count++;
                }
#endif
            }
        }
Ejemplo n.º 26
0
        //批量上传独家优惠到前台
        private void updjyhClick(object sender, RoutedEventArgs e)
        {
            int count = djyhlo.Count();//-当前对象列表-数据剩余条数
            //  System.Windows.MessageBox.Show("数据结果:" + count);
            //***************************
            //循环上传对象列表中的精选商品数据
            int sum = 0;

            for (int i = 0; i < count; i++)
            {
                DObject Dobj    = djyhlo[i] as DObject;
                string  modeStr = "mode=setdjyhdata&spid=" + Dobj.spid + "&splm=" + Dobj.splm + "&imgurl01=" + Dobj.imgurl01 + "&sptitle=" + Dobj.sptitle + "&dplx=" + Dobj.dplx + "&price=" + Dobj.price + "&purchase=" + Dobj.purchase + "&quanPrice=" + Dobj.quanprice + "&outtime=" + Dobj.outtime + "&yhqtgurl=" + Dobj.yhqtgurl + "&xianprice=" + Dobj.xianprice;
                string  str     = WebServiceApp(modeStr);
                //  System.Windows.MessageBox.Show("服务器返回数据:" + str);
                if (str == "no item!")
                {
                    System.Windows.MessageBox.Show("插入的商品已不存在,请核实!" + str);
                    string   result = WebServiceApp("mode=updatahtdjyh&flag=-1&spid=" + Dobj.spid.ToString());
                    string[] res    = result.Split(new Char[] { '"' });
                    if (res[1].ToString() == "1")
                    {
                        sum++;
                        Border br = djyharrayBr[int.Parse(Dobj.uid)] as Border;
                        djyhlbBox.Items.Remove(br);
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("更新数据未成功!错误码:" + res[1]);
                    }
                }
                else
                {
                    string[] tt = str.Split(new Char[] { '"' });

                    if (tt[1].ToString() == "1")
                    {
                        string   result = WebServiceApp("mode=updatahtdjyh&flag=-1&spid=" + Dobj.spid.ToString());
                        string[] res    = result.Split(new Char[] { '"' });
                        if (res[1].ToString() == "1")
                        {
                            sum++;
                            Border br = djyharrayBr[int.Parse(Dobj.uid)] as Border;
                            djyhlbBox.Items.Remove(br);
                        }
                        else
                        {
                            System.Windows.MessageBox.Show("更新数据未成功!错误码:" + res[1]);
                        }
                    }
                    else
                    {
                        System.Windows.MessageBox.Show("插入数据未成功!错误码:" + string.Join("|", tt));
                    }
                };
            }

            djyharrayBr.Clear();
            djyhlo.Clear();
            System.Windows.MessageBox.Show("总共" + count + "条数据,成功插入" + sum + "条数据!" + arrayBr.Count);
        }
Ejemplo n.º 27
0
        protected virtual void CreateEntryParagraphs(DObject aObject)
        {
            string          name = "ENTRY [" + Container.TypeDescription + "]";
            ParserParagraph para = iHelperDObject.CreateMonitorObjectParagraph(name, aObject);

            ParserEngine.Add(para);
        }
Ejemplo n.º 28
0
        public static bool PropertyExists(DTypeDesc caller, object classNameOrObject, string propertyName)
        {
            ScriptContext context = ScriptContext.CurrentContext;
            DTypeDesc     type    = ClassNameOrObjectToType(context, null, caller, classNameOrObject, true);

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

            // determine the calling class context
            //DTypeDesc caller = PhpStackTrace.GetClassContext();
            if (caller != null && caller.IsUnknown)
            {
                caller = PhpStackTrace.GetClassContext();
            }

            DPropertyDesc property;

            if (type.GetProperty(new VariableName(propertyName), caller, out property) == GetMemberResult.OK)
            {
                // CT property was found
                return(true);
            }
            else
            {
                // search RT fields, if possible
                DObject obj = classNameOrObject as DObject;
                return(obj != null && obj.RuntimeFields != null && obj.RuntimeFields.ContainsKey(propertyName));
            }
        }
Ejemplo n.º 29
0
        private void DefineProperty(DObject O, string name, DObject desc)
        {
          if (desc == null || O == null || name == null)
            Trace.Fail("TypeError");

          var getter = new DValue();
          var setter = new DValue();
          var value = new DValue();
          var attributes = PropertyDescriptor.Attributes.NotEnumerable | PropertyDescriptor.Attributes.NotWritable | PropertyDescriptor.Attributes.NotConfigurable;

          attributes = PropertyDescriptor.Attributes.NotEnumerable | PropertyDescriptor.Attributes.NotWritable | PropertyDescriptor.Attributes.NotConfigurable;

          getter.SetUndefined();
          setter.SetUndefined();
          value.SetUndefined();

          value = desc.HasProperty("value") ? desc.GetField("value") : value;

          if (desc.HasProperty("enumerable"))
            attributes &= desc.GetField("enumerable").AsBoolean() ? ~PropertyDescriptor.Attributes.NotEnumerable : attributes;


          if (desc.HasProperty("configurable"))
            attributes &= desc.GetField("configurable").AsBoolean() ? ~PropertyDescriptor.Attributes.NotConfigurable : attributes;

          if (desc.HasProperty("writable"))
            attributes &= desc.GetField("writable").AsBoolean() ? ~PropertyDescriptor.Attributes.NotWritable : attributes;

          if (desc.HasProperty("get"))
          {
            getter = desc.GetField("get");
            if (!ValueTypesHelper.IsUndefined(getter.ValueType) && !ValueTypesHelper.IsFunction(getter.ValueType))
              Trace.Fail("TypeError");
          }

          if (desc.HasProperty("set"))
          {
            setter = desc.GetField("set");
            if (!ValueTypesHelper.IsUndefined(setter.ValueType) && !ValueTypesHelper.IsFunction(setter.ValueType))
              Trace.Fail("TypeError");
          }

          Trace.Assert(
            !((desc.HasProperty("get") || desc.HasProperty("set"))
            && (desc.HasProperty("value") || desc.HasProperty("writable"))),
            "If either getter or setter needs to be defined, value or writable shouldn't be defined.");

          if (desc.HasProperty("value"))
            O.DefineOwnProperty(name, ref value, attributes | PropertyDescriptor.Attributes.Data);
          else
          {
            var property = new DProperty();
            if (ValueTypesHelper.IsFunction(getter.ValueType))
              property.Getter = getter.AsDFunction();
            if (ValueTypesHelper.IsFunction(setter.ValueType))
              property.Setter = setter.AsDFunction();

            O.DefineOwnProperty(name, property, attributes | PropertyDescriptor.Attributes.Accessor);
          }
        }
Ejemplo n.º 30
0
 public void Set(DObject v)
 {
     if (v == null)
         Object = DObject.Undefined;
     else
         v.CopyTo(this);
 }
Ejemplo n.º 31
0
        public CSV(AttributeOf selector = null)
        {
            DProperty[] Props;
            Props = DObject.GetProperties <T>();
            var t = new List <DProperty>();
            var x = new List <DProperty>();

            foreach (var p in Props)
            {
                var attr = selector == null ? p.Attribute : selector(p);
                if ((attr & PropertyAttribute.NonSerializable) == PropertyAttribute.NonSerializable)
                {
                    continue;
                }
                if ((attr & PropertyAttribute.SerializeAsId) == PropertyAttribute.SerializeAsId)
                {
                    x.Add(p);
                }
                else
                {
                    t.Add(p);
                }
            }
            FlProps = t.ToArray();
            IdProps = x.ToArray();
            s       = new StringBuilder();
        }
Ejemplo n.º 32
0
 public void Setup()
 {
     sw = new StringWriter();
     sr = new StringReader("");
     Console.SetOut(sw);
     prog = new DObject("TaskA.Programm");
 }
Ejemplo n.º 33
0
        public JsonResult InsRole(Role _param)
        {
            int result = 0;

            try
            {
                DaoFactory.BeginTransaction();

                DObject dobj = new DObject();
                dobj.Type = CommonConstant.TYPE_ROLE;
                dobj.Name = _param.Name;
                if (DObjectRepository.SelDObject(dobj) != null)
                {
                    throw new Exception("Role 중복입니다.");
                }
                result = DObjectRepository.InsDObject(dobj);
                DaoFactory.Commit();
            }
            catch (Exception ex)
            {
                DaoFactory.Rollback();
                return(Json(new ResultJsonModel {
                    isError = true, resultMessage = ex.Message, resultDescription = ex.ToString()
                }));
            }
            return(Json(result));
        }
Ejemplo n.º 34
0
        public ActorProxy(DObject dObject, ILogger logger)
        {
            this.dObject = dObject;
            this.logger = logger;
            handlers = new EventHandlersOnClientActor();

            this.dObject.OnGetEvent += OnGetEvent;
            handlers.ChangeColor += Handler_OnChangeColor;
        }
Ejemplo n.º 35
0
 /*** Сложение двух матриц ***/
 public DObject Add(DObject dobj)
 {
     if (sx != dobj.sx || sy != dobj.sy) return null;
     DObject ret = new DObject(sx, sy);
     for (int i = 0; i < matrix.Length; i++)
     {
         ret.matrix[i] = matrix[i] + dobj.matrix[i];
     }
     return ret;
 }
Ejemplo n.º 36
0
		// variables may be null when the code is global

		protected LinqContext(DObject outerType, Dictionary<string, object> variables, ScriptContext/*!*/ context, DTypeDesc typeHandle)
		{
			if (context == null)
				throw new ArgumentNullException("context");
			
			this.variables = variables;
			this.outerType = outerType;
			this.context = context;
			this.typeHandle = typeHandle;
		}
Ejemplo n.º 37
0
 /***  Создать копию объекта ***/
 public void clone(DObject dobj)
 {
     if ((sx * sy) != (dobj.sx * dobj.sy)) matrix = new double[dobj.sx * dobj.sy];
     sx = dobj.sx;
     sy = dobj.sy;
     for (int i = 0; i < sx*sy; i++)
     {
         matrix[i] = dobj.matrix[i];
     }
 }
Ejemplo n.º 38
0
    public PropertyMapMetadata(DObject prototype)
    {
      Prototype = prototype;
      if (Prototype == null)
        Level = 0;
      else
        Level = Prototype.Map.Metadata.Level + 1;

      //We create an empty ProperyDescriptor to avoid checking for null all the time
      Root = new PropertyMap(this, null, new PropertyDescriptor(null, Runtime.InvalidFieldId, Runtime.InvalidFieldIndex, PropertyDescriptor.Attributes.NotEnumerable | PropertyDescriptor.Attributes.Undefined), null);
    }
Ejemplo n.º 39
0
        public void QuoteObject(DObject obj)
        {
            Message msg = new Message
            {
                OpCode = MessageOpCode.Quote,
                AckNumber = this._ackNumber
            };

            msg.Attributes["object"] = obj;

            _channel.SendMessage(msg);
        }
Ejemplo n.º 40
0
    public PropertyMapMetadata GetMapMetadataOfPrototype(DObject prototype, bool addIfMissing = true)
    {
      Debug.Assert(prototype != null, "cannot lookup type information for null prototype");

      WeakReference emptyNode = null; //sice we use weakref, we might want to reuse emty elements of the list

#if !SEARCH_CHILDREN_LIST //TODO: we can explore the effect of the following by commening the next few lines
      if (prototype.SubMapsMetadata != null)
        return prototype.SubMapsMetadata;

      var iter = _children.GetEnumerator();
      while (iter.MoveNext())
      {
        var childRef = iter.Current;
        if (!childRef.IsAlive)
        {
          emptyNode = childRef;
          break;
        }
      }
#else
      var iter = _children.GetEnumerator();
      while (iter.MoveNext())
      {
        var childRef = iter.Current;
        if (childRef.IsAlive)
        {
          var child = childRef.Target as PropertyMapMetadata;
          if (child.Prototype == prototype)
            return child;
        }
        else if (emptyNode == null)
          emptyNode = childRef;
      }
#endif
      ///Ok, we did not find any, let's add one to the list
      if (!addIfMissing)
        return null;

      var newRoot = new PropertyMapMetadata(prototype);
      if (emptyNode == null)
      {
        emptyNode = new WeakReference(newRoot);
        _children.AddLast(emptyNode);
      }
      else
        emptyNode.Target = newRoot;

      prototype.SubMapsMetadata = newRoot;

      return newRoot;
    }
Ejemplo n.º 41
0
 public DForwardingProperty (DObject receiver, string field)
 {
     Receiver = receiver;
     ReceiverPD = Receiver.Map.GetPropertyDescriptor(field);
     Debug.Assert(ReceiverPD != null, "receiver field has null descriptor: " + field);
     OnGetDValue = (DObject This, ref DValue v) =>
     {
         ReceiverPD.Get(Receiver, ref v);
     };
     OnSetDValue = (DObject This, ref DValue v) =>
     {
         ReceiverPD.Set(Receiver, ref v);
     };
 }
        public FrontEndServer(IServerCommunicator communicator, ILogger logger, int sleepTimer, IServerDOManager dOManager)
        {
            this.communicator = communicator;
            this.logger = logger;
            this.sleepTimer = sleepTimer;
            this.dOManager = dOManager;

            // Create root DObject
            // TODO - DObject should have OnGetEvent property.
            DObject newObject = new DObject(dOManager);
            newObject.OnGetEvent += RootDObjectHandler;
            rootDObject = newObject;
            dOManager.RegisterObject(newObject);
        }
Ejemplo n.º 43
0
        static PhpReference notsetOperation(DObject self, string name, DTypeDesc caller, PhpReference refrnc)
        {
            bool getter_exists;
            // the CT property has been unset -> try to invoke __get
            PhpReference get_ref = self.InvokeGetterRef(name, caller, out getter_exists);
            if (getter_exists) return get_ref ?? new PhpReference();

            Debug.Assert(refrnc != null);

            refrnc.IsAliased = true;
            refrnc.IsSet = true;

            return refrnc;
        }
Ejemplo n.º 44
0
        //#region ToX
        //public string ToString(DObject This) { return (OnGetString != null) ? OnGetString(This) : ToDValue().ToString(); }// base.ToString(); }
        //public double ToDouble(DObject This) { return (OnGetDouble != null) ? OnGetDouble(This) : ToDValue().ToDouble(); }// base.ToDouble(); }
        //public int ToInt(DObject This) { return (OnGetInt != null) ? OnGetInt(This) : ToDValue().ToInt32(); }// base.ToInt(); }
        //public bool ToBoolean(DObject This) { return (OnGetBoolean != null) ? OnGetBoolean(This) : ToDValue().ToBoolean(); }// base.ToBoolean(); }
        //public DObject ToDObject(DObject This) { return (OnGetDObject != null) ? OnGetDObject(This) : ToDValue().ToDObject(); }// base.ToDObject(); }
        //public DValue ToDValue(DObject This)
        //{
        //    if (OnGetDValue != null)
        //    {
        //        DValue temp = new DValue();
        //        OnGetDValue(This, ref temp);
        //        return temp;
        //    }
        //    else
        //    {
        //        return base.ToDValue();
        //    }
        //}
        //#endregion

        #region Get
        public void Get(DObject This, ref DValue v)
        {
            if (OnGetDValue != null)
                OnGetDValue(This, ref v);
            else if (Getter != null)
            {
                var callFrame = new CallFrame();
                callFrame.Function = Getter;
                callFrame.This = (This);
                Getter.Call(ref callFrame);
                v = callFrame.Return;
            }
            else
                v = base.ToDValue();
        }
        public void SetProperties() {
            var button1 = new Button();
            var parentViewModel = new ViewModel();
            var viewModel = new ViewModel();
            ViewModelExtensions.SetParameter(button1, "test");
            ViewModelExtensions.SetParentViewModel(button1, parentViewModel);

            var dObject = new DObject();
            ViewModelExtensions.SetParameter(dObject, "test");
            ViewModelExtensions.SetParentViewModel(dObject, parentViewModel);

            var button2 = new Button() { DataContext = viewModel };
            ViewModelExtensions.SetParameter(button2, "test");
            Assert.AreEqual("test", viewModel.With(x => x as ISupportParameter).Parameter);
            ViewModelExtensions.SetParentViewModel(button2, parentViewModel);
            Assert.AreEqual(parentViewModel, viewModel.With(x => x as ISupportParentViewModel).ParentViewModel);
        }
Ejemplo n.º 46
0
		/// <summary>
		/// Takes a regular expression <paramref name="pattern"/> and one of <paramref name="replacement"/> or 
		/// <paramref name="callback"/>. Performs replacing on <paramref name="data"/>, which can be
		/// <see cref="PhpArray"/>, in other cases it is converted to string.
		/// If <paramref name="data"/> is <see cref="PhpArray"/>, every value is converted to string and
		/// replacement is performed in place in this array.
		/// Either <paramref name="replacement"/> or <paramref name="callback"/> should be null.
		/// </summary>
		/// <param name="self">Instance of object that called the replace method (replace pattern may contain $this)</param>
		/// <param name="definedVariables">Array with local variables - can be used by replace pattern</param>
		/// <param name="pattern">Regular expression to search.</param>
		/// <param name="replacement">Regular replacement expression. Should be null if callback is specified.</param>
		/// <param name="callback">Callback function that should be called to make replacements. Should be null
		/// if replacement is specified.</param>
		/// <param name="data">Array or string where pattern is searched.</param>
		/// <param name="limit">Max count of replacements for each item in subject.</param>
		/// <param name="descriptor"><see cref="SourceCodeDescriptor"/> for possible lambda function creation.</param>
		/// <param name="count">Cumulated number of replacements.</param>
		/// <returns></returns>
		private static object SimpleReplace(DObject self, Dictionary<string, object> definedVariables, object pattern, 
			string replacement, PhpCallback callback, object data, int limit, SourceCodeDescriptor descriptor, ref int count)
		{
			Debug.Assert(limit >= -1);

			// exactly one of replacement or callback is valid:
			Debug.Assert(replacement != null ^ callback != null);

			PerlRegExpConverter converter = ConvertPattern(pattern, replacement);
			if (converter == null) return null;

			// get types of data we need:
			PhpArray data_array = data as PhpArray;
			string data_string = (data_array == null) ? ConvertData(data, converter) : null;

			// data comprising of a single string:
            if (data_array == null)
            {
                return ReplaceInternal(self, definedVariables, converter, callback, data_string, limit, descriptor, ref count);
            }
            else
            {
                // data is array, process each item:
                var enumerator = data_array.GetFastEnumerator();
                while (enumerator.MoveNext())
                {
                    enumerator.CurrentValue = ReplaceInternal(self, definedVariables, converter, callback,
                        ConvertData(enumerator.CurrentValue, converter), limit, descriptor, ref count);
                }
                enumerator.Dispose();

                // return array with items replaced:
                return data;
            }
		}
Ejemplo n.º 47
0
        public static void SetObjectProperty(DObject/*!*/ obj, string name, object value, DTypeDesc caller)
        {
            Debug.Assert(obj != null && name != null);

            if (ReferenceEquals(obj, ScriptContext.SetterChainSingletonObject))
            {
                ScriptContext context = ScriptContext.CurrentContext;

                if (value is PhpReference)
                {
                    context.AbortSetterChain(false);
                    return;
                }

                // extend and finish the setter chain
                context.ExtendSetterChain(new RuntimeChainProperty(name));
                context.FinishSetterChain(value);
                return;
            }

            obj.SetProperty(name, value, caller);
        }
Ejemplo n.º 48
0
        public static object Replace(ScriptContext/*!*/context, DObject self, Dictionary<string, object> definedVariables, 
			object pattern, object replacement, object data, int limit, out int count)
		{
			count = 0;
			return Replace(context, self, definedVariables, pattern, replacement, null, data, limit, ref count);
		}
Ejemplo n.º 49
0
		/// <summary>
		/// Private mehtod implementing all replace methods. Just one of <paramref name="replacement"/> or <paramref name="callback" /> should be used.
		/// </summary>
        /// <param name="context">Current <see cref="ScriptContext"/>. Must not be null.</param>
        /// <param name="self">Instance of object that called the replace method (replace pattern may contain $this)</param>
        /// <param name="definedVariables"></param>
        /// <param name="pattern"></param>
        /// <param name="replacement"></param>
        /// <param name="callback"></param>
        /// <param name="data"></param>
        /// <param name="limit"></param>
        /// <param name="count"></param>
		/// <returns>String or an array.</returns>
		private static object Replace(ScriptContext/*!*/context, DObject self, Dictionary<string, object> definedVariables, object pattern, object replacement, PhpCallback callback,
			object data, int limit, ref int count)
		{
			// if we have no replacement and no callback, matches are deleted (replaced by an empty string)
			if (replacement == null && callback == null)
				replacement = String.Empty;

			// exactly one of replacement or callback is valid now
			Debug.Assert(replacement != null ^ callback != null);

			// get eval info if it has been captured - is needed even if we do not need them later
            SourceCodeDescriptor descriptor = context.GetCapturedSourceCodeDescriptor();

			// PHP's behaviour for undocumented limit range
			if (limit < -1)
				limit = 0;
            
            PhpArray replacement_array = replacement as PhpArray;

			string replacement_string = null;
			if (replacement_array == null && replacement != null)
				replacement_string = Core.Convert.ObjectToString(replacement);

			// we should return new array, if there is an array passed as subject, it should remain unchanged:
			object data_copy = PhpVariable.DeepCopy(data);

            PhpArray pattern_array = pattern as PhpArray;
            if (pattern_array == null)
            {
                // string pattern
                // string replacement

                if (replacement_array != null)
                {
                    // string pattern and array replacement not allowed:
                    PhpException.InvalidArgument("replacement", LibResources.GetString("replacement_array_pattern_not"));
                    return null;
                }

                // pattern should be treated as string and therefore replacement too:
                return SimpleReplace(self, definedVariables, pattern, replacement_string, callback, data_copy, limit, descriptor, ref count);
            }
            else if (replacement_array == null)
            {
                // array  pattern
                // string replacement

                using (var pattern_enumerator = pattern_array.GetFastEnumerator())
                    while (pattern_enumerator.MoveNext())
                    {
                        data_copy = SimpleReplace(self, definedVariables, pattern_enumerator.CurrentValue, replacement_string,
                                    callback, data_copy, limit, descriptor, ref count);
                    }
            }
            else //if (replacement_array != null)
            {
                // array pattern
                // array replacement

                var replacement_enumerator = replacement_array.GetFastEnumerator();
                bool replacement_valid = true;

                using (var pattern_enumerator = pattern_array.GetFastEnumerator())
                    while (pattern_enumerator.MoveNext())
                    {
                        // replacements are in array, move to next item and take it if possible, in other case take empty string:
                        if (replacement_valid && replacement_enumerator.MoveNext())
                        {
                            replacement_string = Core.Convert.ObjectToString(replacement_enumerator.CurrentValue);
                        }
                        else
                        {
                            replacement_string = string.Empty;
                            replacement_valid = false;  // end of replacement_enumerator, do not call MoveNext again!
                        }

                        data_copy = SimpleReplace(self, definedVariables, pattern_enumerator.CurrentValue, replacement_string,
                                    callback, data_copy, limit, descriptor, ref count);
                    }
            }
            
			// return resulting array or string assigned to data
			return data_copy;
		}
Ejemplo n.º 50
0
			public Evaluator(Regex reg, string replacement, SourceCodeDescriptor sourceCodeDesc, DObject self, Dictionary<string, object> definedVariables)
			{
				this.reg = reg;
				this.definedVariables = definedVariables;
				this.replacement = replacement;
				this.sourceCodeDesc = sourceCodeDesc;
				this.count = 0;
				this.self = self;
			}
Ejemplo n.º 51
0
		public static object Replace(ScriptContext/*!*/context, DObject self, Dictionary<string, object> definedVariables, 
			object pattern, object replacement, object data)
		{
			int count = Int32.MinValue; // disables counting
			return Replace(context, self, definedVariables, pattern, replacement, null, data, -1, ref count);
		}
Ejemplo n.º 52
0
        public static DObject EnsurePropertyIsObject(DObject obj, string name, DTypeDesc caller,
            ScriptContext context)
        {
            Debug.Assert(name != null);

            if (ReferenceEquals(obj, ScriptContext.SetterChainSingletonObject))
            {
                // extend the setter chain if one already exists
                context.ExtendSetterChain(new RuntimeChainProperty(name));

                return ScriptContext.SetterChainSingletonObject;
            }

            // search in CT properties
            DPropertyDesc property;
            GetMemberResult get_res =
                obj.TypeDesc.GetProperty(new VariableName(name), caller, out property);

            if (get_res == GetMemberResult.BadVisibility)
            {
                DObject.ThrowPropertyVisibilityError(name, property, caller);
                return null;
            }

            DObject ret_val;
            object old_val, value;

            // was a CT property found?
            if (get_res == GetMemberResult.OK)
            {
                old_val = property.Get(obj);
                value = old_val;
                ret_val = EnsurePropertyIsObjectInternal(obj, name, caller, ref value, context);

                if (!Object.ReferenceEquals(value, old_val)) property.Set(obj, value);
            }
            else
            {
                // search in RT fields

                var namekey = new IntStringKey(name);
                if (obj.RuntimeFields != null && obj.RuntimeFields.TryGetValue(namekey, out old_val))
                {
                    //old_val = element.Value;
                }
                else
                {
                    PhpReference reference = new PhpSmartReference();
                    reference.IsSet = false;
                    old_val = reference;
                }

                value = old_val;
                ret_val = EnsurePropertyIsObjectInternal(obj, name, caller, ref value, context);

                if (!Object.ReferenceEquals(value, old_val))
                {
                    if (obj.RuntimeFields == null) obj.RuntimeFields = new PhpArray();
                    
                    obj.RuntimeFields[name] = value;
                }
            }

            return ret_val;
        }
Ejemplo n.º 53
0
		/// <summary>
		/// Replaces <paramref name="limit"/> occurences of substrings.
		/// </summary>
		/// <param name="converter">
		/// Converter used for replacement if <paramref name="callback"/> is <B>null</B>.
		/// </param>
		/// <param name="self">Instance of object that called the replace method (replace pattern may contain $this)</param>
		/// <param name="definedVariables">Array with local variables - can be used by replace pattern</param>
		/// <param name="callback">Callback to call for replacement strings.</param>
		/// <param name="str">String to search for matches.</param>
		/// <param name="limit">Max number of replacements performed.</param>
		/// <param name="sourceCodeDesc"><see cref="SourceCodeDescriptor"/> for possible lambda function creation.</param>
		/// <param name="count">Cumulated number of replacements.</param>
		/// <returns></returns>
		private static string ReplaceInternal(DObject self, Dictionary<string, object> definedVariables, PerlRegExpConverter converter, PhpCallback callback,
			string str, int limit, SourceCodeDescriptor sourceCodeDesc, ref int count)
		{
			Debug.Assert(limit >= -1);

			if (callback == null)
			{
				// replace without executing code or counting the number of replacements:
				if ((converter.PerlOptions & PerlRegexOptions.Evaluate) == 0 && count < 0)
					return converter.Regex.Replace(str, converter.DotNetReplaceExpression, limit);

				Evaluator evaluator = new Evaluator(converter.Regex, converter.DotNetReplaceExpression, sourceCodeDesc, self, definedVariables);
				MatchEvaluator match_evaluator;

				if ((converter.PerlOptions & PerlRegexOptions.Evaluate) != 0)
					match_evaluator = new MatchEvaluator(evaluator.ReplaceCodeExecute);
				else
					match_evaluator = new MatchEvaluator(evaluator.ReplaceCount);

				string result = converter.Regex.Replace(str, match_evaluator, limit);
				count += evaluator.Count;
				return result;
			}
			else
			{
                StringBuilder result = new StringBuilder((str != null) ? str.Length : 0);
				int last_index = 0;

				Match m = converter.Regex.Match(str);
				while (m.Success && (limit == -1 || limit-- > 0))
				{
					// append everything from input string to current match
					result.Append(str, last_index, m.Index - last_index);

					// move index after current match
					last_index = m.Index + m.Length;

					PhpArray arr = new PhpArray(m.Groups.Count, 0);
					for (int i = 0; i < m.Groups.Count; i++)
						arr[i] = m.Groups[i].Value;

					// append user callback function result
					string replacement = Core.Convert.ObjectToString(callback.Invoke(arr));
					result.Append(replacement);

					m = m.NextMatch();

					count++;
				}

				// remaining string
				result.Append(str, last_index, str.Length - last_index);
				return result.ToString();
			}
		}
Ejemplo n.º 54
0
        public static PhpReference InvokeStaticMethod(DTypeDesc type, object methodName, DObject self,
            DTypeDesc caller, ScriptContext context)
        {
            if (type == null)
            {
                // error thrown earlier
                return new PhpReference();
            }

            // verify that methodName is a string
            string name = PhpVariable.AsString(methodName);
            if (String.IsNullOrEmpty(name))
            {
                context.Stack.RemoveFrame();
                PhpException.Throw(PhpError.Error, CoreResources.GetString("invalid_method_name"));
                return new PhpReference();
            }

            // find the method desc
            bool isCallStaticMethod;
            DRoutineDesc method = GetStaticMethodDesc(type, name, ref self, caller, context, false, true, out isCallStaticMethod);

            if (method == null) return new PhpReference();

            // invoke the method
            object result;
            var stack = context.Stack;
            stack.LateStaticBindType = type;
               
            if (isCallStaticMethod)
            {
                // __callStatic was found instead, not {methodName}
                PhpArray args = stack.CollectFrame();   // get array with args, remove the previous stack

                // original parameters are passed to __callStatic in an array as the second parameter
                stack.AddFrame(methodName, args);
                result = method.Invoke(self, stack, caller);
            }
            else
            {
//                try
//                {
                    result = method.Invoke(self, stack, caller);
//                }
//                catch (NullReferenceException)
//                {
//                    if (self == null && !method.IsStatic)
//                    {   // $this was null, it is probably caused by accessing $this
//#if DEBUG
//                        throw;
//#else
//                    PhpException.ThisUsedOutOfObjectContext();
//                    result = null;
//#endif
//                    }
//                    else
//                    {
//                        throw;  // $this was not null, this should not be handled here
//                    }
//                }
            }

            return PhpVariable.MakeReference(PhpVariable.Copy(result, CopyReason.ReturnedByCopy));
        }
Ejemplo n.º 55
0
        public static object GetObjectProperty(DObject/*!*/ obj, string name, DTypeDesc caller, bool quiet)
        {
            Debug.Assert(obj != null && name != null);

            object property = obj.GetProperty(name, caller, quiet);

            return PhpVariable.Dereference(property);
        }
Ejemplo n.º 56
0
        /// <summary>
        /// Attemps to find a method desc according to a given class name and method name. Used when
        /// a non-virtual dispatch is about to be performed and when a <c>array(class, method)</c>
        /// callback is being bound.
        /// </summary>
        /// <param name="requestedType">The type whose method should be returned.</param>
        /// <param name="methodName">The method name.</param>
        /// <param name="self">Current <c>$this</c>. Will be set to an instance, on which the resulting
        /// CLR method should be invoked (<B>null</B> if the CLR method is static).</param>
        /// <param name="caller"><see cref="Type"/> of the object that request the lookup.</param>
        /// <param name="context">Current <see cref="ScriptContext"/>.</param>
        /// <param name="quiet">If <B>true</B>, no exceptions will be thrown if an error occurs.</param>
        /// <param name="removeFrame">If <B>true</B>, <see cref="PhpStack.RemoveFrame"/> will be called
        /// before throwing an exception.</param>
        /// <param name="isCallerMethod">Will be set to true, if required method was not found but __callStatic was.</param>
        /// <returns>The <see cref="DRoutineDesc"/> or <B>null</B> on error.</returns>
        internal static DRoutineDesc GetStaticMethodDesc(DTypeDesc requestedType, string methodName, ref DObject self,
            DTypeDesc caller, ScriptContext context, bool quiet, bool removeFrame, out bool isCallerMethod)
        {
            Debug.Assert(requestedType != null);

            isCallerMethod = false;

            DRoutineDesc method;
            GetMemberResult result = requestedType.GetMethod(new Name(methodName), caller, out method);

            if (result == GetMemberResult.NotFound)
            {
                // if not found, perform __callStatic or __call 'magic' method lookup
                Name callMethod = (self != null && requestedType.IsAssignableFrom(self.TypeDesc)) ?
                    Name.SpecialMethodNames.Call : Name.SpecialMethodNames.CallStatic;

                if ((result = requestedType.GetMethod(callMethod, caller, out method)) != GetMemberResult.NotFound)
                {
                    isCallerMethod = true;
                }
                else
                {
                    // there is no such method in the class
                    if (removeFrame) context.Stack.RemoveFrame();
                    if (!quiet) PhpException.UndefinedMethodCalled(requestedType.MakeFullName(), methodName);

                    return null;
                }
            }

            if (result == GetMemberResult.BadVisibility)
            {
                if (removeFrame) context.Stack.RemoveFrame();
                if (!quiet)
                {
                    PhpException.MethodNotAccessible(
                        method.DeclaringType.MakeFullName(),
                        method.MakeFullName(),
                        (caller == null ? String.Empty : caller.MakeFullName()),
                        method.IsProtected);
                }
                return null;
            }

            // check whether the method is abstract
            if (method.IsAbstract)
            {
                if (removeFrame) context.Stack.RemoveFrame();
                if (!quiet) PhpException.AbstractMethodCalled(method.DeclaringType.MakeFullName(), method.MakeFullName());

                return null;
            }

            if (method.IsStatic)
            {
                self = null;
            }
            else
            {
                // check whether self is of acceptable type
                if (self != null && !method.DeclaringType.RealType.IsInstanceOfType(self.RealObject)) self = null;


                /*
                // PHP allows for static invocations of instance method
				if (self == null &&
					(requestedType.IsAbstract || !(requestedType is PhpTypeDesc)) &&
					(method.DeclaringType.IsAbstract || !(method.DeclaringType is PhpTypeDesc)))
				{
					// calling instance methods declared in abstract classes statically through abstract classes
					// is unsupported -  passing null as 'this' to such instance method could result in
					// NullReferenceException even if the method does not touch $this
					if (removeFrame) context.Stack.RemoveFrame();
					if (!quiet)
					{
						PhpException.Throw(PhpError.Error, CoreResources.GetString("nonstatic_method_called_statically",
							method.DeclaringType.MakeFullName(), method.MakeFullName()));
					}
					return null;
				}

				if (self == null)
				{
                    if (!quiet && !context.Config.Variables.ZendEngineV1Compatible)
                    {
                        PhpException.Throw(PhpError.Strict, CoreResources.GetString("nonstatic_method_called_statically",
                            method.DeclaringType.MakeFullName(), method.MakeFullName()));
                    }

					// create a dummy instance to be passed as 'this' to the instance method
					DTypeDesc dummy_type =
						(!requestedType.IsAbstract && requestedType is PhpTypeDesc) ? requestedType : method.DeclaringType;

					self = PhpFunctionUtils.InvokeConstructor(
                        dummy_type,
                        //Emit.Types.ScriptContext_Bool,
                        context, false);
				}*/


                //
                // The code above was commented and replaced with following.
                //
                // We can call instance method, and pass null as 'this', and expect
                // it can fail with NullReferenceException (even if the method does not touch $this).
                // 
                // Note this solution has no side effect as above - invoking constructor of dummy instance.
                //

                // !! self can be null !!

                if (self == null)
                {
                    if (!quiet /*&& !context.Config.Variables.ZendEngineV1Compatible*/)
                    {
                        PhpException.Throw(PhpError.Strict, CoreResources.GetString("nonstatic_method_called_statically",
                            method.DeclaringType.MakeFullName(), method.MakeFullName()));
                    }
                }

            }

            return method;
        }
Ejemplo n.º 57
0
        public static void SetObjectFieldDirectRef(PhpReference value, DObject/*!*/ obj, ref PhpReference/*!*/ field,
            string/*!*/ name, DTypeDesc caller)
        {
            Debug.Assert(obj != null && field != null && name != null);

            if (field.IsSet)
            {
                field = value;
            }
            else
            {
                SetObjectProperty(obj, name, value, caller);
            }
        }
Ejemplo n.º 58
0
        public static PhpReference GetObjectPropertyRef(DObject/*!*/ obj, string name, DTypeDesc caller)
        {
            Debug.Assert(obj != null && name != null);

            if (ReferenceEquals(obj, ScriptContext.SetterChainSingletonObject))
            {
                ScriptContext.CurrentContext.AbortSetterChain(false);
                return new PhpReference();
            }

            return obj.GetPropertyRef(name, caller);
        }
Ejemplo n.º 59
0
        public static PhpReference GetObjectFieldDirectRef(DObject/*!*/ obj, PhpReference/*!*/ field,
            string/*!*/ name, DTypeDesc caller)
        {
            Debug.Assert(obj != null && field != null && name != null);

            if (field.IsSet)
            {
                field.IsAliased = true;
                return field;
            }
            else
            {
                return GetObjectPropertyRef(obj, name, caller);
            }
        }
Ejemplo n.º 60
0
        public static object GetObjectFieldDirect(DObject/*!*/ obj, PhpReference/*!*/ field,
            string/*!*/ name, DTypeDesc caller, bool quiet)
        {
            Debug.Assert(obj != null && field != null && name != null);

            if (field.IsSet)
            {
                return field.Value;
            }
            else
            {
                return GetObjectProperty(obj, name, caller, quiet);
            }
        }