protected object CreateInstanceFromContent(IContentBase content, ContentTypeRegistration registration, CodeFirstModelContext parentContext = null)
        {
            Dictionary <PropertyInfo, CodeFirstLazyInitialiser> dict;
            var instance = CodeFirstModelContext.CreateContextualInstance(registration.ClrType, registration, out dict, parentContext, false);

            //properties on Generic Tab
            foreach (var property in registration.Properties)
            {
                CopyPropertyValueToModel(content, instance, property);
            }

            foreach (var tab in registration.Tabs)
            {
                //tab instance
                Dictionary <PropertyInfo, CodeFirstLazyInitialiser> tabDict;
                var tabInstance = CodeFirstModelContext.CreateContextualInstance(tab.ClrType, tab, out tabDict);
                foreach (var property in tab.Properties)
                {
                    CopyPropertyValueToModel(content, tabInstance, property);
                }
                tab.PropertyOfParent.SetValue(instance, tabInstance);
            }

            foreach (var composition in registration.Compositions)
            {
                CodeFirstModelContext.MoveNextContext(instance, composition);
                composition.PropertyOfContainer.SetValue(instance, CreateInstanceFromContent(content, composition, CodeFirstModelContext.GetContext(instance)));
            }

            return(instance);
        }
        /// <summary>
        /// Extension used to convert an IPublishedContent back to a Typed model instance.
        /// Your model does need to inherit from UmbracoGeneratedBase and contain the correct attributes
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        public T ConvertToModel <T>(IMedia content, CodeFirstModelContext parentContext = null) where T : MediaTypeBase
        {
            //TODO move to base class, use a lambda for the type-dependent operations
            MediaTypeRegistration registration;

            if (!_mediaTypeModule.TryGetMediaType(content.ContentType.Alias, out registration))
            {
                throw new CodeFirstException("Could not find media type registration for media type alias " + content.ContentType.Alias);
            }
            if (registration.ClrType != typeof(T))
            {
                if (registration.ClrType.Inherits(typeof(T)))
                {
                    //Redirect to the underlying type and make one of those instead
                    if (!_mediaTypeModule.TryGetMediaType(typeof(T), out registration))
                    {
                        throw new CodeFirstException("Could not find media type registration for underlying type " + typeof(T).FullName);
                    }
                }
                else
                {
                    throw new CodeFirstException("Registered type for media type " + content.ContentType.Alias + " is " + registration.ClrType.Name + ", not " + typeof(T).Name);
                }
            }

            T instance = (T)CreateInstanceFromContent(content, registration, parentContext);

            (instance as MediaTypeBase).NodeDetails = new MediaNodeDetails(content);
            return(instance);
        }
Example #3
0
        public T ConvertToModel <T>(IPublishedContent content, CodeFirstModelContext parentContext = null) where T : MemberTypeBase
        {
            var result = base.ConvertToModelInternal <T>(content, parentContext);

            GetMemberSpecificProperties(result as MemberTypeBase, content as Umbraco.Web.PublishedCache.MemberPublishedContent);
            return(result);
        }
        /// <summary>
        /// Extension used to convert an IPublishedContent back to a Typed model instance.
        /// Your model does need to inherit from UmbracoGeneratedBase and contain the correct attributes
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        public T ConvertToModel <T>(IContent content, CodeFirstModelContext parentContext = null) where T : DocumentTypeBase
        {
            //TODO move to derived
            DocumentTypeRegistration registration;

            if (!_documentTypeModule.TryGetDocumentType(content.ContentType.Alias, out registration))
            {
                throw new CodeFirstException("Could not find document type registration for document type alias " + content.ContentType.Alias);
            }
            if (registration.ClrType != typeof(T))
            {
                if (registration.ClrType.Inherits(typeof(T)))
                {
                    //Redirect to the underlying type and make one of those instead
                    if (!_documentTypeModule.TryGetDocumentType(typeof(T), out registration))
                    {
                        throw new CodeFirstException("Could not find document type registration for underlying type " + typeof(T).FullName);
                    }
                }
                else
                {
                    throw new CodeFirstException("Registered type for document type " + content.ContentType.Alias + " is " + registration.ClrType.Name + ", not " + typeof(T).Name);
                }
            }

            T instance = (T)CreateInstanceFromContent(content, registration, parentContext);

            (instance as DocumentTypeBase).NodeDetails = new DocumentNodeDetails(content);
            return(instance);
        }
        private string GetHtml()
        {
            var prop = CodeFirstModelContext.GetContext(this).ContentType.Properties.FirstOrDefault(x => x.Alias == SpecialAliases.FileUpload);

            if (prop == null)
            {
                return(string.Empty);
            }
            else
            {
                var val = prop.Metadata.GetValue(this);
                if (val == null)
                {
                    return(string.Empty);
                }
                else
                {
                    if (val is IHtmlString)
                    {
                        return((val as IHtmlString).ToHtmlString());
                    }
                    else
                    {
                        return(HttpUtility.HtmlEncode(val.ToString()));
                    }
                }
            }
        }
        private static void GetContextAttributes <T>(CodeFirstModelContext context, List <T> attributes) where T : CodeFirstContextualAttribute
        {
            if (!CodeFirstManager.Current.Features.UseContextualAttributes)
            {
                return;
            }

            if (context.CurrentProperty != null)
            {
                //Add classes from property
                attributes.AddRange(context.CurrentProperty.Metadata.GetCodeFirstAttributesWithInheritance <T>());
            }

            if (context.ContentType != null)
            {
                //Add classes from current content type
                attributes.AddRange(context.ContentType.ClrType.GetCodeFirstAttributesWithInheritance <T>());
            }

            if (context.CurrentDataType != null)
            {
                //Add classes from the current data type
                attributes.AddRange(context.CurrentDataType.ClrType.GetCodeFirstAttributesWithInheritance <T>());
            }
        }
 private void SetPropertyValueOnModel(object objectInstance, PropertyRegistration registration, object umbracoStoredValue)
 {
     if (registration.DataType.ConverterType != null)
     {
         IDataTypeConverter converter = (IDataTypeConverter)Activator.CreateInstance(registration.DataType.ConverterType);
         var val = converter.Create(umbracoStoredValue, x => CodeFirstModelContext.MoveNextContext(x, registration));
         if (val != null)
         {
             CodeFirstModelContext.MoveNextContext(val, registration);
             var attr = registration.Metadata.GetCodeFirstAttribute <ContentPropertyAttribute>();
             if (attr != null && attr is IDataTypeRedirect)
             {
                 val = (attr as IDataTypeRedirect).GetRedirectedValue(val);
                 if (val != null)
                 {
                     //Keep a second context so wrapped types can still find their property
                     //Will add nothing if the Redirector registered a context already (e.g. called ConvertToModel to create the value).
                     //Hopefully said redirector passed in a parent context so the converted value can still find its way back here.
                     CodeFirstModelContext.MoveNextContext(val, registration);
                 }
             }
             registration.Metadata.SetValue(objectInstance, val);
         }
     }
     else if (umbracoStoredValue != null)
     {
         //Context currently not supported for PEVCs - many are value types, very unlikely to have unique hashes for all values in a request context, none except custom ones would have
         //code to use the context anyway.
         registration.Metadata.SetValue(objectInstance, umbracoStoredValue);
     }
 }
 /// <summary>
 /// Initialises the prevalues and options collections
 /// </summary>
 private void Init()
 {
     if (_preValues == null)
     {
         _preValues = CodeFirstModelContext.GetContext(this)?.CurrentPreValues
                      ??
                      Current.Modules.PreValueCacheModule.Get(Current.Modules.DataTypeModule.GetDataType(GetType()));
         _options = _preValues.Select(x => x.Value).ToList();
     }
 }
        protected object CreateInstanceFromPublishedContent(IPublishedContent content, ContentTypeRegistration registration, CodeFirstModelContext parentContext = null)
        {
            Dictionary <PropertyInfo, CodeFirstLazyInitialiser> dict;
            var instance = CodeFirstModelContext.CreateContextualInstance(registration.ClrType, registration, out dict, parentContext);

            //properties on Generic Tab
            foreach (var property in registration.Properties)
            {
                if (CodeFirstManager.Current.Features.UseLazyLoadingProxies && property.Metadata.GetGetMethod().IsVirtual)
                {
                    dict.Add(property.Metadata, new CodeFirstLazyInitialiser(() => CopyPropertyValueToModel(content, instance, property)));
                }
                else
                {
                    CopyPropertyValueToModel(content, instance, property);
                }
            }

            foreach (var tab in registration.Tabs)
            {
                //tab instance
                Dictionary <PropertyInfo, CodeFirstLazyInitialiser> tabDict;
                var tabInstance = CodeFirstModelContext.CreateContextualInstance(tab.ClrType, tab, out tabDict);
                foreach (var property in tab.Properties)
                {
                    if (CodeFirstManager.Current.Features.UseLazyLoadingProxies && property.Metadata.GetGetMethod().IsVirtual)
                    {
                        tabDict.Add(property.Metadata, new CodeFirstLazyInitialiser(() => CopyPropertyValueToModel(content, tabInstance, property)));
                    }
                    else
                    {
                        CopyPropertyValueToModel(content, tabInstance, property);
                    }
                }
                tab.PropertyOfParent.SetValue(instance, tabInstance);
            }

            foreach (var composition in registration.Compositions)
            {
                var parent = CodeFirstModelContext.GetCompositionParentContext(composition);
                if (CodeFirstManager.Current.Features.UseLazyLoadingProxies && composition.PropertyOfContainer.GetGetMethod().IsVirtual)
                {
                    dict.Add(composition.PropertyOfContainer, new CodeFirstLazyInitialiser(() => composition.PropertyOfContainer.SetValue(instance, CreateInstanceFromPublishedContent(content, composition, parent))));
                }
                else
                {
                    composition.PropertyOfContainer.SetValue(instance, CreateInstanceFromPublishedContent(content, composition, parent));
                }
            }

            CodeFirstModelContext.ResetContext();
            return(instance);
        }
        public object ConvertToModel(IPublishedContent content, CodeFirstModelContext parentContext = null)
        {
            ContentTypeRegistration docType;

            if (_contentTypeModule.TryGetContentType(content.DocumentTypeAlias, out docType))
            {
                MethodInfo convertToModel = GetConvertToModelMethod(docType.ClrType);
                return(convertToModel.Invoke(this, new object[] { content, parentContext }));
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Extension used to convert an IPublishedContent back to a Typed model instance.
        /// Your model does need to inherit from UmbracoGeneratedBase and contain the correct attributes
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="content"></param>
        /// <returns></returns>
        protected Tmodel ConvertToModelInternal <Tmodel>(IPublishedContent content, CodeFirstModelContext parentContext = null) where Tmodel : CodeFirstContentBase <T>
        {
            ContentTypeRegistration registration;

            if (content == null)
            {
                throw new ArgumentNullException("content", Environment.StackTrace);
            }

            if (!_contentTypeModule.TryGetContentType(content.ContentType.Alias, out registration))
            {
                throw new CodeFirstException("Could not find content type registration for content type alias " + content.ContentType.Alias);
            }
            if (registration.ClrType != typeof(Tmodel))
            {
                if (registration.ClrType.Inherits(typeof(Tmodel)))
                {
                    if (typeof(Tmodel).GetCodeFirstAttribute <ContentTypeAttribute>(false) == null)                    //The base type is not an Umb content type, just create the full document and cast the result
                    {
                    }
                    else if (!_contentTypeModule.TryGetContentType(typeof(Tmodel), out registration)) //Redirect to the underlying type and make one of those instead
                    {
                        throw new CodeFirstException("Could not find content type registration for underlying type " + typeof(Tmodel).FullName);
                    }
                }
                else
                {
                    throw new CodeFirstException("Registered type for content type " + content.ContentType.Alias + " is " + registration.ClrType.Name + ", not " + typeof(Tmodel).Name);
                }
            }

            Tmodel instance = (Tmodel)CreateInstanceFromPublishedContent(content, registration, parentContext);

            if (instance == null)
            {
                throw new CodeFirstException("Model could not be created. Target type: " + typeof(Tmodel).Name);
            }

            if ((instance as CodeFirstContentBase <T>) == null)
            {
                throw new CodeFirstException("Created model could not be cast to CodeFirstContentBase<T>. Type of T: " + typeof(T).Name);
            }

            (instance as CodeFirstContentBase <T>).NodeDetails = new T();
            ((instance as CodeFirstContentBase <T>).NodeDetails as ContentNodeDetails).Initialise(content);
            ModelEventDispatcher <Tmodel> .OnLoad(instance, content, new HttpContextWrapper(HttpContext.Current), UmbracoContext.Current, ApplicationContext.Current, CodeFirstModelContext.GetContext(instance));

            return(instance);
        }
Example #12
0
        /// <summary>
        /// Extension used to convert an IPublishedContent back to a Typed model instance.
        /// Your model does need to inherit from UmbracoGeneratedBase and contain the correct attributes
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        public static object ConvertToModel(this IPublishedContent content, CodeFirstModelContext parentContext = null)
        {
            switch (content.ItemType)
            {
            case PublishedItemType.Content:
                return(CodeFirstManager.Current.Modules.DocumentModelModule.ConvertToModel(content, parentContext));

            case PublishedItemType.Media:
                return(CodeFirstManager.Current.Modules.MediaModelModule.ConvertToModel(content, parentContext));

            case PublishedItemType.Member:
                return(CodeFirstManager.Current.Modules.MemberModelModule.ConvertToModel(content, parentContext));

            default:
                throw new NotImplementedException();
            }
        }
        public static IEnumerable <T> GetAttributesFromContextTree <T>(this object key) where T : CodeFirstContextualAttribute
        {
            var attributes = new List <T>();

            if (!CodeFirstManager.Current.Features.UseContextualAttributes)
            {
                return(attributes);
            }

            var context = CodeFirstModelContext.GetContext(key);

            GetContextAttributes(context, attributes);

            var current = context.ParentContext;

            while (current != null)
            {
                GetContextAttributes(current, attributes);
                current = current.ParentContext;
            }
            return(attributes);
        }
Example #14
0
 internal static void OnLoadObject(object model, IPublishedContent contentInstance, HttpContextBase httpContext, UmbracoContext umbContext, ApplicationContext appContext, CodeFirstModelContext modelContext)
 {
     if (model.GetType().Inherits <CodeFirstContentBase>())
     {
         typeof(ModelEventDispatcher <>)
         .MakeGenericType(model.GetType())
         .GetTypeInfo()
         .InvokeMember("OnLoad",
                       BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod,
                       null,
                       null,
                       new object[]
         {
             model,
             contentInstance,
             httpContext,
             umbContext,
             appContext,
             modelContext
         });
     }
     else
     {
         throw new CodeFirstException("Not a valid model type");
     }
 }
Example #15
0
 public static T ConvertMemberToModel <T>(this IPublishedContent content, CodeFirstModelContext parentContext = null) where T : MemberTypeBase
 {
     return(CodeFirstManager.Current.Modules.MemberModelModule.ConvertToModel <T>(content, parentContext));
 }
Example #16
0
 public static T ConvertToModel <T>(this IMedia content, CodeFirstModelContext parentContext = null) where T : MediaTypeBase
 {
     return(CodeFirstManager.Current.Modules.MediaModelModule.ConvertToModel <T>(content, parentContext));
 }
Example #17
0
 /// <summary>
 /// Extension used to convert an IPublishedContent back to a Typed model instance.
 /// Your model does need to inherit from UmbracoGeneratedBase and contain the correct attributes
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="content"></param>
 /// <returns></returns>
 public static T ConvertToModel <T>(this IContent content, CodeFirstModelContext parentContext = null) where T : DocumentTypeBase
 {
     return(CodeFirstManager.Current.Modules.DocumentModelModule.ConvertToModel <T>(content, parentContext));
 }
Example #18
0
 public void OnLoad(Factoid model, HttpContextBase httpContext, UmbracoContext umbContext, ApplicationContext appContext, CodeFirstModelContext modelContext, IPublishedContent currentPage)
 {
 }
 public T ConvertToModel <T>(IPublishedContent content, CodeFirstModelContext parentContext = null) where T : MediaTypeBase
 {
     return(base.ConvertToModelInternal <T>(content, parentContext));
 }
        protected override T GetModelFromId(int id)
        {
            var node = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current).TypedMedia(id);

            return(node == null ? null : node.ConvertMediaToModel <T>(CodeFirstModelContext.GetContext(this)));
        }
 /// <summary>
 /// An event raised whenever a QuestionSet document is being requested. The method
 /// sets up a default viewmodel, which will be passed back and forth by the form postbacks or
 /// ajax posts on the views.
 /// </summary>
 public void OnLoad(QuestionSet model, HttpContextBase httpContext, UmbracoContext umbContext, ApplicationContext appContext, CodeFirstModelContext modelContext, IPublishedContent currentPage, out QuestionSetViewModel viewModel)
 {
     viewModel = new QuestionSetViewModel()
     {
         MaxIndex      = model?.Count - 1 ?? -1,
         SetId         = currentPage?.Id ?? -1,
         QuestionIndex = model?.Count > 0 ? 0 : -1,
         QuestionId    = model.FirstOrDefault()?.NodeDetails?.UmbracoId ?? -1,
         Answer        = new QuestionSetViewModel.QuestionResponse()
         {
             AnswerIndex = -1
         }
     };
 }