public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
 {
     writer.WriteStartObject();
     writer.WritePropertyName("@#IModel");
     writer.WriteValue("0");
     if (_writeTypeInfo)
     {
         writer.WritePropertyName("__type");
         var valueType = value.GetType();
         if (TypeCacheUtils.IsGeneratedType(valueType))
         {
             valueType = valueType.BaseType;
         }
         if (valueType != null)
         {
             var assemblyQualifiedName = valueType.AssemblyQualifiedName;
             writer.WriteValue(assemblyQualifiedName);
         }
     }
     foreach (PropertyInfo prop in value.GetType().GetProperties())
     {
         if (TypeCacheUtils.IsExcludedProperty(prop))
         {
             continue;
         }
         //This check might be innecessary if we are serializing Deltas because the delta should not include the UniqueID
         if (!_writeUniqueId && string.Equals(prop.Name, "UniqueID"))
         {
             continue;
         }
         writer.WritePropertyName(prop.Name);
         serializer.Serialize(writer, prop.GetValue(value, null));
     }
     writer.WriteEndObject();
 }
Exemplo n.º 2
0
        private static void ReportOwnerException(PropertyInfoEx propEx, IStateObject newValue, string old_Uid)
        {
            var stackTrace = new System.Diagnostics.StackTrace(4, true);

            var ownerInfo   = " Not owner info available";
            var ownerObject = StateManager.Current.GetParentEx(newValue);

            if (ownerObject != null)
            {
                var format =
                    " The owner of the object is an instance of class {0}, it is {1}. Look for property {2}. It could have been set during a Build call that is still of process or during an Initialize.Init which is the WebMap equivalent of a constructor. If it is used as parent reference reimplement the property as a non virtual, [StateManagement(None)] calculated property using ViewManager.GetParent(), you can also use [Reference] attribute or disable interception by removing virtual from the property";
                if (StateManager.AllBranchesAttached(ownerObject))
                {
                    ownerInfo = string.Format(format,
                                              TypeCacheUtils.GetOriginalTypeName(ownerObject.GetType()), " ATTACHED ",
                                              StateManager.GetLastPartOfUniqueID(newValue));
                }
                else
                {
                    ownerInfo = string.Format(format, "NOT ATTACHED",
                                              TypeCacheUtils.GetOriginalTypeName(ownerObject.GetType()),
                                              StateManager.GetLastPartOfUniqueID(newValue));
                }
            }
            throw new InvalidOperationException(
                      "LazyBehaviour::ProcessSetter object has already an Owner." + ownerInfo + "\r\n" +
                      "UniqueID: " + old_Uid + "\r\n" +
                      "Additional Info: \r\n" +
                      "ViewModel Type: " + newValue.GetType().FullName + "\r\n" +
                      "Property Type: " + propEx.prop.PropertyType.FullName + "\r\n" +
                      "Error Location: " + stackTrace.ToString());
        }
Exemplo n.º 3
0
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            Type valueType = value.GetType();

            if (TypeCacheUtils.IsControlArray(valueType))
            {
                writer.WriteStartObject();
                var coll = (IObservableCollectionMarkerInterface)value;
                writer.WritePropertyName("UniqueID");
                writer.WriteValue(coll.UniqueID);
                writer.WritePropertyName("Count");
                writer.WriteValue(coll.Count);
                writer.WritePropertyName("@arr");
                writer.WriteValue("1");
                writer.WriteEndObject();
            }
            else
            {
                try
                {
                    base.WriteJson(writer, value, serializer);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.Fail("StateObjectSerializerIndex::WriteJSON error trying to seialize object " + ex.Message);
                    writer.WriteStartObject();
                    writer.WriteEndObject();
                }
            }
        }
        private Delegate PublishInternal(EventPromiseInfo eventHandlerInfo, string eventId, IStateObject source, bool doNotCall, params object[] args)
        {
            var      delegateType  = TypeCacheUtils.GetType(eventHandlerInfo.DelegateType);
            Delegate eventDelegate = PromiseUtils.FromContinuationInfo(delegateType, eventHandlerInfo, source) as Delegate;

            if (eventDelegate == null)
            {
                TraceUtil.TraceError("EventAggregator::PublishInternal Error publishing event. Continuation could not be restored");
                return(null);
            }
            if (doNotCall)
            {
                return(eventDelegate);
            }
            TraceUtil.TraceInformation("Publishing event " + eventId);
            if (eventDelegate != null)
            {
                try
                {
                    eventDelegate.Method.Invoke(eventDelegate.Target, args);
                }
                catch (TargetInvocationException tiex)
                {
                    var baseException = tiex.GetBaseException();
                    PreserveStackTrace(baseException);
                    throw baseException;
                }
            }
            return(eventDelegate);
        }
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject jobj = JObject.Load(reader);
            var     assemblyQualifiedType = jobj["__type"].Value <string>();
            Type    targetType            = Type.GetType(assemblyQualifiedType, false, false);

            if (TypeCacheUtils.IsControlArray(targetType))
            {
                var     size  = jobj["Count"].Value <int>();
                var     uid   = jobj["UniqueID"].Value <string>();
                dynamic value = IocContainerImplWithUnity.Current.ResolveUnPrepared(targetType);
                value.SetupLazy(size, uid);
                return(value);
            }
            object newInstance = IocContainerImplWithUnity.Current.ResolveUnPrepared(targetType);

            foreach (JProperty prop in jobj.Properties().ToList())
            {
                if (prop.Name == "__type")
                {
                    continue;
                }
                //WARNING Fasterflect result might vary frp, the reflection results
                PropertyInfo reflectedProperty = targetType.Property(prop.Name);
                object       adapterValue      = Convert.ChangeType(prop.Value, reflectedProperty.PropertyType);
                reflectedProperty.SetValue(newInstance, adapterValue, null);
            }
            return(newInstance);
        }
 /// <summary>
 /// Indicates if this is a valid type combination
 /// </summary>
 /// <param name="t"></param>
 /// <returns></returns>
 internal bool IsSupportedKeyValuePairDictionary(Type t)
 {
     if (t.IsGenericType)
     {
         var types      = t.GetGenericArguments();
         var key        = types[0];
         var value      = types[1];
         var validKey   = (IsValueTypeOrStringOrTypeNotStruct(key) || typeof(IStateObject).IsAssignableFrom(key));
         var validValue = (IsValueTypeOrStringOrType(value) || typeof(IStateObject).IsAssignableFrom(value) || SurrogatesDirectory.IsSurrogateRegistered(value));
         if (!validValue && value.IsGenericType)
         {
             var genericValueType = value.GetGenericTypeDefinition();
             if (genericValueType == typeof(IList <>))
             {
                 validValue = TypeCacheUtils.IsSupportedGenericTypeForList(value);
             }
             else if (genericValueType == typeof(IDictionary <,>))
             {
                 validValue = IsSupportedKeyValuePairDictionary(value);
             }
         }
         return(validKey && validValue);
     }
     throw new ArgumentException("This method should only be called for generic types");
 }
Exemplo n.º 7
0
        /// <summary>
        /// Watchers can not be applied on IStateObjects. So we need to validate that
        /// </summary>
        /// <param name="type"></param>
        private static void ValidateWatcherType(MemberInfo memInfo)
        {
            Type   type        = null;
            string elementName = memInfo.Name;

            if (memInfo is FieldInfo)
            {
                var finfo = (FieldInfo)memInfo;
                type = finfo.FieldType;
#if DEBUG
                Debug.Assert(!typeof(IStateObject).IsAssignableFrom(type),
                             string.Format("DeltaTracker::ValidateWatcherType Error: The watcher attribute on {0}.{1} is wrong " +
                                           "because watcher attributes are meant to be used on fields that have a FieldType is not an IStateObject",
                                           TypeCacheUtils.GetOriginalTypeName(finfo.DeclaringType), elementName));
#endif
            }
            else if (memInfo is PropertyInfo)
            {
                var pinfo = (PropertyInfo)memInfo;
                type = pinfo.PropertyType;
                var isVirtual = pinfo.GetGetMethod().IsVirtual;
                Debug.Assert(!typeof(IStateObject).IsAssignableFrom(type) && !isVirtual,
                             string.Format("DeltaTracker::ValidateWatcherType Error: The watcher attribute on {0}.{1} is wrong because watcher attributes are meant to be used on non-virtual properties of types that are not an IStateObject",
                                           TypeCacheUtils.GetOriginalTypeName(pinfo.DeclaringType), elementName));
            }
        }
Exemplo n.º 8
0
 public static IEnumerable <PropertyInfo> GetPropertiesForAppState(Type type)
 {
     lock (syncPropsForAppState)
     {
         List <PropertyInfo> props;
         if (!propsfoprAppState.TryGetValue(type, out props))
         {
             props = new List <PropertyInfo>();
             foreach (PropertyInfo prop in type.Properties(BindingFlags.Public | BindingFlags.Instance))
             {
                 //We will load only Visual Objects or Lists
                 if (typeof(IViewModel).IsAssignableFrom(prop.PropertyType) ||
                     typeof(IDependentViewModel).IsAssignableFrom(prop.PropertyType) ||
                     TypeCacheUtils.IsAnIListOfSomethingThatImplementsIStateObject(prop.PropertyType))
                 {
                     //If this is a indexed property then skip
                     if (prop.GetIndexParameters().Length > 0)
                     {
                         continue;
                     }
                     if (TypeCacheUtils.IsExcludedPropertyForClient(prop))
                     {
                         continue;
                     }
                     props.Add(prop);
                 }
             }
             propsfoprAppState.Add(type, props);
         }
         return(props);
     }
 }
Exemplo n.º 9
0
 public static void AddToTypeContractorCache(Type t)
 {
     if (SHORTENTYPENAME)
     {
         lock (SyncTypeTables)
         {
             if (TypeCacheUtils.IsGeneratedType(t))
             {
                 //We will map the intercept types to their base types
                 //This typecontractor cache is used for serialization
                 //We do not need to know the intercepted type
                 var interceptedType = t;
                 TypeCacheUtils.GetOriginalType(ref t);
                 string currentKey;
                 if (!typeContractorReverse.TryGetValue(t, out currentKey))
                 {
                     AddToTypeContractorCache(t);
                     currentKey = typeContractorReverse[t];
                 }
                 typeContractorReverse.Add(interceptedType, currentKey);
             }
             else
             {
                 string key = typeContractorForward.Count.ToBase95ToString(PADDEDCONTRACTEDTYPENAME);
                 if (key.Length == 1)
                 {
                     key += '~';                   //by now the size is 2 then only add one char '~'
                 }
                 typeContractorForward.Add(key, t);
                 typeContractorReverse.Add(t, key);
             }
         }
     }
 }
            private object ReadInputAsType()
            {
                object val = reader.Value; reader.Read();

                val = TypeCacheUtils.GetType((string)val);
                return(val);
            }
 public override JsonContract ResolveContract(Type type)
 {
     //We do not want two different contracts for the proxy type and the actual type
     if (TypeCacheUtils.IsGeneratedType(type))
     {
         TypeCacheUtils.GetOriginalType(ref type);
     }
     return(base.ResolveContract(type));
 }
 public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
 {
     //var longAssemblyName = serializedType.Assembly.FullName;
     if (TypeCacheUtils.IsGeneratedType(serializedType))
     {
         serializedType = serializedType.BaseType;
     }
     TypeCacheUtils.AssemblyQualifiedNameCache(serializedType, out assemblyName, out typeName);
 }
        public void Initialize(IStateManager stateManager, IReferenceManager referenceManager, ISurrogateManager surrogateManager)
        {
            this.stateManager     = stateManager;
            this.referenceManager = referenceManager;
            this.surrogateManager = surrogateManager;
            var tkey   = typeof(TKey);
            var tvalue = typeof(TValue);

            var tkeyIsValueTypeOrStringOrTypeNotStruct = IsValueTypeOrStringOrTypeNotStruct(tkey);
            var tvalueIsValueTypeOrString = IsValueTypeOrStringOrType(tvalue);

            if (tkeyIsValueTypeOrStringOrTypeNotStruct && tvalueIsValueTypeOrString)
            {
                implementation = new DictCase1 <TKey, TValue>();
                CaseType       = 1;
            }
            else if (tkeyIsValueTypeOrStringOrTypeNotStruct &&
                     (typeof(IStateObject).IsAssignableFrom(tvalue) ||
                      TypeCacheUtils.IsIListOrIDictionary(tvalue))


                     )
            {
                implementation = new DictCase2 <TKey, TValue>(stateManager, referenceManager);
                ((DictCase2 <TKey, TValue>)implementation).SetParent(this);
                CaseType = 2;
            }
            else if (tkeyIsValueTypeOrStringOrTypeNotStruct && typeof(Delegate).IsAssignableFrom(tvalue))
            {
                implementation = new DictCase5 <TKey, TValue>(stateManager, surrogateManager);

                CaseType = 5;
            }
            else if (typeof(IStateObject).IsAssignableFrom(tkey) && tvalueIsValueTypeOrString)
            {
                implementation = new DictCase3 <TKey, TValue>();
                CaseType       = 3;
            }
            else if (typeof(IStateObject).IsAssignableFrom(tkey) &&
                     (typeof(IStateObject).IsAssignableFrom(tvalue) || TypeCacheUtils.IsIListOrIDictionary(tvalue))
                     )
            {
                implementation = new DictCase4 <TKey, TValue>();
                CaseType       = 4;
            }
            else if (tkeyIsValueTypeOrStringOrTypeNotStruct && SurrogatesDirectory.IsSurrogateRegistered(tvalue))
            {
                implementation = new DictCase6 <TKey, TValue>(stateManager, surrogateManager, referenceManager);
                ((DictCase6 <TKey, TValue>)implementation).SetParent(this);
                CaseType = 6;
            }
            else
            {
                throw new NotSupportedException();
            }
        }
        public override bool IsCompatibleWith(object value)
        {
            var valueType = value.GetType();

            if (valueType.IsValueType && TypeCacheUtils.IsAnUserStructType(valueType))
            {
                return(true);
            }
            return(false);
        }
Exemplo n.º 15
0
        public static int GetModelTypedInt(Type type)
        {
            if (TypeCacheUtils.IsGeneratedType(type))
            {
                type = type.BaseType;
            }
            int mappedType = 0;

            ClientSideMappingInfo.TryGetValue(type, out mappedType);
            return(mappedType);
        }
        /// <summary>
        ///If field is an Action<> there is no problem
        ///but if field is Func<> then that means that
        ///for int Foo(bool,string) it would be something
        ///like int,bool,string and to find foo we would need to do GetMethod("Foo",,{ bool,string} );
        /// </summary>
        /// <param name="field">field containing delegate inside a DisplayClass</param>
        /// <returns></returns>
        private static Type[] ExtractParameterTypesForDelegateInField(FieldInfo field)
        {
            var parameterTypes = field.FieldType.GetGenericArguments();

            if (TypeCacheUtils.IsFuncType(field.FieldType))
            {
                var res = new Type[parameterTypes.Length - 1];
                Array.Copy(parameterTypes, 0, res, 0, res.Length);
                parameterTypes = res;
            }
            return(parameterTypes);
        }
Exemplo n.º 17
0
        internal static void RegisterDeltaTrackerConverter(Type converterType, AppStateJsonConverter att)
        {
            var modelTypeID = TypeCacheUtils.GetModelTypedInt(att.Model);

            if (modelTypeID <= 0)
            {
                throw new ArgumentException("A Delta Tracker Converter cannot be registered for type " + att.Model);
            }
            var converter = converterType.DelegateForCallMethod("ProcessDelta", new Type[] { typeof(object), typeof(object) });

            converters.Add(modelTypeID, converter);
        }
            public SerializerMethods(JsonReader reader, Type keyType, Type valueType)
            {
                this.reader    = reader;
                this.keyType   = keyType;
                this.valueType = valueType;

                //First assign delegate depending on keyType
                if (typeof(string) == keyType)
                {
                    ReadKeyMethod = ReadInputAsString;
                }
                else if (typeof(Type) == keyType)
                {
                    ReadKeyMethod = ReadInputAsType;
                }
                else if (typeof(IStateObject).IsAssignableFrom(keyType))
                {
                    ReadKeyMethod = ReadInputAsStateObject;
                }
                else if (keyType.IsEnum)
                {
                    ReadKeyMethod = ReadInputAsEnum;
                }
                else
                {
                    ReadKeyMethod = ReadInputAsOther;
                }

                //Second assign delegate depending on valueType
                if (typeof(string) == valueType)
                {
                    ReadValueMethod = ReadInputAsString;
                }
                else if (typeof(Type) == valueType)
                {
                    ReadValueMethod = ReadInputAsType;
                }
                else if (valueType.IsEnum)
                {
                    ReadValueMethod = ReadInputValueAsEnum;
                }
                else if (typeof(IStateObject).IsAssignableFrom(valueType) ||
                         TypeCacheUtils.IsIListOrIDictionary(valueType) ||
                         typeof(Delegate).IsAssignableFrom(valueType) ||
                         SurrogatesDirectory.IsSurrogateRegistered(valueType))
                {
                    ReadValueMethod = ReadInputAsStateObject;
                }
                else
                {
                    ReadValueMethod = ReadInputValueAsOther;
                }
            }
        public T PublishDelegate <T>(string eventId)
        {
            Delegate result = null;

            var eventHandlerInfo = _stateManager.GetObject(eventId) as EventPromiseInfo;

            if (eventHandlerInfo != null)
            {
                var delegateType = TypeCacheUtils.GetType(eventHandlerInfo.DelegateType);
                result = PromiseUtils.FromContinuationInfo(delegateType, eventHandlerInfo) as Delegate;
            }
            return(result == null ? default(T) : (T)(object)Delegate.CreateDelegate(typeof(T), result.Target, result.Method));
        }
Exemplo n.º 20
0
 internal static void InitializeResolver()
 {
     StaticContainer.InitContainer   = () => IocContainerImplWithUnity.Current;
     ConventionBasedHelper.Container = IocContainerImplWithUnity.Current;
     //REgister ContinuationInfo for shorten type info on JSON
     TypeCacheUtils.AddToTypeContractorCache(typeof(PromiseInfo));
     TypeCacheUtils.AddToTypeContractorCache(typeof(UniqueIDGenerator));
     TypeCacheUtils.AddToTypeContractorCache(typeof(ViewsState));
     TypeCacheUtils.AddToTypeContractorCache(typeof(List <ViewInfo>));
     TypeCacheUtils.AddToTypeContractorCache(typeof(List <ClientCommand>));
     TypeCacheUtils.AddToTypeContractorCache(typeof(List <PromiseInfo>));
     TypeCacheUtils.AddToTypeContractorCache(typeof(List <string>));
     TypeCacheUtils.AddAssemblyToTypeContractorCache(typeof(int).Assembly);
     TypeCacheUtils.AddAssemblyToTypeContractorCache(typeof(Bootstrapper).Assembly);
 }
Exemplo n.º 21
0
        /// <summary>
        /// Makes sure that client metadata is already loaded
        /// </summary>
        public static void LoadClientTypeMetadataTable()
        {
            bool hasValues = TypeCacheUtils.DefaultAndAliasMappings.Count > 0;

            if (!hasValues)
            {
                Debug.WriteLine("Loading Client Type Metadata tables");
                foreach (var item in TypeCacheUtils.ClientSideMappingInfo)
                {
                    try
                    {
                        TypeCacheUtils.FillDefaultAndAliasInfoForType(item.Key, item.Value);
                    }
                    catch (Exception) { /*Ignore exception */ }
                }
                Debug.WriteLine("Finished Loading Client Type Metadata tables");
            }
        }
            public SerializerMethods(JsonWriter writer, Type keyType, Type valueType)
            {
                this.writer    = writer;
                this.keyType   = keyType;
                this.valueType = valueType;
                //First assign delegate depending on keyType
                if (typeof(string) == keyType)
                {
                    WriteKeyMethod = WriteKeyGeneric;
                }
                else if (typeof(Type) == keyType)
                {
                    WriteKeyMethod = WriteKeyType;
                }
                else if (typeof(IStateObject).IsAssignableFrom(keyType))
                {
                    WriteKeyMethod = WriteKeyStateObject;
                }
                else
                {
                    WriteKeyMethod = WriteKeyGeneric;
                }

                //Second assign delegate depending on valueType
                if (typeof(string) == valueType)
                {
                    WriteValueMethod = WriteValueGeneric;
                }
                else if (typeof(Type) == valueType)
                {
                    WriteValueMethod = WriteValueType;
                }
                else if (typeof(IStateObject).IsAssignableFrom(valueType) ||
                         TypeCacheUtils.IsIListOrIDictionary(valueType) ||
                         typeof(Delegate).IsAssignableFrom(valueType) ||
                         SurrogatesDirectory.IsSurrogateRegistered(valueType))
                {
                    WriteValueMethod = WriteValueStateObject;
                }
                else
                {
                    WriteValueMethod = WriteValueGeneric;
                }
            }
        private static void RestoreDelegateField(BinaryReader reader, object instance, FieldInfo field)
        {
            //First we retrieve the ID for the target object of delegate
            var targetID = reader.ReadString();

            if (targetID == "NULL")
            {
                //This is an static method
                var declaringTypeName = reader.ReadString();
                var declaringType     = TypeCacheUtils.GetType(declaringTypeName);
            }
            else if (targetID == "INST")
            {
                var methodName = reader.ReadString();
                //Is this an Action<> or Func<>
                if (field.FieldType.IsGenericType)
                {
                    Type[] parameterTypes = ExtractParameterTypesForDelegateInField(field);
                    var    methodInfo     = instance.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, parameterTypes, null);
                    var    delegateValue  = CreateDelegateFromMethodInfo(instance, methodInfo);
                    field.SetValue(instance, delegateValue);
                }
            }
            else
            {
                var targetInstance = StateManager.Current.GetObject(targetID);
                if (targetInstance == null)
                {
                    throw new NotSupportedException("Instance for delegate could not be retrieved");
                }
                //This is an IStateObject
                var methodName = reader.ReadString();
                //Is this an Action<> or Func<>
                if (field.FieldType.IsGenericType)
                {
                    Type[] parameterTypes = ExtractParameterTypesForDelegateInField(field);
                    var    methodInfo     = instance.GetType().GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, parameterTypes, null);
                    var    delegateValue  = CreateDelegateFromMethodInfo(targetInstance, methodInfo);
                    field.SetValue(instance, delegateValue);
                }
            }
        }
Exemplo n.º 24
0
 private void ProcessIfOrphan()
 {
     if (!StateManager.AllBranchesAttached(_current.UniqueID))
     {
         //If we enter here we are Orphans :(
         //We asumme we got here because we are inside a surrogate and
         //that means that there is an StateObjectSurrogate associated with the parentObject
         if (parentCandidate == null)
         {
             var typeName = TypeCacheUtils.GetOriginalTypeName(_current.GetType());
             throw new NotSupportedException("The wrapped stated of type " + typeName + "object with ID" + _current.UniqueID + " does not have a valid parent reference");
         }
         var parentSurrogate = StateManager.Current.surrogateManager.GetSurrogateFor(parentCandidate, generateIfNotFound: false);
         if (parentSurrogate == null)
         {
             var typeName = TypeCacheUtils.GetOriginalTypeName(_current.GetType());
             throw new NotSupportedException("The wrapped stated of type " + typeName + "object with ID" + _current.UniqueID + " does not have a valid parent SURROGATE reference");
         }
         AdoptionInformation.StaticAdopt(parentSurrogate, _current);
     }
 }
Exemplo n.º 25
0
        private static string LoadTypeTable()
        {
            var res = new Dictionary <string, string>(StringComparer.Ordinal);

            TypeCacheUtils.LoadClientTypeMetadataTable();
            foreach (var item in TypeCacheUtils.ClientSideMappingInfo)
            {
                res.Add(item.Value + "", item.Key.FullName.Replace('.', '_'));
            }
            var serializer = new Newtonsoft.Json.JsonSerializer();
            var result     = new Result()
            {
                DefaultsAndAlias = TypeCacheUtils.DefaultAndAliasMappings, TypesInfo = res
            };
            var stringWriter = new System.IO.StringWriter();

            serializer.Serialize(stringWriter, result);
            var typeInfoTable = stringWriter.ToString();

            return(typeInfoTable);
        }
        public object ObjectToRaw(object obj)
        {
            var builderObjectToRaw = new StringBuilder(500);

            using (var writerObjectToRaw = new StringWriter(builderObjectToRaw))
            {
                var type = obj.GetType();
                //No longer necessary TypeCacheUtils typeMarks make the mark of the
                //UnIntercepted and InterceptedTypes equal
                //if (TypeCacheUtils.IsGeneratedType(type))
                //{
                //    TypeCacheUtils.GetOriginalType(ref type);
                //}
                //builderObjectToRaw.Clear();
                string typeMark = null;
                if (TypeCacheUtils.ISSAFETOSHORTENALLTYPES && TypeCacheUtils.SHORTENTYPENAME)
                {
                    typeMark = TypeCacheUtils.AssemblyQualifiedNameCache(type);
                }
#pragma warning disable 0162
                else
                {
                    typeMark = TypeCacheUtils.AssemblyQualifiedNameCache(type);
                }
#pragma warning restore 0162
                builderObjectToRaw.Append(typeMark);
                var depentdsC = obj as IDependentsContainer;
                if (depentdsC != null && depentdsC.Dependents != null)
                {
                    builderObjectToRaw.Append(string.Join(",", depentdsC.Dependents));
                }
                builderObjectToRaw.Append("?");
                using (JsonTextWriter jw = new JsonTextWriter(writerObjectToRaw))
                {
                    jw.ArrayPool = JsonArrayPool.Instance;
                    sessionStorageSerializer.Serialize(writerObjectToRaw, obj, type);
                }
            }
            return(builderObjectToRaw.ToString());
        }
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            writer.WriteStartObject();
            writer.WritePropertyName("$type");
            var valueType = value.GetType();

            if (TypeCacheUtils.IsGeneratedType(valueType))
            {
                valueType = valueType.BaseType;
            }
            if (valueType != null)
            {
                var assemblyQualifiedName = valueType.AssemblyQualifiedName;
                writer.WriteValue(assemblyQualifiedName);
            }
            var viewmodel = (IStateObject)value.GetPropertyValue("ViewModel");
            var uid       = viewmodel.UniqueID;

            writer.WritePropertyName("UniqueID");
            writer.WriteValue(uid);
            writer.WriteEndObject();
        }
        protected override List <MemberInfo> GetSerializableMembers(Type type)
        {
            if (TypeCacheUtils.IsAnStructType(type) ||
                (type == typeof(CurrentState)) ||
                (type == typeof(ViewsState)) ||
                (type == typeof(ClientCommand)))
            {
                return(base.GetSerializableMembers(type));
            }

            List <MemberInfo> props = new List <MemberInfo>();

            foreach (var propEx in TypePropertiesCache.GetArrayPropertiesOrderedByIndex(type))

            {
                if (propEx != null && !propEx.IsExcludedPropertyForSerialization(serverSide, skipUniqueId, skipObjectProperties))
                {
                    props.Add(propEx.prop);
                }
            }
            return(props);
        }
        public System.Web.Mvc.ActionResult QueryClose(string viewId)
        {
            //Find corresponding Form Type

            var genericInterface = typeof(UpgradeHelpers.Interfaces.ILogicWithViewModel <>);
            var view             = StateManager.Current.GetObject(viewId) as UpgradeHelpers.Interfaces.IViewModel;

            if (view == null)
            {
                TraceUtil.TraceError("QueryClose issue for View {0}", viewId);
                return(new UpgradeHelpers.WebMap.Server.AppChanges());
            }
            var viewType = view.GetType();

            //Get original type if View was instrumented
            TypeCacheUtils.GetOriginalType(ref viewType);

            var interfaceBindingFormAndViewTogether = genericInterface.MakeGenericType(viewType);

            //I assume that the matching form logic is defined in the same assembly and that there is only one
            foreach (var clazz in viewType.Assembly.GetTypes())
            {
                if (interfaceBindingFormAndViewTogether.IsAssignableFrom(clazz))
                {
                    var logic = IocContainerImplWithUnity.Current.Resolve(clazz, new object[] { view, }) as UpgradeHelpers.Interfaces.ILogicWithViewModel <UpgradeHelpers.Interfaces.IViewModel>;
                    if (logic == null)
                    {
                        TraceUtil.WriteLine("WebMapViewManagerController::QueryClose error could not recover form object");
                    }
                    else
                    {
                        ViewManager.DisposeView(logic);
                    }
                    break;
                }
            }
            return(new UpgradeHelpers.WebMap.Server.AppChanges());
        }
Exemplo n.º 30
0
        internal void RegisterType(Type typeToRegister)
        {
#if DETAILED_DEBUG
            Trace.TraceInformation("Processing type " + typeToRegister.FullName);
#endif

            if (typeToRegister != null && typeof(IStateObject).IsAssignableFrom(typeToRegister) &&             //This is to make eliminating false cases faster
                (typeof(IDependentModel).IsAssignableFrom(typeToRegister) ||
                 typeof(IDependentViewModel).IsAssignableFrom(typeToRegister) ||
                 typeof(IViewModel).IsAssignableFrom(typeToRegister) ||
                 (typeof(IModel).IsAssignableFrom(typeToRegister))))
            {
                try
                {
                    if (!typeToRegister.IsAbstract && !typeToRegister.IsInterface)
                    {
                        if (typeof(NoInterception).IsAssignableFrom(typeToRegister))
                        {
                            TraceUtil.TraceInformation("Excluding type from interception " + typeToRegister.FullName);
                            non_interceptedTypes.Add(typeToRegister);
                        }
                        else
                        {
                            interceptedTypes.Add(typeToRegister);
                            if (!typeToRegister.IsGenericType)
                            {
                                InitializationHelpers.LoadTypeHierarchy(typeToRegister);
                            }
                        }
                        TypeCacheUtils.AddClientTypeRegistration(typeToRegister);
                    }
                }
                catch (Exception registerTypeException)
                {
                    Trace.TraceError("Bootstrapper::RegisterAllTypes problem while registering type " + typeToRegister.FullName + " Message " + registerTypeException.Message);
                }
            }
        }