private IDList GetChildIDsTemplate(SitecoreClassConfig template, ItemDefinition itemDefinition) { IDList fields = new IDList(); List <string> processed = new List <string>(); var sections = template.Properties .Where(x => x.Property.DeclaringType == template.Type) .Select(x => x.Attribute).OfType <SitecoreFieldAttribute>() .Select(x => x.SectionName); foreach (var section in sections) { if (processed.Contains(section) || section.IsNullOrEmpty()) { continue; } var record = SectionTable.FirstOrDefault(x => x.TemplateId == itemDefinition.ID && x.Name == section); if (record == null) { record = new SectionInfo(section, new ID(Guid.NewGuid()), itemDefinition.ID); SectionTable.Add(record); } processed.Add(section); fields.Add(record.SectionId); } return(fields); }
public void ReadFromItem(ISitecoreService service, object target, Item item, SitecoreClassConfig config) { foreach (var handler in config.DataHandlers) { handler.SetProperty(target, item, service); } }
private void ReadFromItem(object target, Item item, SitecoreClassConfig config) { foreach (var handler in config.DataHandlers) { handler.SetProperty(target, item, this); } }
/// <summary> /// Retrieves an item based on the passed in class based on the version and language properties on the class /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target"></param> /// <returns></returns> private Item GetItemFromSitecore <T>(T target) { Guid guid = InstanceContext.GetClassId(typeof(T), target); SitecoreClassConfig config = InstanceContext.GetSitecoreClass(typeof(T)); Language language = null; int versionNumber = -1; if (config.LanguageProperty != null) { language = config.LanguageProperty.Property.GetValue(target, null) as Language; } if (config.VersionProperty != null) { versionNumber = (int)config.VersionProperty.Property.GetValue(target, null); } if (language != null && versionNumber > 0) { return(_database.GetItem(new ID(guid), language, new global::Sitecore.Data.Version(versionNumber))); } else if (language != null) { return(_database.GetItem(new ID(guid), language)); } else { return(_database.GetItem(new ID(guid))); } }
public InterfaceMethodInterceptor(SitecoreClassConfig config, Item item, ISitecoreService service) { _config = config; _item = item; _service = service; _values = new Dictionary <string, object>(); }
public SitecoreClass() { _properties = new List <SitecoreProperty>(); _config = new SitecoreClassConfig(); _config.Type = typeof(T); _config.ClassAttribute = new Configuration.Attributes.SitecoreClassAttribute(); _config.Properties = _properties; }
public object CreateClass(bool isLazy, bool inferType, Type type, Item item) { if (item == null) { return(null); } SitecoreClassConfig config = null; if (!inferType) { //this retrieves the class based on return type config = InstanceContext.GetSitecoreClass(type); } else { //this retrieves the class by inferring the type from the template ID //if ths return type can not be found then the system will try to create a type //base on the return type config = InstanceContext.GetSitecoreClass(item.TemplateID.Guid, type); if (config == null) { config = InstanceContext.GetSitecoreClass(type); } } if (isLazy || type.IsInterface) { return(ProxyGenerator.CreateProxy(config, this, item, inferType)); } else { if (item == null) { return(null); } //get the class information if (config.CreateObject == null) { Type objType = config.Type; var dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + objType.Name, objType, null, objType); ILGenerator ilGen = dynMethod.GetILGenerator(); ilGen.Emit(OpCodes.Newobj, objType.GetConstructor(Type.EmptyTypes)); ilGen.Emit(OpCodes.Ret); config.CreateObject = (SitecoreClassConfig.Instantiator)dynMethod.CreateDelegate(typeof(SitecoreClassConfig.Instantiator)); } object t = config.CreateObject(); ReadFromItem(t, item, config); return(t); } }
/// <summary> /// Returns a delegate method that will load a class based on its constuctor /// </summary> /// <param name="classConfig">The SitecoreClassConfig to store the delegate method in</param> /// <param name="constructorParameters">The list of contructor parameters</param> /// <param name="delegateType">The type of the delegate function to create</param> /// <returns></returns> internal static void CreateConstructorDelegates(SitecoreClassConfig classConfig) { Type type = classConfig.Type; var constructors = type.GetConstructors(); foreach (var constructor in constructors) { var parameters = constructor.GetParameters(); var dynMethod = new DynamicMethod("DM$OBJ_FACTORY_" + type.Name, type, parameters.Select(x => x.ParameterType).ToArray(), type); ILGenerator ilGen = dynMethod.GetILGenerator(); for (int i = 0; i < parameters.Count(); i++) { ilGen.Emit(OpCodes.Ldarg, i); } ilGen.Emit(OpCodes.Newobj, constructor); ilGen.Emit(OpCodes.Ret); Type genericType = null; switch (parameters.Count()) { case 0: genericType = typeof(Func <>); break; case 1: genericType = typeof(Func <,>); break; case 2: genericType = typeof(Func <, ,>); break; case 3: genericType = typeof(Func <, , ,>); break; case 4: genericType = typeof(Func <, , , ,>); break; default: throw new MapperException("Only supports constructors with a maximum of 4 parameters"); } var delegateType = genericType.MakeGenericType(parameters.Select(x => x.ParameterType).Concat(new [] { type }).ToArray()); classConfig.CreateObjectMethods[constructor] = dynMethod.CreateDelegate(delegateType); } }
public void GetSitecoreClass_NotLoadedClass_ThrowsException() { //Assign SitecoreClassConfig config = null; //Act config = _service.InstanceContext.GetSitecoreClass(typeof(Domain.NotLoaded)); //Assert //no asserts, exception should be thrown }
public void GetSitecoreClass_LoadedClass_ReturnsClassConfig() { //Assign SitecoreClassConfig config = null; //Act config = _service.InstanceContext.GetSitecoreClass(typeof(InstanceContextFixtureNS.TestClass2)); //Assert Assert.IsNotNull(config); Assert.AreEqual(typeof(InstanceContextFixtureNS.TestClass2), config.Type); }
private IEnumerable <SitecoreClassConfig> GetClass(string assembly, string namesp) { Assembly assem = Assembly.Load(assembly); if (assem != null) { try { return(assem.GetTypes().Select(x => { if (x != null && x.Namespace != null && (x.Namespace.Equals(namesp) || x.Namespace.StartsWith(namesp + "."))) { IEnumerable <object> attrs = x.GetCustomAttributes(true); SitecoreClassAttribute attr = attrs.FirstOrDefault(y => y is SitecoreClassAttribute) as SitecoreClassAttribute; if (attr != null) { var config = new SitecoreClassConfig() { Type = x, ClassAttribute = attr, }; //TODO need to wrap in exception handler if (!attr.BranchId.IsNullOrEmpty()) { config.BranchId = new Guid(attr.BranchId); } if (!attr.TemplateId.IsNullOrEmpty()) { config.TemplateId = new Guid(attr.TemplateId); } return config; } } return null; }).Where(x => x != null).ToList()); } catch (ReflectionTypeLoadException ex) { throw new MapperException("Failed to load types {0}".Formatted(ex.LoaderExceptions.First().Message), ex); } } else { return(new List <SitecoreClassConfig>()); } }
private IDList GetChildIDsTemplate(SitecoreClassConfig template, ItemDefinition itemDefinition, CallContext context) { IDList fields = new IDList(); List <string> processed = new List <string>(); var sections = template.Properties .Where(x => x.Property.DeclaringType == template.Type) .Select(x => x.Attribute).OfType <SitecoreFieldAttribute>() .Select(x => new { x.SectionName, x.SectionSortOrder }); var providers = Database.GetDataProviders(); var otherProvider = providers.FirstOrDefault(x => !(x is GlassDataProvider)); //If sitecore contains a section with the same name in the database, use that one instead of creating a new one var existing = otherProvider.GetChildIDs(itemDefinition, context).OfType <ID>().Select(id => otherProvider.GetItemDefinition(id, context)).ToList(); foreach (var section in sections) { if (processed.Contains(section.SectionName) || section.SectionName.IsNullOrEmpty()) { continue; } var record = SectionTable.FirstOrDefault(x => x.TemplateId == itemDefinition.ID && x.Name == section.SectionName); if (record == null) { var exists = existing.FirstOrDefault(def => def.Name.Equals(section)); if (exists != null) { record = new SectionInfo(section.SectionName, exists.ID, itemDefinition.ID, section.SectionSortOrder) { Existing = true }; } else { record = new SectionInfo(section.SectionName, new ID(Guid.NewGuid()), itemDefinition.ID, section.SectionSortOrder); } SectionTable.Add(record); } processed.Add(section.SectionName); if (!record.Existing) { fields.Add(record.SectionId); } } return(fields); }
public void Create_CreatesProxyClassAndCorrectlyReplaces() { //Assign Item item = _db.GetItem(new ID(_itemId)); SitecoreClassConfig config = _context.GetSitecoreClass(typeof(ProxyClassGeneratorFixtureNS.SubClass)); //Act var result = ProxyGenerator.CreateProxy(config, _service, item, false) as ProxyClassGeneratorFixtureNS.SubClass; result.CallMe = "something"; //Assert Assert.AreEqual("something", result.CallMe); }
private IEnumerable <SitecoreClassConfig> ProcessAssembly(Assembly assem, Func <Type, bool> predicate) { if (assem != null) { try { return(assem.GetTypes().Select(x => { if (predicate(x)) { IEnumerable <object> attrs = x.GetCustomAttributes(true); SitecoreClassAttribute attr = attrs.FirstOrDefault(y => y is SitecoreClassAttribute) as SitecoreClassAttribute; if (attr != null) { var config = new SitecoreClassConfig() { Type = x, ClassAttribute = attr, }; //TODO need to wrap in exception handler if (!attr.BranchId.IsNullOrEmpty()) { config.BranchId = new Guid(attr.BranchId); } if (!attr.TemplateId.IsNullOrEmpty()) { config.TemplateId = new Guid(attr.TemplateId); } return config; } } return null; }).Where(x => x != null).ToList()); } catch (ReflectionTypeLoadException ex) { throw new MapperException("Failed to load types {0}".Formatted(ex.LoaderExceptions.First().Message), ex); } } else { return(new List <SitecoreClassConfig>()); } }
public virtual object CreateClass(ISitecoreService service, bool isLazy, bool inferType, Type type, Item item, params object[] constructorParameters) { //check there is an item to create a class from if (item == null) { return(null); } //check that there are some constructor arguments SitecoreClassConfig config = null; if (!inferType) { //this retrieves the class based on return type config = Context.StaticContext.GetSitecoreClass(type); } else { //this retrieves the class by inferring the type from the template ID //if ths return type can not be found then the system will try to create a type //base on the return type config = TypeInferrer.InferrerType(item, type); } //if the class should be lazy loaded or is an interface then load using a proxy if (isLazy || type.IsInterface) { return(ProxyGenerator.CreateProxy(config, service, item, inferType)); } else { ConstructorInfo constructor = config.Type.GetConstructor(constructorParameters == null || constructorParameters.Count() == 0 ? Type.EmptyTypes : constructorParameters.Select(x => x.GetType()).ToArray()); if (constructor == null) { throw new MapperException("No constructor for class {0} with parameters {1}".Formatted(config.Type.FullName, string.Join(",", constructorParameters.Select(x => x.GetType().FullName).ToArray()))); } Delegate conMethod = config.CreateObjectMethods[constructor]; object t = conMethod.DynamicInvoke(constructorParameters); ReadFromItem(service, t, item, config); return(t); } }
public static object CreateProxy(SitecoreClassConfig config, ISitecoreService service, Item item, bool inferType) { object proxy = null; Type type = config.Type; if (type.IsInterface) { proxy = _generator.CreateInterfaceProxyWithoutTarget(type, new InterfaceMethodInterceptor(config, item, service)); } else { proxy = _generator.CreateClassProxy(type, _options, new ProxyClassInterceptor(type, service, item, inferType)); } return(proxy); }
private IEnumerable <SitecoreClassConfig> GetClass(string assembly, string namesp) { Assembly assem = Assembly.Load(assembly); if (assem != null) { return(assem.GetTypes().Select(x => { if (x != null && x.Namespace != null && x.Namespace.StartsWith(namesp)) { IEnumerable <object> attrs = x.GetCustomAttributes(true); SitecoreClassAttribute attr = attrs.FirstOrDefault(y => y is SitecoreClassAttribute) as SitecoreClassAttribute; if (attr != null) { var config = new SitecoreClassConfig() { Type = x, ClassAttribute = attr, }; //TODO need to wrap in exception handler if (!attr.BranchId.IsNullOrEmpty()) { config.BranchId = new Guid(attr.BranchId); } if (!attr.TemplateId.IsNullOrEmpty()) { config.TemplateId = new Guid(attr.TemplateId); } return config; } } return null; }).Where(x => x != null).ToList()); } else { return(new List <SitecoreClassConfig>()); } }
private IEnumerable<SitecoreClassConfig> GetClass(string assembly, string namesp) { Assembly assem = Assembly.Load(assembly); if (assem != null) { try { return assem.GetTypes().Select(x => { if (x != null && x.Namespace != null && (x.Namespace.Equals(namesp) || x.Namespace.StartsWith(namesp + "."))) { IEnumerable<object> attrs = x.GetCustomAttributes(true); SitecoreClassAttribute attr = attrs.FirstOrDefault(y => y is SitecoreClassAttribute) as SitecoreClassAttribute; if (attr != null) { var config = new SitecoreClassConfig() { Type = x, ClassAttribute = attr, }; //TODO need to wrap in exception handler if (!attr.BranchId.IsNullOrEmpty()) config.BranchId = new Guid(attr.BranchId); if (!attr.TemplateId.IsNullOrEmpty()) config.TemplateId = new Guid(attr.TemplateId); return config; } } return null; }).Where(x => x != null).ToList(); } catch (ReflectionTypeLoadException ex) { throw new MapperException("Failed to load types {0}".Formatted(ex.LoaderExceptions.First().Message), ex); } } else { return new List<SitecoreClassConfig>(); } }
/// <summary> /// Creates a new Sitecore item. /// </summary> /// <typeparam name="T">The type of the new item to create. This type must have either a TemplateId or BranchId defined on the SitecoreClassAttribute or fluent equivalent</typeparam> /// <typeparam name="K">The type of the parent item</typeparam> /// <param name="parent">The parent of the new item to create. Must have the SitecoreIdAttribute or fluent equivalent</param> /// <param name="newItem">New item to create, must have the attribute SitecoreInfoAttribute of type SitecoreInfoType.Name or the fluent equivalent</param> /// <returns></returns> public T Create <T, K>(K parent, T newItem) where T : class where K : class { try { Guid id = InstanceContext.GetClassId(typeof(T), newItem); if (id != Guid.Empty) { throw new MapperException("You are trying to create an item on a class that doesn't have an empty ID value"); } } catch (SitecoreIdException ex) { //we can swallow this exception for now //should look to do this beeter } Guid parentId = Guid.Empty; try { parentId = InstanceContext.GetClassId(typeof(K), parent); } catch (SitecoreIdException ex) { throw new MapperException("Failed to get parent ID", ex); } if (parentId == Guid.Empty) { throw new MapperException("Guid for parent is empty"); } Item pItem = GetItemFromSitecore <K>(parent); if (pItem == null) { throw new MapperException("Could not find parent item with ID {0}".Formatted(parentId)); } SitecoreClassConfig scClass = InstanceContext.GetSitecoreClass(typeof(T)); var nameProperty = scClass.Properties.Where(x => x.Attribute is SitecoreInfoAttribute) .Cast <SitecoreProperty>().FirstOrDefault(x => x.Attribute.CastTo <SitecoreInfoAttribute>().Type == SitecoreInfoType.Name); if (nameProperty == null) { throw new MapperException("Type {0} does not have a property with SitecoreInfoType.Name".Formatted(typeof(T).FullName)); } string name = string.Empty; try { name = nameProperty.Property.GetValue(newItem, null).ToString(); } catch { throw new MapperException("Failed to get item name"); } if (name.IsNullOrEmpty()) { throw new MapperException("New class has no name"); } Guid templateId = scClass.TemplateId; Guid branchId = scClass.BranchId; Item item = null; if (templateId != Guid.Empty) { item = pItem.Add(name, new TemplateID(new ID(templateId))); } else if (branchId != Guid.Empty) { item = pItem.Add(name, new BranchId(new ID(branchId))); } else { throw new MapperException("Type {0} does not have a Template ID or Branch ID".Formatted(typeof(T).FullName)); } if (item == null) { throw new MapperException("Failed to create item"); } //write new data to the item item.Editing.BeginEdit(); WriteToItem <T>(newItem, item); item.Editing.EndEdit(); //then read it back ReadFromItem(newItem, item, scClass); return(newItem); // return CreateClass<T>(false, false, item); }
private void BaseTemplateChecks(ItemDefinition template, DataProvider provider, CallContext context, SitecoreClassConfig config) { //check base templates var templateItem = Database.GetItem(template.ID); var baseTemplatesField = templateItem[BaseTemplatesFieldId]; StringBuilder sb = new StringBuilder(baseTemplatesField); global::Sitecore.Diagnostics.Log.Info("Type {0}".Formatted(config.Type.FullName), this); Action <Type> idCheck = (type) => { global::Sitecore.Diagnostics.Log.Info("ID Check {0}".Formatted(type.FullName), this); if (!Classes.ContainsKey(type)) { return; } var baseConfig = Classes[type]; if (baseConfig != null && baseConfig.ClassAttribute.CodeFirst) { if (!baseTemplatesField.Contains(baseConfig.ClassAttribute.TemplateId)) { sb.Append("|{0}".Formatted(baseConfig.ClassAttribute.TemplateId)); } } }; Type baseType = config.Type.BaseType; while (baseType != null) { idCheck(baseType); baseType = baseType.BaseType; } config.Type.GetInterfaces().ForEach(x => idCheck(x)); if (baseTemplatesField != sb.ToString()) { templateItem.Editing.BeginEdit(); templateItem[BaseTemplatesFieldId] = sb.ToString(); templateItem.Editing.EndEdit(); } }
public T Create <T, K>(K parent, string name, T data) where T : class where K : class { //check that the data is not null and if it has an ID check that it is empty if (data != null) { } Guid guid = Guid.Empty; try { guid = InstanceContext.GetClassId(typeof(K), parent); } catch (SitecoreIdException ex) { throw new MapperException("Failed to get parent ID", ex); } if (guid == Guid.Empty) { throw new MapperException("Guid for parent is empty"); } Item pItem = _database.GetItem(new ID(guid)); if (pItem == null) { throw new MapperException("Could not find parent item"); } SitecoreClassConfig scClass = InstanceContext.GetSitecoreClass(typeof(T)); Guid templateId = scClass.TemplateId; Guid branchId = scClass.BranchId; Item item = null; if (templateId != Guid.Empty) { item = pItem.Add(name, new TemplateID(new ID(templateId))); } else if (branchId != Guid.Empty) { item = pItem.Add(name, new BranchId(new ID(branchId))); } else { throw new MapperException("Type {0} does not have a Template ID or Branch ID".Formatted(typeof(T).FullName)); } if (item == null) { throw new MapperException("Failed to create child with name {0} and parent {1}".Formatted(name, item.Paths.FullPath)); } //if we have data save it to the item if (data != null) { item.Editing.BeginEdit(); WriteToItem <T>(data, item); item.Editing.EndEdit(); } return(CreateClass <T>(false, false, item)); }
private IEnumerable<SitecoreClassConfig> ProcessAssembly(Assembly assem, Func<Type, bool> predicate) { if (assem != null) { try { return assem.GetTypes().Select(x => { if (predicate(x)) { IEnumerable<object> attrs = x.GetCustomAttributes(true); SitecoreClassAttribute attr = attrs.FirstOrDefault(y => y is SitecoreClassAttribute) as SitecoreClassAttribute; if (attr != null) { var config = new SitecoreClassConfig() { Type = x, ClassAttribute = attr, }; //TODO need to wrap in exception handler if (!attr.BranchId.IsNullOrEmpty()) config.BranchId = new Guid(attr.BranchId); if (!attr.TemplateId.IsNullOrEmpty()) config.TemplateId = new Guid(attr.TemplateId); return config; } } return null; }).Where(x => x != null).ToList(); } catch (Exception ex) { //throw new MapperException("Failed to load types {0}".Formatted(ex.LoaderExceptions.First().Message), ex); //don't mind assemblies that contain dynamic types... } } return new List<SitecoreClassConfig>(); }
private IEnumerable<SitecoreClassConfig> GetClass(string assembly, string namesp) { Assembly assem = Assembly.Load(assembly); if (assem != null) { return assem.GetTypes().Select(x => { if (x != null && x.Namespace != null && x.Namespace.StartsWith(namesp)) { IEnumerable<object> attrs = x.GetCustomAttributes(true); SitecoreClassAttribute attr = attrs.FirstOrDefault(y=>y is SitecoreClassAttribute) as SitecoreClassAttribute; if (attr != null) { var config = new SitecoreClassConfig() { Type = x, ClassAttribute = attr, }; //TODO need to wrap in exception handler if (!attr.BranchId.IsNullOrEmpty()) config.BranchId = new Guid(attr.BranchId); if (!attr.TemplateId.IsNullOrEmpty()) config.TemplateId = new Guid(attr.TemplateId); return config; } } return null; }).Where(x => x != null).ToList(); } else { return new List<SitecoreClassConfig>(); } }