public AccountViewModel (AccountObject account)
		{
			if (account == null) {
				throw new ArgumentNullException ("account");
			}
			Account = account;

			PropertyGroups = new ObservableCollection<PropertyGroup> ();

			var general = new PropertyGroup ("General");
			general.Add ("Name", account.Name, PropertyType.Generic);
			general.Add ("Industry", account.Industry, PropertyType.Generic);
			general.Add ("Account", account.AccountNumber, PropertyType.Generic);
			general.Add ("Modified", account.LastModified==null?"":account.LastModified.ToString(), PropertyType.Generic);

			if (general.Properties.Count > 0) {
				PropertyGroups.Add (general);
			}

			var phone = new PropertyGroup ("Contact");

			phone.Add ("Phone", account.Phone, PropertyType.Phone);
			phone.Add ("Website", account.Website, PropertyType.Url);

			if (phone.Properties.Count > 0) {
				PropertyGroups.Add (phone);
			}
		}
 protected RealEstateSpace(string name, SpaceKeys position, PropertyGroup.Groups group, int cost, int rent)
 {
     Name = name;
     Position = position;
     Group = group;
     Cost = cost;
     Rent = rent;
 }
        /// <summary>
        /// Install a Daemon
        /// </summary>
        /// <param name="machineID">Machine ID</param>
        /// <param name="mapPath">An Aneka Daemon Binaries path for future uses</param>
        public void InstallDaemon(int machineID, string mapPath)
        {
            try
            {
                CloudWebPortal.Areas.Aneka.Models.Machine machine = db.Machines.Find(machineID);
                global::Aneka.PAL.Management.Model.Machine AnekaMachine = machineManagment.ToAnekaPALMachine(machine);
                Daemon daemon = machine.Daemon;

                Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/");
                String RepoAccessURL = rootWebConfig.AppSettings.Settings["RepoAccessURL"].Value;
                String RepoAccessUser = rootWebConfig.AppSettings.Settings["RepoAccessUser"].Value;
                String RepoAccessPassword = rootWebConfig.AppSettings.Settings["RepoAccessPassword"].Value;

                //Repository Group
                Property Method = new Property("Method", "File");
                Property Location = new Property("Location", RepoAccessURL);
                Property Username = new Property("Username", RepoAccessUser);
                Property Password = new Property("Password", RepoAccessPassword);
                Property Platform = new Property("Platform", "Windows");
                PropertyGroup RepositoryGroup = new PropertyGroup("Repository");
                RepositoryGroup.Add(Method);
                RepositoryGroup.Add(Location);
                RepositoryGroup.Add(Username);
                RepositoryGroup.Add(Password);
                RepositoryGroup.Add(Platform);

                //Send Loader Binaries
                //string anekaDaemonBinaries = mapPath + "Repository\\Daemon\\";
                string RepoLocalLocation = rootWebConfig.AppSettings.Settings["RepoLocalLocation"].Value;
                Property DaemonPort = new Property("Port", daemon.Port);
                Property FreshInstall = new Property("FreshInstall", "True");
                Property EnableAutoUpdate = new Property("EnableAutoUpdate", "False");
                Property DaemonHomeDirectory = new Property("HomeDirectory", daemon.Directory + "\\Runtime\\Daemon\\");
                PropertyGroup DaemonGroup = new PropertyGroup("Daemon");
                DaemonGroup.Add(DaemonPort);
                DaemonGroup.Add(FreshInstall);
                DaemonGroup.Add(EnableAutoUpdate);
                DaemonGroup.Add(DaemonHomeDirectory);
                ConfigurationBase daemonInstallerConfig = new ConfigurationBase();
                daemonInstallerConfig.Add(DaemonGroup);
                daemonInstallerConfig.Add(RepositoryGroup);
                machine.isInProgress = true;
                machine.ProgressMesage = "Installing Binaries";
                db.SaveChanges();
                daemonManager.Install(AnekaMachine, daemonInstallerConfig, RepoLocalLocation + "\\Loader\\" );

                finishedActivity(machineID);
            }
            catch (Exception ex)
            {
                CloudWebPortal.Areas.Aneka.Models.Machine machine = db.Machines.Find(machineID);
                machine.StatusEnum = DaemonProbeStatus.Unknown;
                machine.ProgressMesage = "Error while stopping daemon: " + ex.Message;
                machine.isInProgress = false;
                db.SaveChanges();
            }
        }
        public PropertyGroup[] GetConfigurationProperties(int groupId)
        {
            PropertyGroup group = new PropertyGroup("options", _translation.GetLanguageResourceValue("configuration_options"), 1);

            group.Properties.Add(new Property("groupid",  "", PropertyType.Int, 1, groupId.ToString()) { Visible = false, Editable = false });
            group.Properties.Add(new Property("label",  _translation.GetLanguageResourceValue("configuration_label"), PropertyType.String, 2,  "") { DescriptionText = _translation.GetLanguageResourceValue("configuration_label_description") });

            return new PropertyGroup[] { group };
        }
        public PropertyGroup[] GetConfigurationProperties()
        {
            PropertyGroup group = new PropertyGroup("config", "", 1);

            Property p = new Property("user", _translation.GetLanguageResourceValue("link_to_user"), PropertyType.String, 1, "current");
            p.SelectableValues.Add(new PropertyValue("current", _translation.GetLanguageResourceValue("link_to_user_current"), 0));
            p.SelectableValues.Add(new PropertyValue("accessing", _translation.GetLanguageResourceValue("link_to_user_accessing"), 1));
            group.Properties.Add(p);

            p = new Property("label", _translation.GetLanguageResourceValue("label"), PropertyType.String, 2, "Polls");
            p.ControlType = typeof(Telligent.Evolution.Controls.ContentFragmentTokenStringControl);
            group.Properties.Add(p);

            return new PropertyGroup[] { group };
        }
Esempio n. 6
0
        public BuildTarget(int lineNumber, PropertyGroup targetProps, ItemGroup targetItems)
        {
            LineNumber = lineNumber;
            Properties = targetProps;
            Items = targetItems;
            Name = targetProps.GetRequiredValue("TargetName");
            InputFiles = targetItems.GetRequiredValue("TargetInputs");
            OutputFiles = targetItems.GetRequiredValue("TargetOutputs");

            Func<IList<ParsedPath>, IEnumerable<string>> extractAndSortExtensions = (files) =>
            {
                return files.Select<ParsedPath, string>(f => f.Extension).Distinct<string>().OrderBy(s => s, StringComparer.CurrentCultureIgnoreCase);
            };

            InputExtensions = extractAndSortExtensions(InputFiles);
            OutputExtensions = extractAndSortExtensions(OutputFiles);
        }
Esempio n. 7
0
        public static string ProjectFile(string xml, string fileName)
        {
            var original = XDocument.Parse(xml.Replace("xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"", string.Empty));
            var root     = new XElement(XName.Get("Project"));
            var isWpf    = IsWpf(original);

            root.SetAttributeValue(XName.Get("Sdk"), isWpf ? "Microsoft.NET.Sdk.WindowsDesktop" : "Microsoft.NET.Sdk");
            foreach (var element in original.Root.Elements())
            {
                var localName = element.Name.LocalName;
                switch (localName)
                {
                case "PropertyGroup":
                {
                    if (PropertyGroup.TryMigrate(element, fileName, isWpf, out var migratedElement))
                    {
                        if (migratedElement != null)
                        {
                            root.Add(migratedElement);
                        }
                    }

                    continue;
                }

                case "ItemGroup":
                {
                    if (ItemGroup.TryMigrate(element, isWpf, out var migratedElement))
                    {
                        if (migratedElement != null)
                        {
                            root.Add(migratedElement);
                        }
                    }

                    continue;
                }

                case "Choose":
                    continue;

                case "Import":
                {
                    if (element.Attribute(XName.Get("Project")) is { } pa)
                    {
                        switch (pa.Value)
                        {
                        case "$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props":
                        case "$(MSBuildToolsPath)\\Microsoft.CSharp.targets":
                        case "$(VSToolsPath)\\TeamTest\\Microsoft.TestTools.targets":
                            continue;
                        }
                    }

                    break;
                }
                }

                root.Add(element);
            }

            return(new XDocument(root).ToString());
 public RailroadSpace(string name, SpaceKeys position, PropertyGroup.Groups group, int cost, int rent)
     : base(name, position, group, cost, rent)
 {
 }
Esempio n. 9
0
 public PropertyGroup AddPropertyGroup(string name, Color groupColour)
 {
     PropertyGroup newGroup = FindPropertyGroup(name);
     if (newGroup == null)
     {
         newGroup = new PropertyGroup(name, groupColour, this);
         propertyGroupList.Add(newGroup);
         newGroup.groupInstance.transform.SetParent(mainPanel.transform, false);
     }
     return newGroup;
 }
Esempio n. 10
0
        public void Adding_PropertyGroup_To_ContentType_Results_In_Dirty_Entity()
        {
            // Arrange
            var contentType = MockedContentTypes.CreateTextpageContentType();
            contentType.ResetDirtyProperties();

            // Act
            var propertyGroup = new PropertyGroup { Name = "Test Group", SortOrder = 3 };
            contentType.PropertyGroups.Add(propertyGroup);

            // Assert
            Assert.That(contentType.IsDirty(), Is.True);
            Assert.That(contentType.PropertyGroups.Any(x => x.Name == "Test Group"), Is.True);
            //Assert.That(contentType.IsPropertyDirty("PropertyGroups"), Is.True);
        }
Esempio n. 11
0
 void btnNew_Click(object sender, EventArgs e)
 {
     PropertyGroup r = new PropertyGroup();
     r.Name = "NewPropertyGroup";
     int n;
     if (tempDef.PropertyGroup.ContainsKey(r.Name)) {
         n = 2;
         while (tempDef.PropertyGroup.ContainsKey(r.Name + n)) n++;
         r.Name = r.Name + n;
     }
     tempDef.PropertyGroup.Add(r.Name, r);
     _editForm.Name = r.Name;
     _editForm.DefinitionType = DefinitionType.Local;
     _editForm.Refresh();
     tempDef.RegisterChange(r.Guid);
     WAFContext.FlagChangeInTemporaryDefinition();
     WAFContext.UpdateTemporaryLocalDefinitionFile();
     list.SetSelected(r.Name);
     setQuery();
 }
Esempio n. 12
0
 private bool IsWholeGroupOwned(PropertyGroup group)
 {
     bool AllAreOwned = true;
     foreach (ILocation i in propertyList.Values.Where(j => j is RentableLocation && j.Group == group))
     {
         AllAreOwned &= SpaceIsOwned(i.SpaceNumber);
     }
     return AllAreOwned;
 }
        /// <summary>
        /// Adds a PropertyGroup.
        /// This method will also check if a group already exists with the same name and link it to the parent.
        /// </summary>
        /// <param name="groupName">Name of the PropertyGroup to add</param>
        /// <returns>Returns <c>True</c> if a PropertyGroup with the passed in name was added, otherwise <c>False</c></returns>
        public override bool AddPropertyGroup(string groupName)
        {
            if (PropertyGroups.Any(x => x.Name == groupName))
                return false;

            var propertyGroup = new PropertyGroup {Name = groupName, SortOrder = 0};

            if (CompositionPropertyGroups.Any(x => x.Name == groupName))
            {
                var firstGroup = CompositionPropertyGroups.First(x => x.Name == groupName && x.ParentId.HasValue == false);
                propertyGroup.SetLazyParentId(new Lazy<int?>(() => firstGroup.Id));
            }

            if (PropertyGroups.Any())
            {
                var last = PropertyGroups.Last();
                propertyGroup.SortOrder = last.SortOrder + 1;
            }

            PropertyGroups.Add(propertyGroup);
            return true;
        }
Esempio n. 14
0
        private void HandleAlreadyRenamedPropertyGroup(IContentType contentType, string oldName, PropertyGroup groupWithNewName)
        {
            var oldGroup = GetPropertyGroupOrNull(contentType, oldName);

            if (oldGroup == null)
            {
                return;
            }

            if (oldGroup.PropertyTypes.Count > 0)
            {
                var propertiesToMove = oldGroup.PropertyTypes.ToArray();
                foreach (var property in propertiesToMove)
                {
                    MovePropertyInternal(contentType, property, groupWithNewName.Name);
                }
            }

            RemovePropertyGroupInternal(contentType, oldGroup.Name);
        }
Esempio n. 15
0
        /// <summary>
        /// Adds a group of properties to the GtkTable, starting at the specified row.
        /// </summary>
        /// <param name="table">Table to be modified.</param>
        /// <param name="properties">Property group to be modified.</param>
        /// <param name="startRow">The row to which the first property will be added (used for recursive calls).</param>
        /// <param name="columnOffset">The number of columns to offset for this propertygroup (0 = single. >0 multiply models reported as columns).</param>

        protected void AddPropertiesToTable(ref Grid table, PropertyGroup properties, ref int startRow, int columnOffset)

        {
            // Using a regular for loop is not practical because we can
            // sometimes have multiple rows per property (e.g. if it has separators).
            foreach (Property property in properties.Properties)
            {
                if (property.Separators != null)
                {
                    foreach (string separator in property.Separators)
                    {
                        Label separatorLabel = new Label($"<b>{separator}</b>")
                        {
                            Xalign = 0, UseMarkup = true
                        };
                        separatorLabel.StyleContext.AddClass("separator");
                        propertyTable.Attach(separatorLabel, 0, startRow, 3, 1);

                        startRow++;
                    }
                }

                if (columnOffset == 0) // only perform on first or only entry
                {
                    Label label = new Label(property.Name);
                    label.TooltipText = property.Tooltip;
                    label.Xalign      = 0;

                    label.MarginEnd = 10;
                    propertyTable.Attach(label, 0, startRow, 1, 1);
                }

                if (!string.IsNullOrEmpty(property.Tooltip))
                {
                    Button info = new Button(new Image(Stock.Info, IconSize.Button));
                    info.TooltipText = property.Tooltip;
                    propertyTable.Attach(info, 1, startRow, 1, 1);
                    info.Clicked += OnInfoButtonClicked;
                }

                Widget inputWidget = GenerateInputWidget(property);
                inputWidget.Name        = property.ID.ToString();
                inputWidget.TooltipText = property.Tooltip;


                propertyTable.Attach(inputWidget, 2 + columnOffset, startRow, 1, 1);
                inputWidget.Hexpand = true;


                startRow++;
            }

            foreach (PropertyGroup subProperties in properties.SubModelProperties)
            {
                Label label = new Label($"<b>{subProperties.Name} Properties</b>");
                label.Xalign    = 0;
                label.UseMarkup = true;
                propertyTable.Attach(label, 0, startRow, 2, 1);
                label.Ypad = 5;
                startRow++;
                AddPropertiesToTable(ref table, subProperties, ref startRow, columnOffset);
            }
        }
Esempio n. 16
0
        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            Init();

            var path = txtPath.Text?.Trim();

            if (string.IsNullOrEmpty(path) || !Directory.Exists(path))
            {
                MessageBox.Show("Please input the correct path which includes .csproj files!", "error");
                return;
            }

            SenparcTrace.SendCustomLog("Task", "Search .csproj files begin.");

            var csprojFiles = Directory.GetFiles(path, "*.csproj", SearchOption.AllDirectories);

            if (csprojFiles == null || csprojFiles.Length == 0)
            {
                MessageBox.Show("No valiable .csproj file!", "error");
                return;
            }

            foreach (var file in csprojFiles)
            {
                try
                {
                    var doc           = XDocument.Load(file);
                    var propertyGroup = doc.Root.Elements("PropertyGroup").FirstOrDefault();
                    if (propertyGroup == null)
                    {
                        SenparcTrace.SendCustomLog("Task Falid", $"{file} is not a valid xml.csproj file.");
                        continue;
                    }

                    var projectFile = PropertyGroup.GetObjet(propertyGroup, file);
                    ProjectFiles.Add(projectFile);
                    ProjectDocuments.Add(doc);

                    SenparcTrace.SendCustomLog("Task", $"[Success] Load file:{file}");
                }
                catch (Exception ex)
                {
                    SenparcTrace.SendCustomLog("Task", $"[Faild] Load file:{file}");
                    SenparcTrace.SendCustomLog("Error", ex.Message);
                }
            }

            if (ProjectFiles.Count == 0)
            {
                MessageBox.Show("No valiable .csproj file!", "error");
                return;
            }

            if (lbFiles.Items.Count > 0)
            {
                lbFiles.SelectedIndex = 0;//default select the first item.
            }

            //lbFiles.DataContext = ProjectFiles;
            //lbFiles.ItemsSource = ProjectFiles;

            //foreach (var projectFile in ProjectFiles)
            //{
            //    BindFileData.Add(new KeyValuePair<string, string>(projectFile.FileName, projectFile.FullFilePath));
            //}
            //lbFiles.ItemsSource = BindFileData;
        }
        private static PropertyGroupCollection GetPropertyTypeGroupCollection(MemberTypeReadOnlyDto dto, MemberType memberType, Dictionary <string, PropertyType> standardProps)
        {
            // see PropertyGroupFactory, repeating code here...

            var propertyGroups = new PropertyGroupCollection();

            foreach (var groupDto in dto.PropertyTypeGroups.Where(x => x.Id.HasValue))
            {
                var group = new PropertyGroup(MemberType.SupportsPublishingConst);

                // if the group is defined on the current member type,
                // assign its identifier, else it will be zero
                if (groupDto.ContentTypeNodeId == memberType.Id)
                {
                    // note: no idea why Id is nullable here, but better check
                    if (groupDto.Id.HasValue == false)
                    {
                        throw new Exception("GroupDto.Id has no value.");
                    }
                    group.Id = groupDto.Id.Value;
                }

                group.Key           = groupDto.UniqueId;
                group.Name          = groupDto.Text;
                group.SortOrder     = groupDto.SortOrder;
                group.PropertyTypes = new PropertyTypeCollection(MemberType.SupportsPublishingConst);

                //Because we are likely to have a group with no PropertyTypes we need to ensure that these are excluded
                var localGroupDto = groupDto;
                var typeDtos      = dto.PropertyTypes.Where(x => x.Id.HasValue && x.Id > 0 && x.PropertyTypeGroupId.HasValue && x.PropertyTypeGroupId.Value == localGroupDto.Id.Value);
                foreach (var typeDto in typeDtos)
                {
                    //Internal dictionary for adding "MemberCanEdit" and "VisibleOnProfile" properties to each PropertyType
                    memberType.MemberTypePropertyTypes.Add(typeDto.Alias,
                                                           new MemberTypePropertyProfileAccess(typeDto.ViewOnProfile, typeDto.CanEdit, typeDto.IsSensitive));

                    var tempGroupDto = groupDto;

                    //ensures that any built-in membership properties have their correct dbtype assigned no matter
                    //what the underlying data type is
                    var propDbType = MemberTypeRepository.GetDbTypeForBuiltInProperty(
                        typeDto.Alias,
                        typeDto.DbType.EnumParse <ValueStorageType>(true),
                        standardProps);

                    var propertyType = new PropertyType(
                        typeDto.PropertyEditorAlias,
                        propDbType.Result,
                        //This flag tells the property type that it has an explicit dbtype and that it cannot be changed
                        // which is what we want for the built-in properties.
                        propDbType.Success,
                        typeDto.Alias)
                    {
                        DataTypeId       = typeDto.DataTypeId,
                        Description      = typeDto.Description,
                        Id               = typeDto.Id.Value,
                        Name             = typeDto.Name,
                        Mandatory        = typeDto.Mandatory,
                        SortOrder        = typeDto.SortOrder,
                        ValidationRegExp = typeDto.ValidationRegExp,
                        PropertyGroupId  = new Lazy <int>(() => tempGroupDto.Id.Value),
                        CreateDate       = memberType.CreateDate,
                        UpdateDate       = memberType.UpdateDate,
                        Key              = typeDto.UniqueId
                    };

                    // reset dirty initial properties (U4-1946)
                    propertyType.ResetDirtyProperties(false);
                    group.PropertyTypes.Add(propertyType);
                }

                // reset dirty initial properties (U4-1946)
                group.ResetDirtyProperties(false);
                propertyGroups.Add(group);
            }

            return(propertyGroups);
        }
        public override PropertyGroup[] GetPropertyGroups()
        {
            PropertyGroup group = new PropertyGroup("GeneralSettings", TranslatablePluginController.GetLanguageResourceValue("fragment_propertygroup_general"), 0);

            Property headerTitle = new Property("headerTitle",
                                                TranslatablePluginController.GetLanguageResourceValue("fragment_property_title"), PropertyType.String, 0, "${resource:default_property_title}")
            {
                ControlType = typeof(ContentFragmentTokenStringControl)
            };

            group.Properties.Add(headerTitle);

            PropertyGroup defaultContent = new PropertyGroup("DefaultContent", TranslatablePluginController.GetLanguageResourceValue("fragment_propertygroup_defaultContent"), 0);

            Property property = new Property("default_content", TranslatablePluginController.GetLanguageResourceValue(
                                                 "fragment_property_content"), PropertyType.Html, 1, "")
            {
                ControlType = typeof(HtmlEditorStringControl)
            };

            property.Attributes["EnableHtmlScrubbing"] = "false";
            property.Attributes["width"]             = "100%";
            property.Attributes["height"]            = "300px";
            property.Attributes["enablehtmlediting"] = "true";
            property.Attributes["ContentTypeId"]     = InlineContentPart.InlineContentContentTypeId.ToString();
            defaultContent.Properties.Add(property);


            PropertyGroup anoymousContent = new PropertyGroup("AnonymousContent", TranslatablePluginController.GetLanguageResourceValue("fragment_propertygroup_anonymousContent"), 0);

            property = new Property("anonymous_content", TranslatablePluginController.GetLanguageResourceValue(
                                        "fragment_property_content"), PropertyType.Html, 1, "")
            {
                ControlType = typeof(HtmlEditorStringControl)
            };

            property.Attributes["EnableHtmlScrubbing"] = "false";
            property.Attributes["width"]             = "100%";
            property.Attributes["height"]            = "300px";
            property.Attributes["enablehtmlediting"] = "true";
            property.Attributes["ContentTypeId"]     = InlineContentPart.InlineContentContentTypeId.ToString();
            anoymousContent.Properties.Add(property);


            property = new Property("inlinecontenttype",
                                    TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_type"),
                                    PropertyType.String, 2, "Contextual")
            {
                DescriptionResourceName = "fragment_property_inlinecontent_type_description"
            };

            property.SelectableValues.Add(new PropertyValue("Contextual", TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_contextual"), (int)ContextMode.Context));
            property.SelectableValues.Add(new PropertyValue("GroupContextual", TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_groupcontextual"), (int)ContextMode.GroupContext));
            property.SelectableValues.Add(new PropertyValue("ByName", TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_byname"), (int)ContextMode.Name));

            group.Properties.Add(property);

            property = new Property("dynamicname", TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_dynamicname"), PropertyType.Bool, 3, bool.FalseString)
            {
                DescriptionResourceName = "fragment_property_inlinecontent_dynamicname_description"
            };

            group.Properties.Add(property);

            property = new Property("inlinecontentname", TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_name"), PropertyType.String, 4, string.Empty);
            group.Properties.Add(property);

            return(new[] { group, defaultContent, anoymousContent });
        }
Esempio n. 19
0
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            var ct = applicationContext.Services.ContentTypeService
                     .GetAllContentTypes().FirstOrDefault(x => x.Alias == "UcommentatorSettings");

            if (ct == null)
            {
                var textstring = applicationContext.Services.DataTypeService.GetDataTypeDefinitionByPropertyEditorAlias("umbraco.Textbox")
                                 .FirstOrDefault(x => x.Name.ToLower() == "textstring");
                var trueFalse =
                    applicationContext.Services.DataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(
                        "Umbraco.TrueFalse")
                    .FirstOrDefault(x => x.Name.ToLower() == "true/false");

                ContentType uCommentatorType = new ContentType(-1);
                uCommentatorType.Name          = "uCommentatorSettings";
                uCommentatorType.Alias         = "UcommentatorSettings";
                uCommentatorType.AllowedAsRoot = true;
                uCommentatorType.Icon          = "icon-wrench";

                var propGroup = new PropertyGroup()
                {
                    Name = "Settings"
                };

                uCommentatorType.AddPropertyGroup("Settings");

                var api_key = new PropertyType(textstring)
                {
                    Alias     = "api_key",
                    Name      = "API_KEY",
                    Mandatory = true
                };

                var api_secret = new PropertyType(textstring)
                {
                    Alias     = "api_secret",
                    Name      = "API_SECRET",
                    Mandatory = true
                };

                var access_token = new PropertyType(textstring)
                {
                    Alias     = "access_token",
                    Name      = "ACCESS_TOKEN",
                    Mandatory = true
                };

                var shortname = new PropertyType(textstring)
                {
                    Alias     = "shortname",
                    Name      = "Shortname",
                    Mandatory = true
                };

                var category = new PropertyType(textstring)
                {
                    Alias     = "category",
                    Name      = "Category",
                    Mandatory = true
                };

                var limit = new PropertyType(textstring)
                {
                    Alias     = "itemPerPage",
                    Name      = "Item per Page",
                    Mandatory = true
                };

                var enableSSO = new PropertyType(trueFalse)
                {
                    Alias     = "enableSSO",
                    Name      = "Enable SSO?",
                    Mandatory = false
                };

                var ssoName = new PropertyType(textstring)
                {
                    Alias       = "ssoName",
                    Name        = "SSO Name",
                    Description = "Fill this if you enable SSO.",
                    Mandatory   = false
                };

                var ssoButton = new PropertyType(textstring)
                {
                    Alias       = "ssoButton",
                    Name        = "SSO Button URL",
                    Description = "Fill this if you enable SSO.",
                    Mandatory   = false
                };

                var ssoIcon = new PropertyType(textstring)
                {
                    Alias       = "ssoIcon",
                    Name        = "SSO Icon URL",
                    Description = "Fill this if you enable SSO.",
                    Mandatory   = false
                };

                var ssoLogin = new PropertyType(textstring)
                {
                    Alias       = "ssoLogin",
                    Name        = "SSO Login URL",
                    Description = "Fill this if you enable SSO.",
                    Mandatory   = false
                };

                var ssoLogout = new PropertyType(textstring)
                {
                    Alias       = "ssoLogout",
                    Name        = "SSO Logout URL",
                    Description = "Fill this if you enable SSO.",
                    Mandatory   = false
                };

                uCommentatorType.AddPropertyType(api_key, "Settings");
                uCommentatorType.AddPropertyType(api_secret, "Settings");
                uCommentatorType.AddPropertyType(access_token, "Settings");
                uCommentatorType.AddPropertyType(shortname, "Settings");
                uCommentatorType.AddPropertyType(category, "Settings");
                uCommentatorType.AddPropertyType(limit, "Settings");
                uCommentatorType.AddPropertyType(enableSSO, "Settings");
                uCommentatorType.AddPropertyType(ssoName, "Settings");
                uCommentatorType.AddPropertyType(ssoButton, "Settings");
                uCommentatorType.AddPropertyType(ssoIcon, "Settings");
                uCommentatorType.AddPropertyType(ssoLogin, "Settings");
                uCommentatorType.AddPropertyType(ssoLogout, "Settings");

                ApplicationContext.Current.Services.ContentTypeService.Save(uCommentatorType);
            }

            var root     = new Node(-1);
            var settings = root.ChildrenAsList.FirstOrDefault(x => x.NodeTypeAlias == "UcommentatorSettings");

            if (settings == null)
            {
                IContent doc = ApplicationContext.Current.Services.ContentService.CreateContent("uCommentator Settings", -1,
                                                                                                "UcommentatorSettings");

                doc.SetValue("api_key", "your api_key");
                doc.SetValue("api_secret", "your api_secret");
                doc.SetValue("access_token", "your access_token");
                doc.SetValue("shortname", "your shortname");
                doc.SetValue("category", "your category");
                doc.SetValue("itemPerPage", 10);
                doc.SetValue("enableSSO", 0);
                doc.SetValue("ssoName", "Example SSO");
                doc.SetValue("ssoButton", "http://example.com/images/samplenews.gif");
                doc.SetValue("ssoIcon", "http://example.com/favicon.png");
                doc.SetValue("ssoLogout", "http://example.com/login/");
                doc.SetValue("ssoLogout", "http://example.com/logout/");

                applicationContext.Services.ContentService.SaveAndPublishWithStatus(doc);
            }

            installer = new LanguageInstaller();
            installer.CheckAndInstallLanguageActions();
            ServerVariablesParser.Parsing += ServerVariablesParser_Parsing;

            var us   = applicationContext.Services.UserService;
            var user = us.GetByProviderKey(0);

            if (!user.AllowedSections.Any(x => x == "uCommentator"))
            {
                user.AddAllowedSection("uCommentator");
                us.Save(user);
            }
        }
Esempio n. 20
0
        public static MSVSProjectFile FromFile(string filepath)
        {
            var ProjectFileName = new FileInfo(filepath);

            var Document = XDocument.Load(filepath);


            var HintPaths = Document.Root.Elements(nsItemGroup).Elements(nsReference).Elements(nsHintPath).Select(k => k.Value).ToArray();

            var DefaultNamespace = Enumerable.First(
                from PropertyGroup in Document.Root.Elements(nsPropertyGroup)
                //from RootNamespace in PropertyGroup.Elements(nsRootNamespace)
                //select RootNamespace.Value

                from __AssemblyName in PropertyGroup.Elements(nsAssemblyName)
                select __AssemblyName.Value
                );


            // emulate $safeprojectname$
            DefaultNamespace = DefaultNamespace.Replace(" ", "_");

            #region GetFilesByType
            Func <XName, IEnumerable <ProjectFileInfo> > GetFilesByType =
                FileType =>
                from ItemGroup in Document.Root.Elements(nsItemGroup)

                from None in ItemGroup.Elements(FileType)

                // <Link>%(RecursiveDir)%(FileName)%(Extension)</Link>
                let Link0 = None.Element(nsLink)

                            // Include = "Y:\\opensource\\github\\elastic-droid\\src\\**\\*.*"
                            let Include0 = None.Attribute("Include").Value

                                           // https://sites.google.com/a/jsc-solutions.net/work/knowledge-base/15-dualvr/20141127
                                           // what about *.java ?
                                           let Wildcard = @"**\*.*"
                                                          let IsWildcard = Include0.EndsWith(Wildcard)

                                                                           let IncludeWildcard = Include0.TakeUntilLastOrNull(Wildcard)

                                                                                                 let Include1 = !IsWildcard ?
                                                                                                                new[] { Include0 } :
            Directory.EnumerateFiles(IncludeWildcard, "*.*", SearchOption.AllDirectories)


            from Include in Include1

            let IncludeDirectory = Path.GetDirectoryName(Include)

                                   let Replace = new
            {
                Extension    = Path.GetExtension(Include),
                FileName     = Path.GetFileNameWithoutExtension(Include),
                RecursiveDir = IncludeDirectory.SkipUntilOrEmpty(IncludeWildcard),
            }

            //let Include = Include0
            let Link = Link0 == null ? null : new
            {
                Value =
                    Link0.Value
                    .Replace("%(Extension)", Replace.Extension)
                    .Replace("%(FileName)", Replace.FileName)
                    .Replace("%(RecursiveDir)", Replace.RecursiveDir == "" ? "" : Replace.RecursiveDir + "\\")
            }

            // Directory In Project
            let Directory = Path.GetDirectoryName(Link != null ? Link.Value : Include).Replace("\\", "/")

                            let File = new FileInfo(
                Link != null ?
                Include :
                Path.Combine(ProjectFileName.Directory.FullName, Include)
                )

                                       select new ProjectFileInfo {
                File = File, NamespaceDirectory = Directory
            };
            #endregion



            #region HasReference
            Func <FileInfo, bool> HasReference =
                AssemblyFile =>
            {
                var TargetHintPath = GetRelativePath(
                    ProjectFileName.Directory.FullName,
                    AssemblyFile.FullName
                    );


                return(Enumerable.Any(
                           from ItemGroup in Document.Root.Elements(nsItemGroup)
                           from Reference in ItemGroup.Elements(nsReference)
                           from HintPath in Reference.Elements(nsHintPath)
                           where TargetHintPath == HintPath.Value
                           select new { HintPath, Reference, ItemGroup }
                           ));
            };
            #endregion

            #region GetAssemblyReferences
            Func <FileInfo[]> GetAssemblyReferences =
                delegate
            {
                var a =
                    from ItemGroup in Document.Root.Elements(nsItemGroup)
                    from Reference in ItemGroup.Elements(nsReference)
                    from HintPath in Reference.Elements(nsHintPath)
                    let AssemblyReferencePath = Path.Combine(new FileInfo(filepath).Directory.FullName, HintPath.Value)
                                                select new FileInfo(AssemblyReferencePath);


                //            <Reference Include="My.Solutions.Pages.OpCode.AssetsLibrary">
                //  <HintPath>bin\staging.AssetsLibrary\My.Solutions.Pages.OpCode.AssetsLibrary.dll</HintPath>
                //</Reference>

                return(a.ToArray());
            };
            #endregion

            #region GetProjectReferences
            Func <MSVSProjectFile[]> GetProjectReferences =
                delegate
            {
                var a =
                    from ItemGroup in Document.Root.Elements(nsItemGroup)
                    from ProjectReference in ItemGroup.Elements(nsProjectReference)
                    let Include = ProjectReference.Attribute("Include")
                                  let ProjectReferencePath = Path.Combine(new FileInfo(filepath).Directory.FullName, Include.Value)
                                                             where File.Exists(ProjectReferencePath)
                                                             select(MSVSProjectFile) new FileInfo(ProjectReferencePath);

                //<ItemGroup>
                //  <ProjectReference Include="..\..\My.Solutions.Pages.OpCode\My.Solutions.Pages.OpCode\My.Solutions.Pages.OpCode.csproj">
                //    <Project>{5823d538-ea39-4d2a-9c15-f3bce76c9781}</Project>
                //    <Name>My.Solutions.Pages.OpCode</Name>
                //  </ProjectReference>



                return(a.ToArray());
            };
            #endregion


            MSVSProjectFile __this = null;

            #region AddReference
            Action <FileInfo, AssemblyName> AddReference =
                (AssemblyFile, Name) =>
            {
                /* add reference
                 * <Reference Include="AutoGeneratedReferences.Components.JohDoe.TextComponent, Version=0.0.0.0, Culture=neutral, processorArchitecture=MSIL">
                 * <SpecificVersion>False</SpecificVersion>
                 * <HintPath>bin\staging\AutoGeneratedReferences.Components.JohDoe.TextComponent.dll</HintPath>
                 * </Reference>
                 */

                if (!AssemblyFile.Exists)
                {
                    return;
                }

                //var TargetHintPath = AssemblyFile.FullName.Substring(ProjectFileName.Directory.FullName.Length + 1);
                var TargetHintPath = GetRelativePath(
                    ProjectFileName.Directory.FullName,
                    AssemblyFile.FullName
                    );

                // sanity check
                if (!HasReference(AssemblyFile))
                {
                    var TargetItemGroup = Enumerable.First(
                        from ItemGroup in Document.Root.Elements(nsItemGroup)
                        from Reference in ItemGroup.Elements(nsReference)
                        select ItemGroup
                        );

                    TargetItemGroup.Add(
                        new XElement(nsReference,
                                     new XAttribute("Include", Name.ToString()),
                                     new XElement(nsHintPath, TargetHintPath)
                                     )
                        );

                    __this.RaiseReferenceAdded();
                }
            };
            #endregion

            Action Save = delegate
            {
                Document.Save(filepath);
            };

            return(__this = new MSVSProjectFile
            {
                Document = Document,

                HintPaths = HintPaths,
                DefaultNamespace = DefaultNamespace,
                NoneFiles = GetFilesByType(nsNone).ToArray(),
                ContentFiles = GetFilesByType(nsContent).ToArray(),
                HasReference = HasReference,
                AddReference = AddReference,
                Save = Save,
                GetProjectReferences = GetProjectReferences,
                GetAssemblyReferences = GetAssemblyReferences
            });
        }
   public DrawCardLocation(int spaceNumber, PropertyGroup @group) : base(spaceNumber, @group)
   {
 
   }
Esempio n. 22
0
 private XElement SerializePropertyType(IPropertyType propertyType, IDataType definition, PropertyGroup propertyGroup)
 => new XElement("GenericProperty",
                 new XElement("Name", propertyType.Name),
                 new XElement("Alias", propertyType.Alias),
                 new XElement("Key", propertyType.Key),
                 new XElement("Type", propertyType.PropertyEditorAlias),
                 new XElement("Definition", definition.Key),
                 propertyGroup != null ? new XElement("Tab", propertyGroup.Name, new XAttribute("Alias", propertyGroup.Alias)) : null, // TODO Replace with PropertyGroupAlias
                 new XElement("SortOrder", propertyType.SortOrder),
                 new XElement("Mandatory", propertyType.Mandatory.ToString()),
                 new XElement("LabelOnTop", propertyType.LabelOnTop.ToString()),
                 propertyType.MandatoryMessage != null ? new XElement("MandatoryMessage", propertyType.MandatoryMessage) : null,
                 propertyType.ValidationRegExp != null ? new XElement("Validation", propertyType.ValidationRegExp) : null,
                 propertyType.ValidationRegExpMessage != null ? new XElement("ValidationRegExpMessage", propertyType.ValidationRegExpMessage) : null,
                 propertyType.Description != null ? new XElement("Description", new XCData(propertyType.Description)) : null);
Esempio n. 23
0
        public static Lazy <IContentType> GetContentTypeDefinition(Type modelType)
        {
            //Check for BaseType different from ContentTypeBase
            bool hasParent = modelType.BaseType != null && modelType.BaseType != typeof(ContentTypeBase) && modelType.BaseType != typeof(object);
            var  parent    = new Lazy <IContentType>();

            if (hasParent)
            {
                var isResolved = _contentTypeCache.ContainsKey(modelType.BaseType.FullName);
                parent = isResolved
                             ? _contentTypeCache[modelType.BaseType.FullName].ContentType
                             : GetContentTypeDefinition(modelType.BaseType);
            }

            var contentTypeAttribute = modelType.FirstAttribute <ContentTypeAttribute>();
            var contentTypeAlias     = contentTypeAttribute == null?modelType.Name.ToUmbracoAlias() : contentTypeAttribute.Alias;

            //Check if ContentType already exists by looking it up by Alias.
            var existing = ApplicationContext.Current.Services.ContentTypeService.GetContentType(contentTypeAlias);

            Lazy <IContentType> contentType = contentTypeAttribute == null
                                                 ? PlainPocoConvention(modelType, existing)
                                                 : ContentTypeConvention(contentTypeAttribute, modelType, existing);

            //Check for interfaces that'll be used for ContentTypeComposition
            var mixins = GetAliasesFromTypeInterfaces(modelType);

            var definitions   = new List <PropertyDefinition>();
            int order         = 0;
            var objProperties = modelType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).ToList();

            foreach (var propertyInfo in objProperties)
            {
                var propertyTypeAttribute = propertyInfo.FirstAttribute <PropertyTypeConventionAttribute>();
                var definition            = propertyTypeAttribute == null
                                     ? new PropertyDefinition()
                                     : propertyTypeAttribute.GetPropertyConvention();

                //DataTypeDefinition fallback
                if (definition.DataTypeDefinition == null)
                {
                    definition.DataTypeDefinition = Conventions.GetDataTypeDefinitionByAttributeOrType(null, propertyInfo.PropertyType);
                }

                if (string.IsNullOrEmpty(definition.PropertyGroup))
                {
                    definition.PropertyGroup = "Generic Properties";
                }

                //Alias fallback
                if (string.IsNullOrEmpty(definition.Alias))
                {
                    var aliasAttribute = propertyInfo.FirstAttribute <AliasAttribute>();
                    definition.Alias = Conventions.GetPropertyTypeAlias(aliasAttribute, propertyInfo.Name);
                    definition.Name  = Conventions.GetPropertyTypeName(aliasAttribute, propertyInfo.Name);
                }

                //Description fallback
                if (string.IsNullOrEmpty(definition.Description))
                {
                    var descriptionAttribute = propertyInfo.FirstAttribute <DescriptionAttribute>();
                    definition.Description = descriptionAttribute != null
                                                 ? descriptionAttribute.Description
                                                 : string.Empty;
                }

                //SortOrder fallback
                if (definition.Order == default(int))
                {
                    var sortOrderAttribute = propertyInfo.FirstAttribute <SortOrderAttribute>();
                    definition.Order = sortOrderAttribute != null ? sortOrderAttribute.Order : order;
                }

                definitions.Add(definition);
                order++;
            }

            //Loop through definitions for PropertyGroups and create those that not already exists
            var groupDefinitions = definitions.DistinctBy(d => d.PropertyGroup);

            foreach (var groupDefinition in groupDefinitions)
            {
                var groupExists = contentType.Value.PropertyGroups.Contains(groupDefinition.PropertyGroup);
                if (groupExists == false)
                {
                    var propertyGroup = new PropertyGroup {
                        Name = groupDefinition.PropertyGroup
                    };
                    contentType.Value.PropertyGroups.Add(propertyGroup);
                }
            }

            //Loop through definitions for PropertyTypes and add them to the correct PropertyGroup
            foreach (var definition in definitions)
            {
                var group = contentType.Value.PropertyGroups.First(x => x.Name == definition.PropertyGroup);
                //Check if a PropertyType with the same alias already exists, as we don't want to override existing ones
                if (group.PropertyTypes.Contains(definition.Alias))
                {
                    continue;
                }

                var propertyType = new PropertyType(definition.DataTypeDefinition)
                {
                    Mandatory        = definition.Mandatory,
                    ValidationRegExp = definition.ValidationRegExp,
                    SortOrder        = definition.Order,
                    Alias            = definition.Alias,
                    Name             = definition.Name
                };

                group.PropertyTypes.Add(propertyType);
            }

            //If current ContentType has a Parent the ParentId should be set and the ContentType added to the composition.
            if (hasParent)
            {
                contentType.Value.SetLazyParentId(new Lazy <int>(() => parent.Value.Id));
                contentType.Value.AddContentType(parent.Value);
            }
            //Add the resolved ContentType to the internal cache
            var field = new DependencyField {
                ContentType = contentType, Alias = contentType.Value.Alias
            };
            var dependencies = new List <string>();

            //If current type has a parent (inherited model) we add the alias of that type as a dependency
            if (hasParent)
            {
                dependencies.Add(parent.Value.Alias);
            }
            //Check ContentType for existing 'Allowed ContentTypes'
            if (contentType.Value.AllowedContentTypes.Any())
            {
                dependencies.AddRange(contentType.Value.AllowedContentTypes.Select(allowed => allowed.Alias));
            }
            //Check for interfaces with AliasAttribute and add those as dependencies
            //NOTE: might also be an idea to check if ContentType has already been created/added to cache that implements the interface.
            if (mixins.Any())
            {
                foreach (var mixin in mixins)
                {
                    if (dependencies.Contains(mixin.Item1))
                    {
                        continue;
                    }

                    dependencies.Add(mixin.Item1);
                    var isMixinResolved = _contentTypeCache.ContainsKey(mixin.Item2);

                    Lazy <IContentType> compositionType = null;

                    if (isMixinResolved)
                    {
                        compositionType = _contentTypeCache[mixin.Item2].ContentType;
                    }
                    else
                    {
                        GetContentTypeDefinition(mixin.Item3);
                        compositionType = _contentTypeCache[mixin.Item2].ContentType;
                    }

                    contentType.Value.AddContentType(compositionType.Value);
                }
            }
            field.DependsOn = dependencies.ToArray();
            _contentTypeCache.AddOrUpdate(modelType.FullName, field, (x, y) => field);
            return(contentType);
        }
Esempio n. 24
0
        public static Project CreateDefaultConsole(Guid projectGuid, string rootNameSpace, string assemblyName, string targetFrameworkVersion)
        {
            var project = Project.CreatePreVS2017Project();

            var import = new Import(@"$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props")
            {
                Condition = @"Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"
            };

            project.Add(import);

            var propertyGroup = new PropertyGroup();

            propertyGroup.SetProperty("Configuration", "Debug", " '$(Configuration)' == '' ");
            propertyGroup.SetProperty("Platform", "AnyCPU", " '$(Platform)' == '' ");
            propertyGroup.SetProperty("ProjectGuid", $"{{{projectGuid.ToString().ToUpper()}}}");
            propertyGroup.SetProperty("OutputType", "Exe");
            propertyGroup.SetProperty("RootNamespace", rootNameSpace);
            propertyGroup.SetProperty("AssemblyName", assemblyName);
            propertyGroup.SetProperty("TargetFrameworkVersion", targetFrameworkVersion);
            propertyGroup.SetProperty("FileAlignment", "512");
            propertyGroup.SetProperty("AutoGenerateBindingRedirects", "true");
            propertyGroup.SetProperty("Deterministic", "true");
            project.Add(propertyGroup);

            var debugPropertyGroup = new PropertyGroup {
                Condition = " '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "
            };

            debugPropertyGroup.SetProperty("PlatformTarget", "AnyCPU");
            debugPropertyGroup.SetProperty("DebugSymbols", "true");
            debugPropertyGroup.SetProperty("DebugType", "true");
            debugPropertyGroup.SetProperty("DebugSymbols", "full");
            debugPropertyGroup.SetProperty("Optimize", "false");
            debugPropertyGroup.SetProperty("OutputPath", @"bin\Debug\");
            debugPropertyGroup.SetProperty("DefineConstants", "DEBUG;TRACE");
            debugPropertyGroup.SetProperty("ErrorReport", "prompt");
            debugPropertyGroup.SetProperty("WarningLevel", "4");
            project.Add(debugPropertyGroup);

            var releasePropertyGroup = new PropertyGroup {
                Condition = " '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "
            };

            releasePropertyGroup.SetProperty("PlatformTarget", "AnyCPU");
            releasePropertyGroup.SetProperty("DebugType", "pdbonly");
            releasePropertyGroup.SetProperty("Optimize", "true");
            releasePropertyGroup.SetProperty("OutputPath", @"bin\Release\");
            releasePropertyGroup.SetProperty("DefineConstants", "TRACE");
            releasePropertyGroup.SetProperty("ErrorReport", "prompt");
            releasePropertyGroup.SetProperty("WarningLevel", "4");
            project.Add(releasePropertyGroup);

            var referenceItemGroup = new ItemGroup();

            referenceItemGroup.Add(new Reference("System"));
            referenceItemGroup.Add(new Reference("System.Core"));
            referenceItemGroup.Add(new Reference("System.Xml.Linq"));
            referenceItemGroup.Add(new Reference("System.Data.DataSetExtensions"));
            referenceItemGroup.Add(new Reference("Microsoft.CSharp"));
            referenceItemGroup.Add(new Reference("System.Data"));
            referenceItemGroup.Add(new Reference("System.Net.Http"));
            referenceItemGroup.Add(new Reference("System.Xml"));
            project.Add(referenceItemGroup);

            var targetsImport = new Import(@"$(MSBuildToolsPath)\Microsoft.CSharp.targets");

            project.Add(targetsImport);

            return(project);
        }
Esempio n. 25
0
 public Location(int spaceNumber, PropertyGroup group)
 {
     SpaceNumber = spaceNumber;
     Group = group;
 }
Esempio n. 26
0
        private ContentType CreateProductContentType(IEnumerable <IDataTypeDefinition> allDataTypeDefinitions, IContentTypeService contentTypeService, List <ITemplate> templates)
        {
            ContentType contentType = new ContentType(-1);

            contentType.Alias            = "product";
            contentType.Name             = "Product";
            contentType.Icon             = "icon-tag";
            contentType.AllowedTemplates = templates.Where(t => t.Alias.ToLowerInvariant() == "product");

            PropertyGroup contentPropertyGroup = new PropertyGroup(new PropertyTypeCollection(new List <PropertyType> {
                new PropertyType(allDataTypeDefinitions.FirstOrDefault(d => d.PropertyEditorAlias == "Umbraco.MediaPicker2" && !d.Name.ToLowerInvariant().Contains("multiple")))
                {
                    Alias = "image",
                    Name  = "Image",
                },
                new PropertyType(allDataTypeDefinitions.FirstOrDefault(d => d.PropertyEditorAlias == "Umbraco.Textbox"))
                {
                    Alias = "productName",
                    Name  = "Name",
                },
                new PropertyType(allDataTypeDefinitions.FirstOrDefault(d => d.PropertyEditorAlias == "Umbraco.Textbox"))
                {
                    Alias = "sku",
                    Name  = "Sku",
                },
                new PropertyType(allDataTypeDefinitions.FirstOrDefault(d => d.PropertyEditorAlias == "Umbraco.Textbox"))
                {
                    Alias            = "priceJMD",
                    Name             = "Price",
                    ValidationRegExp = @"^(\s*|\d+(?:[,|\.]\d+)?)$",
                },
                new PropertyType(allDataTypeDefinitions.FirstOrDefault(d => d.PropertyEditorAlias == "TeaCommerce.StockManagement"))
                {
                    Alias = "stock",
                    Name  = "Stock",
                },
                new PropertyType(allDataTypeDefinitions.FirstOrDefault(d => d.PropertyEditorAlias == "Umbraco.TinyMCEv3"))
                {
                    Alias = "description",
                    Name  = "Description",
                },
            }))
            {
                Name = "Content"
            };

            contentType.PropertyGroups.Add(contentPropertyGroup);

            PropertyGroup variantsPropertyGroup = new PropertyGroup(new PropertyTypeCollection(new List <PropertyType> {
                new PropertyType(allDataTypeDefinitions.FirstOrDefault(d => d.PropertyEditorAlias == "TeaCommerce.VariantEditor"))
                {
                    Alias = "variants",
                    Name  = "Variants",
                },
            }))
            {
                Name = "Variants"
            };

            contentType.PropertyGroups.Add(variantsPropertyGroup);
            contentTypeService.Save(contentType);

            return(contentType);
        }
Esempio n. 27
0
        public IMemberType AddDialogueMemberType()
        {
            #region DataType Ids
            //-49	    Umbraco.TrueFalse
            //-51	    Umbraco.Integer
            //-87	    Umbraco.TinyMCEv3
            //-88	    Umbraco.Textbox
            //-89	    Umbraco.TextboxMultiple
            //-90	    Umbraco.UploadField
            //-92	    Umbraco.NoEdit
            //-36	    Umbraco.DateTime
            //-37	    Umbraco.ColorPickerAlias
            //-38	    Umbraco.FolderBrowser
            //-39	    Umbraco.DropDownMultiple
            //-40	    Umbraco.RadioButtonList
            //-41	    Umbraco.Date
            //-42	    Umbraco.DropDown
            //-43	    Umbraco.CheckBoxList
            //1034	    Umbraco.ContentPickerAlias
            //1035	    Umbraco.MediaPicker
            //1036	    Umbraco.MemberPicker
            //1040	    Umbraco.RelatedLinks
            //1041	    Umbraco.Tags
            //1045	    Umbraco.MultipleMediaPicker
            //1077	    Apt.PartialPicker
            //1089	    Umbraco.ImageCropper
            //1092	    Umbraco.TinyMCEv3
            //1103	    Our.Umbraco.FilePicker
            //1104	    Umbraco.MemberGroupPicker
            //1105	    Apt.CssPicker
            //1128	    Dialogue.ThemePicker
            //1132	    Dialogue.Permissions
            //1147	    Umbraco.MultipleTextstring
            #endregion

            var label = _dataTypeService.GetDataTypeDefinitionById(-92);
            var upload = _dataTypeService.GetDataTypeDefinitionById(-90);
            var textstring = _dataTypeService.GetDataTypeDefinitionById(-88);
            var textboxMultiple = _dataTypeService.GetDataTypeDefinitionById(-89);
            var truefalse = _dataTypeService.GetDataTypeDefinitionById(-49);
            var numeric = _dataTypeService.GetDataTypeDefinitionById(-51);
            var datetime = _dataTypeService.GetDataTypeDefinitionById(-36);

            // Profile, Settings, Social Tokens

            // Create the member Type
            var memType = new MemberType(-1)
            {
                Alias = AppConstants.MemberTypeAlias,
                Name = "Dialogue Member"
            };

            // Create the Profile group/tab
            var profileGroup = new PropertyGroup
            {
                Name = "Profile",
            };
            profileGroup.PropertyTypes.Add(new PropertyType(label)
            {
                Alias = "email",
                Name = "Email",
                SortOrder = 0,
                Description = "This is a bit rubbish, but it's the only way to get the email from the new member service at the current time"
            });
            profileGroup.PropertyTypes.Add(new PropertyType(upload)
            {
                Alias = "avatar",
                Name = "Avatar",
                SortOrder = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Alias = "website",
                Name = "Website",
                SortOrder = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Alias = "twitter",
                Name = "Twitter",
                SortOrder = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(textboxMultiple)
            {
                Alias = "signature",
                Name = "Signature",
                SortOrder = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(datetime)
            {
                Alias = "lastActiveDate",
                Name = "Last Active Date",
                SortOrder = 0,
                Description = ""
            });
            memType.PropertyGroups.Add(profileGroup);

            // Create the Settings group/tab
            var settingsGroup = new PropertyGroup
            {
                Name = "Settings",
            };
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias = "canEditOtherMembers",
                Name = "Can Edit Other Members",
                SortOrder = 0,
                Description = "Enable this and the user can edit other members posts, their profiles and ban members (Usually use in conjunction with moderate permissions)."
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias = "disableEmailNotifications",
                Name = "Disable Email Notifications",
                SortOrder = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias = "disablePosting",
                Name = "Disable Posting",
                SortOrder = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias = "disablePrivateMessages",
                Name = "Disable Private Messages",
                SortOrder = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias = "disableFileUploads",
                Name = "Disable File Uploads",
                SortOrder = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(numeric)
            {
                Alias = "postCount",
                Name = "Post Count",
                SortOrder = 0,
                Description = "The users post count. This is kept like this to help reduce SQL queries and improve performance of the forum"
            });
            memType.PropertyGroups.Add(settingsGroup);

            // Create the Settings group/tab
            var socialGroup = new PropertyGroup
            {
                Name = "Social Tokens",
            };
            socialGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Name = "Facebook Access Token",
                Alias = "facebookAccessToken",
                SortOrder = 0,
                Description = ""
            });
            socialGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Name = "Facebook Id",
                Alias = "facebookId",
                SortOrder = 0,
                Description = ""
            });
            socialGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Name = "Google Access Token",
                Alias = "googleAccessToken",
                SortOrder = 0,
                Description = ""
            });
            socialGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Name = "Google Id",
                Alias = "googleId",
                SortOrder = 0,
                Description = ""
            });
            memType.PropertyGroups.Add(socialGroup);

            // Add Slug
            memType.AddPropertyType(new PropertyType(textstring)
            {
                Name = "Slug",
                Alias = "slug",
                SortOrder = 0,
                Description = "This is what we use to look up the member in the front end"
            });

            _memberTypeService.Save(memType);

            return memType;
        }
        private void GenerateSetMethodBody(ICommonAssembly assembly, IHasMethods viewModelBaseType, ICommonType viewModelType, PropertyGroup group, FieldReference field)
        {
            log.Info("Generate set method body...");

            var property = group.Property;

            if (property.SetMethod == null)
            {
                log.Debug($"Create set accessor method for property '{property.Name}'");
                var setMethod = new MethodDefinition($"set_{property.Name}", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.SpecialName, assembly.MonoCecil.MainModule.TypeSystem.Void);
                setMethod.Parameters.Add(new ParameterDefinition("value", ParameterAttributes.None, property.MonoCecil.PropertyType));

                property.MonoCecil.SetMethod = setMethod;
                viewModelType.MonoCecil.Methods.Add(setMethod);
            }

            var setMethodFromViewModelBaseWithGeneric = new GenericInstanceMethod(viewModelBaseType.GetMethod("Set", new[] { typeof(string).FullName, "T&", "T", typeof(bool).FullName }, true).MonoCecil);

            setMethodFromViewModelBaseWithGeneric.GenericArguments.Add(property.MonoCecil.PropertyType);

            var importedSetMethodFromViewModelBaseWithGeneric = assembly.MonoCecil.MainModule.ImportReference(setMethodFromViewModelBaseWithGeneric);
            var callMethodAfterSetPropertyInstructions        = CreateCallMethodInstructions(group.CalledMethodAfterSetProperty).ToArray();

            property.MonoCecil.SetMethod.Body.Variables.Clear();
            property.MonoCecil.SetMethod.Body.Instructions.Clear();

            CreateCallMethodInstructions(group.CalledMethodBeforeSetProperty).ForEach(property.MonoCecil.SetMethod.Body.Instructions.Add);
            property.MonoCecil.SetMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
            property.MonoCecil.SetMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldstr, property.Name));
            property.MonoCecil.SetMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
            property.MonoCecil.SetMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldflda, field));
            property.MonoCecil.SetMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_1));
            property.MonoCecil.SetMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldc_I4_0));
            property.MonoCecil.SetMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Call, importedSetMethodFromViewModelBaseWithGeneric));

            var returnInstruction = Instruction.Create(OpCodes.Ret);

            if (group.CalledMethodAfterSuccessSetProperty != null)
            {
                var firstInstructionAfterJump = callMethodAfterSetPropertyInstructions.FirstOrDefault() ?? returnInstruction;
                property.MonoCecil.SetMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse_S, firstInstructionAfterJump));
                CreateCallMethodInstructions(group.CalledMethodAfterSuccessSetProperty).ForEach(property.MonoCecil.SetMethod.Body.Instructions.Add);
            }
            else
            {
                property.MonoCecil.SetMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Pop));
            }

            callMethodAfterSetPropertyInstructions.ForEach(property.MonoCecil.SetMethod.Body.Instructions.Add);
            property.MonoCecil.SetMethod.Body.Instructions.Add(returnInstruction);

            property.MonoCecil.SetMethod.RemoveAttributes <CompilerGeneratedAttribute>();

            log.Info("Set method body was generated");
        }
Esempio n. 29
0
 protected void AssertTab(PropertyGroup propertyGroup, ExpectedTab tab, string typeAlias)
 {
     Assert(propertyGroup, x => x.Name == tab.Name, "Tab name doesn't match. Tab: " + tab.Name + ", type: " + typeAlias);
     Assert(propertyGroup, x => x.SortOrder == tab.SortOrder || tab.SortOrder == 0, "Tab sort order doesn't match. Tab: " + tab.Name + ", type: " + typeAlias);
     AssertProperties(propertyGroup.PropertyTypes, tab.Properties, typeAlias, tab.Name);
 }
        public static IEnumerable <PropertyGroup> BuildEntity(IEnumerable <PropertyTypeGroupDto> groupDtos,
                                                              bool isPublishing,
                                                              int contentTypeId,
                                                              DateTime createDate,
                                                              DateTime updateDate,
                                                              Func <string, ValueStorageType, string, PropertyType> propertyTypeCtor)
        {
            // groupDtos contains all the groups, those that are defined on the current
            // content type, and those that are inherited from composition content types
            var propertyGroups = new PropertyGroupCollection();

            foreach (var groupDto in groupDtos)
            {
                var group = new PropertyGroup(isPublishing);

                try
                {
                    group.DisableChangeTracking();

                    // if the group is defined on the current content type,
                    // assign its identifier, else it will be zero
                    if (groupDto.ContentTypeNodeId == contentTypeId)
                    {
                        group.Id = groupDto.Id;
                    }

                    group.Key       = groupDto.UniqueId;
                    group.Type      = (PropertyGroupType)groupDto.Type;
                    group.Name      = groupDto.Text;
                    group.Alias     = groupDto.Alias;
                    group.SortOrder = groupDto.SortOrder;

                    group.PropertyTypes = new PropertyTypeCollection(isPublishing);

                    //Because we are likely to have a group with no PropertyTypes we need to ensure that these are excluded
                    var typeDtos = groupDto.PropertyTypeDtos.Where(x => x.Id > 0);
                    foreach (var typeDto in typeDtos)
                    {
                        var tempGroupDto = groupDto;
                        var propertyType = propertyTypeCtor(typeDto.DataTypeDto.EditorAlias,
                                                            typeDto.DataTypeDto.DbType.EnumParse <ValueStorageType>(true),
                                                            typeDto.Alias);

                        try
                        {
                            propertyType.DisableChangeTracking();

                            propertyType.Alias                   = typeDto.Alias;
                            propertyType.DataTypeId              = typeDto.DataTypeId;
                            propertyType.DataTypeKey             = typeDto.DataTypeDto.NodeDto.UniqueId;
                            propertyType.Description             = typeDto.Description;
                            propertyType.Id                      = typeDto.Id;
                            propertyType.Key                     = typeDto.UniqueId;
                            propertyType.Name                    = typeDto.Name;
                            propertyType.Mandatory               = typeDto.Mandatory;
                            propertyType.MandatoryMessage        = typeDto.MandatoryMessage;
                            propertyType.SortOrder               = typeDto.SortOrder;
                            propertyType.ValidationRegExp        = typeDto.ValidationRegExp;
                            propertyType.ValidationRegExpMessage = typeDto.ValidationRegExpMessage;
                            propertyType.PropertyGroupId         = new Lazy <int>(() => tempGroupDto.Id);
                            propertyType.CreateDate              = createDate;
                            propertyType.UpdateDate              = updateDate;
                            propertyType.Variations              = (ContentVariation)typeDto.Variations;

                            // reset dirty initial properties (U4-1946)
                            propertyType.ResetDirtyProperties(false);
                            group.PropertyTypes.Add(propertyType);
                        }
                        finally
                        {
                            propertyType.EnableChangeTracking();
                        }
                    }

                    // reset dirty initial properties (U4-1946)
                    group.ResetDirtyProperties(false);
                    propertyGroups.Add(group);
                }
                finally
                {
                    group.EnableChangeTracking();
                }
            }

            return(propertyGroups);
        }
        public string GetDynamicFormXml()
        {
            ContentDetails details = GetCurrentContentDetails();

            MetaData metaData = GetCurrentMetaData(details);

            PropertyGroup group = new PropertyGroup("Meta", "Meta Options", 0);

            PropertySubGroup subGroup = new PropertySubGroup("Options", "Main Options", 0)
            {
            };

            group.PropertySubGroups.Add(subGroup);

            int order = 0;
            subGroup.Properties.Add(new Property("Inherit", "Inherit From Parent", PropertyType.Bool, order++, metaData.InheritData.ToString()));
            subGroup.Properties.Add(new Property("Title", "Title", PropertyType.String, order++, metaData.Title));
            subGroup.Properties.Add(new Property("Description", "Description", PropertyType.String, order++, metaData.Description));
            subGroup.Properties.Add(new Property("Keywords", "Keywords", PropertyType.String, order++, metaData.Keywords));

            PropertySubGroup extendedGroup = new PropertySubGroup("Options", "Extended Tags", 1);

            group.PropertySubGroups.Add(extendedGroup);

            foreach (string extendedEntry in _metaConfig.ExtendedEntries)
            {
                extendedGroup.Properties.Add(new Property(extendedEntry, extendedEntry, PropertyType.String, order++, metaData.ExtendedMetaTags.ContainsKey(extendedEntry) ? metaData.ExtendedMetaTags[extendedEntry] : string.Empty));
            }

            StringBuilder sb = new StringBuilder();

            using(StringWriter sw = new StringWriter(sb))
            using (XmlTextWriter tw = new XmlTextWriter(sw))
                group.Serialize(tw);

            return sb.ToString();
        }
Esempio n. 32
0
 public void PropertyGroupParsed(XmlNode node, PropertyGroup group)
 {
 }
		public static PropertyGroup GetOrAddPropertyGroup(IContentType contentType, string groupName)
		{
			var group = contentType.PropertyGroups.FirstOrDefault(g => g.Name == groupName);
			if (group == null)
			{
				var sortOrder = contentType.PropertyGroups.Select(g => g.SortOrder).OrderByDescending(x => x).FirstOrDefault() + 1;
				group = new PropertyGroup { Name = groupName, SortOrder = sortOrder };
				contentType.PropertyGroups.Add(group);
			}
			return group;
		}
        private List<CompilerClass> LoadCompilerClasses(ItemGroup itemGroup, PropertyGroup propGroup)
        {
            List<CompilerClass> compilerClasses = new List<CompilerClass>();
            IList<ParsedPath> paths = itemGroup.GetRequiredValue("CompilerAssembly");

            foreach (var path in paths)
            {
                Assembly assembly = null;

                try
                {
                    // We use Assembly.Load so that the test assembly and subsequently loaded
                    // assemblies end up in the correct load context.  If the assembly cannot be
                    // found it will raise a AssemblyResolve event where we will search for the
                    // assembly.
                    assembly = Assembly.LoadFrom(path);
                }
                catch (Exception e)
                {
                    throw new ApplicationException(String.Format("Unable to load content compiler assembly file '{0}'. {1}", path, e.ToString()), e);
                }

                Type[] types;

                // We won't get dependency errors until we actually try to reflect on all the types in the assembly
                try
                {
                    types = assembly.GetTypes();
                }
                catch (ReflectionTypeLoadException e)
                {
                    string message = String.Format("Unable to reflect on assembly '{0}'", path);

                    // There is one entry in the exceptions array for each null in the types array,
                    // and they correspond positionally.
                    foreach (Exception ex in e.LoaderExceptions)
                        message += Environment.NewLine + "   " + ex.Message;

                    // Not being able to reflect on classes in the test assembly is a critical error
                    throw new ApplicationException(message, e);
                }

                // Go through all the types in the test assembly and find all the
                // compiler classes, those that inherit from IContentCompiler.
                foreach (var type in types)
                {
                    Type interfaceType = type.GetInterface(typeof(IContentCompiler).ToString());

                    if (interfaceType != null)
                    {
                        CompilerClass compilerClass = new CompilerClass(assembly, type);

                        compilerClasses.Add(compilerClass);
                    }
                }
            }

            return compilerClasses;
        }
        public override PropertyGroup[] GetPropertyGroups()
        {
            PropertyGroup group = new PropertyGroup("GeneralSettings",TranslatablePluginController.GetLanguageResourceValue("fragment_propertygroup_general"), 0);

            Property headerTitle = new Property("headerTitle",
                TranslatablePluginController.GetLanguageResourceValue("fragment_property_title"), PropertyType.String, 0, "${resource:default_property_title}") 
                                            {ControlType = typeof (ContentFragmentTokenStringControl)};

            group.Properties.Add(headerTitle);

            PropertyGroup defaultContent = new PropertyGroup("DefaultContent", TranslatablePluginController.GetLanguageResourceValue("fragment_propertygroup_defaultContent"), 0);

        	Property property = new Property("default_content",TranslatablePluginController.GetLanguageResourceValue(
        	                                 	"fragment_property_content"), PropertyType.Html, 1, ""){ControlType = typeof (HtmlEditorStringControl)};

        	property.Attributes["EnableHtmlScrubbing"] = "false";
            property.Attributes["width"] = "100%";
            property.Attributes["height"] = "300px";
            property.Attributes["enablehtmlediting"] = "true";
            property.Attributes["ContentTypeId"] = InlineContentPart.InlineContentContentTypeId.ToString();
            defaultContent.Properties.Add(property);


            PropertyGroup anoymousContent = new PropertyGroup("AnonymousContent", TranslatablePluginController.GetLanguageResourceValue("fragment_propertygroup_anonymousContent"), 0);

            property = new Property("anonymous_content", TranslatablePluginController.GetLanguageResourceValue(
                                    "fragment_property_content"), PropertyType.Html, 1, "") { ControlType = typeof(HtmlEditorStringControl) };

            property.Attributes["EnableHtmlScrubbing"] = "false";
            property.Attributes["width"] = "100%";
            property.Attributes["height"] = "300px";
            property.Attributes["enablehtmlediting"] = "true";
            property.Attributes["ContentTypeId"] = InlineContentPart.InlineContentContentTypeId.ToString();
            anoymousContent.Properties.Add(property);


            property = new Property("inlinecontenttype",
                TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_type"),
                PropertyType.String, 2, "Contextual")
            {
                DescriptionResourceName ="fragment_property_inlinecontent_type_description"
            };

            property.SelectableValues.Add(new PropertyValue("Contextual", TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_contextual"), (int)ContextMode.Context));
            property.SelectableValues.Add(new PropertyValue("GroupContextual", TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_groupcontextual"), (int)ContextMode.GroupContext));
            property.SelectableValues.Add(new PropertyValue("ByName", TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_byname"), (int)ContextMode.Name));

            group.Properties.Add(property);

            property = new Property("dynamicname", TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_dynamicname"), PropertyType.Bool, 3, bool.FalseString)
            {
                DescriptionResourceName ="fragment_property_inlinecontent_dynamicname_description"
            };

            group.Properties.Add(property);

            property = new Property("inlinecontentname", TranslatablePluginController.GetLanguageResourceValue("fragment_property_inlinecontent_name"), PropertyType.String, 4, string.Empty);
            group.Properties.Add(property);

            return new[] { group , defaultContent , anoymousContent };
        }
        private void SafeExecute()
        {
            if (!NoLogo)
                Console.WriteLine(Parser.LogoBanner);

            if (!runningFromCommandLine)
            {
                Parser.GetTargetArguments(this);
                Output.Message(MessageImportance.Normal, Parser.CommandName + Parser.Arguments);
            }

            if (ShowHelp)
            {
                Console.WriteLine(Parser.Usage);
                return;
            }

            if (String.IsNullOrEmpty(ContentPath))
            {
                Output.Error("A .content file must be specified");
                return;
            }

            this.ContentPath = this.ContentPath.MakeFullPath();

            if (!File.Exists(this.ContentPath))
            {
                Output.Error("Content file '{0}' does not exist", this.ContentPath);
                return;
            }

            // Initialize properties from the environment and command line
            PropertyGroup globalProps = new PropertyGroup();

            globalProps.AddFromEnvironment();
            globalProps.AddWellKnownProperties(
                new ParsedPath(Assembly.GetExecutingAssembly().Location, PathType.File).VolumeAndDirectory,
                ContentPath.VolumeAndDirectory);
            globalProps.AddFromPropertyString(this.Properties);

            BuildContext buildContext = new BuildContext(this.Output, this.ContentPath);

            ContentFileV2 contentFile = null;

            try
            {
                contentFile = ContentFileReaderV2.ReadFile(this.ContentPath);
            }
            catch (Exception e)
            {
                throw new ContentFileException(this.ContentPath, (int)e.Data["LineNumber"], "Problem reading content file", e);
            }

            Output.Message(MessageImportance.Low, "Read content file '{0}'", this.ContentPath);

            ItemGroup globalItems = new ItemGroup();

            globalItems.ExpandAndAddFromList(contentFile.Items, globalProps);

            List<CompilerClass> compilerClasses = LoadCompilerClasses(globalItems, globalProps);

            this.NewestAssemblyWriteTime = FindNewestAssemblyWriteTime(compilerClasses);
            this.ContentPathWriteTime = File.GetLastWriteTime(this.ContentPath);

            List<BuildTarget> BuildTargets = PrepareBuildTargets(contentFile.Targets, globalItems, globalProps);

            foreach (var buildTarget in BuildTargets)
            {
                bool compilerFound = false;

                foreach (var compilerClass in compilerClasses)
                {
                    if (buildTarget.InputExtensions.SequenceEqual(compilerClass.InputExtensions) &&
                        buildTarget.OutputExtensions.SequenceEqual(compilerClass.OutputExtensions))
                    {
                        compilerFound = true;

                        string msg = String.Format("Building target '{0}' with '{1}' compiler", buildTarget.Name, compilerClass.Name);

                        foreach (var input in buildTarget.InputFiles)
                        {
                            msg += Environment.NewLine + "\t" + input;
                        }

                        msg += Environment.NewLine + "\t->";

                        foreach (var output in buildTarget.OutputFiles)
                        {
                            msg += Environment.NewLine + "\t" + output;
                        }

                        Output.Message(MessageImportance.Normal, msg);

                        if (TestMode)
                            continue;

                        compilerClass.ContextProperty.SetValue(compilerClass.Instance, buildContext, null);
                        compilerClass.TargetProperty.SetValue(compilerClass.Instance, buildTarget, null);

                        try
                        {
                            compilerClass.CompileMethod.Invoke(compilerClass.Instance, null);
                        }
                        catch (TargetInvocationException e)
                        {
                            ContentFileException contentEx = e.InnerException as ContentFileException;

                            if (contentEx != null)
                            {
                                contentEx.EnsureFileNameAndLineNumber(buildContext.ContentFile, buildTarget.LineNumber);
                                throw contentEx;
                            }
                            else
                            {
                                throw new ContentFileException(
                                    this.ContentPath, buildTarget.LineNumber, "Unable to compile target '{0}'".CultureFormat(buildTarget.Name), e.InnerException);
                            }
                        }

                        // Ensure that the output files were generated
                        foreach (var outputFile in buildTarget.OutputFiles)
                        {
                            if (!File.Exists(outputFile))
                            {
                                throw new ContentFileException(this.ContentPath, buildTarget.LineNumber,
                                    "Output file '{0}' was not generated".CultureFormat(outputFile));
                           	}
                        }
                    }
                }

                if (!compilerFound)
                    Output.Warning("No compiler found for target '{0}' for extensions '{1}' -> '{2}'",
                   		buildTarget.Name,
                        String.Join(Path.PathSeparator.ToString(), buildTarget.InputExtensions),
                        String.Join(Path.PathSeparator.ToString(), buildTarget.OutputExtensions));
            }

            Output.Message(MessageImportance.Normal, "Done");
        }
Esempio n. 37
0
        public ToolFlags CopyAndBuildFlags(BSPBuilder bsp, List <string> projectFiles, string subdir, ref PropertyList configurableProperties)
        {
            List <ParsedCondition> conditions    = null;
            List <string>          allConditions = new List <string>();

            if (SimpleFileConditions != null)
            {
                allConditions.AddRange(SimpleFileConditions);
            }
            if (SmartFileConditions != null)
            {
                foreach (var str in SmartFileConditions)
                {
                    int      idx    = str.IndexOf('|');
                    string   name   = str.Substring(0, idx);
                    string   id     = "com.sysprogs.bspoptions." + name.Replace(' ', '_');
                    string[] values = str.Substring(idx + 1).Split(';');

                    PropertyEntry entry;
                    if (values.Length == 1)
                    {
                        var    val = values[0];
                        string regex, value;
                        idx = val.IndexOf("=>");
                        if (idx == -1)
                        {
                            regex = val;
                            value = "1";
                        }
                        else
                        {
                            regex = val.Substring(0, idx);
                            value = val.Substring(idx + 2);
                        }

                        allConditions.Add($"{regex}: $${id}$$ == {value}");

                        entry = new PropertyEntry.Boolean {
                            ValueForTrue = value, Name = name, UniqueID = id, DefaultValue = true
                        };
                    }
                    else
                    {
                        List <PropertyEntry.Enumerated.Suggestion> suggestions = new List <PropertyEntry.Enumerated.Suggestion>();

                        foreach (var val in values)
                        {
                            idx = val.IndexOf("=>");
                            string regex = val.Substring(0, idx);
                            string value = val.Substring(idx + 2);
                            allConditions.Add($"{regex}: $${id}$$ == {value}");
                            suggestions.Add(new PropertyEntry.Enumerated.Suggestion {
                                InternalValue = value
                            });
                        }

                        entry = new PropertyEntry.Enumerated {
                            Name = name, UniqueID = id, SuggestionList = suggestions.ToArray()
                        };
                    }

                    if (configurableProperties?.PropertyGroups == null)
                    {
                        configurableProperties = new PropertyList {
                            PropertyGroups = new List <PropertyGroup>()
                        }
                    }
                    ;

                    var grp = configurableProperties.PropertyGroups.FirstOrDefault(g => g.Name == null && g.UniqueID == null);
                    if (grp == null)
                    {
                        configurableProperties.PropertyGroups.Insert(0, grp = new PropertyGroup());
                    }

                    grp.Properties.Add(entry);
                }
            }

            if (allConditions.Count > 0)
            {
                conditions = new List <ParsedCondition>();
                foreach (var cond in allConditions)
                {
                    int idx = cond.IndexOf(':');
                    if (idx == -1)
                    {
                        throw new Exception("Invalid simple condition format");
                    }

                    Regex     rgFile     = new Regex(cond.Substring(0, idx), RegexOptions.IgnoreCase);
                    string    rawCond    = cond.Substring(idx + 1).Trim();
                    Condition parsedCond = ParseCondition(rawCond);
                    conditions.Add(new ParsedCondition {
                        Regex = rgFile, Condition = parsedCond
                    });
                }
            }

            string expandedSourceFolder = SourceFolder;

            bsp.ExpandVariables(ref expandedSourceFolder);

            if (TargetFolder == null)
            {
                TargetFolder = Path.GetFileName(expandedSourceFolder);
            }
            TargetFolder = TargetFolder.Replace('\\', '/');
            if (subdir == null)
            {
                subdir = "";
            }
            string absTarget = Path.Combine(bsp.BSPRoot, subdir, TargetFolder);

            Directory.CreateDirectory(absTarget);

            string folderInsideBSPPrefix = TargetFolder;

            if (!string.IsNullOrEmpty(subdir))
            {
                folderInsideBSPPrefix = subdir + "/" + TargetFolder;
            }
            folderInsideBSPPrefix = folderInsideBSPPrefix.Replace('\\', '/');
            if (folderInsideBSPPrefix == "/")
            {
                folderInsideBSPPrefix = "";
            }
            else if (folderInsideBSPPrefix != "" && !folderInsideBSPPrefix.StartsWith("/"))
            {
                folderInsideBSPPrefix = "/" + folderInsideBSPPrefix;
            }

            var copyMasks         = new CopyFilters(FilesToCopy);
            var autoIncludes      = new CopyFilters(AutoIncludeMask);
            var potentialSymlinks = new CopyFilters(SymlinkResolutionMask);
            var projectContents   = new CopyFilters(ProjectInclusionMask);

            var filesToCopy = Directory.GetFiles(expandedSourceFolder, "*", SearchOption.AllDirectories)
                              .Where(f => !bsp.SkipHiddenFiles || (File.GetAttributes(f) & FileAttributes.Hidden) != FileAttributes.Hidden)
                              .Select(f => f.Substring(expandedSourceFolder.Length + 1))
                              .Where(f => copyMasks.IsMatch(f))
                              .ToArray();

            foreach (var dir in filesToCopy.Select(f => Path.Combine(absTarget, Path.GetDirectoryName(f))).Distinct())
            {
                Directory.CreateDirectory(dir);
            }

            List <IRenameRule> rules = new List <IRenameRule>();

            foreach (var r in (RenameRules ?? "").Split(';').Select(s => s.Trim()).Where(s => s != ""))
            {
                int idx = r.IndexOf("=>");
                rules.Add(new RenameRule {
                    OldName = r.Substring(0, idx), NewName = r.Substring(idx + 2)
                });
            }
            foreach (var r in (AdvancedRenameRules ?? "").Split(';').Where(s => s != ""))
            {
                int idx = r.IndexOf("=>");
                rules.Add(new AdvancedRenamingRule {
                    OldName = new Regex(r.Substring(0, idx), RegexOptions.IgnoreCase), NewNameFormat = r.Substring(idx + 2)
                });
            }

            var includeDirs = filesToCopy.Where(f => autoIncludes.IsMatch(f)).Select(f => Path.GetDirectoryName(f).Replace('\\', '/')).Distinct().Select(d => "$$SYS:BSP_ROOT$$" + folderInsideBSPPrefix + (string.IsNullOrEmpty(d) ? "" : ("/" + d))).ToList();

            foreach (var f in filesToCopy)
            {
                string renamedRelativePath = f;
                string pathInsidePackage   = Path.Combine(subdir, TargetFolder, f);
                if (pathInsidePackage.Length > 170)
                {
                    if (!bsp.OnFilePathTooLong(pathInsidePackage))
                    {
                        continue;
                    }
                }

                string targetFile = Path.Combine(absTarget, f);
                string newName    = rules?.FirstOrDefault(r => r.Matches(f))?.Apply(targetFile);

                if (newName == null)
                {
                    if (bsp.RenamedFileTable.TryGetValue(targetFile, out newName) || bsp.RenamedFileTable.TryGetValue(targetFile.Replace('/', '\\'), out newName))
                    {
                    }
                }

                if (newName != null)
                {
                    var oldTargetFile = targetFile;
                    targetFile          = Path.Combine(Path.GetDirectoryName(targetFile), newName);
                    renamedRelativePath = Path.Combine(Path.GetDirectoryName(renamedRelativePath), newName);
                    bsp.RenamedFileTable[oldTargetFile] = newName;
                }

                if (AlreadyCopied)
                {
                    if (!File.Exists(targetFile))
                    {
                        throw new Exception(targetFile + " required by a copy job marked as 'Already Copied' does not exist");
                    }
                }
                else
                {
                    bool resolved      = false;
                    var  absSourcePath = Path.Combine(expandedSourceFolder, f);
                    if (potentialSymlinks.IsMatch(f))
                    {
                        for (; ;)
                        {
                            var contents = File.ReadAllLines(absSourcePath);
                            if (contents.Length == 1 && File.Exists(Path.Combine(Path.GetDirectoryName(absSourcePath), contents[0])))
                            {
                                absSourcePath = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(absSourcePath), contents[0]));
                            }
                            else
                            {
                                break;
                            }
                        }
                    }

                    if (!resolved)
                    {
                        File.Copy(absSourcePath, targetFile, true);
                    }
                }

                File.SetAttributes(targetFile, File.GetAttributes(targetFile) & ~FileAttributes.ReadOnly);
                string encodedPath = "$$SYS:BSP_ROOT$$" + folderInsideBSPPrefix + "/" + renamedRelativePath.Replace('\\', '/');

                if (projectContents.IsMatch(f))
                {
                    projectFiles.Add(encodedPath.Replace('\\', '/'));
                }

                if (conditions != null)
                {
                    foreach (var cond in conditions)
                    {
                        if (cond.Regex.IsMatch(f))
                        {
                            bsp.MatchedFileConditions.Add(new FileCondition {
                                ConditionToInclude = cond.Condition, FilePath = encodedPath
                            });
                            cond.UseCount++;
                            break;
                        }
                    }
                }
            }

            if (AdditionalProjectFiles != null)
            {
                foreach (var spec in AdditionalProjectFiles.Split(';'))
                {
                    string encodedPath = "$$SYS:BSP_ROOT$$" + folderInsideBSPPrefix + "/" + spec;
                    projectFiles.Add(encodedPath);
                }
            }

            var unusedConditions = conditions?.Where(c => c.UseCount == 0)?.ToArray();

            if ((unusedConditions?.Length ?? 0) != 0)
            {
                throw new Exception(string.Format("Found {0} unused conditions. Please recheck your rules.", unusedConditions.Length));
            }

            if (Patches != null)
            {
                foreach (var p in Patches)
                {
                    foreach (var fn in p.FilePath.Split(';'))
                    {
                        List <string> allLines = File.ReadAllLines(Path.Combine(absTarget, fn)).ToList();
                        p.Apply(allLines);

                        string targetPath = p.TargetPath;
                        if (targetPath == null)
                        {
                            targetPath = fn;
                        }
                        Directory.CreateDirectory(Path.GetDirectoryName(Path.Combine(absTarget, targetPath)));
                        File.WriteAllLines(Path.Combine(absTarget, targetPath), allLines);
                    }
                }
            }

            if (GuardedFiles != null)
            {
                foreach (var gf in GuardedFiles)
                {
                    int    idx    = gf.IndexOf("=>");
                    Regex  rgFile = new Regex(gf.Substring(0, idx));
                    string macro  = gf.Substring(idx + 2);
                    var    fn     = Path.Combine(absTarget, filesToCopy.First(f => rgFile.IsMatch(f)));

                    List <string> lines = new List <string>(File.ReadAllLines(fn));
                    int           i     = 0;
                    //1. Find first #include
                    for (i = 0; i < lines.Count; i++)
                    {
                        if (lines[i].Trim().StartsWith("#include"))
                        {
                            break;
                        }
                    }

                    //2. Find first non-preprocessor line
                    for (; i < lines.Count; i++)
                    {
                        if (!string.IsNullOrWhiteSpace(lines[i]) && !lines[i].Trim().StartsWith("#include"))
                        {
                            break;
                        }
                    }

                    if (i == lines.Count)
                    {
                        throw new Exception("Cannot find a place to insert guard in " + fn);
                    }

                    lines.Insert(i, string.Format("#if defined({0}) && {0}", macro));
                    lines.Add("#endif //" + macro);
                    File.WriteAllLines(fn, lines);
                }
            }

            if (AdditionalIncludeDirs != null)
            {
                includeDirs.AddRange(AdditionalIncludeDirs.Split(';').Select(d => MapIncludeDir(absTarget, d)));
            }

            return(new ToolFlags
            {
                PreprocessorMacros = (PreprocessorMacros == null) ? null : PreprocessorMacros.Split(';'),
                IncludeDirectories = includeDirs.ToArray()
            });
        }
Esempio n. 38
0
        /// <summary>
        /// A helper method that will create a basic/generic member for use with a generic membership provider
        /// </summary>
        /// <returns></returns>
        internal static IMember CreateGenericMembershipProviderMember(string name, string email, string username, string password)
        {
            var identity = int.MaxValue;

            var memType = new MemberType(-1);
            var propGroup = new PropertyGroup
                {
                    Name = "Membership",
                    Id = --identity
                };
            propGroup.PropertyTypes.Add(new PropertyType(Constants.PropertyEditors.TextboxAlias, DataTypeDatabaseType.Ntext)
                {
                    Alias = Constants.Conventions.Member.Comments,
                    Name = Constants.Conventions.Member.CommentsLabel,
                    SortOrder = 0,
                    Id = --identity
                });
            propGroup.PropertyTypes.Add(new PropertyType(Constants.PropertyEditors.TrueFalseAlias, DataTypeDatabaseType.Integer)
                {
                    Alias = Constants.Conventions.Member.IsApproved,
                    Name = Constants.Conventions.Member.IsApprovedLabel,
                    SortOrder = 3,
                    Id = --identity
                });
            propGroup.PropertyTypes.Add(new PropertyType(Constants.PropertyEditors.TrueFalseAlias, DataTypeDatabaseType.Integer)
                {
                    Alias = Constants.Conventions.Member.IsLockedOut,
                    Name = Constants.Conventions.Member.IsLockedOutLabel,
                    SortOrder = 4,
                    Id = --identity
                });
            propGroup.PropertyTypes.Add(new PropertyType(Constants.PropertyEditors.NoEditAlias, DataTypeDatabaseType.Date)
                {
                    Alias = Constants.Conventions.Member.LastLockoutDate,
                    Name = Constants.Conventions.Member.LastLockoutDateLabel,
                    SortOrder = 5,
                    Id = --identity
                });
            propGroup.PropertyTypes.Add(new PropertyType(Constants.PropertyEditors.NoEditAlias, DataTypeDatabaseType.Date)
                {
                    Alias = Constants.Conventions.Member.LastLoginDate,
                    Name = Constants.Conventions.Member.LastLoginDateLabel,
                    SortOrder = 6,
                    Id = --identity
                });
            propGroup.PropertyTypes.Add(new PropertyType(Constants.PropertyEditors.NoEditAlias, DataTypeDatabaseType.Date)
                {
                    Alias = Constants.Conventions.Member.LastPasswordChangeDate,
                    Name = Constants.Conventions.Member.LastPasswordChangeDateLabel,
                    SortOrder = 7,
                    Id = --identity
                });

            memType.PropertyGroups.Add(propGroup);

            return new Member(name, email, username, password, -1, memType);
        }
Esempio n. 39
0
        public IMemberType AddDialogueMemberType()
        {
            #region DataType Ids
            //-49	    Umbraco.TrueFalse
            //-51	    Umbraco.Integer
            //-87	    Umbraco.TinyMCEv3
            //-88	    Umbraco.Textbox
            //-89	    Umbraco.TextboxMultiple
            //-90	    Umbraco.UploadField
            //-92	    Umbraco.NoEdit
            //-36	    Umbraco.DateTime
            //-37	    Umbraco.ColorPickerAlias
            //-38	    Umbraco.FolderBrowser
            //-39	    Umbraco.DropDownMultiple
            //-40	    Umbraco.RadioButtonList
            //-41	    Umbraco.Date
            //-42	    Umbraco.DropDown
            //-43	    Umbraco.CheckBoxList
            //1034	    Umbraco.ContentPickerAlias
            //1035	    Umbraco.MediaPicker
            //1036	    Umbraco.MemberPicker
            //1040	    Umbraco.RelatedLinks
            //1041	    Umbraco.Tags
            //1045	    Umbraco.MultipleMediaPicker
            //1077	    Apt.PartialPicker
            //1089	    Umbraco.ImageCropper
            //1092	    Umbraco.TinyMCEv3
            //1103	    Our.Umbraco.FilePicker
            //1104	    Umbraco.MemberGroupPicker
            //1105	    Apt.CssPicker
            //1128	    Dialogue.ThemePicker
            //1132	    Dialogue.Permissions
            //1147	    Umbraco.MultipleTextstring
            #endregion

            var label           = _dataTypeService.GetDataTypeDefinitionById(-92);
            var upload          = _dataTypeService.GetDataTypeDefinitionById(-90);
            var textstring      = _dataTypeService.GetDataTypeDefinitionById(-88);
            var textboxMultiple = _dataTypeService.GetDataTypeDefinitionById(-89);
            var truefalse       = _dataTypeService.GetDataTypeDefinitionById(-49);
            var numeric         = _dataTypeService.GetDataTypeDefinitionById(-51);
            var datetime        = _dataTypeService.GetDataTypeDefinitionById(-36);

            // Profile, Settings, Social Tokens

            // Create the member Type
            var memType = new MemberType(-1)
            {
                Alias = DialogueConfiguration.Instance.MemberTypeAlias,
                Name  = "Dialogue Member"
            };

            // Create the Profile group/tab
            var profileGroup = new PropertyGroup
            {
                Name = "Profile",
            };
            profileGroup.PropertyTypes.Add(new PropertyType(label)
            {
                Alias       = "email",
                Name        = "Email",
                SortOrder   = 0,
                Description = "This is a bit rubbish, but it's the only way to get the email from the new member service at the current time"
            });
            profileGroup.PropertyTypes.Add(new PropertyType(upload)
            {
                Alias       = "avatar",
                Name        = "Avatar",
                SortOrder   = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Alias       = "website",
                Name        = "Website",
                SortOrder   = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Alias       = "twitter",
                Name        = "Twitter",
                SortOrder   = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(textboxMultiple)
            {
                Alias       = "signature",
                Name        = "Signature",
                SortOrder   = 0,
                Description = ""
            });
            profileGroup.PropertyTypes.Add(new PropertyType(datetime)
            {
                Alias       = "lastActiveDate",
                Name        = "Last Active Date",
                SortOrder   = 0,
                Description = ""
            });
            memType.PropertyGroups.Add(profileGroup);

            // Create the Settings group/tab
            var settingsGroup = new PropertyGroup
            {
                Name = "Settings",
            };
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias       = "canEditOtherMembers",
                Name        = "Can Edit Other Members",
                SortOrder   = 0,
                Description = "Enable this and the user can edit other members posts, their profiles and ban members (Usually use in conjunction with moderate permissions)."
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias       = "disableEmailNotifications",
                Name        = "Disable Email Notifications",
                SortOrder   = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias       = "disablePosting",
                Name        = "Disable Posting",
                SortOrder   = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias       = "disablePrivateMessages",
                Name        = "Disable Private Messages",
                SortOrder   = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(truefalse)
            {
                Alias       = "disableFileUploads",
                Name        = "Disable File Uploads",
                SortOrder   = 0,
                Description = ""
            });
            settingsGroup.PropertyTypes.Add(new PropertyType(numeric)
            {
                Alias       = "postCount",
                Name        = "Post Count",
                SortOrder   = 0,
                Description = "The users post count. This is kept like this to help reduce SQL queries and improve performance of the forum"
            });
            memType.PropertyGroups.Add(settingsGroup);

            // Create the Settings group/tab
            var socialGroup = new PropertyGroup
            {
                Name = "Social Tokens",
            };
            socialGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Name        = "Facebook Access Token",
                Alias       = "facebookAccessToken",
                SortOrder   = 0,
                Description = ""
            });
            socialGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Name        = "Google Access Token",
                Alias       = "googleAccessToken",
                SortOrder   = 0,
                Description = ""
            });
            socialGroup.PropertyTypes.Add(new PropertyType(textstring)
            {
                Name        = "Microsoft Access Token",
                Alias       = "microsoftAccessToken",
                SortOrder   = 0,
                Description = ""
            });
            memType.PropertyGroups.Add(socialGroup);

            // Add Slug
            memType.AddPropertyType(new PropertyType(textstring)
            {
                Name        = "Slug",
                Alias       = "slug",
                SortOrder   = 0,
                Description = "This is what we use to look up the member in the front end"
            });

            _memberTypeService.Save(memType);

            return(memType);
        }
        private void PatchGroup(ICommonAssembly assembly, IHasMethods viewModelBaseType, ICommonType viewModelType, PropertyGroup group)
        {
            RemoveDefaultField(viewModelType, group.Property.Name);

            var field = group.Field?.MonoCecil ?? CreateField(viewModelType, group.Property);

            GenerateGetMethodBody(viewModelType, group, field);
            GenerateSetMethodBody(assembly, viewModelBaseType, viewModelType, group, field);
        }
Esempio n. 41
0
        public void Ent_PropGroup_Prop_KString_VString_RULToSet()
        {
            EtagairCore core = Common.CreateCoreInMemory();

            // create an entity template to instantiate
            EntityTempl entTemplComputer = core.EditorTempl.CreateEntityTempl("TemplComputer");

            // create the group Core
            PropGroupTempl propGroupTemplCore = core.EditorTempl.CreatePropGroupTempl(entTemplComputer, "Core");

            // create a property template without the value: will be created on the instantiation
            PropTempl propTemplType = core.EditorTempl.CreatePropTempl(entTemplComputer, propGroupTemplCore, "Type", (string)null);

            // On prop type, Add Rule: add property, V=RULE:ToSet, type= string
            PropTemplRuleValueToSet rule = new PropTemplRuleValueToSet();

            rule.ValueType = PropValueType.String;
            core.EditorTempl.AddPropTemplRule(entTemplComputer, propTemplType, rule);

            //====Instantiate
            EntityTemplToInst templToInst = core.ProcessTempl.CreateEntity(entTemplComputer);

            Assert.AreEqual(TemplToInstState.InProgress, templToInst.State, "the state should be InProgress");
            Assert.AreEqual(TemplToInstStep.NeedAction, templToInst.NextStep, "the next step should be NeedAction");

            //---provide an action to the rule (to execute it automatically): Property value set on instantiation
            PropTemplRuleActionValueToSet action = new PropTemplRuleActionValueToSet();

            action.SetRule(rule);
            action.SetValueString("Intel");

            // adds actions to rules and create the entity
            core.ProcessTempl.AddActionsToCreateEntity(templToInst, action);

            Assert.AreEqual(TemplToInstState.InProgress, templToInst.State, "the state should be InProgress");
            Assert.AreEqual(TemplToInstStep.Starts, templToInst.NextStep, "the next step should be NeedAction");

            // create the entity, use action
            core.ProcessTempl.CompleteCreateEntity(templToInst);

            // check that the execution finishes with success
            Assert.AreEqual(TemplToInstState.Success, templToInst.State, "the state should be sucess");
            Assert.AreEqual(TemplToInstStep.Ends, templToInst.NextStep, "the next step should be ends");

            //=====Check the creation

            //----check the prop group: Core
            PropertyBase  propBase  = core.Searcher.FindPropertyByKey(templToInst.Entity, templToInst.Entity.PropertyRoot, "Core", false);
            PropertyGroup propGroup = propBase as PropertyGroup;

            Assert.IsNotNull(propGroup, "the propgroup Core should exists");

            // Check the prop group key
            PropertyKeyString propGroupKey = propGroup.Key as PropertyKeyString;

            Assert.IsNotNull(propGroupKey, "the propgroup key Core should exists");
            Assert.AreEqual("Core", propGroupKey.Key, "the key should be Core");

            //----check the property child: Type=Computer
            propBase = core.Searcher.FindPropertyByKey(templToInst.Entity, propGroup, "Type", false);
            Property prop = propBase as Property;

            Assert.IsNotNull(prop, "the prop child Type should exists");

            // find the prop Intel (inside the group Core) from the root property
            PropertyBase propBaseTypeIntel = core.Searcher.FindPropertyByKey(templToInst.Entity, "Type", true);
            Property     propTypeIntel     = propBaseTypeIntel as Property;

            Assert.IsNotNull(propTypeIntel, "the prop child Type should exists (find from the root)");

            // check the prop key: Type, find the prop from the parent
            PropertyKeyString propKeyString = prop.Key as PropertyKeyString;

            Assert.IsNotNull(propKeyString, "the prop key string Type should exists");
            Assert.AreEqual("Type", propKeyString.Key, "the key should be Type");

            // check the prop value
            //PropertyValueString propValueString = prop.Value as PropertyValueString;
            ValString propValueString = prop.Value as ValString;

            Assert.IsNotNull(propValueString, "the prop key string Type should exists");
            Assert.AreEqual("Intel", propValueString.Value, "the value should be Intel");
        }
Esempio n. 42
0
 /// <summary>
 /// Returns the Property object for the given property group
 /// </summary>
 /// <param name="content"></param>
 /// <param name="propertyGroup"></param>
 /// <returns></returns>
 public static IEnumerable <IProperty> GetPropertiesForGroup(this IContentBase content, PropertyGroup propertyGroup)
 {
     //get the properties for the current tab
     return(content.Properties
            .Where(property => propertyGroup.PropertyTypes is not null && propertyGroup.PropertyTypes
                   .Select(propertyType => propertyType.Id)
                   .Contains(property.PropertyTypeId)));
 }
        private List<BuildTarget> PrepareBuildTargets(List<ContentFileV2.Target> rawTargets, ItemGroup globalItems, PropertyGroup globalProps)
        {
            List<BuildTarget> buildTargets = new List<BuildTarget>();

            foreach (var rawTarget in rawTargets)
            {
                try
                {
                    PropertyGroup targetProps = new PropertyGroup(globalProps);

                    targetProps.Set("TargetName", rawTarget.Name);

                    if (rawTarget.Properties != null)
                        targetProps.ExpandAndAddFromList(rawTarget.Properties, targetProps);

                    ItemGroup targetItems = new ItemGroup(globalItems);

                    ParsedPathList inputFiles = new ParsedPathList();
                    string[] list = rawTarget.Inputs.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var rawInputFile in list)
                    {
                        ParsedPath pathSpec = null;
                        string s = targetProps.ReplaceVariables(rawInputFile);

                        try
                        {
                            pathSpec = new ParsedPath(s, PathType.File).MakeFullPath();
                        }
                        catch (Exception e)
                        {
                            throw new ContentFileException("Bad path '{0}'".CultureFormat(s), e);
                        }

                        if (pathSpec.HasWildcards)
                        {
                            if (!Directory.Exists(pathSpec.VolumeAndDirectory))
                            {
                                throw new ContentFileException("Directory '{0}' does not exist".CultureFormat(pathSpec.VolumeAndDirectory));
                            }

                            IList<ParsedPath> files = DirectoryUtility.GetFiles(pathSpec, SearchScope.DirectoryOnly);

                            if (files.Count == 0)
                            {
                                throw new ContentFileException("Wildcard input refers to no files after expansion");
                            }

                            inputFiles = new ParsedPathList(inputFiles.Concat(files));
                        }
                        else
                        {
                            if (!File.Exists(pathSpec))
                            {
                                throw new ContentFileException("Input file '{0}' does not exist".CultureFormat(pathSpec));
                            }

                            inputFiles.Add(pathSpec);
                        }
                    }

                    ParsedPathList outputFiles = new ParsedPathList();

                    list = rawTarget.Outputs.Split(';');

                    foreach (var rawOutputFile in list)
                    {
                        string s = targetProps.ReplaceVariables(rawOutputFile);

                        try
                        {
                            ParsedPath outputFile = new ParsedPath(s, PathType.File).MakeFullPath();

                            outputFiles.Add(outputFile);
                        }
                        catch (Exception e)
                        {
                            throw new ContentFileException("Bad path '{0}'".CultureFormat(s), e);
                        }
                    }

                    targetItems.Set("TargetInputs", inputFiles);
                    targetItems.Set("TargetOutputs", outputFiles);

                    bool needsRebuild = IsCompileRequired(inputFiles, outputFiles);

                    if (!needsRebuild)
                        continue;

                    buildTargets.Add(new BuildTarget(rawTarget.LineNumber, targetProps, targetItems));
                }
                catch (Exception e)
                {
                    throw new ContentFileException(this.ContentPath, rawTarget.LineNumber, "Error preparing targets", e);
                }
            }

            return buildTargets;
        }
        public IEnumerable <PropertyGroup> BuildEntity(IEnumerable <PropertyTypeGroupDto> groupDtos)
        {
            // groupDtos contains all the groups, those that are defined on the current
            // content type, and those that are inherited from composition content types
            var propertyGroups = new PropertyGroupCollection();

            foreach (var groupDto in groupDtos)
            {
                var group = new PropertyGroup();

                try
                {
                    group.DisableChangeTracking();

                    // if the group is defined on the current content type,
                    // assign its identifier, else it will be zero
                    if (groupDto.ContentTypeNodeId == _contentTypeId)
                    {
                        group.Id = groupDto.Id;
                    }

                    group.Name          = groupDto.Text;
                    group.SortOrder     = groupDto.SortOrder;
                    group.PropertyTypes = new PropertyTypeCollection();
                    group.Key           = groupDto.UniqueId;

                    //Because we are likely to have a group with no PropertyTypes we need to ensure that these are excluded
                    var typeDtos = groupDto.PropertyTypeDtos.Where(x => x.Id > 0);
                    foreach (var typeDto in typeDtos)
                    {
                        var tempGroupDto = groupDto;
                        var propertyType = _propertyTypeCtor(typeDto.DataTypeDto.PropertyEditorAlias,
                                                             typeDto.DataTypeDto.DbType.EnumParse <DataTypeDatabaseType>(true),
                                                             typeDto.Alias);

                        try
                        {
                            propertyType.DisableChangeTracking();

                            propertyType.Alias = typeDto.Alias;
                            propertyType.DataTypeDefinitionId = typeDto.DataTypeId;
                            propertyType.Description          = typeDto.Description;
                            propertyType.Id               = typeDto.Id;
                            propertyType.Key              = typeDto.UniqueId;
                            propertyType.Name             = typeDto.Name;
                            propertyType.Mandatory        = typeDto.Mandatory;
                            propertyType.SortOrder        = typeDto.SortOrder;
                            propertyType.ValidationRegExp = typeDto.ValidationRegExp;
                            propertyType.PropertyGroupId  = new Lazy <int>(() => tempGroupDto.Id);
                            propertyType.CreateDate       = _createDate;
                            propertyType.UpdateDate       = _updateDate;

                            //on initial construction we don't want to have dirty properties tracked
                            // http://issues.umbraco.org/issue/U4-1946
                            propertyType.ResetDirtyProperties(false);
                            group.PropertyTypes.Add(propertyType);
                        }
                        finally
                        {
                            propertyType.EnableChangeTracking();
                        }
                    }
                    //on initial construction we don't want to have dirty properties tracked
                    // http://issues.umbraco.org/issue/U4-1946
                    group.ResetDirtyProperties(false);
                    propertyGroups.Add(group);
                }
                finally
                {
                    group.EnableChangeTracking();
                }
            }

            return(propertyGroups);
        }
Esempio n. 45
0
        public PropertyGroup ConstructorInitializesPropertyGroupCorrectly(PropertyGroup group)
        {
            location = new Location(0, group);

            return location.Group;
        }
Esempio n. 46
0
 public Railroad(string name, PropertyGroup railroadGroup) : base(name, railroadGroup, 200, 25)
 {
 }
 public void PropertyGroupParsed(XmlNode node, PropertyGroup group)
 {
 }
Esempio n. 48
0
 protected override void Visit(PropertyGroup group)
 {
     VisitList(group.Members);
 }
Esempio n. 49
0
 public ILocation GetClosest(int spaceNumber, PropertyGroup desiredGroup)
 {
     return propertyList.Values.Where(x => x.Group == desiredGroup)
                                 .OrderBy(y => Math.Abs(y.SpaceNumber - spaceNumber))
                                 .ThenByDescending(x => x.SpaceNumber)
                                 .First();
 }
        public void Can_Deep_Clone()
        {
            var pg = new PropertyGroup(
                new PropertyTypeCollection(new[]
            {
                new PropertyType("TestPropertyEditor", DataTypeDatabaseType.Nvarchar, "test")
                {
                    Id                   = 3,
                    CreateDate           = DateTime.Now,
                    DataTypeDefinitionId = 5,
                    PropertyEditorAlias  = "propTest",
                    Description          = "testing",
                    Key                  = Guid.NewGuid(),
                    Mandatory            = true,
                    Name                 = "Test",
                    PropertyGroupId      = new Lazy <int>(() => 11),
                    SortOrder            = 9,
                    UpdateDate           = DateTime.Now,
                    ValidationRegExp     = "xxxx",
                    DataTypeDatabaseType = DataTypeDatabaseType.Nvarchar
                },
                new PropertyType("TestPropertyEditor", DataTypeDatabaseType.Nvarchar, "test2")
                {
                    Id                   = 4,
                    CreateDate           = DateTime.Now,
                    DataTypeDefinitionId = 6,
                    PropertyEditorAlias  = "propTest",
                    Description          = "testing2",
                    Key                  = Guid.NewGuid(),
                    Mandatory            = true,
                    Name                 = "Test2",
                    PropertyGroupId      = new Lazy <int>(() => 12),
                    SortOrder            = 10,
                    UpdateDate           = DateTime.Now,
                    ValidationRegExp     = "yyyy",
                    DataTypeDatabaseType = DataTypeDatabaseType.Nvarchar
                }
            }))
            {
                Id         = 77,
                CreateDate = DateTime.Now,
                Key        = Guid.NewGuid(),
                Name       = "Group1",
                SortOrder  = 555,
                UpdateDate = DateTime.Now,
                ParentId   = 9
            };

            var clone = (PropertyGroup)pg.DeepClone();

            Assert.AreNotSame(clone, pg);
            Assert.AreEqual(clone, pg);
            Assert.AreEqual(clone.Id, pg.Id);
            Assert.AreEqual(clone.CreateDate, pg.CreateDate);
            Assert.AreEqual(clone.Key, pg.Key);
            Assert.AreEqual(clone.Name, pg.Name);
            Assert.AreEqual(clone.SortOrder, pg.SortOrder);
            Assert.AreEqual(clone.UpdateDate, pg.UpdateDate);
            Assert.AreEqual(clone.ParentId, pg.ParentId);
            Assert.AreNotSame(clone.PropertyTypes, pg.PropertyTypes);
            Assert.AreEqual(clone.PropertyTypes, pg.PropertyTypes);
            Assert.AreEqual(clone.PropertyTypes.Count, pg.PropertyTypes.Count);
            for (var i = 0; i < pg.PropertyTypes.Count; i++)
            {
                Assert.AreNotSame(clone.PropertyTypes[i], pg.PropertyTypes[i]);
                Assert.AreEqual(clone.PropertyTypes[i], pg.PropertyTypes[i]);
            }

            //This double verifies by reflection
            var allProps = clone.GetType().GetProperties();

            foreach (var propertyInfo in allProps)
            {
                Assert.AreEqual(propertyInfo.GetValue(clone, null), propertyInfo.GetValue(pg, null));
            }
        }
        public static Lazy<IContentType> GetContentTypeDefinition(Type modelType)
        {
            //Check for BaseType different from ContentTypeBase
            bool hasParent = modelType.BaseType != null && modelType.BaseType != typeof(ContentTypeBase) && modelType.BaseType != typeof(object);
            var parent = new Lazy<IContentType>();
            if(hasParent)
            {
                var isResolved = _contentTypeCache.ContainsKey(modelType.BaseType.FullName);
                parent = isResolved
                             ? _contentTypeCache[modelType.BaseType.FullName].ContentType
                             : GetContentTypeDefinition(modelType.BaseType);
            }

            var contentTypeAttribute = modelType.FirstAttribute<ContentTypeAttribute>();
            var contentTypeAlias = contentTypeAttribute == null ? modelType.Name.ToUmbracoAlias() : contentTypeAttribute.Alias;
            //Check if ContentType already exists by looking it up by Alias.
            var existing = ApplicationContext.Current.Services.ContentTypeService.GetContentType(contentTypeAlias);
            
            Lazy<IContentType> contentType = contentTypeAttribute == null
                                                 ? PlainPocoConvention(modelType, existing)
                                                 : ContentTypeConvention(contentTypeAttribute, modelType, existing);

            //Check for interfaces that'll be used for ContentTypeComposition
            var mixins = GetAliasesFromTypeInterfaces(modelType);

            var definitions = new List<PropertyDefinition>();
            int order = 0;
            var objProperties = modelType.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly).ToList();
            foreach (var propertyInfo in objProperties)
            {
                var propertyTypeAttribute = propertyInfo.FirstAttribute<PropertyTypeConventionAttribute>();
                var definition = propertyTypeAttribute == null
                                     ? new PropertyDefinition()
                                     : propertyTypeAttribute.GetPropertyConvention();

                //DataTypeDefinition fallback
                if(definition.DataTypeDefinition == null)
                {
                    definition.DataTypeDefinition = Conventions.GetDataTypeDefinitionByAttributeOrType(null, propertyInfo.PropertyType);
                }

                if(string.IsNullOrEmpty(definition.PropertyGroup))
                {
                    definition.PropertyGroup = "Generic Properties";
                }

                //Alias fallback
                if (string.IsNullOrEmpty(definition.Alias))
                {
                    var aliasAttribute = propertyInfo.FirstAttribute<AliasAttribute>();
                    definition.Alias = Conventions.GetPropertyTypeAlias(aliasAttribute, propertyInfo.Name);
                    definition.Name = Conventions.GetPropertyTypeName(aliasAttribute, propertyInfo.Name);
                }

                //Description fallback
                if (string.IsNullOrEmpty(definition.Description))
                {
                    var descriptionAttribute = propertyInfo.FirstAttribute<DescriptionAttribute>();
                    definition.Description = descriptionAttribute != null
                                                 ? descriptionAttribute.Description
                                                 : string.Empty;
                }

                //SortOrder fallback
                if (definition.Order == default(int))
                {
                    var sortOrderAttribute = propertyInfo.FirstAttribute<SortOrderAttribute>();
                    definition.Order = sortOrderAttribute != null ? sortOrderAttribute.Order : order;
                }

                definitions.Add(definition);
                order++;
            }

            //Loop through definitions for PropertyGroups and create those that not already exists
            var groupDefinitions = definitions.DistinctBy(d => d.PropertyGroup);
            foreach (var groupDefinition in groupDefinitions)
            {
                var groupExists = contentType.Value.PropertyGroups.Contains(groupDefinition.PropertyGroup);
                if(groupExists == false)
                {
                    var propertyGroup = new PropertyGroup {Name = groupDefinition.PropertyGroup};
                    contentType.Value.PropertyGroups.Add(propertyGroup);
                }
            }

            //Loop through definitions for PropertyTypes and add them to the correct PropertyGroup
            foreach (var definition in definitions)
            {
                var group = contentType.Value.PropertyGroups.First(x => x.Name == definition.PropertyGroup);
                //Check if a PropertyType with the same alias already exists, as we don't want to override existing ones
                if(group.PropertyTypes.Contains(definition.Alias)) continue;

                var propertyType = new PropertyType(definition.DataTypeDefinition)
                                       {
                                           Mandatory = definition.Mandatory,
                                           ValidationRegExp = definition.ValidationRegExp,
                                           SortOrder = definition.Order,
                                           Alias = definition.Alias,
                                           Name = definition.Name
                                       };

                group.PropertyTypes.Add(propertyType);
            }

            //If current ContentType has a Parent the ParentId should be set and the ContentType added to the composition.
            if(hasParent)
            {
                contentType.Value.SetLazyParentId(new Lazy<int>(() => parent.Value.Id));
                contentType.Value.AddContentType(parent.Value);
            }
            //Add the resolved ContentType to the internal cache
            var field = new DependencyField {ContentType = contentType, Alias = contentType.Value.Alias};
            var dependencies = new List<string>();
            //If current type has a parent (inherited model) we add the alias of that type as a dependency
            if(hasParent)
            {
                dependencies.Add(parent.Value.Alias);
            }
            //Check ContentType for existing 'Allowed ContentTypes'
            if(contentType.Value.AllowedContentTypes.Any())
            {
                dependencies.AddRange(contentType.Value.AllowedContentTypes.Select(allowed => allowed.Alias));
            }
            //Check for interfaces with AliasAttribute and add those as dependencies 
            //NOTE: might also be an idea to check if ContentType has already been created/added to cache that implements the interface.
            if(mixins.Any())
            {
                foreach (var mixin in mixins)
                {
                    if(dependencies.Contains(mixin.Item1)) continue;

                    dependencies.Add(mixin.Item1);
                    var isMixinResolved = _contentTypeCache.ContainsKey(mixin.Item2);

                    Lazy<IContentType> compositionType = null;

                    if (isMixinResolved)
                    {
                        compositionType = _contentTypeCache[mixin.Item2].ContentType;
                    }
                    else
                    {
                        GetContentTypeDefinition(mixin.Item3);
                        compositionType = _contentTypeCache[mixin.Item2].ContentType;
                    }

                    contentType.Value.AddContentType(compositionType.Value);
                }
            }
            field.DependsOn = dependencies.ToArray();
            _contentTypeCache.AddOrUpdate(modelType.FullName, field, (x, y) => field);
            return contentType;
        }
Esempio n. 52
0
        public ConfigurationFileTemplateEx BuildConfigurationFileTemplate(string file, ConfigFileDefinition cf)
        {
            Regex rgIfndef = new Regex("^#ifndef ([^ ]+)");
            Regex rgDefine = new Regex("^#define ([^ ]+)( )([^ ]+)$");

            Regex rgGroup = new Regex("^<h>[ \t]+(.*)");

            List <string> precedingComments = new List <string>();
            List <string> allProperties     = new List <string>();
            string        lastIfndef        = null;

            PropertyList propertyList = new PropertyList {
                PropertyGroups = new List <PropertyGroup>()
            };
            PropertyGroup group = null;

            foreach (var line in File.ReadAllLines(file))
            {
                string previousLineIfndef = lastIfndef;
                lastIfndef = null;
                Match m;
                var   trimmedLine = line.Trim();
                if (trimmedLine == "")
                {
                    continue;
                }

                if (trimmedLine.StartsWith("//"))
                {
                    string comment = trimmedLine.Substring(2).Trim();
                    m = rgGroup.Match(comment);
                    if (m.Success)
                    {
                        if (group != null && group.Properties.Count > 0)
                        {
                            propertyList.PropertyGroups.Add(group);
                        }

                        group = new PropertyGroup {
                            Name = m.Groups[1].Value.Trim()
                        };
                    }
                    else
                    {
                        precedingComments.Add(comment);
                    }
                }
                else if ((m = rgIfndef.Match(trimmedLine)).Success)
                {
                    lastIfndef = m.Groups[1].Value;
                }
                else if ((m = rgDefine.Match(trimmedLine)).Success)
                {
                    if (m.Groups[1].Value == previousLineIfndef)
                    {
                        if (group == null)
                        {
                            group = new PropertyGroup {
                                Name = "Other Properties"
                            }
                        }
                        ;

                        var prop = ParseSingleProperty(m.Groups[1].Value, m.Groups[2].Value, precedingComments);
                        if (prop != null)
                        {
                            group.Properties.Add(prop);
                            allProperties.Add(prop.UniqueID);
                        }
                    }

                    precedingComments.Clear();
                }
                else
                {
                    precedingComments.Clear();
                }
            }

            if (group != null && group.Properties.Count > 0)
            {
                propertyList.PropertyGroups.Add(group);
            }

            return(new ConfigurationFileTemplateEx(new ConfigurationFileTemplate
            {
                PropertyClasses = new ConfigurationFilePropertyClass[]
                {
                    new ConfigurationFilePropertyClass
                    {
                        NormalRegex = new SerializableRegularExpression(rgDefine.ToString()),
                        Template = "#define {0}{1}{2}",
                        Properties = allProperties.ToArray(),
                        NameIndex = 1,
                        IndentIndex = 2,
                        ValueIndex = 3,
                    }
                },
                TargetFileName = Path.GetFileName(file),
                PropertyList = propertyList,
                UserFriendlyName = "nRF5x SDK Configuration",
            }));
        }

        Regex rgMacroDescription = new Regex("<(.)> ([^ ]+)[ ]*-(.*)");
        Regex rgEnumValue        = new Regex("<([0-9]+)=>[ \t]*(.*)");
        /// <summary>
        /// Adds a PropertyType to a specific PropertyGroup
        /// </summary>
        /// <param name="propertyType"><see cref="PropertyType"/> to add</param>
        /// <param name="propertyGroupName">Name of the PropertyGroup to add the PropertyType to</param>
        /// <returns>Returns <c>True</c> if PropertyType was added, otherwise <c>False</c></returns>
        public override bool AddPropertyType(PropertyType propertyType, string propertyGroupName)
        {
            if (PropertyTypeExists(propertyType.Alias) == false)
            {
                if (PropertyGroups.Contains(propertyGroupName))
                {
                    propertyType.PropertyGroupId = new Lazy<int>(() => PropertyGroups[propertyGroupName].Id);
                    PropertyGroups[propertyGroupName].PropertyTypes.Add(propertyType);
                }
                else
                {
                    //If the PropertyGroup doesn't already exist we create a new one 
                    var propertyTypes = new List<PropertyType> { propertyType };
                    var propertyGroup = new PropertyGroup(new PropertyTypeCollection(propertyTypes)) { Name = propertyGroupName, SortOrder = 1 };
                    //and check if its an inherited PropertyGroup, which exists in the composition
                    if (CompositionPropertyGroups.Any(x => x.Name == propertyGroupName))
                    {
                        var parentPropertyGroup = CompositionPropertyGroups.First(x => x.Name == propertyGroupName && x.ParentId.HasValue == false);
                        propertyGroup.SortOrder = parentPropertyGroup.SortOrder;
                        //propertyGroup.ParentId = parentPropertyGroup.Id;
                        propertyGroup.SetLazyParentId(new Lazy<int?>(() => parentPropertyGroup.Id));
                    }

                    PropertyGroups.Add(propertyGroup);
                }

                return true;
            }

            return false;
        }
Esempio n. 54
0
        public IEnumerable <PropertyGroup> BuildEntity(IEnumerable <PropertyTypeGroupDto> dto)
        {
            var propertyGroups = new PropertyGroupCollection();

            foreach (var groupDto in dto)
            {
                var group = new PropertyGroup();
                //Only assign an Id if the PropertyGroup belongs to this ContentType
                if (groupDto.ContentTypeNodeId == _id)
                {
                    group.Id = groupDto.Id;

                    if (groupDto.ParentGroupId.HasValue)
                    {
                        group.ParentId = groupDto.ParentGroupId.Value;
                    }
                }
                else
                {
                    //If the PropertyGroup is inherited, we add a reference to the group as a Parent.
                    group.ParentId = groupDto.Id;
                }

                group.Name          = groupDto.Text;
                group.SortOrder     = groupDto.SortOrder;
                group.PropertyTypes = new PropertyTypeCollection();

                //Because we are likely to have a group with no PropertyTypes we need to ensure that these are excluded
                var typeDtos = groupDto.PropertyTypeDtos.Where(x => x.Id > 0);
                foreach (var typeDto in typeDtos)
                {
                    var tempGroupDto = groupDto;
                    var propertyType = _propertyTypeCtor(typeDto.DataTypeDto.PropertyEditorAlias,
                                                         typeDto.DataTypeDto.DbType.EnumParse <DataTypeDatabaseType>(true),
                                                         typeDto.Alias);

                    propertyType.Alias = typeDto.Alias;
                    propertyType.DataTypeDefinitionId = typeDto.DataTypeId;
                    propertyType.Description          = typeDto.Description;
                    propertyType.Id               = typeDto.Id;
                    propertyType.Key              = typeDto.UniqueId;
                    propertyType.Name             = typeDto.Name;
                    propertyType.Mandatory        = typeDto.Mandatory;
                    propertyType.SortOrder        = typeDto.SortOrder;
                    propertyType.ValidationRegExp = typeDto.ValidationRegExp;
                    propertyType.PropertyGroupId  = new Lazy <int>(() => tempGroupDto.Id);
                    propertyType.CreateDate       = _createDate;
                    propertyType.UpdateDate       = _updateDate;

                    //on initial construction we don't want to have dirty properties tracked
                    // http://issues.umbraco.org/issue/U4-1946
                    propertyType.ResetDirtyProperties(false);
                    group.PropertyTypes.Add(propertyType);
                }
                //on initial construction we don't want to have dirty properties tracked
                // http://issues.umbraco.org/issue/U4-1946
                group.ResetDirtyProperties(false);
                propertyGroups.Add(group);
            }

            return(propertyGroups);
        }
Esempio n. 55
0
        public void Can_Add_New_Property_To_New_PropertyType_In_New_PropertyGroup()
        {
            // Arrange
            var contentType = MockedContentTypes.CreateTextpageContentType();
            var content = MockedContent.CreateTextpageContent(contentType, "Textpage", -1);

            // Act
            var propertyType = new PropertyType(new Guid(), DataTypeDatabaseType.Ntext)
                                   {
                                       Alias = "subtitle",
                                       Name = "Subtitle",
                                       Description = "Optional subtitle",
                                       HelpText = "",
                                       Mandatory = false,
                                       SortOrder = 3,
                                       DataTypeDefinitionId = -88
                                   };
            var propertyGroup = new PropertyGroup {Name = "Test Group", SortOrder = 3};
            propertyGroup.PropertyTypes.Add(propertyType);
            contentType.PropertyGroups.Add(propertyGroup);
            content.Properties.Add(new Property(propertyType){ Value = "Subtitle Test"});

            // Assert
            Assert.That(content.Properties.Count, Is.EqualTo(5));
            Assert.That(content.PropertyTypes.Count(), Is.EqualTo(5));
            Assert.That(content.PropertyGroups.Count(), Is.EqualTo(3));
            Assert.That(content.Properties["subtitle"].Value, Is.EqualTo("Subtitle Test"));
            Assert.That(content.Properties["title"].Value, Is.EqualTo("Textpage textpage"));
        }
 public RentableLocation(int spaceNumber, int rent, int price, PropertyGroup group) : base(spaceNumber, group)
 {
     Rent = rent;
     Price = price;
 }
        protected override PropertyGroup GetRootGroup()
        {
            PropertyGroup group = new PropertyGroup("autouserCleanup", "User Encouragement", 0);
            group.DescriptionText = "Sends an email to try and encourage users to renengage with the site.";

            Property accountAge = new Property("accountAge", "Inactivity Period (months)", PropertyType.Int, 3, "24")
            {
                DescriptionText = "A period after which users start recieving encouragement to re-engage the site"

            };
            group.Properties.Add(accountAge);

            Property accountDeleteAge = new Property("accountDeleteAge", "Encouragement Period (months)", PropertyType.Int, 4, "1")
            {
                DescriptionText = "A period after which the user is then emailed to re-engage with content updates"
            };

            group.Properties.Add(accountDeleteAge);

            Property testButton = new Property("testButton", "Test Settings", PropertyType.Custom, 5, "")
            {
                ControlType = typeof(TestSettingButton)
            };

            group.Properties.Add(testButton);


            return group;
        }
Esempio n. 58
0
 /// <summary>
 /// Display properties and their values to the user.
 /// </summary>
 /// <param name="properties">Properties to be displayed/edited.</param>
 public override void DisplayProperties(PropertyGroup properties)
 {
     throw new NotImplementedException("Single models is not supported in PropertyMultiModelView");
 }