예제 #1
0
        /// <summary>
        /// Initializes the available property array.
        /// </summary>
        private void OnEnable()
        {
            // If the preset is a child of a StateConfiguration asset then the AllPublic MemberVisiblity type should be shown.
            if (!AssetDatabase.IsMainAsset(target))
            {
                var mainAsset = AssetDatabase.LoadAssetAtPath(AssetDatabase.GetAssetPath(target), TypeUtility.GetType("Opsive.UltimateCharacterController.StateSystem.StateConfiguration"));
                if (mainAsset != null)
                {
                    m_Visiblity = MemberVisibility.AllPublic;
                }
            }

            InitializeAvailablePropertyArray();
        }
예제 #2
0
 public override void GetObjectData(SerializationInfo info, StreamingContext context)
 {
     base.GetObjectData(info, context);
     info.AddValue(TypeUtility.GetMemberName <AlibabaException, int>((obj) => obj.ErrorCode), this.ErrorCode);
 }
예제 #3
0
 protected override bool IsValidProperty()
 {
     return(TypeUtility.IsArrayOrList(DrawerProperty.ValueType));
 }
        // Emit a surrogate property for a CLR property.
        // The surrogate code we'll generate will look like this:
        // public <PropertyType> <PropertyName> {
        //     get {
        //         // For normal types.
        //         return _$wrapper.<PropertyName>;
        //
        //         // For Binary.
        //         Binary value = _$wrapper.<PropertyName>;
        //         if (value == null) {
        //             return null;
        //         }
        //         return value.ToArray();
        //     }
        //     set {
        //         if (value == null) {
        //             return;
        //         }
        //
        //         // For normal types.
        //         _$wrapper.<PropertyName> = value;
        //
        //         // For Binary.
        //         Binary valueToStore;
        //         if (value == null) {
        //             valueToStore = null;
        //         }
        //         else {
        //             valueToStore = new Binary(value);
        //         }
        //         _$wrapper.<PropertyName> = valueToStore;
        //     }
        // }
        private static void EmitClrProperty(TypeBuilder typeBuilder, FieldInfo wrapperField, PropertyDescriptor pd, PropertyInfo pi, string name)
        {
            Type            propertyType    = SerializationUtility.GetClientType(pi.PropertyType);
            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name, PropertyAttributes.None, propertyType, null);

            CustomAttributeBuilder dataMemberAtt = DataContractSurrogateGenerator.GetDataMemberAttributeBuilder(
                pd.Attributes.OfType <DataMemberAttribute>().FirstOrDefault());

            propertyBuilder.SetCustomAttribute(dataMemberAtt);

            // get {
            //     return ((Entity)$wrapper).Property;
            // }
            MethodBuilder getPropertyMethodBuilder = typeBuilder.DefineMethod("get_" + name, MethodAttributes.Public, propertyType, Type.EmptyTypes);
            ILGenerator   generator = getPropertyMethodBuilder.GetILGenerator();

            // Push the wrapper object onto the stack.
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldfld, wrapperField);
            generator.Emit(OpCodes.Castclass, pi.DeclaringType);

            // Call the property getter.
            generator.Emit(OpCodes.Callvirt, pi.GetGetMethod());

            // Deal with client-server type conversions.
            if (propertyType != pi.PropertyType)
            {
                EmitToClientConversion(generator, pi.PropertyType, propertyType);
            }

            generator.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropertyMethodBuilder);

            MethodBuilder setPropertyMethodBuilder = typeBuilder.DefineMethod("set_" + name, MethodAttributes.Public, null, new Type[] { propertyType });

            generator = setPropertyMethodBuilder.GetILGenerator();

            Label returnLabel = generator.DefineLabel();

            // Data members require a getter and setter. However, if the real property is read-only, make sure
            // our surrogate property setter is a no-op.
            MethodInfo setMethod = pi.GetSetMethod();

            if (setMethod != null && setMethod.IsPublic)
            {
                // NOTE: We don't ever set null values, because a property may be required. For
                //       original objects however it's possible that required properties are not
                //       roundtripped, as they may not have RoundtripOriginalAttribute.
                // set {
                //     if (value != null) {
                //         _$wrapper.Property = value;
                //     }
                // }

                // If the value is null, return.
                if (!propertyType.IsValueType)
                {
                    generator.Emit(OpCodes.Ldarg_1);
                    EmitBranchIfNull(generator, propertyType, returnLabel);
                }
                else if (TypeUtility.IsNullableType(propertyType))
                {
                    generator.Emit(OpCodes.Ldarga_S, 1);
                    EmitBranchIfNull(generator, propertyType, returnLabel);
                }

                // Push the wrapper object onto the stack.
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldfld, wrapperField);
                generator.Emit(OpCodes.Castclass, pi.DeclaringType);

                // Push the value onto the stack.
                generator.Emit(OpCodes.Ldarg_1);

                // Deal with client-server type conversions.
                if (propertyType != pi.PropertyType)
                {
                    EmitToServerConversion(generator, propertyType, pi.PropertyType);
                }

                // Call the property setter.
                generator.Emit(OpCodes.Callvirt, setMethod);
            }

            generator.MarkLabel(returnLabel);
            generator.Emit(OpCodes.Ret);
            propertyBuilder.SetSetMethod(setPropertyMethodBuilder);
        }
예제 #5
0
 /// <summary>
 /// Determines whether the given assembly is mscorlib
 /// </summary>
 /// <param name="assemblyName">assembly name to test</param>
 /// <returns><c>true</c> if the assembly is mscorlib</returns>
 internal static bool IsAssemblyMsCorlib(AssemblyName assemblyName)
 {
     return(String.Compare(assemblyName.Name, "mscorlib", StringComparison.OrdinalIgnoreCase) == 0 && TypeUtility.IsSystemAssembly(assemblyName.FullName));
 }
예제 #6
0
    private void SetAdd2(HttpPostedFile FindFile)
    {
        string dir    = "";
        string status = "";

        string lsAddFileInfo = "";  // 테이블에 저장될 파일정보
        string lsAddName     = "";  //중복되면 시간을 붙여 파일명으로 만든다.
        string lsFileName    = System.IO.Path.GetFileName(FindFile.FileName);

        string sText  = "";
        string sValue = "";

        string sTmpText = "";

        // dialogArguments가 있는지 체크한다.
        mArgs = hArgArray.Value.ToString().Split(';');

        if (Page.IsPostBack == true)
        {
            if (lsFileName == "")
            {
                return;
            }

            if (mArgs[GetArgsInfo(EN_ARGS_INFO.TBLINFO)] == "EXCEL")
            {
                // 엑셀파일일 경우는 파일 하나만 추가하도록 조정한다.
                dir = CS_EXCELPATH + DateTime.Now.ToString("yyyyMMdd") + "/";

                if (lsFileName.Substring(lsFileName.LastIndexOf(".") + 1).ToUpper() != "XLS" ||
                    lsFileName.Substring(lsFileName.LastIndexOf(".") + 1).ToUpper() != "XLSX")
                {
                    PageUtility.AlertMessage("엑셀파일만 업로드할 수 있습니다!");
                    return;
                }

                if (lbFileList.Items.Count > 0)
                {
                    PageUtility.AlertMessage("엑셀파일이 이미 추가되어 있습니다.");
                    return;
                }
            }
            else
            {
                // 일반파일일 경우
                dir = CS_MAPPATH + mArgs[GetArgsInfo(EN_ARGS_INFO.SAVEINFO)] + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";

                if (mArgs.Length < 3)
                {
                    PageUtility.AlertMessage("파일첨부에 대한 정보를 알 수 없습니다!", false, true);
                    return;
                }

                // AttachNo 추출여부 확인
                if (hSaveAttachNo.Value == "")
                {
                    //Biz_Base_FileUpload biz = new Biz_Base_FileUpload();
                    //hSaveAttachNo.Value = biz.GetAttachNo(mArgs[GetArgsInfo(EN_ARGS_INFO.SAVEINFO)] + "_F");

                    hSaveAttachNo.Value = mArgs[GetArgsInfo(EN_ARGS_INFO.SAVEINFO)] + "_F" + DateTime.Now.ToString("yyyyMMddHHmmss");
                }

                for (int i = 0; i < lbFileList.Items.Count; i++)
                {
                    sTmpText = lbFileList.Items[i].Text;
                    if (sTmpText.Substring(0, sTmpText.LastIndexOf(" (")) == lsFileName)
                    {
                        PageUtility.AlertMessage("이미 추가되어 있습니다!");

                        if (lbFileList.SelectedIndex >= 0)
                        {
                            lbFileList.Items[lbFileList.SelectedIndex].Selected = false;
                        }

                        lbFileList.Items[i].Selected = true;

                        return;
                    }
                }
            }

            int iPostedFileSize = (FindFile.ContentLength / 1000);
            try
            {
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                while (true)
                {
                    if (File.Exists(dir + lsAddName + lsFileName))
                    {
                        lsAddName = DateTime.Now.ToString("HHmmss") + "_";
                    }
                    else
                    {
                        break;
                    }
                }

                if ((this.ITotalSize + iPostedFileSize) > this.IFileLimitSize)
                {
                    PageUtility.AlertMessage("파일용량을 초과하였습니다.");
                    return;
                }

                FindFile.SaveAs(dir + lsAddName + lsFileName);
                miFilesProcessed++;
                status += "&nbsp;&nbsp;- " + lsFileName + "<br>";

                sValue = dir + lsAddName + lsFileName;
                sText  = System.IO.Path.GetFileName(FindFile.FileName) + " (" + TypeUtility.GetByte2Str(FindFile.InputStream.Length) + ")";

                lbFileList.Items.Add(new ListItem(sText, sValue));

                hSaveFiles.Value += sText + ";" + sValue;

                /*
                 * AttachNo, v_FileName, v_FileSize, p_FileSize, p_FullPath
                 * */
                lsAddFileInfo = hSaveAttachNo.Value + ";"
                                + System.IO.Path.GetFileName(FindFile.FileName) + ";"
                                + TypeUtility.GetByte2Str(FindFile.InputStream.Length) + ";"
                                + FindFile.InputStream.Length.ToString() + ";"
                                + (dir + lsAddName + lsFileName);

                // 파일저장 테이블에 인서트
                int iProcess = 0;
                Biz_Base_FileUpload bizUpload = new Biz_Base_FileUpload();

                switch (mArgs[GetArgsInfo(EN_ARGS_INFO.TBLINFO)])
                {
                case "EXCEL":
                    // 저장이 엑셀업로드용 이라면 실제 디렉토리정보를 리턴한다.
                    hSaveAttachNo.Value = (dir + lsAddName + lsFileName);
                    break;

                case "FILE":
                    iProcess = bizUpload.AddFileInfo(TypeUtility.GetSplit(lsAddFileInfo));
                    break;

                case "PROCFILE":
                    // 추후에 ICM_PROCFILE에 업데이트 하는 모듈 개발해야 한다. (2006.02.25 강신규)
                    iProcess = bizUpload.AddFileInfo(TypeUtility.GetSplit(lsAddFileInfo));
                    break;
                }

                // 파일 저장정보 변경시 changeflag 셋팅
                if (this.hChangeFlag.Value != "T")
                {
                    this.hChangeFlag.Value = "T";
                }

                this.ITotalSize       += iPostedFileSize;
                lblEnableAttKbyte.Text = Convert.ToString(this.IFileLimitSize - this.ITotalSize);
            }
            catch (Exception err)
            {
                // 파일처리가 되었다면 삭제한다.
                DeleteFile(true);
                lblStatus.Text = "Error saving file " + dir + err.ToString();
            }
        }
    }
예제 #7
0
 /// <summary>
 /// Returns <c>true</c> if the given type one of our supported simple types (or a collection thereof),
 /// or if the type is a complex type (or a collection thereof).
 /// </summary>
 /// <param name="type">The type to test</param>
 /// <returns><c>true</c> if the type is a primitive or one of the accepted types</returns>
 private static bool IsPredefinedOrComplexType(Type type)
 {
     return(TypeUtility.IsPredefinedType(type) || TypeUtility.IsComplexType(type) || TypeUtility.IsComplexTypeCollection(type));
 }
예제 #8
0
        private void DrawTargetingStage()
        {
            EditorGUILayout.LabelField("Interaction", EditorStyles.boldLabel);
            EditorWindowTools.StartIndentedSection();
            EditorGUILayout.HelpBox("If your player will be configured to use interaction components such as Selector or Proximity Selector, you can configure this NPC to be usable by the player.", MessageType.Info);
            if (!lookedUpDimension)
            {
                lookedUpDimension = true;
                dimension         = (npcObject.GetComponent <Collider2D>() != null) ? Dimension.In2D : Dimension.In3D;
            }
            dimension = (Dimension)EditorGUILayout.EnumPopup(new GUIContent("Scene Is...", "Is this NPC in a 2D or 3D scene?"), dimension);

            var usable    = npcObject.GetComponent <Usable>();
            var hasUsable = (usable != null);

            hasUsable = EditorGUILayout.Toggle("Usable By Player", hasUsable);
            if (usable == null && hasUsable)
            {
                usable = npcObject.AddComponent(TypeUtility.GetWrapperType(typeof(PixelCrushers.DialogueSystem.Usable))) as Usable;
            }
            else if (usable != null && !hasUsable)
            {
                DestroyImmediate(usable);
                usable       = null;
                usableEditor = null;
            }
            if (usable != null)
            {
                if (usableEditor == null)
                {
                    usableEditor = Editor.CreateEditor(usable);
                }
                usableEditor.OnInspectorGUI();
            }

            var hasTriggerCollider    = false;
            var hasNontriggerCollider = false;

            if (dimension == Dimension.In2D)
            {
                var colliders = npcObject.GetComponents <Collider2D>();
                foreach (var collider in colliders)
                {
                    if (collider.isTrigger)
                    {
                        hasTriggerCollider = true;
                    }
                    else
                    {
                        hasNontriggerCollider = true;
                    }
                }
            }
            else
            {
                var colliders = npcObject.GetComponents <Collider>();
                foreach (var collider in colliders)
                {
                    if (collider.isTrigger)
                    {
                        hasTriggerCollider = true;
                    }
                    else
                    {
                        hasNontriggerCollider = true;
                    }
                }
            }

            if (hasNontriggerCollider)
            {
                EditorGUILayout.HelpBox("This NPC has a collider. If you want to edit its properties, click Select NPC.", MessageType.None);
            }
            else
            {
                if (hasUsable)
                {
                    EditorGUILayout.HelpBox("This NPC has a Usable component. It also needs a collider so the player's Selector or Proximity Selector can detect it.", MessageType.None);
                }
                else
                {
                    EditorGUILayout.HelpBox("If this NPC will take action on collision enter/exit, it needs a collider.", MessageType.None);
                }
                hasTriggerCollider = EditorGUILayout.Toggle("Add Collider", hasTriggerCollider);
                if (hasTriggerCollider)
                {
                    if (dimension == Dimension.In2D)
                    {
                        npcObject.AddComponent <CircleCollider2D>();
                        var rb = npcObject.GetComponent <Rigidbody2D>();
                        if (rb == null)
                        {
                            rb             = npcObject.AddComponent <Rigidbody2D>();
                            rb.isKinematic = true;
                        }
                    }
                    else
                    {
                        npcObject.AddComponent <CapsuleCollider>();
                        var rb = npcObject.GetComponent <Rigidbody>();
                        if (rb == null)
                        {
                            rb             = npcObject.AddComponent <Rigidbody>();
                            rb.isKinematic = true;
                        }
                    }
                }
            }

            if (hasTriggerCollider)
            {
                EditorGUILayout.HelpBox("This NPC has a trigger collider. If you want to edit its properties, click Select NPC.", MessageType.None);
            }
            else
            {
                EditorGUILayout.HelpBox("If this NPC will take action on trigger enter/exit, it needs a trigger collider.", MessageType.None);
                hasTriggerCollider = EditorGUILayout.Toggle("Add Trigger Collider", hasTriggerCollider);
                if (hasTriggerCollider)
                {
                    if (dimension == Dimension.In2D)
                    {
                        var circleCollider = npcObject.AddComponent <CircleCollider2D>();
                        circleCollider.isTrigger = true;
                        circleCollider.radius    = 1.5f;
                        var rb = npcObject.GetComponent <Rigidbody2D>();
                        if (rb == null)
                        {
                            rb             = npcObject.AddComponent <Rigidbody2D>();
                            rb.isKinematic = true;
                        }
                    }
                    else
                    {
                        SphereCollider sphereCollider = npcObject.AddComponent <SphereCollider>();
                        sphereCollider.isTrigger = true;
                        sphereCollider.radius    = 1.5f;
                        var rb = npcObject.GetComponent <Rigidbody>();
                        if (rb == null)
                        {
                            rb             = npcObject.AddComponent <Rigidbody>();
                            rb.isKinematic = true;
                        }
                    }
                }
            }
            if (GUILayout.Button("Select NPC", GUILayout.Width(100)))
            {
                Selection.activeGameObject = npcObject;
            }
            EditorWindowTools.EndIndentedSection();
            DrawNavigationButtons(true, true, false);
        }
예제 #9
0
        private void GenerateEntityQueryMethod(DomainOperationEntry domainOperationEntry)
        {
            string queryMethodName = domainOperationEntry.Name + QuerySuffix;

            Type entityType = TypeUtility.GetElementType(domainOperationEntry.ReturnType);

            CodeMemberMethod queryMethod = new CodeMemberMethod();

            queryMethod.Name       = queryMethodName;
            queryMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final; // Final needed, else becomes virtual

            queryMethod.ReturnType = CodeGenUtilities.GetTypeReference(TypeConstants.EntityQueryTypeFullName, this._domainServiceDescription.DomainServiceType.Namespace, false);
            queryMethod.ReturnType.TypeArguments.Add(CodeGenUtilities.GetTypeReference(entityType.FullName, this._domainServiceDescription.DomainServiceType.Namespace, true));

            DomainOperationParameter[] domainOperationEntryParameters = domainOperationEntry.Parameters.ToArray();

            // Generate <summary> doc comment
            string comment = string.Format(CultureInfo.CurrentCulture, Resource.EntityCodeGen_ConstructorComments_Summary_DomainContext, entityType.Name, domainOperationEntry.Name);

            queryMethod.Comments.AddRange(CodeGenUtilities.GenerateSummaryCodeComment(comment, this.ClientProxyGenerator.IsCSharp));

            // Generate <param> doc comments
            foreach (DomainOperationParameter paramInfo in domainOperationEntryParameters)
            {
                comment = string.Format(CultureInfo.CurrentCulture, Resource.CodeGen_Query_Method_Parameter_Comment, paramInfo.Name);
                queryMethod.Comments.AddRange(CodeGenUtilities.GenerateParamCodeComment(paramInfo.Name, comment, this.ClientProxyGenerator.IsCSharp));
            }

            // Generate <returns> doc comments
            comment = string.Format(CultureInfo.CurrentCulture, Resource.CodeGen_Query_Method_Returns_Comment, domainOperationEntry.AssociatedType.Name);
            queryMethod.Comments.AddRange(CodeGenUtilities.GenerateReturnsCodeComment(comment, this.ClientProxyGenerator.IsCSharp));

            // Propagate custom validation attributes
            IEnumerable <Attribute> methodAttributes = domainOperationEntry.Attributes.Cast <Attribute>();

            CustomAttributeGenerator.GenerateCustomAttributes(
                this.ClientProxyGenerator,
                this._proxyClass,
                ex => string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeMethod, ex.Message, queryMethod.Name, this._proxyClass.Name, ex.InnerException.Message),
                methodAttributes,
                queryMethod.CustomAttributes,
                queryMethod.Comments);

            // add any domain operation entry parameters first

            CodeVariableReferenceExpression paramsRef = new CodeVariableReferenceExpression("parameters");

            if (domainOperationEntryParameters.Length > 0)
            {
                // need to generate the user parameters dictionary
                CodeTypeReference dictionaryTypeReference = CodeGenUtilities.GetTypeReference(
                    typeof(Dictionary <string, object>),
                    this.ClientProxyGenerator,
                    this._proxyClass);

                CodeVariableDeclarationStatement paramsDef = new CodeVariableDeclarationStatement(
                    dictionaryTypeReference,
                    "parameters",
                    new CodeObjectCreateExpression(dictionaryTypeReference, new CodeExpression[0]));
                queryMethod.Statements.Add(paramsDef);
            }
            foreach (DomainOperationParameter paramInfo in domainOperationEntryParameters)
            {
                CodeParameterDeclarationExpression paramDecl = new CodeParameterDeclarationExpression(
                    CodeGenUtilities.GetTypeReference(
                        CodeGenUtilities.TranslateType(paramInfo.ParameterType),
                        this.ClientProxyGenerator,
                        this._proxyClass),
                    paramInfo.Name);

                // Propagate parameter level validation attributes
                IEnumerable <Attribute> paramAttributes = paramInfo.Attributes.Cast <Attribute>();

                string commentHeader =
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resource.ClientCodeGen_Attribute_Parameter_FailedToGenerate,
                        paramInfo.Name);

                CustomAttributeGenerator.GenerateCustomAttributes(
                    this.ClientProxyGenerator,
                    this._proxyClass,
                    ex => string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeMethodParameter, ex.Message, paramDecl.Name, queryMethod.Name, this._proxyClass.Name, ex.InnerException.Message),
                    paramAttributes,
                    paramDecl.CustomAttributes,
                    queryMethod.Comments,
                    commentHeader);

                // add the parameter to the query method
                queryMethod.Parameters.Add(paramDecl);

                // add the parameter and value to the params dictionary
                queryMethod.Statements.Add(new CodeMethodInvokeExpression(
                                               new CodeMethodReferenceExpression(paramsRef, "Add"),
                                               new CodePrimitiveExpression(paramInfo.Name),
                                               new CodeVariableReferenceExpression(paramInfo.Name)));
            }

            // add argument for queryName
            CodeExpressionCollection arguments = new CodeExpressionCollection();

            arguments.Add(new CodePrimitiveExpression(domainOperationEntry.Name));

            // add argument for parameters
            if (domainOperationEntryParameters.Length > 0)
            {
                arguments.Add(paramsRef);
            }
            else
            {
                arguments.Add(new CodePrimitiveExpression(null));
            }

            // add argument for hasSideEffects
            QueryAttribute queryAttribute = (QueryAttribute)domainOperationEntry.OperationAttribute;

            arguments.Add(new CodePrimitiveExpression(queryAttribute.HasSideEffects));

            // add argument for isComposable
            arguments.Add(new CodePrimitiveExpression(queryAttribute.IsComposable));

            // this.ValidateMethod("methodName", parameters);
            CodeExpression paramsExpr = new CodePrimitiveExpression(null);

            if (domainOperationEntryParameters.Length > 0)
            {
                paramsExpr = paramsRef;
            }
            CodeExpressionStatement validateMethodCall = new CodeExpressionStatement(
                new CodeMethodInvokeExpression(
                    new CodeThisReferenceExpression(),
                    "ValidateMethod",
                    new CodeExpression[]
            {
                new CodePrimitiveExpression(queryMethodName),
                paramsExpr
            }));

            queryMethod.Statements.Add(validateMethodCall);

            // ----------------------------------------------------------------
            // method call: base.CreateQuery(arguments...)
            // ----------------------------------------------------------------
            CodeTypeReference             entityTypeRef     = CodeGenUtilities.GetTypeReference(entityType.FullName, this._domainServiceDescription.DomainServiceType.Namespace, true);
            CodeMethodReferenceExpression createQueryMethod = new CodeMethodReferenceExpression(new CodeBaseReferenceExpression(), "CreateQuery", entityTypeRef);
            CodeMethodReturnStatement     createQueryCall   = new CodeMethodReturnStatement(new CodeMethodInvokeExpression(createQueryMethod, arguments.Cast <CodeExpression>().ToArray()));

            queryMethod.Statements.Add(createQueryCall);

            this._proxyClass.Members.Add(queryMethod);
        }
예제 #10
0
        private void DrawActorStage()
        {
            EditorGUILayout.LabelField("Dialogue Actor Component (Optional)", EditorStyles.boldLabel);
            EditorWindowTools.StartIndentedSection();
            EditorGUILayout.HelpBox("A Dialogue Actor component lets you specify which actor in the database this GameObject is associated with if the GameObject doesn't have the same name as the actor. You can also set actor-specific UI settings.", MessageType.Info);
            var dialogueActor    = npcObject.GetComponent <DialogueActor>();
            var hasDialogueActor = dialogueActor != null;

            if (dialogueActor == null)
            {
                dialogueActorEditor = null;
            }
            var useDialogueActor = EditorGUILayout.Toggle("Use Dialogue Actor", hasDialogueActor);

            if (useDialogueActor && !hasDialogueActor)
            {
                dialogueActor    = npcObject.AddComponent(TypeUtility.GetWrapperType(typeof(PixelCrushers.DialogueSystem.DialogueActor))) as DialogueActor;
                hasDialogueActor = true;
            }
            else if (!useDialogueActor && hasDialogueActor)
            {
                DestroyImmediate(dialogueActor);
                dialogueActor       = null;
                hasDialogueActor    = false;
                dialogueActorEditor = null;
            }
            if (hasDialogueActor)
            {
                if (dialogueActorEditor == null)
                {
                    dialogueActorEditor = Editor.CreateEditor(dialogueActor);
                }
                dialogueActorEditor.OnInspectorGUI();
            }

            EditorWindowTools.DrawHorizontalLine();
            var defaultCameraAngle    = npcObject.GetComponent <DefaultCameraAngle>();
            var hasDefaultCameraAngle = defaultCameraAngle != null;

            EditorGUILayout.BeginHorizontal();
            var useDefaultCameraAngle = EditorGUILayout.Toggle("Override Default Camera Angle", hasDefaultCameraAngle);

            EditorGUILayout.HelpBox("The default camera angle is 'Closeup'. You can override it here.", MessageType.None);
            EditorGUILayout.EndHorizontal();
            if (useDefaultCameraAngle && !hasDefaultCameraAngle)
            {
                defaultCameraAngle    = npcObject.AddComponent(TypeUtility.GetWrapperType(typeof(PixelCrushers.DialogueSystem.DefaultCameraAngle))) as DefaultCameraAngle;
                hasDefaultCameraAngle = true;
            }
            else if (!useDefaultCameraAngle && hasDefaultCameraAngle)
            {
                DestroyImmediate(defaultCameraAngle);
                defaultCameraAngle    = null;
                hasDefaultCameraAngle = false;
            }
            if (hasDefaultCameraAngle)
            {
                EditorGUILayout.BeginHorizontal();
                defaultCameraAngle.cameraAngle = EditorGUILayout.TextField("Angle", defaultCameraAngle.cameraAngle);
                EditorGUILayout.HelpBox("Specify the default camera angle for this NPC.", MessageType.None);
                EditorGUILayout.EndHorizontal();
            }

            DrawBarkGroupSection();
            if (GUILayout.Button("Select NPC", GUILayout.Width(100)))
            {
                Selection.activeGameObject = npcObject;
            }
            EditorWindowTools.EndIndentedSection();
            DrawNavigationButtons(true, (database != null), false);
        }
예제 #11
0
        private void DrawActionsStage()
        {
            EditorGUILayout.LabelField("Actions", EditorStyles.boldLabel);
            EditorWindowTools.StartIndentedSection();
            EditorGUILayout.LabelField("Dialogue System Trigger", EditorStyles.boldLabel);
            var dialogueSystemTrigger = npcObject.GetComponent <DialogueSystemTrigger>();

            EditorGUILayout.HelpBox("A Dialogue System Trigger runs actions when an event occurs, such as when the player uses the NPC.", MessageType.None);
            var hasDialogueSystemTrigger = (dialogueSystemTrigger != null);

            hasDialogueSystemTrigger = EditorGUILayout.Toggle("Dialogue System Trigger", hasDialogueSystemTrigger);
            if (hasDialogueSystemTrigger && dialogueSystemTrigger == null)
            {
                dialogueSystemTrigger = npcObject.AddComponent(TypeUtility.GetWrapperType(typeof(PixelCrushers.DialogueSystem.DialogueSystemTrigger))) as DialogueSystemTrigger;
            }
            else if (!hasDialogueSystemTrigger && dialogueSystemTrigger != null)
            {
                DestroyImmediate(dialogueSystemTrigger);
                dialogueSystemTrigger       = null;
                hasDialogueSystemTrigger    = false;
                dialogueSystemTriggerEditor = null;
            }
            if (hasDialogueSystemTrigger)
            {
                if (dialogueSystemTriggerEditor == null)
                {
                    dialogueSystemTriggerEditor = Editor.CreateEditor(dialogueSystemTrigger);
                }
                dialogueSystemTriggerEditor.OnInspectorGUI();
            }

            EditorWindowTools.DrawHorizontalLine();
            EditorGUILayout.LabelField("Dialogue System Events", EditorStyles.boldLabel);
            var dialogueSystemEvents = npcObject.GetComponent <DialogueSystemEvents>();

            if (dialogueSystemEvents != null)
            {
                EditorGUILayout.HelpBox("A Dialogue System Events component is a handy way to configure activity such as disabling components and setting animator states when Dialogue System events occur. To configure Dialogue System Events in the Inspector view, click Select NPC.", MessageType.None);
            }
            else
            {
                EditorGUILayout.HelpBox("A Dialogue System Events component is a handy way to configure activity such as disabling components and setting animator states when Dialogue System events occur.", MessageType.None);
            }
            var hasDialogueSystemEvents = (dialogueSystemEvents != null);

            hasDialogueSystemEvents = EditorGUILayout.Toggle("Dialogue System Events", dialogueSystemEvents);
            if (hasDialogueSystemEvents && dialogueSystemEvents == null)
            {
                dialogueSystemEvents = npcObject.AddComponent(TypeUtility.GetWrapperType(typeof(PixelCrushers.DialogueSystem.DialogueSystemEvents))) as DialogueSystemEvents;
            }
            else if (!hasDialogueSystemEvents && dialogueSystemEvents != null)
            {
                DestroyImmediate(dialogueSystemEvents);
                dialogueSystemEvents    = null;
                hasDialogueSystemEvents = false;
            }

            EditorWindowTools.DrawHorizontalLine();
            DrawBarkOnIdleSection();

            if (GUILayout.Button("Select NPC", GUILayout.Width(100)))
            {
                Selection.activeGameObject = npcObject;
            }
            EditorWindowTools.EndIndentedSection();
            DrawNavigationButtons(true, true, false);
        }
예제 #12
0
        internal static async Task ExecuteWithWatchersAsync(IFunctionInstance instance,
                                                            IReadOnlyDictionary <string, IValueProvider> parameters,
                                                            TraceWriter traceWriter,
                                                            CancellationTokenSource functionCancellationTokenSource)
        {
            IFunctionInvoker       invoker        = instance.Invoker;
            IReadOnlyList <string> parameterNames = invoker.ParameterNames;

            Tuple <object[], IDelayedException> preparedParameters = await PrepareParametersAsync(parameterNames, parameters);

            object[]          invokeParameters        = preparedParameters.Item1;
            IDelayedException delayedBindingException = preparedParameters.Item2;

            if (delayedBindingException != null)
            {
                // This is done inside a watcher context so that each binding error is publish next to the binding in
                // the parameter status log.
                delayedBindingException.Throw();
            }

            // if the function is a Singleton, aquire the lock
            SingletonLock singleton = await GetSingletonLockAsync(parameters);

            if (singleton != null)
            {
                await singleton.AcquireAsync(functionCancellationTokenSource.Token);
            }

            // Create a source specifically for timeouts
            using (CancellationTokenSource timeoutTokenSource = new CancellationTokenSource())
            {
                MethodInfo       method           = instance.FunctionDescriptor.Method;
                TimeoutAttribute timeoutAttribute = TypeUtility.GetHierarchicalAttributeOrNull <TimeoutAttribute>(method);
                bool             throwOnTimeout   = timeoutAttribute == null ? false : timeoutAttribute.ThrowOnTimeout;
                var      timer         = StartFunctionTimeout(instance, timeoutAttribute, timeoutTokenSource, traceWriter);
                TimeSpan timerInterval = timer == null ? TimeSpan.MinValue : TimeSpan.FromMilliseconds(timer.Interval);
                try
                {
                    await InvokeAsync(invoker, invokeParameters, timeoutTokenSource, functionCancellationTokenSource,
                                      throwOnTimeout, timerInterval, instance);
                }
                finally
                {
                    if (timer != null)
                    {
                        timer.Stop();
                        timer.Dispose();
                    }
                }
            }

            // Process any out parameters and persist any pending values.
            // Ensure IValueBinder.SetValue is called in BindStepOrder. This ordering is particularly important for
            // ensuring queue outputs occur last. That way, all other function side-effects are guaranteed to have
            // occurred by the time messages are enqueued.
            string[] parameterNamesInBindOrder = SortParameterNamesInStepOrder(parameters);
            foreach (string name in parameterNamesInBindOrder)
            {
                IValueProvider provider = parameters[name];
                IValueBinder   binder   = provider as IValueBinder;

                if (binder != null)
                {
                    object argument = invokeParameters[GetParameterIndex(parameterNames, name)];

                    try
                    {
                        // This could do complex things that may fail. Catch the exception.
                        await binder.SetValueAsync(argument, functionCancellationTokenSource.Token);
                    }
                    catch (OperationCanceledException)
                    {
                        throw;
                    }
                    catch (Exception exception)
                    {
                        string message = String.Format(CultureInfo.InvariantCulture,
                                                       "Error while handling parameter {0} after function returned:", name);
                        throw new InvalidOperationException(message, exception);
                    }
                }
            }

            if (singleton != null)
            {
                await singleton.ReleaseAsync(functionCancellationTokenSource.Token);
            }
        }
예제 #13
0
        private static object Liquidize(object obj, bool restrictTypes)
        {
            if (obj == null)
            {
                return(obj);
            }
            if (obj is ILiquidizable)
            {
                return(((ILiquidizable)obj).ToLiquid());
            }
            if (obj is string)
            {
                return(obj);
            }
            if (obj is IEnumerable)
            {
                return(obj);
            }
            if (obj.GetType().IsPrimitive)
            {
                return(obj);
            }
            if (obj is decimal)
            {
                return(obj);
            }
            if (obj is DateTime)
            {
                return(obj);
            }
            if (obj is DateTimeOffset)
            {
                return(obj);
            }
            if (obj is TimeSpan)
            {
                return(obj);
            }
            if (obj is Guid)
            {
                return(obj);
            }
            if (TypeUtility.IsAnonymousType(obj.GetType()))
            {
                return(obj);
            }
            if (obj is KeyValuePair <string, object> )
            {
                return(obj);
            }

            var safeTypeTransformer = Template.GetSafeTypeTransformer(obj.GetType());

            if (safeTypeTransformer != null)
            {
                return(safeTypeTransformer(obj));
            }
            if (obj.GetType().GetCustomAttributes(typeof(LiquidTypeAttribute), false).Any())
            {
                var attr = (LiquidTypeAttribute)obj.GetType().GetCustomAttributes(typeof(LiquidTypeAttribute), false).First();
                return(new DropProxy(obj, attr.AllowedMembers));
            }

            if (restrictTypes)
            {
                throw new SyntaxException(Liquid.ResourceManager.GetString("ContextObjectInvalidException"), obj.ToString());
            }

            else
            {
                var properties    = obj.GetType().GetProperties();
                var propertyNames = properties.Select(p => p.Name);

                return(new DropProxy(obj, propertyNames.ToArray()));
            }
        }
        private void AddAsyncMethodImplementation(
            TypeBuilder classBuilder,
            int interfaceId,
            MethodDescription methodDescription,
            MethodBodyTypes methodBodyTypes,
            string interfaceName)
        {
            var interfaceMethod = methodDescription.MethodInfo;
            var parameters      = interfaceMethod.GetParameters();
            var methodBuilder   = CodeBuilderUtils.CreateExplitInterfaceMethodBuilder(
                classBuilder,
                interfaceMethod);
            var ilGen           = methodBuilder.GetILGenerator();
            var parameterLength = parameters.Length;

            if (methodDescription.HasCancellationToken)
            {
                // Cancellation token is tracked locally and should not be serialized and sent
                // as a part of the request body.
                parameterLength -= 1;
            }

            LocalBuilder requestMessage = null;

            if (parameterLength > 0)
            {
                // Create Wrapped Message
                // create requestBody and assign the values to its field from the arguments
                var wrappedRequestBody = CreateWrappedRequestBody(methodDescription, methodBodyTypes, ilGen, parameters);

                // create IServiceRemotingRequestMessageBody message
                requestMessage = this.CreateRequestRemotingMessageBody(methodDescription, interfaceName, ilGen, parameterLength, wrappedRequestBody);

                // Check if requestMessage is not implementing WrappedMessage , then call SetParam
                this.SetParameterIfNeeded(ilGen, requestMessage, parameterLength, parameters);
            }

            var objectTask = ilGen.DeclareLocal(typeof(Task <IActorResponseMessageBody>));

            // call the base InvokeMethodAsync method
            ilGen.Emit(OpCodes.Ldarg_0);                       // base
            ilGen.Emit(OpCodes.Ldc_I4, interfaceId);           // interfaceId
            ilGen.Emit(OpCodes.Ldc_I4, methodDescription.Id);  // methodId
            ilGen.Emit(OpCodes.Ldstr, methodDescription.Name); // method name

            if (requestMessage != null)
            {
                ilGen.Emit(OpCodes.Ldloc, requestMessage);
            }
            else
            {
                ilGen.Emit(OpCodes.Ldnull);
            }

            // Cancellation token argument
            if (methodDescription.HasCancellationToken)
            {
                // Last argument should be the cancellation token
                var cancellationTokenArgIndex = parameters.Length;
                ilGen.Emit(OpCodes.Ldarg, cancellationTokenArgIndex);
            }
            else
            {
                var cancellationTokenNone = typeof(CancellationToken).GetMethod("get_None");
                ilGen.EmitCall(OpCodes.Call, cancellationTokenNone, null);
            }

            ilGen.EmitCall(OpCodes.Call, this.invokeAsyncMethodInfo, null);
            ilGen.Emit(OpCodes.Stloc, objectTask);

            // call the base method to get the continuation task and
            // convert the response body to return value when the task is finished
            if (TypeUtility.IsTaskType(methodDescription.ReturnType) &&
                methodDescription.ReturnType.GetTypeInfo().IsGenericType)
            {
                var retvalType = methodDescription.ReturnType.GetGenericArguments()[0];

                ilGen.Emit(OpCodes.Ldarg_0);                      // base pointer
                ilGen.Emit(OpCodes.Ldc_I4, interfaceId);          // interfaceId
                ilGen.Emit(OpCodes.Ldc_I4, methodDescription.Id); // methodId
                ilGen.Emit(OpCodes.Ldloc, objectTask);            // task<IServiceRemotingResponseMessageBody>
                ilGen.Emit(OpCodes.Call, this.continueWithResultMethodInfo.MakeGenericMethod(retvalType));
                ilGen.Emit(OpCodes.Ret);                          // return base.ContinueWithResult<TResult>(task);
            }
            else
            {
                ilGen.Emit(OpCodes.Ldarg_0);           // base pointer
                ilGen.Emit(OpCodes.Ldloc, objectTask); // task<object>
                ilGen.Emit(OpCodes.Call, this.continueWithMethodInfo);
                ilGen.Emit(OpCodes.Ret);               // return base.ContinueWith(task);
            }
        }
예제 #15
0
            public static IBinding TryBuild <TUserType>(
                BindToStreamBindingProvider <TAttribute> parent,
                BindingProviderContext context)
            {
                // Allowed Param types:
                //  Stream
                //  any T with a Stream --> T conversion
                // out T, with a Out<Stream,T> --> void conversion

                var parameter     = context.Parameter;
                var parameterType = parameter.ParameterType;


                var attributeSource = TypeUtility.GetResolvedAttribute <TAttribute>(parameter);

                // Stream is either way; all other types are known.
                FileAccess?declaredAccess = GetFileAccessFromAttribute(attributeSource);

                Type argHelperType;
                bool isRead;

                IConverterManager cm = parent._converterManager;
                INameResolver     nm = parent._nameResolver;

                object converterParam = null;

                {
                    if (parameter.IsOut)
                    {
                        var outConverter = cm.GetConverter <ApplyConversion <TUserType, Stream>, object, TAttribute>();
                        if (outConverter != null)
                        {
                            converterParam = outConverter;
                            isRead         = false;
                            argHelperType  = typeof(OutArgBaseValueProvider <>).MakeGenericType(typeof(TAttribute), typeof(TUserType));
                        }
                        else
                        {
                            throw new InvalidOperationException($"No stream converter to handle {typeof(TUserType).FullName}.");
                        }
                    }
                    else
                    {
                        var converter = cm.GetConverter <Stream, TUserType, TAttribute>();
                        if (converter != null)
                        {
                            converterParam = converter;

                            if (parameterType == typeof(Stream))
                            {
                                if (!declaredAccess.HasValue)
                                {
                                    throw new InvalidOperationException("When binding to Stream, the attribute must specify a FileAccess direction.");
                                }
                                switch (declaredAccess.Value)
                                {
                                case FileAccess.Read:
                                    isRead = true;

                                    break;

                                case FileAccess.Write:
                                    isRead = false;
                                    break;

                                default:
                                    throw new NotImplementedException("ReadWrite access is not supported. Pick either Read or Write.");
                                }
                            }
                            else
                            {
                                // For backwards compat, we recognize TextWriter as write;
                                // anything else should explicitly set the FileAccess flag.
                                if (typeof(TextWriter).IsAssignableFrom(typeof(TUserType)))
                                {
                                    isRead = false;
                                }
                                else
                                {
                                    isRead = true;
                                }
                            }


                            argHelperType = typeof(ValueProvider <>).MakeGenericType(typeof(TAttribute), typeof(TUserType));
                        }
                        else
                        {
                            // This rule can't bind.
                            // Let another try.
                            context.BindingErrors.Add(String.Format(Constants.BindingAssemblyConflictMessage, typeof(Stream).AssemblyQualifiedName, typeof(TUserType).AssemblyQualifiedName));
                            return(null);
                        }
                    }
                }

                VerifyAccessOrThrow(declaredAccess, isRead);
                if (!parent.IsSupportedByRule(isRead))
                {
                    return(null);
                }

                var cloner = new AttributeCloner <TAttribute>(attributeSource, context.BindingDataContract, nm);

                ParameterDescriptor param;

                if (parent.BuildParameterDescriptor != null)
                {
                    param = parent.BuildParameterDescriptor(attributeSource, parameter, nm);
                }
                else
                {
                    param = new ParameterDescriptor
                    {
                        Name         = parameter.Name,
                        DisplayHints = new ParameterDisplayHints
                        {
                            Description = isRead ? "Read Stream" : "Write Stream"
                        }
                    };
                }

                var      fileAccess = isRead ? FileAccess.Read : FileAccess.Write;
                IBinding binding    = new StreamBinding(cloner, param, parent, argHelperType, parameterType, fileAccess, converterParam);

                return(binding);
            }
예제 #16
0
 public void GettingTheBaseType_GivenAnyType_ReturnsExpectedType(Type type, Type root)
 {
     Assert.That(TypeUtility.GetRootType(type), Is.EqualTo(root));
 }
예제 #17
0
 public void DisplayName_Default()
 {
     Assert.That(_instance.DisplayName, Is.EqualTo(TypeUtility.GetPartialAssemblyQualifiedName(typeof(ClassDerivedFromBindableObjectWithIdentityBase))));
 }
예제 #18
0
 public void GettingTheBaseType_GivenAnInterface_ReturnsNull(Type type)
 {
     Assert.That(TypeUtility.GetRootType(type), Is.EqualTo(null));
 }
예제 #19
0
        /// <summary>
        /// Returns true if the specified operation should be inferred as an
        /// IEnumerable or singleton returning query method. Also checks if the
        /// base element type or the type of the singleton is a valid entity type.
        /// </summary>
        /// <param name="operation">The operation to inspect.</param>
        /// <returns>True if the operation is a query method, false otherwise.</returns>
        private bool IsQueryMethod(DomainOperationEntry operation)
        {
            Type elementType = TypeUtility.GetElementType(operation.ReturnType);

            return(this.IsEntityType(elementType));
        }
예제 #20
0
 public void ResolvingATypeName_GivenAnyType_ReturnsExpectedName(Type type, string expected)
 {
     Assert.That(TypeUtility.GetTypeDisplayName(type), Is.EqualTo(expected));
     // Purposefully calling it twice for test stability: This is not a cheap operation and the result may be cached.
     Assert.That(TypeUtility.GetTypeDisplayName(type), Is.EqualTo(expected));
 }
        // Emit a surrogate property for a virtual property (a property that doesn't exist on the physical CLR type).
        // The PropertyDescriptor for each virtual property is initialized in the type initializer of a surrogate type.
        // The surrogate code we'll generate will look like this:
        // public <PropertyType> <PropertyName> {
        //     get {
        //         // For reference types.
        //         return (<PropertyType>)$<PropertyName>.GetValue(_$wrapper);
        //
        //         // For value types.
        //         object value = $<PropertyName>.GetValue(_$wrapper);
        //         if (value == null) {
        //             return default(value);
        //         }
        //         return (<PropertyType>)value;
        //
        //         // For Binary.
        //         Binary value = (Binary)$<PropertyName>.GetValue(_$wrapper);
        //         if (value == null) {
        //             return null;
        //         }
        //         return value.ToArray();
        //     }
        //     set {
        //         if (value == null) {
        //             return;
        //         }
        //
        //         // For normal types.
        //         $<PropertyName>.SetValue(_$wrapper, value);
        //
        //         // For value types.
        //         $<PropertyName>.SetValue(_$wrapper, (object)value);
        //
        //         // For Binary.
        //         Binary valueToStore;
        //         if (value == null) {
        //             valueToStore = null;
        //         }
        //         else {
        //             valueToStore = new Binary(value);
        //         }
        //         $<PropertyName>.SetValue(_$wrapper, valueToStore);
        //     }
        // }
        private static void EmitAttachedProperty(TypeBuilder typeBuilder, FieldInfo wrapperField, Lazy <ILGenerator> typeInitializerFactory, PropertyDescriptor pd, string name)
        {
            // private static PropertyDescriptor $property;
            FieldBuilder propertyDescFieldBuilder = typeBuilder.DefineField("$" + name, typeof(PropertyDescriptor), FieldAttributes.Private | FieldAttributes.Static);

            EmitPropertyInitializer(propertyDescFieldBuilder, typeInitializerFactory, name);

            Type            propertyType    = SerializationUtility.GetClientType(pd.PropertyType);
            PropertyBuilder propertyBuilder = typeBuilder.DefineProperty(name, PropertyAttributes.None, propertyType, null);

            CustomAttributeBuilder dataMemberAtt = DataContractSurrogateGenerator.GetDataMemberAttributeBuilder(
                pd.Attributes[typeof(DataMemberAttribute)] as DataMemberAttribute);

            propertyBuilder.SetCustomAttribute(dataMemberAtt);

            // get {
            //     return $property.GetValue(_$wrapper);
            // }
            MethodBuilder getPropertyMethodBuilder = typeBuilder.DefineMethod("get_" + name, MethodAttributes.Public, propertyType, Type.EmptyTypes);
            ILGenerator   generator = getPropertyMethodBuilder.GetILGenerator();

            // Get the PropertyDescriptor.
            generator.Emit(OpCodes.Ldsfld, propertyDescFieldBuilder);

            // Push the wrapper object onto the stack. We'll use it as an argument for our
            // call to GetValue later on.
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Ldfld, wrapperField);

            // PropertyDescriptor.GetValue(_$wrapper).
            generator.Emit(OpCodes.Callvirt, typeof(PropertyDescriptor).GetMethod("GetValue"));

            // Unbox/cast.
            DynamicMethodUtility.EmitFromObjectConversion(generator, pd.PropertyType);

            // Deal with client-server type conversions.
            if (propertyType != pd.PropertyType)
            {
                EmitToClientConversion(generator, pd.PropertyType, propertyType);
            }

            generator.Emit(OpCodes.Ret);

            propertyBuilder.SetGetMethod(getPropertyMethodBuilder);

            MethodBuilder setPropertyMethodBuilder = typeBuilder.DefineMethod("set_" + name, MethodAttributes.Public, null, new Type[] { propertyType });

            generator = setPropertyMethodBuilder.GetILGenerator();

            Label returnLabel = generator.DefineLabel();

            // Data members require a getter and setter. However, if the real property is read-only, make sure
            // our surrogate property setter is a no-op.
            if (!pd.IsReadOnly)
            {
                // NOTE: We don't ever set null values, because a property may be required. For
                //       original objects however it's possible that required properties are not
                //       roundtripped, as they may not have RoundtripOriginalAttribute.
                // set {
                //     if (value != null) {
                //         $property.SetValue(_$wrapper, value);
                //     }
                // }

                // If the value is null, return.
                if (!propertyType.IsValueType)
                {
                    generator.Emit(OpCodes.Ldarg_1);
                    EmitBranchIfNull(generator, propertyType, returnLabel);
                }
                else if (TypeUtility.IsNullableType(propertyType))
                {
                    generator.Emit(OpCodes.Ldarga_S, 1);
                    EmitBranchIfNull(generator, propertyType, returnLabel);
                }

                // Get the PropertyDescriptor.
                generator.Emit(OpCodes.Ldsfld, propertyDescFieldBuilder);

                // Push the wrapper object onto the stack. We'll use it as an argument for our
                // call to SetValue later on.
                generator.Emit(OpCodes.Ldarg_0);
                generator.Emit(OpCodes.Ldfld, wrapperField);

                // Push the value onto the stack. We'll use it as the 2nd argument for
                // our call to SetValue.
                generator.Emit(OpCodes.Ldarg_1);

                // Deal with client-server type conversions.
                if (propertyType != pd.PropertyType)
                {
                    EmitToServerConversion(generator, propertyType, pd.PropertyType);
                }

                // Box value types.
                DynamicMethodUtility.EmitToObjectConversion(generator, pd.PropertyType);

                // PropertyDescriptor.SetValue(_$wrapper, value).
                generator.Emit(OpCodes.Callvirt, typeof(PropertyDescriptor).GetMethod("SetValue"));
            }

            generator.MarkLabel(returnLabel);
            generator.Emit(OpCodes.Ret);
            propertyBuilder.SetSetMethod(setPropertyMethodBuilder);
        }
예제 #22
0
 private static void OnRecompile()
 {
     FieldTools = TypeUtility.GetImplementationsOfOpenGeneric <ScalarFieldTool>(typeof(ScalarFieldTool <>));
 }
예제 #23
0
            public TypePropertyMetadata(PropertyDescriptor descriptor)
            {
                Name = descriptor.Name;

                Type elementType = TypeUtility.GetElementType(descriptor.PropertyType);

                IsArray = !elementType.Equals(descriptor.PropertyType);
                // TODO: What should we do with nullable types here?
                ClrType = elementType;

                AttributeCollection propertyAttributes = TypeDescriptorExtensions.ExplicitAttributes(descriptor);

                // TODO, 336102, ReadOnlyAttribute for editability?  RIA used EditableAttribute?
                ReadOnlyAttribute readonlyAttr = (ReadOnlyAttribute)propertyAttributes[typeof(ReadOnlyAttribute)];

                IsReadOnly = (readonlyAttr != null) ? readonlyAttr.IsReadOnly : false;

                AssociationAttribute associationAttr = (AssociationAttribute)propertyAttributes[typeof(AssociationAttribute)];

                if (associationAttr != null)
                {
                    Association = new TypePropertyAssociationMetadata(associationAttr);
                }

                RequiredAttribute requiredAttribute = (RequiredAttribute)propertyAttributes[typeof(RequiredAttribute)];

                if (requiredAttribute != null)
                {
                    _validationRules.Add(new TypePropertyValidationRuleMetadata(requiredAttribute));
                }

                RangeAttribute rangeAttribute = (RangeAttribute)propertyAttributes[typeof(RangeAttribute)];

                if (rangeAttribute != null)
                {
                    Type operandType = rangeAttribute.OperandType;
                    operandType = Nullable.GetUnderlyingType(operandType) ?? operandType;
                    if (operandType.Equals(typeof(Double)) ||
                        operandType.Equals(typeof(Int16)) ||
                        operandType.Equals(typeof(Int32)) ||
                        operandType.Equals(typeof(Int64)) ||
                        operandType.Equals(typeof(Single)))
                    {
                        _validationRules.Add(new TypePropertyValidationRuleMetadata(rangeAttribute));
                    }
                }

                StringLengthAttribute stringLengthAttribute = (StringLengthAttribute)propertyAttributes[typeof(StringLengthAttribute)];

                if (stringLengthAttribute != null)
                {
                    _validationRules.Add(new TypePropertyValidationRuleMetadata(stringLengthAttribute));
                }

                DataTypeAttribute dataTypeAttribute = (DataTypeAttribute)propertyAttributes[typeof(DataTypeAttribute)];

                if (dataTypeAttribute != null)
                {
                    if (dataTypeAttribute.DataType.Equals(DataType.EmailAddress) ||
                        dataTypeAttribute.DataType.Equals(DataType.Url))
                    {
                        _validationRules.Add(new TypePropertyValidationRuleMetadata(dataTypeAttribute));
                    }
                }
            }
        public override void Register()
        {
            var types = new List <Metadata.TypeInfo>();

            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Revolute)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Prismatic)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Distance)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Weld)));
            types.Add(MetadataManager.GetTypeOfNetType(typeof(Component_Constraint2D_Fixed)));

            foreach (var type in types)
            {
                var displayName = TypeUtility.GetUserFriendlyNameForInstanceOfType(type.GetNetType());

                var a = new EditorAction();
                a.Name = "Add " + displayName;
                //a.ImageSmall = Properties.Resources.New_16;
                //a.ImageBig = Properties.Resources.New_32;

                a.QatSupport = true;
                //a.qatAddByDefault = true;
                a.ContextMenuSupport = EditorContextMenuWinForms.MenuTypeEnum.Document;

                Component_PhysicalBody2D GetBody(object obj)
                {
                    if (obj is Component_PhysicalBody2D body)
                    {
                        return(body);
                    }

                    var c = obj as Component;

                    if (c != null)
                    {
                        var body2 = c.GetComponent <Component_PhysicalBody2D>();
                        if (body2 != null)
                        {
                            return(body2);
                        }
                    }

                    return(null);
                }

                a.GetState += delegate(EditorAction.GetStateContext context)
                {
                    if (context.ObjectsInFocus.DocumentWindow != null)
                    {
                        object[] selectedObjects = context.ObjectsInFocus.Objects;
                        if (selectedObjects.Length == 2)
                        {
                            var bodyA = GetBody(selectedObjects[0]);
                            var bodyB = GetBody(selectedObjects[1]);

                            if (bodyA != null && bodyB != null)
                            {
                                context.Enabled = true;
                            }
                            //if( selectedObjects[ 0 ] is Component_PhysicalBody2D && selectedObjects[ 1 ] is Component_PhysicalBody2D )
                            //	context.Enabled = true;
                        }
                    }
                };

                a.Click += delegate(EditorAction.ClickContext context)
                {
                    object[] selectedObjects = context.ObjectsInFocus.Objects;
                    if (selectedObjects.Length == 2)
                    {
                        var bodyA = GetBody(selectedObjects[0]);
                        var bodyB = GetBody(selectedObjects[1]);
                        //var bodyA = (Component_PhysicalBody2D)context.ObjectsInFocus.Objects[ 0 ];
                        //var bodyB = (Component_PhysicalBody2D)context.ObjectsInFocus.Objects[ 1 ];

                        var parent = ComponentUtility.FindNearestCommonParent(new Component[] { bodyA, bodyB });
                        if (parent != null)
                        {
                            var data = new NewObjectWindow.CreationDataClass();

                            data.initDocumentWindow = context.ObjectsInFocus.DocumentWindow;
                            data.initParentObjects  = new List <object>();
                            data.initParentObjects.Add(parent);
                            data.initLockType = type;

                            data.additionActionBeforeEnabled = delegate(NewObjectWindow window)
                            {
                                var constraint = (Component_Constraint2D)data.createdComponentsOnTopLevel[0];

                                constraint.BodyA = ReferenceUtility.MakeReference <Component_PhysicalBody2D>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyA));
                                constraint.BodyB = ReferenceUtility.MakeReference <Component_PhysicalBody2D>(
                                    null, ReferenceUtility.CalculateThisReference(constraint, bodyB));

                                if (constraint is Component_Constraint2D_Distance)
                                {
                                    var pos  = bodyA.Transform.Value.Position;
                                    var posB = bodyB.Transform.Value.Position;

                                    var distance = (posB - pos).Length();

                                    var rot = Quaternion.FromDirectionZAxisUp((posB - pos).GetNormalize());
                                    var scl = new Vector3(distance, distance, distance);

                                    constraint.Transform = new Transform(pos, rot, scl);
                                }
                                else
                                {
                                    var pos = (bodyA.Transform.Value.Position + bodyB.Transform.Value.Position) * 0.5;
                                    constraint.Transform = new Transform(pos, Quaternion.Identity);
                                }
                            };

                            EditorAPI.OpenNewObjectWindow(data);
                        }
                    }
                };

                EditorActions.Register(a);
            }
        }
예제 #25
0
 public AlibabaException(SerializationInfo info, StreamingContext context)
     : base(info, context)
 {
     this.ErrorCode = info.GetInt32(TypeUtility.GetMemberName <AlibabaException, int>((obj) => obj.ErrorCode));
 }
예제 #26
0
 public Type GetProxyForType_WhenArgumentIsSpecifiedDataType_ReturnsExpectedValue(Type dataType)
 {
     return(TypeUtility.GetProxyForDataType(dataType));
 }
        public static DragAndDropVisualMode HandleClipPaneObjectDragAndDrop(IEnumerable <UnityObject> objectsBeingDropped, TrackAsset targetTrack, bool perform, TimelineAsset timeline, TrackAsset parent, PlayableDirector director, double candidateTime, TypeResolver typeResolver, TrackAsset insertBefore = null)
        {
            if (timeline == null)
            {
                return(DragAndDropVisualMode.Rejected);
            }

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

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

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

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

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

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

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

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

            // No tracks or markers support this object
            if (!(markerTypes.Any() || validTrackTypes.Any()))
            {
                return(DragAndDropVisualMode.Rejected);
            }
            // track is not compatible with marker
            if (targetTrack != null && markerTypes.Any(o => !TypeUtility.DoesTrackSupportMarkerType(targetTrack, o)))
            {
                // track is not compatible with object
                if (!validTrackTypes.Contains(targetTrack.GetType()))
                {
                    return(DragAndDropVisualMode.Rejected);
                }
            }

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

            return(DragAndDropVisualMode.Copy);
        }
예제 #28
0
    /// <summary>
    /// IsMandatory
    ///     : 필수값 체크
    /// </summary>
    /// <returns></returns>
    private bool IsMandatory(out string sErr, bool abEdit)
    {
        bool bRet = true;

        sErr = "";

        if (abEdit)
        {
            //if (TypeUtility.GetNumString(GetRequest("empid")) == "")
            if (TypeUtility.GetNumString(empId) == "")
            {
                sErr = "alert('수정정보를 정확히 알 수 없습니다.\n\n다시 시도해 주십시요.');";
                bRet = false;
            }
        }

        if (GetValue(txtDeptID.Text) == "")
        {
            sErr = "alert('[부서]를 알 수 없습니다.');";
            bRet = false;
        }
        else if (GetValue(txtDeptName.Text) == "")
        {
            sErr = "alert('[부서]를 알 수 없습니다.');";
            bRet = false;
        }
        else if (GetValue(txtLoginID.Text) == "")
        {
            sErr = "alert('[사용자아이디]를 알 수 없습니다.');"
                   + "try {eval(document.forms[0]." + txtLoginID.ClientID + ".select());} catch(e){}"
                   + "try {eval(document.forms[0]." + txtLoginID.ClientID + ".select());} catch(e){}";

            bRet = false;
        }
        else if (GetValue(txtName.Text) == "")
        {
            sErr = "alert('[사용자명]을 알 수 없습니다.');"
                   + "try {eval(document.forms[0]." + txtName.ClientID + ".select());} catch(e){}"
                   + "try {eval(document.forms[0]." + txtName.ClientID + ".select());} catch(e){}";

            bRet = false;
        }
        else if (PageUtility.GetByValueDropDownList(ddlPositionDuty) == "0")
        {
            sErr = "alert('[직책]을 선택하십시요.');"
                   + "try {eval(document.forms[0]." + ddlPositionDuty.ClientID + ".select());} catch(e){}"
                   + "try {eval(document.forms[0]." + ddlPositionDuty.ClientID + ".select());} catch(e){}";

            bRet = false;
        }
        else if (PageUtility.GetByValueDropDownList(ddlPositionRank) == "0")
        {
            sErr = "alert('[직위]를 선택하십시요.');"
                   + "try {eval(document.forms[0]." + ddlPositionRank.ClientID + ".select());} catch(e){}"
                   + "try {eval(document.forms[0]." + ddlPositionRank.ClientID + ".select());} catch(e){}";

            bRet = false;
        }
        else if (PageUtility.GetByValueDropDownList(ddlPositionGrp) == "0")
        {
            sErr = "alert('[직군]를 선택하십시요.');"
                   + "try {eval(document.forms[0]." + ddlPositionGrp.ClientID + ".select());} catch(e){}"
                   + "try {eval(document.forms[0]." + ddlPositionGrp.ClientID + ".select());} catch(e){}";

            bRet = false;
        }
        else if (PageUtility.GetByValueDropDownList(ddlPositionClass) == "0")
        {
            sErr = "alert('[직급]을 선택하십시요.');"
                   + "try {eval(document.forms[0]." + ddlPositionClass.ClientID + ".select());} catch(e){}"
                   + "try {eval(document.forms[0]." + ddlPositionClass.ClientID + ".select());} catch(e){}";

            bRet = false;
        }
        else if (PageUtility.GetByValueDropDownList(ddlPositionKind) == "0")
        {
            sErr = "alert('[직종]을 선택하십시요.');"
                   + "try {eval(document.forms[0]." + ddlPositionKind.ClientID + ".select());} catch(e){}"
                   + "try {eval(document.forms[0]." + ddlPositionKind.ClientID + ".select());} catch(e){}";

            bRet = false;
        }

        // 추가일 경우에는 아이디의 중복확인을 처리한다.
        if (mode.ToUpper() == "NEW")
        {
            EmpInfos emp = new EmpInfos();

            if (!emp.CheckLoginID(GetValue(txtLoginID.Text)))
            {
                sErr = "alert('입력하신 [사용자아이디]는 이미 존재합니다.');"
                       + "try {eval(document.forms[0]." + txtLoginID.ClientID + ".select());} catch(e){}"
                       + "try {eval(document.forms[0]." + txtLoginID.ClientID + ".select());} catch(e){}";

                bRet = false;
            }
        }

        return(bRet);
    }
        private void DrawSavingStage()
        {
            EditorGUILayout.LabelField("Save System Settings", EditorStyles.boldLabel);
            EditorWindowTools.StartIndentedSection();

            var hasSaveSystem = DialogueManager.instance.GetComponent <PixelCrushers.SaveSystem>() != null;
            var useSaveSystem = EditorGUILayout.Toggle("Use Save System", hasSaveSystem);

            if (useSaveSystem && !hasSaveSystem)
            {
                DialogueManager.instance.gameObject.AddComponent(TypeUtility.GetWrapperType(typeof(PixelCrushers.SaveSystem)));
                hasSaveSystem = true;
            }
            else if (!useSaveSystem && hasSaveSystem)
            {
                DestroyImmediate(DialogueManager.instance.GetComponent <PixelCrushers.SaveSystem>());
                hasSaveSystem = false;
            }
            if (hasSaveSystem)
            {
                EditorGUILayout.HelpBox("The Dialogue System will automatically add a Player Prefs Saved Game Data Storer and JSON Data Serializer at runtime unless you add a different type of Saved Game Data Storer or Data Serializer component to it. For example, you can manually add a Disk Saved Game Data Storer if you want to save games to local disk files.", MessageType.None);
            }

            if (hasSaveSystem)
            {
                var dsSaver = DialogueManager.instance.GetComponent <DialogueSystemSaver>();
                if (dsSaver == null)
                {
                    dsSaver = DialogueManager.instance.gameObject.AddComponent(TypeUtility.GetWrapperType(typeof(PixelCrushers.DialogueSystem.DialogueSystemSaver))) as PixelCrushers.DialogueSystem.DialogueSystemSaver;
                    dsSaver.saveAcrossSceneChanges = true;
                }

                var transitionManager    = DialogueManager.instance.GetComponent <PixelCrushers.SceneTransitionManager>();
                var hasTransitionManager = (transitionManager != null);
                var useTransitionManager = EditorGUILayout.Toggle("Use Scene Transitions", hasTransitionManager);
                if (useTransitionManager && !hasTransitionManager)
                {
                    hasTransitionManager = true;
                    transitionManager    = DialogueManager.instance.gameObject.AddComponent(TypeUtility.GetWrapperType(typeof(PixelCrushers.StandardSceneTransitionManager))) as PixelCrushers.StandardSceneTransitionManager;
                    var stdTransitionMgr = transitionManager as StandardSceneTransitionManager;
                    stdTransitionMgr.pauseDuringTransition = true;
                    if (DialogueManager.instance.transform.Find("SceneFaderCanvas") == null)
                    {
                        var faderCanvasPrefab = AssetDatabase.LoadMainAssetAtPath("Assets/Plugins/Pixel Crushers/Dialogue System/Prefabs/Art/SceneFaderCanvas.prefab");
                        if (faderCanvasPrefab == null)
                        {
                            EditorUtility.DisplayDialog("Prefab Not Found", "This wizard can't find the SceneFaderCanvas prefab. You may have moved the Dialogue System to a different folder in your project. Scene transitions will not fade to black.", "OK");
                        }
                        else
                        {
                            var prefabGO = PrefabUtility.InstantiatePrefab(faderCanvasPrefab) as GameObject;
                            prefabGO.transform.SetParent(DialogueManager.instance.transform, false);
                            UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
                            stdTransitionMgr.leaveSceneTransition.animator              = prefabGO.GetComponent <Animator>();
                            stdTransitionMgr.leaveSceneTransition.trigger               = "Show";
                            stdTransitionMgr.leaveSceneTransition.animationDuration     = 1;
                            stdTransitionMgr.leaveSceneTransition.minTransitionDuration = 1;
                            stdTransitionMgr.enterSceneTransition.animator              = prefabGO.GetComponent <Animator>();
                            stdTransitionMgr.enterSceneTransition.trigger               = "Hide";
                        }
                    }
                }
                else if (!useTransitionManager && hasTransitionManager)
                {
                    DestroyImmediate(transitionManager);
                    hasTransitionManager = false;
                }
                if (hasTransitionManager)
                {
                    EditorGUILayout.HelpBox("The Dialogue Manager's Scene Transition Manager will fade to black by default. If you want to use a separate loading scene, inspect the Dialogue Manager and set the Loading Scene Name field.", MessageType.None);
                }
            }

            EditorWindowTools.EndIndentedSection();
            DrawNavigationButtons(true, true, false);
        }
예제 #30
0
        /// <summary>
        /// Draws the preset values within the inspector.
        /// </summary>
        public override void OnInspectorGUI()
        {
            // Show all of the fields.
            serializedObject.Update();

            EditorGUI.BeginChangeCheck();

            EditorGUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            var preset = target as PersistablePreset;

            if (preset == null)
            {
                return;
            }
            var fullName  = preset.Data.ObjectType;
            var splitName = fullName.Split('.');

            GUILayout.Label(splitName[splitName.Length - 1] + " Preset", EditorStyles.boldLabel);
            GUILayout.FlexibleSpace();
            EditorGUILayout.EndHorizontal();

            // Show the property values within a table.
            var objType = TypeUtility.GetType(preset.Data.ObjectType);

            if (objType != null)
            {
                // Populate the position map so ObjectInspector.DrawProperties to know which properties to draw.
                var valuePositionMap = new Dictionary <int, int>(preset.Data.ValueHashes.Length);
                for (int i = 0; i < preset.Data.ValueHashes.Length; ++i)
                {
                    valuePositionMap.Add(preset.Data.ValueHashes[i], i);
                }

                // Draw all of the serialized properties. Implement the start and end callbacks so the delete button can be drawn next to a foldout in the case of a list, class, or struct.
                Utility.ObjectInspector.DrawProperties(objType, null, 0, valuePositionMap, preset.Data, m_Visiblity, () => { GUILayout.BeginHorizontal(); }, (index, unityObjectIndexes) =>
                {
                    Shared.Editor.Utility.EditorUtility.RecordUndoDirtyObject(preset, "Change Value");
                    var removed = false;
                    if (GUILayout.Button(Utility.InspectorStyles.DeleteIcon, Utility.InspectorStyles.NoPaddingButtonStyle, GUILayout.Width(16)))
                    {
                        RemoveElement(index, unityObjectIndexes);
                        removed = true;
                    }
                    serializedObject.ApplyModifiedProperties();
                    GUILayout.EndHorizontal();
                    return(removed);
                });
            }

            GUILayout.BeginHorizontal();
            GUILayout.FlexibleSpace();
            GUI.enabled = m_AvailableProperies.Count > 0 && !Application.isPlaying; // Only allow the popup if properties can be selected.
            var selectedPropertyIndex = EditorGUILayout.Popup(0, m_AvailablePropertyNames, GUILayout.MaxWidth(150));

            GUI.enabled = true;
            GUILayout.EndHorizontal();
            // If the selected property index isn't 0 then a property should be added.
            if (selectedPropertyIndex != 0)
            {
                var property = m_AvailableProperies[selectedPropertyIndex - 1];
                if (property != null)
                {
                    // Add the new property to the serialization.
                    object value = null;
                    if (!typeof(UnityEngine.Object).IsAssignableFrom(property.PropertyType))
                    {
                        // Lists require special handling.
                        if (typeof(IList).IsAssignableFrom(property.PropertyType))
                        {
                            if (property.PropertyType.IsArray)
                            {
                                var elementType = property.PropertyType.GetElementType();
                                value = Array.CreateInstance(elementType, 0);
                            }
                            else
                            {
                                var baseType = property.PropertyType;
                                while (!baseType.IsGenericType)
                                {
                                    baseType = baseType.BaseType;
                                }
                                var elementType = baseType.GetGenericArguments()[0];
                                if (property.PropertyType.IsGenericType)
                                {
                                    value = Activator.CreateInstance(typeof(List <>).MakeGenericType(elementType)) as IList;
                                }
                                else
                                {
                                    value = Activator.CreateInstance(property.PropertyType) as IList;
                                }
                            }
                        }
                        else
                        {
                            var getMethod = property.GetGetMethod();
                            if (getMethod != null)
                            {
                                // A new GameObject must be created so the component can be added to it. MonoBehaviours cannot use Activator.CreateInstance.
                                GameObject gameObject = null;
                                object     obj;
                                var        objectType = TypeUtility.GetType(preset.Data.ObjectType);
                                if (typeof(MonoBehaviour).IsAssignableFrom(objectType))
                                {
                                    gameObject = new GameObject();
                                    obj        = gameObject.AddComponent(objectType);
                                }
                                else
                                {
                                    obj = Activator.CreateInstance(objectType);
                                }
                                value = getMethod.Invoke(obj, null);
                                if (value == null)
                                {
                                    if (getMethod.ReturnType == typeof(string))
                                    {
                                        value = string.Empty;
                                    }
                                    else
                                    {
                                        value = Activator.CreateInstance(getMethod.ReturnType);
                                    }
                                }
                                if (gameObject != null)
                                {
                                    DestroyImmediate(gameObject);
                                }
                            }
                        }
                    }
                    Serialization.AddProperty(property, value, null, preset.Data, m_Visiblity);
                    InitializeAvailablePropertyArray();
                }
            }

            if (EditorGUI.EndChangeCheck())
            {
                Shared.Editor.Utility.EditorUtility.RecordUndoDirtyObject(preset, "Change Value");
                serializedObject.ApplyModifiedProperties();
            }
        }