예제 #1
0
        public void Scene_sensor_config_is_generated()
        {
            // Arrange
            var transformer = new MqttSensorConfigTransformer(new DummyConfiguration(), new DeviceTranslator());
            var definition  = new DeviceDefinition
            {
                DeviceId = "Test device",
                Platform = "hubitat",
                Sensors  = new[] { new SensorDefinition {
                                       Type = "scene"
                                   } },
            };
            var expectedConfig = @"
# Test device scene, from hubitat via MQTT
- platform: mqtt
  name: Test device scene
  state_topic: hubitat/Test device/scene
  force_update: true
".Trim();

            // Action
            var result = transformer.TransformConfig(definition);

            // Assert
            Assert.AreEqual(1, result.Keys.Count, "One entity type returned");
            Assert.AreEqual("sensor", result.Keys.First(), "The type of the entity returned is correct");
            Assert.AreEqual(1, result["sensor"].Count, "Only one entity returned");

            var config = result["sensor"].First();

            Assert.AreEqual(expectedConfig, config.Entity, "Config declared as expected");
            Assert.IsEmpty(config.Customization, "Customization declared as expected");
        }
예제 #2
0
        protected virtual int ConvertPosition(DeviceDefinition device, string targetPlaceholder, int insertPosition)
        {
            Assert.ArgumentNotNull(device, "device");
            if (insertPosition == 0 || device.Renderings == null)
            {
                return(0);
            }

            int num = 0;

            for (int i = 0; i < device.Renderings.Count; i++)
            {
                RenderingDefinition item = device.Renderings[i] as RenderingDefinition;
                Assert.IsNotNull(item, "rendering");
                string placeholder = item.Placeholder;
                if (AreEqualPlaceholders(placeholder, targetPlaceholder))
                {
                    num++;
                }
                if (num == insertPosition)
                {
                    return(i + 1);
                }
            }

            return(device.Renderings.Count);
        }
예제 #3
0
        /// <summary>
        /// Generates the Home Assistant entity id for the sensor.
        /// </summary>
        /// <param name="sensorType">Sensor type</param>
        /// <param name="definition">Device definition</param>
        /// <returns>The id of the entity as used in Home Assistant</returns>
        protected string GetSensorEntityId(string sensorType, DeviceDefinition definition)
        {
            var name = GetSensorName(sensorType, definition);
            var id   = $"{GetSensorEntityType(sensorType)}.{FormatAsId(name)}";

            return(id);
        }
예제 #4
0
        protected override void ProcessRenderings(Item item, LayoutDefinition layout, DeviceDefinition device,
            IEnumerable<RenderingDefinition> renderings)
        {
            if (renderings.Any())
            {
                if (!ShouldProcess(item.GetProviderPath(),
                    $"Remove rendering(s) '{renderings.Select(r => r.ItemID.ToString()).Aggregate((seed, curr) => seed + ", " + curr)}' from device {Device.Name}"))
                    return;

                foreach (
                    var instanceRendering in
                        renderings.Select(rendering => device.Renderings.Cast<RenderingDefinition>()
                            .FirstOrDefault(r => r.UniqueId == rendering.UniqueId))
                            .Where(instanceRendering => instanceRendering != null)
                            .Reverse())
                {
                    device.Renderings.Remove(instanceRendering);
                }

                item.Edit(p =>
                {
                    var outputXml = layout.ToXml();
                    Item[LayoutFieldId] = outputXml;
                });
            }
            else
            {
                WriteError(typeof(ObjectNotFoundException), "Cannot find a rendering to remove",
                    ErrorIds.RenderingNotFound, ErrorCategory.ObjectNotFound, null);
            }
        }
예제 #5
0
        protected string GetButtonActivitySensorId(DeviceDefinition definition)
        {
            var name = GetSensorName(SensorType.Button, definition);
            var id   = FormatAsId($"{name} active");

            return(id);
        }
        public void Configured_platform_prefix_is_used()
        {
            // Arrange
            var transformer = new MqttActuatorConfigTransformer(new DummyConfiguration());
            var definition  = new DeviceDefinition
            {
                DeviceId  = "Test switch",
                Platform  = "smartthings",
                Actuators = new[] { new ActuatorDefinition {
                                        Type = "switch"
                                    } },
            };
            var expectedPartialConfig = @"
  state_topic: this/is/a/test/Test switch/switch
  command_topic: this/is/a/test/Test switch/switch
".Trim();

            // Action
            var result = transformer.TransformConfig(definition);

            // Assert
            Assert.AreEqual(1, result.Keys.Count, "One entity type returned");
            Assert.AreEqual("switch", result.Keys.First(), "The type of the entity returned is correct");
            Assert.AreEqual(1, result["switch"].Count, "Only one entity returned");

            var config = result["switch"].First();

            Assert.IsTrue(config.Entity.Contains(expectedPartialConfig), config.Entity, "Config declared as expected");
            Assert.IsEmpty(config.Customization, "Customization declared as expected");
        }
예제 #7
0
        public void CleanRenderings(Item item, string renderingID, string placeholder)
        {
            LayoutField      layoutField      = new LayoutField(item.Fields[FieldIDs.FinalLayoutField]);
            LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
            DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(GetDefaultDeviceItem(item.Database).ID.ToString());

            List <string> placeholders = new List <string>();

            foreach (RenderingDefinition rendering in deviceDefinition.Renderings)
            {
                if (rendering.ItemID.ToLower() == "{C1624533-ED68-41AC-B03C-BFDE4D9B1F2A}".ToLower())
                {
                    placeholders.Add(StringUtil.EnsurePrefix('/', rendering.Placeholder + "/" + placeholder + "_" + new Guid(rendering.UniqueId).ToString("D").ToLower()));
                }
            }
            List <RenderingDefinition> renderingsToRemove = new List <RenderingDefinition>();

            foreach (RenderingDefinition rendering in deviceDefinition.Renderings)
            {
                if (rendering.ItemID.ToLower() == renderingID.ToLower() && placeholders.Contains(rendering.Placeholder))
                {
                    renderingsToRemove.Add(rendering);
                }
            }
            foreach (var rendering in renderingsToRemove)
            {
                deviceDefinition.Renderings.Remove(rendering);
            }
            using (new SecurityDisabler())
            {
                item.Editing.BeginEdit();
                layoutField.Value = layoutDefinition.ToXml();
                item.Editing.EndEdit();
            }
        }
예제 #8
0
        public void Customizations_as_expected()
        {
            // Arrange
            var transformer = new MqttSensorConfigTransformer(new DummyConfiguration(), new DeviceTranslator());
            var definition  = new DeviceDefinition
            {
                DeviceId = "Test device",
                Platform = "hubitat",
                Sensors  = new[] { new SensorDefinition {
                                       Type      = "battery",
                                       Customize = new Dictionary <string, string> {
                                           { "my_custom_attr", "The value" }
                                       },
                                   } },
            };
            var expectedCustomization = $@"
sensor.test_device_battery:
  my_custom_attr: The value
".Trim();

            // Action
            var result = transformer.TransformConfig(definition);

            // Assert
            Assert.AreEqual(1, result.Keys.Count, "One entity type returned");
            Assert.AreEqual("sensor", result.Keys.First(), "The type of the entity returned is correct");
            Assert.AreEqual(1, result["sensor"].Count, "Only one entity returned");

            var config = result["sensor"].First();

            //Assert.IsTrue(config.Entity.Contains(expectedPartialConfig), config.Entity, "Config declared as expected");

            Assert.AreEqual(expectedCustomization, config.Customization, "Customization declared as expected");
        }
예제 #9
0
        public void Contact_sensor_config_is_generated_with_device_class()
        {
            // Arrange
            var transformer = new MqttSensorConfigTransformer(new DummyConfiguration(), new DeviceTranslator());
            var definition  = new DeviceDefinition
            {
                DeviceId = "Test door",
                Platform = "hubitat",
                Sensors  = new[] { new SensorDefinition {
                                       Type = "contact", DeviceClass = "door"
                                   } },
            };
            var expectedConfig = @"
# Test door contact, from hubitat via MQTT
- platform: mqtt
  name: Test door contact
  device_class: door
  state_topic: hubitat/Test door/contact
  payload_on: open
  payload_off: closed
".Trim();

            // Action
            var result = transformer.TransformConfig(definition);

            // Assert
            Assert.AreEqual(1, result.Keys.Count, "One entity type returned");
            Assert.AreEqual("binary_sensor", result.Keys.First(), "The type of the entity returned is correct");
            Assert.AreEqual(1, result["binary_sensor"].Count, "Only one entity returned");

            var config = result["binary_sensor"].First();

            Assert.AreEqual(expectedConfig, config.Entity, "Config declared as expected");
        }
예제 #10
0
        /// <summary>Renders the placeholders.</summary>
        /// <param name="deviceDefinition">The device definition.</param>
        private void RenderPlaceholders(DeviceDefinition deviceDefinition)
        {
            Assert.ArgumentNotNull((object)deviceDefinition, "deviceDefinition");
            ArrayList placeholders = deviceDefinition.Placeholders;

            if (placeholders == null)
            {
                return;
            }
            foreach (PlaceholderDefinition placeholderDefinition in placeholders)
            {
                Item   obj            = (Item)null;
                string metaDataItemId = placeholderDefinition.MetaDataItemId;
                if (!string.IsNullOrEmpty(metaDataItemId))
                {
                    obj = Client.ContentDatabase.GetItem(metaDataItemId);
                }
                XmlControl xmlControl = Resource.GetWebControl("DeviceRendering") as XmlControl;
                Assert.IsNotNull((object)xmlControl, typeof(XmlControl));
                this.Placeholders.Controls.Add((System.Web.UI.Control)xmlControl);
                ID id = ID.Parse(placeholderDefinition.UniqueId);
                if (placeholderDefinition.UniqueId == this.UniqueId)
                {
                    xmlControl["Background"] = (object)"#D0EBF6";
                }
                string str = "ph_" + (object)id.ToShortID();
                xmlControl["ID"]       = (object)str;
                xmlControl["Header"]   = (object)placeholderDefinition.Key;
                xmlControl["Click"]    = (object)("OnPlaceholderClick(\"" + placeholderDefinition.UniqueId + "\")");
                xmlControl["DblClick"] = (object)"device:editplaceholder";
                xmlControl["Icon"]     = obj == null ? (object)"Imaging/24x24/layer_blend.png" : (object)obj.Appearance.Icon;
            }
        }
        public DeviceItem(DeviceDefinition device, ConnectionDefinition connection, AgentDefinition agent)
        {
            Connection                 = new Connection();
            Connection.Address         = connection.Address;
            Connection.Port            = connection.Port;
            Connection.PhysicalAddress = connection.PhysicalAddress;

            Agent               = new Agent();
            Agent.BufferSize    = agent.BufferSize;
            Agent.InstanceId    = agent.InstanceId;
            Agent.Sender        = agent.Sender;
            Agent.TestIndicator = agent.TestIndicator;
            Agent.Timestamp     = agent.Timestamp;
            Agent.Version       = agent.Version;

            Id             = device.Id;
            Uuid           = device.Uuid;
            Name           = device.Name;
            Iso841Class    = device.Iso841Class;
            NativeName     = device.NativeName;
            SampleInterval = device.SampleInterval;
            SampleRate     = device.SampleRate;
            Manufacturer   = device.Manufacturer;
            Model          = device.Model;
            SerialNumber   = device.SerialNumber;
            Description    = device.Description;
        }
예제 #12
0
 protected void AddPlaceholder(ClientPipelineArgs args)
 {
     if (args.IsPostBack)
     {
         if (string.IsNullOrEmpty(args.Result) || !(args.Result != "undefined"))
         {
             return;
         }
         LayoutDefinition layoutDefinition = CustomDeviceEditor.GetLayoutDefinition();
         DeviceDefinition device           = layoutDefinition.GetDevice(this.DeviceID);
         string           placeholderKey;
         Item             dialogResult = SelectPlaceholderSettingsOptions.ParseDialogResult(args.Result, Client.ContentDatabase, out placeholderKey);
         if (dialogResult == null || string.IsNullOrEmpty(placeholderKey))
         {
             return;
         }
         PlaceholderDefinition placeholderDefinition = new PlaceholderDefinition()
         {
             UniqueId       = ID.NewID.ToString(),
             MetaDataItemId = dialogResult.Paths.FullPath,
             Key            = placeholderKey
         };
         device.AddPlaceholder(placeholderDefinition);
         CustomDeviceEditor.SetDefinition(layoutDefinition);
         this.Refresh();
     }
     else
     {
         SheerResponse.ShowModalDialog(new SelectPlaceholderSettingsOptions()
         {
             IsPlaceholderKeyEditable = true
         }.ToUrlString().ToString(), "460px", "460px", string.Empty, true);
         args.WaitForPostBack();
     }
 }
예제 #13
0
        /// <summary>Raises the load event.</summary>
        /// <param name="e">
        /// The <see cref="T:System.EventArgs" /> instance containing the event data.
        /// </param>
        /// <remarks>
        /// This method notifies the server control that it should perform actions common to each HTTP
        /// request for the page it is associated with, such as setting up a database query. At this
        /// stage in the page life cycle, server controls in the hierarchy are created and initialized,
        /// view state is restored, and form controls reflect client-side data. Use the IsPostBack
        /// property to determine whether the page is being loaded in response to a client post back,
        /// or if it is being loaded and accessed for the first time.
        /// </remarks>
        protected override void OnLoad(EventArgs e)
        {
            Assert.ArgumentNotNull((object)e, "e");
            base.OnLoad(e);
            if (Context.ClientPage.IsEvent)
            {
                return;
            }
            this.DeviceID = WebUtil.GetQueryString("de");
            DeviceDefinition device = CustomDeviceEditor.GetLayoutDefinition().GetDevice(this.DeviceID);

            if (device.Layout != null)
            {
                this.Layout.Value = device.Layout;
            }
            this.Personalize.Visible = Policy.IsAllowed("Page Editor/Extended features/Personalization");
#if (!SC72 && !SC75 && !SC80)
            this.Test.Visible = Sitecore.Xdb.Configuration.XdbSettings.Enabled && Policy.IsAllowed("Page Editor/Extended features/Testing");
#else
            this.Test.Visible = Policy.IsAllowed("Page Editor/Extended features/Testing");
#endif

            this.Refresh();
            this.SelectedIndex = -1;
        }
        public KeyedCollection <ConfigEntry> GetButtonActivitySensor(DeviceDefinition device)
        {
            var buttons = _deviceTranslator.TranslateButtonDefinition(device);

            if (!buttons.Any())
            {
                return(new KeyedCollection <ConfigEntry>());
            }


            var lines  = buttons.Select(i => $"is_state('{GetButtonEntityId(i.Item1,i.Item2,device)}', 'on')");
            var entity = $@"
# {device.Name} activity
- platform: template
  sensors:
    {GetButtonActivitySensorId(device)}:
      friendly_name: {device.Name}
      value_template: >
        {{{{ {string.Join($"{Environment.NewLine}        or ", lines)}
        }}}}
".Trim();

            return(new KeyedCollection <ConfigEntry>()
            {
                { EntityType.BinarySensor, new ConfigEntry {
                      Entity = entity, Customization = string.Empty
                  } }
            });
        }
        protected override RenderingDefinition DoReplaceRendering(RenderingDefinition sourceRendering, Item targetRenderingItem, DeviceDefinition device)
        {
            Assert.ArgumentNotNull(sourceRendering, "sourceRendering");
            Assert.ArgumentNotNull(targetRenderingItem, "targetRenderingItem");
            Assert.ArgumentNotNull(device, "device");
            RenderingDefinition definition = new RenderingDefinition
            {
                UniqueId = sourceRendering.UniqueId,
                Cachable = sourceRendering.Cachable,
                Conditions = sourceRendering.Conditions,
                Datasource = sourceRendering.Datasource,
                ItemID = targetRenderingItem.ID.ToString(),
                MultiVariateTest = sourceRendering.MultiVariateTest,
                Parameters = sourceRendering.Parameters,
                Placeholder = sourceRendering.Placeholder,
                Rules = sourceRendering.Rules,
                VaryByData = sourceRendering.VaryByData,
                ClearOnIndexUpdate = sourceRendering.ClearOnIndexUpdate,
                VaryByDevice = sourceRendering.VaryByDevice,
                VaryByLogin = sourceRendering.VaryByLogin,
                VaryByParameters = sourceRendering.VaryByParameters,
                VaryByQueryString = sourceRendering.VaryByQueryString,
                VaryByUser = sourceRendering.VaryByUser
            };

            if (device.Renderings != null)
            {
                int index = device.Renderings.IndexOf(sourceRendering);
                device.Renderings.RemoveAt(index);
                device.Renderings.Insert(index, definition);
            }
            return definition;
        }
예제 #16
0
        public void RemoveDevice(DeviceDefinition device)
        {
            _definitions.Value.Remove(device);
            Definitions.Remove(device);

            _definitions.Save();
        }
예제 #17
0
        public void Multiple_entities_are_generated()
        {
            // Arrange
            var transformer = new MqttSensorConfigTransformer(new DummyConfiguration(), new DeviceTranslator());
            var definition  = new DeviceDefinition
            {
                DeviceId = "Test multisensor",
                Platform = "hubitat",
                Name     = "Test device",
                Sensors  = new[] {
                    new SensorDefinition {
                        Type = "battery"
                    },
                    new SensorDefinition {
                        Type = "motion"
                    },
                    new SensorDefinition {
                        Type = "temperature"
                    },
                },
            };

            // Action
            var result = transformer.TransformConfig(definition);

            // Assert
            Assert.AreEqual(2, result.Keys.Count, "Multiple entity types returned");
            Assert.Contains("sensor", result.Keys, "Expected entity types returned");
            Assert.Contains("binary_sensor", result.Keys, "Expected entity types returned");
            Assert.AreEqual(2, result["sensor"].Count, "Expected number of entities returned");
            Assert.AreEqual(1, result["binary_sensor"].Count, "Expected number of entities returned");
        }
예제 #18
0
        /// <summary>
        /// Generate Home Assistant configuration file entries for the actuators in the provided device.
        /// </summary>
        /// <param name="definition">Device properties</param>
        /// <returns>Configuration file entries covering all actuators defined in the device</returns>
        public KeyedCollection <ConfigEntry> TransformConfig(DeviceDefinition definition)
        {
            if (definition.Actuators == null)
            {
                return(new KeyedCollection <ConfigEntry>());
            }

            if (string.IsNullOrWhiteSpace(definition.DeviceId))
            {
                throw new ValidationException($"{nameof(definition.DeviceId)} requires a value.");
            }

            var configs = new KeyedCollection <ConfigEntry>();

            foreach (var actuator in definition.Actuators)
            {
                var config = FormatActuatorDefinition(new ActuatorConfig
                {
                    Type     = actuator.Type,
                    Name     = definition.Name,
                    Platform = definition.Platform,
                    DeviceId = definition.DeviceId,
                    Icon     = actuator.Icon,
                });
                configs.Add(config.Key, config.Value);
            }

            return(configs);
        }
예제 #19
0
        public void Generated_name_with_apostrophe_is_as_expected()
        {
            // Arrange
            var transformer = new MqttSensorConfigTransformer(new DummyConfiguration(), new DeviceTranslator());
            var definition  = new DeviceDefinition
            {
                DeviceId = "Test user's button",
                Platform = "hubitat",
                Sensors  = new[] { new SensorDefinition {
                                       Type = "button"
                                   } },
            };
            var expectedPartialConfig = $@"
  name: Test users button
".Trim();
            var expectedCustomization = $@"
binary_sensor.test_users_button:
  friendly_name: Test user's button
".Trim();

            // Action
            var result = transformer.TransformConfig(definition);

            // Assert
            Assert.AreEqual(1, result.Keys.Count, "One entity type returned");
            Assert.AreEqual("binary_sensor", result.Keys.First(), "The type of the entity returned is correct");
            Assert.AreEqual(1, result["binary_sensor"].Count, "Only one entity returned");

            var config = result["binary_sensor"].First();

            Assert.IsTrue(config.Entity.Contains(expectedPartialConfig), config.Entity, "Config declared as expected");

            Assert.AreEqual(expectedCustomization, config.Customization, "Customization declared as expected");
        }
예제 #20
0
        /// <summary>
        /// Updates the state of the commands.
        /// </summary>
        private void UpdateRenderingsCommandsState()
        {
            if (this.SelectedIndex < 0)
            {
                this.ChangeButtonsState(true);
                return;
            }
            LayoutDefinition layoutDefinition = DeviceEditorForm.GetLayoutDefinition();
            DeviceDefinition device           = layoutDefinition.GetDevice(this.DeviceID);

            System.Collections.ArrayList renderings = device.Renderings;
            if (renderings == null)
            {
                this.ChangeButtonsState(true);
                return;
            }
            RenderingDefinition renderingDefinition = renderings[this.SelectedIndex] as RenderingDefinition;

            if (renderingDefinition == null)
            {
                this.ChangeButtonsState(true);
                return;
            }
            this.ChangeButtonsState(false);
            this.Personalize.Disabled = !string.IsNullOrEmpty(renderingDefinition.MultiVariateTest);
            this.Test.Disabled        = DeviceEditorForm.HasRenderingRules(renderingDefinition);
        }
예제 #21
0
        public void Hold_release_button_sensor_config_is_generated(string sensorType)
        {
            // Arrange
            var transformer = new MqttSensorConfigTransformer(new DummyConfiguration(), new DeviceTranslator());
            var definition  = new DeviceDefinition
            {
                DeviceId = "Test button",
                Platform = "hubitat",
                Sensors  = new[] { new SensorDefinition {
                                       Type = sensorType
                                   } },
            };
            var expectedConfig = @"
# Test button hold, from hubitat via MQTT
- platform: mqtt
  name: Test button hold
  state_topic: hubitat/Test button/1/hold
  payload_on: held
  payload_off: released
".Trim();

            // Action
            var result = transformer.TransformConfig(definition);

            // Assert
            Assert.AreEqual(1, result.Keys.Count, "One entity type returned");
            Assert.AreEqual("binary_sensor", result.Keys.First(), "The type of the entity returned is correct");
            Assert.AreEqual(1, result["binary_sensor"].Count, "Only one entity returned");

            var config = result["binary_sensor"].First();

            Assert.AreEqual(expectedConfig, config.Entity, "Config declared as expected");
            Assert.IsEmpty(config.Customization, "Customization declared as expected");
        }
예제 #22
0
        /// <summary>
        /// Handles a click on the OK button.
        /// </summary>
        /// <param name="sender">
        /// The sender.
        /// </param>
        /// <param name="args">
        /// The arguments.
        /// </param>
        /// <remarks>
        /// When the user clicks OK, the dialog is closed by calling
        /// the <see cref="M:Sitecore.Web.UI.Sheer.ClientResponse.CloseWindow">CloseWindow</see> method.
        /// </remarks>
        protected override void OnOK(object sender, System.EventArgs args)
        {
            Assert.ArgumentNotNull(sender, "sender");
            Assert.ArgumentNotNull(args, "args");
            if (this.Layout.Value.Length > 0)
            {
                Item item = Client.ContentDatabase.GetItem(this.Layout.Value);
                if (item == null)
                {
                    Context.ClientPage.ClientResponse.Alert("Layout not found.");
                    return;
                }
                if (item.TemplateID == TemplateIDs.Folder || item.TemplateID == TemplateIDs.Node)
                {
                    Context.ClientPage.ClientResponse.Alert(Translate.Text("\"{0}\" is not a layout.", new object[]
                    {
                        item.DisplayName
                    }));
                    return;
                }
            }
            LayoutDefinition layoutDefinition = DeviceEditorForm.GetLayoutDefinition();
            DeviceDefinition device           = layoutDefinition.GetDevice(this.DeviceID);

            System.Collections.ArrayList renderings = device.Renderings;
            if (renderings != null && renderings.Count > 0 && this.Layout.Value.Length == 0)
            {
                Context.ClientPage.ClientResponse.Alert("You must specify a layout when you specify renderings.");
                return;
            }
            device.Layout = this.Layout.Value;
            DeviceEditorForm.SetDefinition(layoutDefinition);
            Context.ClientPage.ClientResponse.SetDialogValue("yes");
            base.OnOK(sender, args);
        }
예제 #23
0
        ///<summary>
        ///	When working with the Presentation Layer for Sitecore, you can specify a Datasource as a property
        ///	for a control.  However, accessing the item that is set brings a bit of a challenge.  Hopefully this fixes that.
        ///</summary>
        ///<param name = "database">Sitecore Database to Use.  Usually From Context.</param>
        ///<param name = "device">Sitecore Device to Use.  Usually from Context.</param>
        ///<param name = "item">Item to get the Layout Renderings from.</param>
        ///<param name = "sublayoutItem">
        ///	Item reference to the Sublayout or Webcontrol that you would like to use for getting the datasource from.
        ///</param>
        ///<returns>Datasource Item.  If no Datasource Item is listed in the layout properties, returns Null.</returns>
        ///<exception cref = "ItemNotFoundException">Thrown when Sitecore can't find a specified datasource item entry.</exception>
        public static Item GetDatasourceFromControl(Database database, DeviceItem device, Item item, Item sublayoutItem)
        {
            Item datasourceItem = null;

            // Get the Layout definition from the current item
            string           rend   = item.Fields["__renderings"].Value;
            LayoutDefinition layout = LayoutDefinition.Parse(rend);
            // Get the current device definition
            DeviceDefinition deviceDef = layout.GetDevice(device.ID.ToString());
            // Get the sublayout to find
            Item mySublayout = database.GetItem(sublayoutItem.ID);
            // Get the definition for the sublayout
            RenderingDefinition rendering = deviceDef.GetRendering(mySublayout.ID.ToString());

            if (!String.IsNullOrEmpty(rendering.Datasource))
            {
                datasourceItem = database.GetItem(rendering.Datasource);
                if (datasourceItem == null)
                {
                    throw new ItemNotFoundException("Could not find datasource item at " + rendering.Datasource);
                }
            }

            return(datasourceItem);
        }
예제 #24
0
        protected void Remove(Message message)
        {
            Assert.ArgumentNotNull(message, "message");
            int selectedIndex = this.SelectedIndex;

            if (selectedIndex < 0)
            {
                return;
            }
            LayoutDefinition layoutDefinition = DeviceEditorForm.GetLayoutDefinition();
            DeviceDefinition device           = layoutDefinition.GetDevice(this.DeviceID);

            System.Collections.ArrayList renderings = device.Renderings;
            if (renderings == null)
            {
                return;
            }
            if (selectedIndex < 0 || selectedIndex >= renderings.Count)
            {
                return;
            }
            renderings.RemoveAt(selectedIndex);
            if (selectedIndex >= 0)
            {
                this.SelectedIndex--;
            }
            DeviceEditorForm.SetDefinition(layoutDefinition);
            this.Refresh();
        }
예제 #25
0
 public ReplaceRenderingRuleContext(RenderingDefinition sourceRendering, Item targetRenderingItem, DeviceDefinition device)
     : base(new ID(sourceRendering.ItemID))
 {
     SourceRendering     = sourceRendering;
     TargetRenderingItem = targetRenderingItem;
     Device = device;
 }
예제 #26
0
        protected void SortUp(Message message)
        {
            Assert.ArgumentNotNull(message, "message");
            if (this.SelectedIndex <= 0)
            {
                return;
            }
            LayoutDefinition layoutDefinition = DeviceEditorForm.GetLayoutDefinition();
            DeviceDefinition device           = layoutDefinition.GetDevice(this.DeviceID);

            System.Collections.ArrayList renderings = device.Renderings;
            if (renderings == null)
            {
                return;
            }
            RenderingDefinition renderingDefinition = renderings[this.SelectedIndex] as RenderingDefinition;

            if (renderingDefinition == null)
            {
                return;
            }
            renderings.Remove(renderingDefinition);
            renderings.Insert(this.SelectedIndex - 1, renderingDefinition);
            this.SelectedIndex--;
            DeviceEditorForm.SetDefinition(layoutDefinition);
            this.Refresh();
        }
예제 #27
0
        public void AddRendering(Item item, string renderingID, string placeholder, Item datasource)
        {
            LayoutField      layoutField      = new LayoutField(item.Fields[FieldIDs.FinalLayoutField]);
            LayoutDefinition layoutDefinition = LayoutDefinition.Parse(layoutField.Value);
            DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(GetDefaultDeviceItem(item.Database).ID.ToString());

            foreach (RenderingDefinition rendering in deviceDefinition.Renderings)
            {
                if (rendering.ItemID.ToLower() == "{C1624533-ED68-41AC-B03C-BFDE4D9B1F2A}".ToLower())
                {
                    placeholder = StringUtil.EnsurePrefix('/', rendering.Placeholder + "/" + placeholder + "_" + new Guid(rendering.UniqueId).ToString("D").ToLower());
                    break;
                }
            }
            var newRendering = new RenderingDefinition
            {
                Placeholder = placeholder,
                ItemID      = renderingID,
                Datasource  = datasource.ID.ToString()
            };

            deviceDefinition.AddRendering(newRendering);
            using (new SecurityDisabler())
            {
                item.Editing.BeginEdit();
                layoutField.Value = layoutDefinition.ToXml();
                item.Editing.EndEdit();
            }
        }
예제 #28
0
        /// <summary>
        /// Refreshes this instance.
        /// </summary>
        private void Refresh()
        {
            this.Renderings.Controls.Clear();
            this.Placeholders.Controls.Clear();
            this.Controls = new System.Collections.ArrayList();
            LayoutDefinition layoutDefinition = DeviceEditorForm.GetLayoutDefinition();
            DeviceDefinition device           = layoutDefinition.GetDevice(this.DeviceID);

            if (device.Renderings == null)
            {
                SheerResponse.SetOuterHtml("Renderings", this.Renderings);
                SheerResponse.SetOuterHtml("Placeholders", this.Placeholders);
                SheerResponse.Eval("if (!scForm.browser.isIE) { scForm.browser.initializeFixsizeElements(); }");
                return;
            }
            int selectedIndex = this.SelectedIndex;

            this.RenderRenderings(device, selectedIndex, 0);
            this.RenderPlaceholders(device);
            this.UpdateRenderingsCommandsState();
            this.UpdatePlaceholdersCommandsState();
            SheerResponse.SetOuterHtml("Renderings", this.Renderings);
            SheerResponse.SetOuterHtml("Placeholders", this.Placeholders);
            SheerResponse.Eval("if (!scForm.browser.isIE) { scForm.browser.initializeFixsizeElements(); }");
        }
예제 #29
0
        private async void btnControlsConfigure_Click(object sender, RoutedEventArgs e)
        {
            // get button name
            Button button = (Button)sender;
            string name   = button.Name;

            // remove beginning and end
            name = name.Replace("btn", "").Replace("Configure", "");

            // get the relevant combox
            //ComboBox cb = (ComboBox)this.FindName("cmb" + name);

            // get the virtual port number
            //ComboBoxItem typeItem = (ComboBoxItem)cb.SelectedItem;
            //string selectedString = cb.SelectionBoxItem.ToString();
            //int portNum = Convert.ToInt32(selectedString.Replace("Virtual Port ", ""));

            // Get device definition for this controller
            DeviceDefinition dev = Lynx.GamePad(0);

            mw.ControllerDefinition = dev;

            // launch controller configuration window
            Grid RootGrid = (Grid)mw.FindName("RootGrid");
            await mw.ShowChildWindowAsync(new ConfigureController()
            {
                IsModal         = true,
                AllowMove       = false,
                Title           = "Controller Configuration",
                CloseOnOverlay  = false,
                CloseByEscape   = false,
                ShowCloseButton = false
            }, RootGrid);
        }
예제 #30
0
        public void Threshold_sensor_config_is_generated()
        {
            // Arrange
            var transformer = new MqttSensorConfigTransformer(new DummyConfiguration(), new DeviceTranslator());
            var definition  = new DeviceDefinition
            {
                DeviceId = "Test meter",
                Platform = "hubitat",
                Sensors  = new[] { new SensorDefinition {
                                       Type = "power-threshold", OnCondition = "< 5"
                                   } },
            };
            var expectedConfig = @"
# Test meter, from hubitat via MQTT
- platform: mqtt
  name: Test meter
  state_topic: hubitat/Test meter/power
  value_template: '{%if (value | float) < 5-%}on{%-else-%}off{%-endif%}'
  payload_on: 'on'
  payload_off: 'off'
".Trim();

            // Action
            var result = transformer.TransformConfig(definition);

            // Assert
            Assert.AreEqual(1, result.Keys.Count, "One entity type returned");
            Assert.AreEqual("binary_sensor", result.Keys.First(), "The type of the entity returned is correct");
            Assert.AreEqual(1, result["binary_sensor"].Count, "Only one entity returned");

            var config = result["binary_sensor"].First();

            Assert.AreEqual(expectedConfig, config.Entity, "Config declared as expected");
            Assert.IsEmpty(config.Customization, "Customization declared as expected");
        }
예제 #31
0
        protected string GetButtonActivityEntityId(DeviceDefinition definition)
        {
            var sensorId = GetButtonActivitySensorId(definition);
            var id       = $"{EntityType.BinarySensor}.{sensorId}";

            return(id);
        }
예제 #32
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log, ExecutionContext executionContext)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var config           = executionContext.BuildConfiguraion();
            var account          = AccountConfigration.Load().First();
            var deviceDefinition = DeviceDefinition.Load();

            var token = await Extensions.GetS2SAccessToken(account.ClientId, config[account.ClientSecretSettingName], account.Resource, account.Authority);

            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.AccessToken);

            var fb = new FarmBeatsClient(account.Url, _httpClient);

            foreach (var dm in deviceDefinition.deviceModels)
            {
                await fb.CreateDeviceModel(dm);
            }

            foreach (var sm in deviceDefinition.sensorModels)
            {
                await fb.CreateSensorModel(sm);
            }

            return(new OkObjectResult("OK"));
        }
예제 #33
0
        protected override void ProcessLayout(Item item, LayoutDefinition layout, DeviceDefinition device)
        {
            if (!ShouldProcess(item.GetProviderPath(), "Add rendering " + Instance.ItemID))
            {
                return;
            }
            var rendering = new RenderingDefinition
            {
                ItemID = Instance.ItemID,
                Placeholder = PlaceHolder ?? Instance.Placeholder,
                Datasource = DataSource ?? Instance.Datasource,
                Cachable = Instance.Cachable,
                VaryByData = Instance.VaryByData,
                VaryByDevice = Instance.VaryByDevice,
                VaryByLogin = Instance.VaryByLogin,
                VaryByParameters = Instance.VaryByParameters,
                VaryByQueryString = Instance.VaryByQueryString,
                VaryByUser = Instance.VaryByUser
            };

            if (Parameter != null)
            {
                var parameters = new UrlString(rendering.Parameters ?? string.Empty);
                foreach (string name in Parameter.Keys)
                    if (parameters.Parameters.AllKeys.Contains(name))
                    {
                        parameters.Parameters[name] = Parameter[name].ToString();
                    }
                    else
                    {
                        parameters.Add(name, Parameter[name].ToString());
                    }
                rendering.Parameters = parameters.ToString();
            }

            //todo: add support for conditions
            //renderingDefinition.Conditions
            //todo: add support for multivariate tests
            //rendering.MultiVariateTest

            if (Index > -1)
            {
                device.Insert(index, rendering);
            }
            else
            {
                device.AddRendering(rendering);
            }

            item.Edit(p =>
            {
                var outputXml = layout.ToXml();
                Item["__Renderings"] = outputXml;
            });
        }
        protected virtual void InsertRenderingAt(DeviceDefinition device, RenderingDefinition renderingDefinition, int insertPosition, IEnumerable<ID> allowedRenderingsIds, string renderingUniqueId = "")
        {
            Assert.ArgumentNotNull((object)device, "device");
            Assert.ArgumentNotNull((object)renderingDefinition, "renderingDefinition");

            // Insert Rendering by it's Unique Id
            if (!string.IsNullOrEmpty(renderingUniqueId) && device != null && device.Renderings != null)
            {
                string uniqueId = string.Concat("{", renderingUniqueId, "}");
                // Try
                for (int index = 0; index < device.Renderings.Count; ++index)
                {
                    RenderingDefinition rendering = device.Renderings[index] as RenderingDefinition;

                    if (rendering.UniqueId == uniqueId)
                    {
                        device.Insert(index + 1, renderingDefinition);
                    }
                }
            }

            if (insertPosition == 0)
                device.Insert(insertPosition, renderingDefinition);
            else if (device.Renderings == null)
            {
                device.AddRendering(renderingDefinition);
            }
            else
            {
                ID[] idArray = Enumerable.ToArray<ID>(allowedRenderingsIds);
                int num = 0;
                for (int index = 0; index < device.Renderings.Count; ++index)
                {
                    RenderingDefinition rendering = device.Renderings[index] as RenderingDefinition;
                    Assert.IsNotNull((object)rendering, "rendering");
                    string placeholder = rendering.Placeholder;
                    if (string.IsNullOrEmpty(placeholder) && Enumerable.Any<ID>((IEnumerable<ID>)idArray, (Func<ID, bool>)(p => p == ID.Parse(rendering.ItemID))))
                        placeholder = renderingDefinition.Placeholder;

                    if (InsertRendering.AreEqualPlaceholders(placeholder, renderingDefinition.Placeholder))
                        ++num;

                    if (num == insertPosition)
                    {
                        device.Insert(index + 1, renderingDefinition);
                        break;
                    }
                }
            }
        }
예제 #35
0
        protected override void ProcessRenderings(Item item, LayoutDefinition layout, DeviceDefinition device,
            IEnumerable<RenderingDefinition> renderings)
        {
            if (ShouldProcess(item.GetProviderPath(),
                string.Format("Remove rendering(s) '{0}' from device {1}",
                    renderings.Select(r => r.ItemID.ToString()).Aggregate((seed, curr) => seed + ", " + curr),
                    Device.Name)))
            {
                foreach (
                    var instanceRendering in
                        renderings.Select(rendering => device.Renderings.Cast<RenderingDefinition>()
                            .FirstOrDefault(r => r.UniqueId == rendering.UniqueId))
                            .Where(instanceRendering => instanceRendering != null))
                {
                    device.Renderings.Remove(instanceRendering);
                }

                item.Edit(p =>
                {
                    var outputXml = layout.ToXml();
                    Item["__Renderings"] = outputXml;
                });
            }
        }
        private static void DeleteRenderingNode(DeviceDefinition device)
        {
            ArrayList renderings = new ArrayList();
             foreach (RenderingDefinition rendering in device.Renderings)
             {
            if (!ContainRenderingsID(rendering.ItemID))
            {
               renderings.Add(rendering);
            }
             }

             device.Renderings = renderings;
        }
예제 #37
0
 protected override void ProcessRenderings(Item item, LayoutDefinition layout, DeviceDefinition device,
     IEnumerable<RenderingDefinition> renderings)
 {
     renderings.ToList().ForEach(r => WriteObject(ItemShellExtensions.WrapInItemOwner(SessionState, item, r)));
 }
        private void BuildRendering(Border border, DeviceDefinition deviceDefinition, RenderingDefinition renderingDefinition, int index, int conditionsCount)
        {
            Assert.ArgumentNotNull(border, "border");
            Assert.ArgumentNotNull(deviceDefinition, "deviceDefinition");
            Assert.ArgumentNotNull(renderingDefinition, "renderingDefinition");

            string itemId = renderingDefinition.ItemID;
            if (itemId == null)
            {
                return;
            }

            Item obj = Client.ContentDatabase.GetItem(itemId);
            if (obj == null)
            {
                return;
            }

            string displayName = obj.DisplayName;
            string icon = obj.Appearance.Icon;
            string str1 = string.Empty;
            string str2 = displayName;

            if (str1.Length > 0 && str1 != "content")
            {
                str2 = string.Format("{0} {1} {2}.", str2, Translate.Text("in"), str1);
            }

            if (Settings.Analytics.Enabled && conditionsCount > 1)
            {
                str2 += string.Format("<span class=\"{0}\">{1}</span>", conditionsCount > 9
                        ? "scConditionContainer scLongConditionContainer"
                        : "scConditionContainer",
                    conditionsCount);
            }

            Border border1 = new Border();
            border1.Style.Add("float", "left");

            Border borderX = new Border();

            var renderingIconAnchor = new HtmlGenericControl
            {
                InnerHtml = "<a onclick='window.open(\"/sitecore/shell/Applications/Content%20Editor.aspx?fo=" +
                    itemId + "\",\"myWin\",\"width=800,height=600\"); return false;' taget='_blank' class='linkIcon'>" +
                    Images.GetImage(icon, 16, 16, "absmiddle", "0px 4px 0px 0px") + "</a>",
            };
            renderingIconAnchor.Style.Add("float", "left");

            borderX.Controls.Add(renderingIconAnchor);
            borderX.Controls.Add(border1);

            var clearBoth = new HtmlGenericControl("div");
            clearBoth.Style.Add("clear","both");
            borderX.Controls.Add(clearBoth);

            border.Controls.Add(borderX);

            string str3 = StringUtil.GetString(EditRenderingClick).Replace("$Device", deviceDefinition.ID).Replace("$Index", index.ToString());

            if (!string.IsNullOrEmpty(str3))
            {
                border1.RollOver = true;
                border1.Class = "scRollOver";
                border1.Click = str3;
            }

            var literal = new Sitecore.Web.UI.HtmlControls.Literal(
                string.Format("<div class='scRendering' style='padding:2px;position:relative'>{0}</div>", str2)
                );

            border1.Controls.Add(literal);
        }
예제 #39
0
 protected abstract void ProcessLayout(Item item, LayoutDefinition layout, DeviceDefinition device);
예제 #40
0
        protected override void ProcessLayout(Item item, LayoutDefinition layout, DeviceDefinition device)
        {
            if (device == null || device.Renderings == null)
            {
                return;
            }

            var renderings = device.Renderings.Cast<RenderingDefinition>();

            if (Instance != null)
            {
                renderings = new[] {Instance};
            }
            else if (!string.IsNullOrEmpty(UniqueId))
            {
                renderings =
                    renderings.Where(r => string.Equals(r.UniqueId, UniqueId, StringComparison.OrdinalIgnoreCase));
            }
            else
            {
                if (Rendering != null)
                {
                    renderings = renderings.Where(r => r.ItemID == Rendering.ID.ToString());
                }

                if (!string.IsNullOrEmpty(DataSource))
                {
                    renderings = WildcardFilter(DataSource, renderings, r => r.Datasource);
                }

                if (!string.IsNullOrEmpty(PlaceHolder))
                {
                    renderings = WildcardFilter(PlaceHolder, renderings, r => r.Placeholder);
                }

                if (Index > -1)
                {
                    renderings = renderings.Skip(index).Take(1);
                }
            }

            if (paramPatterns != null)
            {
                var paramFilteredRenderings = new List<RenderingDefinition>();
                foreach (var rendering in renderings)
                {
                    if (string.IsNullOrEmpty(rendering.Parameters))
                    {
                        continue;
                    }
                    var parsedParams = new UrlString(rendering.Parameters);
                    var match = true;
                    foreach (var param in paramPatterns)
                    {
                        if (!parsedParams.Parameters.AllKeys.Contains(param.Key, StringComparer.OrdinalIgnoreCase))
                        {
                            match = false;
                            break;
                        }
                        if (!param.Value.IsMatch(parsedParams.Parameters[param.Key]))
                        {
                            match = false;
                            break;
                        }
                    }
                    if (match)
                    {
                        paramFilteredRenderings.Add(rendering);
                    }
                }
                renderings = paramFilteredRenderings;
            }
            ProcessRenderings(item, layout, device, renderings);
        }
        /// <summary>
        /// Renders the specified device definition.
        /// </summary>
        /// <param name="deviceDefinition">
        /// The device definition.
        /// </param>
        /// <param name="selectedIndex">
        /// Index of the selected.
        /// </param>
        /// <param name="index">
        /// The index.
        /// </param>
        private void RenderRenderings(DeviceDefinition deviceDefinition, int selectedIndex, int index)
        {
            Assert.ArgumentNotNull(deviceDefinition, "deviceDefinition");
            ArrayList renderings = deviceDefinition.Renderings;
            if (renderings == null)
            {
                return;
            }
            foreach (RenderingDefinition rendering in renderings)
            {
                if (rendering.ItemID == null)
                {
                    continue;
                }
                Item item = Client.ContentDatabase.GetItem(rendering.ItemID);
                XmlControl webControl = Resource.GetWebControl("DeviceRendering") as XmlControl;
                Assert.IsNotNull(webControl, typeof(XmlControl));
                HtmlGenericControl htmlGenericControl = new HtmlGenericControl("div");
                htmlGenericControl.Style.Add("padding", "0");
                htmlGenericControl.Style.Add("margin", "0");
                htmlGenericControl.Style.Add("border", "0");
                htmlGenericControl.Style.Add("position", "relative");
                htmlGenericControl.Controls.Add(webControl);
                string uniqueID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("R");
                this.Renderings.Controls.Add(htmlGenericControl);
                htmlGenericControl.ID = Sitecore.Web.UI.HtmlControls.Control.GetUniqueID("C");
                webControl["Click"] = string.Concat("OnRenderingClick(\"", index, "\")");
                webControl["DblClick"] = "device:edit";
                if (index == selectedIndex)
                {
                    webControl["Background"] = "#D0EBF6";
                }
                this.Controls.Add(uniqueID);
                if (item == null)
                {
                    webControl["ID"] = uniqueID;
                    webControl["Icon"] = "Applications/24x24/forbidden.png";
                    webControl["Header"] = "Unknown rendering";
                    webControl["Placeholder"] = string.Empty;
                    webControl["Description"] = string.Empty;

                }
                else
                {
                    webControl["ID"] = uniqueID;
                    webControl["Icon"] = item.Appearance.Icon;
                    webControl["Header"] = item.DisplayName;
                    webControl["Placeholder"] = WebUtil.SafeEncode(rendering.Placeholder);
                    webControl["Description"] = GetDescriptionValue(rendering);
                }
                if (Settings.Analytics.Enabled && rendering.Rules != null && !rendering.Rules.IsEmpty)
                {
                    int num = rendering.Rules.Elements("rule").Count<XElement>();
                    if (num > 1)
                    {
                        HtmlGenericControl str = new HtmlGenericControl("span");
                        if (num <= 9)
                        {
                            str.Attributes["class"] = "scConditionContainer";
                        }
                        else
                        {
                            str.Attributes["class"] = "scConditionContainer scLongConditionContainer";
                        }
                        str.InnerText = num.ToString();
                        htmlGenericControl.Controls.Add(str);
                    }
                }
                index++;
            }
        }
 /// <summary>
 /// Renders the placeholders.
 /// </summary>
 /// <param name="deviceDefinition">
 /// The device definition.
 /// </param>
 private void RenderPlaceholders(DeviceDefinition deviceDefinition)
 {
     Assert.ArgumentNotNull(deviceDefinition, "deviceDefinition");
     ArrayList placeholders = deviceDefinition.Placeholders;
     if (placeholders == null)
     {
         return;
     }
     foreach (PlaceholderDefinition placeholder in placeholders)
     {
         Item item = null;
         string metaDataItemId = placeholder.MetaDataItemId;
         if (!string.IsNullOrEmpty(metaDataItemId))
         {
             item = Client.ContentDatabase.GetItem(metaDataItemId);
         }
         XmlControl webControl = Resource.GetWebControl("DeviceRendering") as XmlControl;
         Assert.IsNotNull(webControl, typeof(XmlControl));
         this.Placeholders.Controls.Add(webControl);
         ID d = ID.Parse(placeholder.UniqueId);
         if (placeholder.UniqueId == this.UniqueId)
         {
             webControl["Background"] = "#D0EBF6";
         }
         string str = string.Concat("ph_", d.ToShortID());
         webControl["ID"] = str;
         webControl["Header"] = placeholder.Key;
         webControl["Click"] = string.Concat("OnPlaceholderClick(\"", placeholder.UniqueId, "\")");
         webControl["DblClick"] = "device:editplaceholder";
         if (item == null)
         {
             webControl["Icon"] = "Imaging/24x24/layer_blend.png";
         }
         else
         {
             webControl["Icon"] = item.Appearance.Icon;
         }
     }
 }
        private void RenderRenderings(DeviceDefinition deviceDefinition, int selectedIndex, int index)
        {
            Assert.ArgumentNotNull(deviceDefinition, "deviceDefinition");
            ArrayList renderings = deviceDefinition.Renderings;

            if (renderings == null)
            {
                return;
            }

            foreach (RenderingDefinition renderingDefinition in renderings)
            {
                if (renderingDefinition.ItemID != null)
                {
                    Item obj = Client.ContentDatabase.GetItem(renderingDefinition.ItemID);

                    XmlControl xmlControl = Resource.GetWebControl("DeviceRendering") as XmlControl;
                    Assert.IsNotNull(xmlControl, typeof(XmlControl));

                    HtmlGenericControl htmlGenericControl1 = new HtmlGenericControl("div");
                    htmlGenericControl1.Style.Add("padding", "0");
                    htmlGenericControl1.Style.Add("margin", "0");
                    htmlGenericControl1.Style.Add("border", "0");
                    htmlGenericControl1.Style.Add("position", "relative");
                    htmlGenericControl1.Controls.Add(xmlControl);

                    string uniqueId = Control.GetUniqueID("R");
                    Renderings.Controls.Add((System.Web.UI.Control)htmlGenericControl1);
                    htmlGenericControl1.ID = Control.GetUniqueID("C");
                    xmlControl["Click"] = ("OnRenderingClick(\"" + index + "\")");
                    xmlControl["DblClick"] = "device:edit";

                    if (index == selectedIndex)
                    {
                        xmlControl["Background"] = "#D0EBF6";
                    }

                    Controls.Add(uniqueId);

                    if (obj != null)
                    {
                        xmlControl["ID"] = uniqueId;
                        xmlControl["Icon"] = obj.Appearance.Icon;
                        xmlControl["Header"] = obj.DisplayName;
                        xmlControl["HeaderID"] = obj.ID;
                        xmlControl["Placeholder"] = WebUtil.SafeEncode(renderingDefinition.Placeholder);

                        var dataSourceItem = Client.ContentDatabase.GetItem(renderingDefinition.Datasource);
                        if (dataSourceItem != null)
                        {
                            xmlControl["DataSourcePath"] = WebUtil.SafeEncode(dataSourceItem.Paths.FullPath);
                            xmlControl["DataSourceID"] = WebUtil.SafeEncode(renderingDefinition.Datasource);
                        }
                    }
                    else
                    {
                        xmlControl["ID"] = uniqueId;
                        xmlControl["Icon"] = "Applications/24x24/forbidden.png";
                        xmlControl["Header"] = "Unknown rendering";
                        xmlControl["Placeholder"] = string.Empty;
                    }

                    if (Settings.Analytics.Enabled && renderingDefinition.Rules != null && !renderingDefinition.Rules.IsEmpty)
                    {
                        int num = Enumerable.Count(renderingDefinition.Rules.Elements("rule"));

                        if (num > 1)
                        {
                            HtmlGenericControl htmlGenericControl2 = new HtmlGenericControl("span");

                            if (num > 9)
                            {
                                htmlGenericControl2.Attributes["class"] = "scConditionContainer scLongConditionContainer";
                            }
                            else
                            {
                                htmlGenericControl2.Attributes["class"] = "scConditionContainer";
                            }

                            htmlGenericControl2.InnerText = num.ToString();
                            htmlGenericControl1.Controls.Add(htmlGenericControl2);
                        }
                    }

                    ++index;
                }
            }
        }
        private void RenderPlaceholders(DeviceDefinition deviceDefinition)
        {
            Assert.ArgumentNotNull(deviceDefinition, "deviceDefinition");
            ArrayList placeholders = deviceDefinition.Placeholders;

            if (placeholders == null)
            {
                return;
            }

            foreach (PlaceholderDefinition placeholderDefinition in placeholders)
            {
                Item obj = null;
                string metaDataItemId = placeholderDefinition.MetaDataItemId;

                if (!string.IsNullOrEmpty(metaDataItemId))
                {
                    obj = Client.ContentDatabase.GetItem(metaDataItemId);
                }

                XmlControl xmlControl = Resource.GetWebControl("DeviceRendering") as XmlControl;
                Assert.IsNotNull(xmlControl, typeof(XmlControl));

                Placeholders.Controls.Add((System.Web.UI.Control)xmlControl);
                ID id = ID.Parse(placeholderDefinition.UniqueId);

                if (placeholderDefinition.UniqueId == UniqueId)
                {
                    xmlControl["Background"] = "#D0EBF6";
                }

                string str = "ph_" + id.ToShortID();
                xmlControl["ID"] = str;
                xmlControl["Header"] = placeholderDefinition.Key;
                xmlControl["Click"] = ("OnPlaceholderClick(\"" + placeholderDefinition.UniqueId + "\")");
                xmlControl["DblClick"] = "device:editplaceholder";
                xmlControl["Icon"] = obj == null ? "Imaging/24x24/layer_blend.png" : obj.Appearance.Icon;
            }
        }
예제 #45
0
 protected abstract void ProcessRenderings(Item item, LayoutDefinition layout, DeviceDefinition device,
     IEnumerable<RenderingDefinition> renderings);
예제 #46
0
 private void AssertLayout(DeviceDefinition expected, DeviceDefinition actual)
 {
   Assert.That(actual.Layout, Is.EqualTo(expected.Layout));
   Assert.That(actual.Renderings.Count, Is.EqualTo(expected.Renderings.Count));
   
   for (var i = 0; i < expected.Renderings.Count; i++)
   {
     Assert.That(((RenderingDefinition)actual.Renderings[i]).ToXml(), Is.EqualTo(((RenderingDefinition)expected.Renderings[i]).ToXml()));
   }
 }
        /// <summary>
        /// Copy from Sitecore as as, just to make compile.
        /// </summary>
        private void BuildPlaceholder(Border border, DeviceDefinition deviceDefinition, PlaceholderDefinition placeholderDefinition)
        {
            Assert.ArgumentNotNull(border, "border");
            Assert.ArgumentNotNull(deviceDefinition, "deviceDefinition");
            Assert.ArgumentNotNull(placeholderDefinition, "placeholderDefinition");

            string metaDataItemId = placeholderDefinition.MetaDataItemId;

            Border border1 = new Border();
            border.Controls.Add(border1);

            string str1 = StringUtil.GetString(EditPlaceholderClick)
                .Replace("$Device", deviceDefinition.ID)
                .Replace("$UniqueID", placeholderDefinition.UniqueId);

            Assert.IsNotNull(metaDataItemId, "placeholder id");

            Item obj = Client.ContentDatabase.GetItem(metaDataItemId);

            string str2;
            if (obj != null)
            {
                string displayName = obj.DisplayName;
                str2 = Images.GetImage(obj.Appearance.Icon, 16, 16, "absmiddle", "0px 4px 0px 0px") + displayName;
            }
            else
            {
                str2 = Images.GetImage("Imaging/16x16/layer_blend.png", 16, 16, "absmiddle", "0px 4px 0px 0px") + placeholderDefinition.Key;
            }

            if (!string.IsNullOrEmpty(str1))
            {
                border1.RollOver = true;
                border1.Class = "scRollOver";
                border1.Click = str1;
            }

            var literal = new Sitecore.Web.UI.HtmlControls.Literal(string.Format("<div style=\"padding:2\">{0}</div>", str2));
            border1.Controls.Add(literal);
        }