Exemple #1
0
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            var propName = binder.Name;
            var prop     = _parent.GetType().GetProperty(propName);

            if (prop != null)
            {
                result = prop.GetValue(_parent, null);
            }
            else
            {
                result = 0;
            }
            return(true);
        }
Exemple #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());
        }
        internal void SyncDirtyModel(JToken jobj)
        {
            string       uniqueId = ((JProperty)(jobj)).Name;
            IStateObject obj      = StateManager.Current.GetObject(uniqueId);

            Debug.Assert(obj != null, "Model to sync was not found ID:" + uniqueId);
            JToken val = jobj.FirstOrDefault();

            if (val != null && (!(val is JArray) || (((JArray)val).Count > 0 && ((JArray)val)[0].HasValues)))
            {
                var  type          = obj.GetType();
                bool converterUsed = false;
                foreach (var converter in convertersForAppChanges)
                {
                    if (converter.CanConvert(type))
                    {
                        var ns = converter.GetType().Namespace;
                        if (ns != null && ns.Equals("UpgradeHelpers.BasicViewModels.SerializationAndStorage", StringComparison.Ordinal))
                        {
                            using (JsonReader reader = val.CreateReader())
                            {
                                reader.Read();
                                converter.ReadJson(reader, type, obj, syncDirtyModelsSerializer);
                                converterUsed = true;
                                break;
                            }
                        }
                    }
                }
                if (!converterUsed)
                {
                    syncDirtyModelsSerializer.Populate(val.CreateReader(), obj);
                }
            }
        }
Exemple #4
0
        /// <summary>
        /// Retrieves type information for an state object
        /// </summary>
        /// <param name="m"></param>
        /// <returns>0 if not found or a number greater that 0 from the type map table</returns>
        public static int GetModelTypedInt(IStateObject m)
        {
            if (ClientSideMappingInfo == null || m == null)
            {
                return(0);
            }
            var type = m.GetType();

            return(GetModelTypedInt(type));
        }
Exemple #5
0
        private static void ReportInvalidStateObject(PropertyInfoEx propEx, IStateObject newValue)
        {
            var stackTrace = new System.Diagnostics.StackTrace(3, true);

            throw new InvalidOperationException(
                      "LazyBehaviour::ProcessSetter old_Uid was null. This might happen if the ViewModel is instantiated with new instead of using Container.Resolve<T>.\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());
        }
Exemple #6
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);
     }
 }
Exemple #7
0
        public static ActionResult DefaultEventHandlerBasedOnConventions(Type refType, string id, string form, IStateObject viewFromClient,
                                                                         string eventSender)
        {
            string classForLogic = string.Format("{0}.{1}", refType.Namespace, form);
            Type   classType     = refType.Assembly.GetType(classForLogic, false);

            if (classType != null)
            {
                ////Get Reflection reference to static method Create

                //var createMethod = classType.BaseType.GetMethod("Create");
                MethodInfo method = classType.GetMethod(id, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

                if (method != null)
                {
                    //TODO StateManager.Instance.Save(viewFromClient);
                    object instance = Container.Resolve(refType, null);


                    int    lastUnderscode = method.Name.LastIndexOf("_");
                    string propertyName   = method.Name.Substring(0, lastUnderscode);


                    object       argEventSender = viewFromClient;
                    PropertyInfo prop           = viewFromClient.GetType().GetProperty(propertyName);
                    if (prop != null)
                    {
                        argEventSender = prop.GetValue(viewFromClient, null);
                        if (argEventSender != null && typeof(IList <>).IsAssignableFrom(prop.PropertyType))
                        {
                            //Control array
                            int index = 0;
                            if (int.TryParse(eventSender, out index))
                            {
                                argEventSender = ((IList)argEventSender)[index];
                            }
                        }
                    }

                    method.Invoke(instance, new[] { argEventSender, null });
                }
                return(new AppChanges());
            }
            else
            {
                return(new JsonResult {
                    Data = "NotAHandler", ContentType = null, ContentEncoding = null, JsonRequestBehavior = JsonRequestBehavior.DenyGet
                });
            }
        }
Exemple #8
0
        /// <summary>
        ///     Given the instance it tries to add the bit array to the dictionary of bit arrays
        ///     representing the state (modified or not) of the model properties.
        /// </summary>
        /// <param name="model">The instance of IChangesTrackeable</param>
        public void AddsBitArray(IStateObject model)
        {
            BitArray data;

            if (!bitArrays.TryGetValue(model, out data))
            {
                var props = TypePropertiesCache.GetArrayPropertiesOrderedByIndex(model.GetType());
                bitArrays.Add(model, new BitArray(props.Count));
            }
            else
            {
                data.SetAll(false);
            }
        }
Exemple #9
0
        //[StateManagement(StateManagementValues.None)]
        //public virtual UpgradeHelpers.Interfaces.ILogicView<UpgradeHelpers.Interfaces.IViewModel> ParentForm
        //{
        //    get { return GetParentForm(this); }
        //}

        private UpgradeHelpers.Interfaces.ILogicView <UpgradeHelpers.Interfaces.IViewModel> GetParentForm(IStateObject obj)
        {
            IStateObject parent = ViewManager.GetParent(obj);

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

            if (typeof(IViewModel).IsAssignableFrom(parent.GetType()))
            {
                return((UpgradeHelpers.Interfaces.ILogicView <UpgradeHelpers.Interfaces.IViewModel>)parent);
            }

            return(GetParentForm(parent));
        }
Exemple #10
0
        private void RegisterWatchablePropertiesAndFieldsEx(IStateObject model)
        {
            var modelType = model.GetType();
            var winfo     = LoadWatcherInfo(modelType);

            //It this type has no watchers, just exit.
            if (Object.ReferenceEquals(winfo, NOINFO))
            {
                return;
            }
            //If the type has watchers then the delta tracker associated the model with its watchers info
            watchedInfoEx = watchedInfoEx ?? new Dictionary <IStateObject, WatchedInfoEx>(ComparerByReference.CommonInstance);
            if (!watchedInfoEx.ContainsKey(model))
            {
                lock (watchedInfoExLock)
                {
                    watchedInfoEx.Add(model, new WatchedInfoEx(winfo, model));
                }
            }
        }
Exemple #11
0
 public override void SaveObject(IStateObject obj)
 {
     try
     {
         object rawData = _serializer.ObjectToRaw(obj);
         SaveRaw(obj.UniqueID, rawData);
     }
     catch (Exception ex)
     {
         TraceUtil.TraceError("SessionStorageManager::SaveObject id:{0} type:{1} Exception {2}", obj.UniqueID, obj.GetType(), ex.Message);
     }
 }
Exemple #12
0
        /// <summary>
        ///     Given the property Index and its instance, it sets in the corresponding bit array at
        ///     the corresponding index (of the property) the value to true (modified)
        ///     Assumming that model is not a dirty model
        /// </summary>
        /// <param name="model">The instance of IChangesTrackeable</param>
        /// <param name="property">The name of the property</param>
        public void MarkAsModified(IStateObject model, int index)
        {
            if (model.UniqueID == null ||
                IsDirtyModel(model) ||
                !StateManager.AllBranchesAttached(model))
            {
                return;
            }
            BitArray data;

            lock (modifiedLock)
            {
                if (!bitArrays.TryGetValue(model, out data))
                {
                    int typePropertiesLength = TypePropertiesCache.GetArrayPropertiesCount(model.GetType());
                    bitArrays.Add(model, data = new BitArray(typePropertiesLength));
                }
                if (data == null)
                {
                    int typePropertiesLength = TypePropertiesCache.GetArrayPropertiesCount(model.GetType());
                    bitArrays[model] = data = new BitArray(typePropertiesLength);
                }
            }
            data.Set(index, true);
        }
Exemple #13
0
        /// <summary>
        ///     Given the property name and its instance, it sets in the corresponding bit array at
        ///     the corresponding index (of the property) the value to true (modified)
        ///     Assumming that model is not a dirty model
        /// </summary>
        /// <param name="model">The instance of IChangesTrackeable</param>
        /// <param name="property">The name of the property</param>
        public void MarkAsModified(IStateObject model, string property)
        {
            if (model.UniqueID == null ||
                IsDirtyModel(model) ||
                !StateManager.AllBranchesAttached(model))
            {
                return;
            }

            PropertiesExDictionary typeProperties = TypePropertiesCache.GetPropertiesIndexPositionOfType(model.GetType());
            int propertyIndex;

            if (!typeProperties.TryGetValue(property, out propertyIndex))
            {
                return;
            }
            BitArray data;

            lock (modifiedLock)
            {
                if (!bitArrays.TryGetValue(model, out data))
                {
                    bitArrays.Add(model, data = new BitArray(typeProperties.PropertiesList.Count));
                }
                if (data == null)
                {
                    bitArrays[model] = data = new BitArray(typeProperties.PropertiesList.Count);
                }
            }
            data.Set(propertyIndex, true);
        }
Exemple #14
0
        /// <summary>
        ///     It collects all the delta objects int the given instance
        /// </summary>
        /// <param name="instance">The instance</param>
        /// <returns>The changes found in the instance</returns>
        public object GetDeltas(IStateObject instance)
        {
            //  Arrayway
            BitArray bitArray;
            Delta    delta = null;

            // if model has been subscribed to any delta tracker
            if (bitArrays.TryGetValue(instance, out bitArray))
            {
                if (bitArray == null)
                {
                    return(null);
                }
                if (instance is IReturnWholeObjectAsDelta)
                {
                    return(instance);
                }
                var propertiesMatchingBitArrays = TypePropertiesCache.GetArrayPropertiesOrderedByIndex(instance.GetType());
                var dataCount = bitArray.Count;
                for (var bitArrayPosition = 0; bitArrayPosition < dataCount; bitArrayPosition++)
                {
                    if (bitArray.Get(bitArrayPosition))
                    {
                        var propertyInfoEx = propertiesMatchingBitArrays[bitArrayPosition];
                        if (!propertyInfoEx.mustIgnoreMemberForClient)
                        {
                            object propValue = propertyInfoEx.prop.GetValue(instance);
                            if (delta == null)
                            {
                                delta = new Delta();
                            }
                            delta.Add(propertyInfoEx.prop.Name, propValue);
                        }
                    }
                }
            }
            if (delta != null)
            {
                //We are including the UniqueID in the delta
                if (delta.Count > 0)
                {
                    delta["UniqueID"] = instance.UniqueID;
                }
            }
            return(delta);
        }