Beispiel #1
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;
        }
Beispiel #2
0
        protected override void ProcessItem(Item item)
        {
            LayoutField layoutField = item.Fields[FieldIDs.LayoutField];
            if (layoutField != null && !string.IsNullOrEmpty(layoutField.Value))
            {
                var layout = LayoutDefinition.Parse(layoutField.Value);
                if (Device == null)
                {
                    Device = CurrentDatabase.Resources.Devices.GetAll().FirstOrDefault(d => d.IsDefault);
                }

                if (Device == null)
                {
                    WriteError(
                        new ErrorRecord(
                            new ObjectNotFoundException(
                                "Device not provided and no default device in the system is defined."),
                            "sitecore_device_not_found", ErrorCategory.InvalidData, null));
                    return;
                }

                var device = layout.GetDevice(Device.ID.ToString());
                if (device != null)
                {
                    ProcessLayout(item, layout, device);
                }
            }
        }
Beispiel #3
0
 public void DeleteDeviceItem(DeviceItem device)
 {
     if (device != null)
     {
         this.DeleteDevice(device.deviceId);
         device.updateConfig   = false;
         device.updateWithNode = false;
         device.deleted        = true;
     }
 }
Beispiel #4
0
        private void button8_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem != null)
            {
                DeviceItem            item = (DeviceItem)comboBox1.SelectedItem;
                DeviceListener.Device d    = deviceListener.Find(item.id);

                deviceListener.SDCardPlayFileStop(d);
            }
        }
Beispiel #5
0
 public void UpdateActiveDevice(DeviceItem device)
 {
     this.activeDevice = device;
     this.formDeviceBaseInfo.UpdateActiveDevice(device);
     this.formDeviceBaseInfo.RefreshDeviceBaseInforListView(device);
     this.formDevicePropertys.UpdateActiveDevice(device);
     this.formDevicePropertys.RefreshDevicePropertysListView(device);
     this.formDeviceValues.UpdateActiveDevice(device);
     this.formDeviceValues.RefreshDeviceValues(null);
 }
        private void ConnectToApp(DeviceItem deviceItem)
        {
            _currentDevice = deviceItem;

            var isLocal = _currentDevice.DeviceType == DeviceTypes.Local;

            ClearSimulatorWindowButton.IsEnabled = !isLocal;

            if (isLocal)
            {
                LogToResultsWindow("Running locally (regular .Net)");
            }
            else
            {
                _currentDevice.MainXamarinAssemblyName = SimpleHttpServer.SendCustomCommand(_currentDevice.DeviceAddress, "GetMainXamarinAssembly");
                if (_currentDevice.DeviceType == DeviceTypes.iOS)
                {
                    var cssFilesJson = SimpleHttpServer.SendCustomCommand(_currentDevice.DeviceAddress, "GetPixateCssFiles");
                    _currentDevice.PixateCssPaths = UtilityMethods.JsonDecode <string[]>(cssFilesJson);
                }
                LogToResultsWindow("Connected to device '{0}' on [{1}]", _currentDevice.DeviceName, _currentDevice.DeviceAddress);
            }

            UpdateCodeTypesComboBox();

            Title = String.Format("ProtoPad - {0}", _currentDevice.DeviceName);

            SetText(true);

            SendCodeButton.IsEnabled     = true;
            LoadAssemblyButton.IsEnabled = true;

            StatusLabel.Content = "";

            if (_currentDevice.DeviceType != DeviceTypes.iOS)
            {
                return; // todo: locate and provide Android Emulator file path if applicable
            }

            var wrapText      = EditorHelpers.GetWrapText(CodeTypes.Expression, _currentDevice.DeviceType, null);
            var getFolderCode = wrapText.Replace("__STATEMENTSHERE__", "Environment.GetFolderPath(Environment.SpecialFolder.Personal)");
            var result        = SendCode(_currentDevice.DeviceAddress, false, getFolderCode);

            if (result == null || result.Results == null)
            {
                return;
            }
            var folder = result.Results.FirstOrDefault();

            if (folder == null)
            {
                return;
            }
            StatusLabel.Content = folder.ResultValue.PrimitiveValue.ToString();
        }
Beispiel #7
0
        private static async Task <List <DeviceItem> > GetDeviceItems(HttpClient client, List <string> deviceNames)
        {
            Console.Write("GetDeviceItems started...");

            List <DeviceItem> ret = new List <DeviceItem>();

            foreach (var deviceName in deviceNames)
            {
                // DEVICE

                Device device = new Device {
                    Name = deviceName, MadeById = (int)EnumLegalEntity.UNKNOWN
                };

                List <Device> devices = await DevicesAPI.GetByFilterAsync(client, device);

                if (devices == null || devices.Count == 0)
                {
                    device.Id = await DevicesAPI.CreateAsync(client, device);
                }
                else if (devices.Count == 1)
                {
                    device = devices[0];
                }
                else
                {
                    throw new Exception($"More than one device with name [{deviceName}]");
                }

                // DEVICE ITEM

                DeviceItem deviceItem = new DeviceItem {
                    CodeNum = "0", DeviceId = device.Id
                };

                List <DeviceItem> deviceItems = await DeviceItemsAPI.GetByFilterAsync(client, deviceItem);

                if (deviceItems == null || deviceItems.Count == 0)
                {
                    deviceItem.Id = await DeviceItemsAPI.CreateAsync(client, deviceItem);
                }
                else if (deviceItems.Count == 1)
                {
                    deviceItem = deviceItems[0];
                }
                else
                {
                    throw new Exception($"More than one device item for device with name [{deviceName}]");
                }

                ret.Add(deviceItem);
            }
            Console.WriteLine($" and endeded. {ret.Count} items generated.");
            return(ret);
        }
        public object ComputeFieldValue(IIndexable indexable)
        {
            var item = (SitecoreIndexableItem)indexable;

            var result = new List <string>();

            var database = item.Item.Database;

            // Get all renderings
            var renderings = item.Item.Visualization.GetRenderings(DeviceItem.ResolveDevice(database), false);

            foreach (var reference in renderings)
            {
                // Get the source item
                if (reference.RenderingItem == null)
                {
                    continue;
                }

                var datasource = reference.Settings.DataSource;

                if (string.IsNullOrEmpty(datasource))
                {
                    continue;
                }

                var sourceId = ID.Parse(datasource);

                var source = database.GetItem(sourceId, item.Item.Language);

                if (source == null)
                {
                    continue;
                }

                // Go through all fields
                foreach (Field field in source.Fields)
                {
                    var value = GetFieldValue(field);

                    if (!string.IsNullOrEmpty(value))
                    {
                        result.Add(value);
                    }
                }
            }

            if (result.Any())
            {
                return(result);
            }

            return(null);
        }
Beispiel #9
0
        private void refreshDeviceSelectionView()
        {
            DEIFlags flags = DEIFlags.DICFG_AllClasses;

            bool driverLessOnly = deviceSelection_DriverlessOnlyCheckBox.Checked;
            bool connnectedOnly = deviceSelection_ConnectedOnlyCheckBox.Checked;

            if (connnectedOnly)
            {
                flags = flags | DEIFlags.DICFG_Present;
            }

            if (driverLessOnly)
            {
                flags |= DEIFlags.Driverless;
            }

#if DEBUG
            flags |= DEIFlags.IncludeWindowsServices;
#endif
            cmdRemoveDevice.Enabled = false;
            gridDeviceSelection.Rows.Clear();

            if (deviceSelection_CreateNewRadio.Checked)
            {
                mCurrentDeviceItem  = new DeviceItem();
                wizMain.NextEnabled = true;
                deviceSelection_RefreshButton.Enabled = false;
                return;
            }
            deviceSelection_RefreshButton.Enabled = true;

            DeviceEnumeratorInfo deInfo = new DeviceEnumeratorInfo(flags, Handle);
            mDeviceList = deInfo.DeviceList;
            DeviceSelectionHelper.EnumerateDevices(deInfo);

            foreach (DeviceItem deviceItem in mDeviceList)
            {
                int iRow =
                    gridDeviceSelection.Rows.Add(new object[]
                {
                    "0x" + deviceItem.VendorID, "0x" + deviceItem.ProductID, deviceItem.DeviceDescription,
                    deviceItem.Manufacturer, deviceItem.mDriverless, deviceItem.mDeviceId
                });
                gridDeviceSelection.Rows[iRow].Tag = deviceItem;
                deviceItem.ResetDirty();
            }

            wizMain.NextEnabled = (gridDeviceSelection.Rows.Count > 0);
            if (wizMain.NextEnabled && mCurrentDeviceItem == null)
            {
                mCurrentDeviceItem = (DeviceItem)gridDeviceSelection.SelectedRows[0].Tag;
            }
        }
Beispiel #10
0
 public void NotifyListUpdate(DeviceItem device)
 {
     if (device == null)
     {
         this.Notify(REFRESH_DEVICE_LIST_EVENT, DeviceOperateEvent.ListAll.ToString(), null, "");
     }
     else
     {
         this.Notify(REFRESH_DEVICE_EVENT, DeviceOperateEvent.ListUpdate.ToString(), device, "");
     }
 }
Beispiel #11
0
        /// <summary>
        /// Deploy and run the package.
        /// </summary>
        public void Run(DeviceItem device, Action <LauncherStates, string> stateUpdate)
        {
            // Save argument
            this.stateUpdate = stateUpdate;

            // Prepare output
            outputPane.EnsureLoaded();

            // Start the device.
            Task.Factory.StartNew(() => RunOnStartedDevice(device.Device), cancellationTokenSource.Token);
        }
Beispiel #12
0
 private void SaveDeviceConfigMenuItem_OnClick(object sender, RoutedEventArgs e)
 {
     if (string.IsNullOrWhiteSpace(_device?.FilePath))
     {
         SaveDeviceConfigAsMenuItem_OnClick(sender, e);
     }
     else
     {
         _device = WriteDeviceConfig(DeviceConfigPanel.DeviceConfig, _device.FilePath);
     }
 }
        /// <summary>
        /// Get software object from provided DeviceItem
        /// </summary>
        /// <param name="device"></param>
        /// <returns>PlcSoftware object</returns>
        public static PlcSoftware GetSoftwareFrom(DeviceItem device)
        {
            SoftwareContainer softwareContainer = ((IEngineeringServiceProvider)device).GetService <SoftwareContainer>();

            if (softwareContainer != null)
            {
                return(softwareContainer.Software as PlcSoftware);
            }

            return(null);
        }
Beispiel #14
0
        private void button7_Click(object sender, EventArgs e)
        {
            if (comboBox4.SelectedItem != null)
            {
                DeviceItem            item = (DeviceItem)comboBox4.SelectedItem;
                DeviceListener.Device d    = deviceListener.Find(item.id);

                int vol = (int)numericUpDown2.Value;
                deviceListener.AudioSetVolume(d, vol);
            }
        }
 private void ToggleButton_Checked(object sender, RoutedEventArgs e)
 {
     if (tbtnPower.IsChecked == true)
     {
         DeviceItem.setPowerAsync(1);
     }
     else
     {
         DeviceItem.setPowerAsync(0);
     }
 }
Beispiel #16
0
 private DeviceItemGridItemModel CreateItem(DeviceItem entity)
 {
     return(new DeviceItemGridItemModel
     {
         DeviceItemPrice = Utils.DecimalToString(entity.Price),
         Id = entity.DeviceItemID,
         DeviceItemTitle = entity.Title,
         DeviceItemCostPrice = Utils.DecimalToString(entity.CostPrice),
         DeviceItemCount = Utils.DecimalToString(entity.Count)
     });
 }
Beispiel #17
0
        public static bool HasRendering(this Item item)
        {
            // Resolve device
            var device = DeviceItem.ResolveDevice(item.Database);

            if (device == null)
            {
                return(false);
            }

            return(item.Visualization.GetRenderings(device, false).Any());
        }
Beispiel #18
0
        /// <summary>
        /// MIDI入力ポートを開く
        /// </summary>
        public void MidiOpen(int num)
        {
            var list = GetDeviceList();

            if (list.Count <= num)
            {
                return;
            }
            mSelectedDevice = list[num];
            waveout_getChannelParamPtr();
            waveout_midiOpen(mSelectedDevice.ID);
        }
Beispiel #19
0
        /// <summary>
        /// Сохраняет в базе модель создания элемента.
        /// </summary>
        /// <param name="token">Токен безопасности.</param>
        /// <param name="model">Модель создания сущности для сохранения.</param>
        /// <param name="result">Результат выполнения.</param>
        /// <param name="isEdit">Признак редактирования.</param>
        public DeviceItemGridItemModel SaveModel(SecurityToken token, DeviceItemCreateModel model, JGridSaveModelResult result, bool isEdit)
        {
            if (model.WarehouseItemID == null && string.IsNullOrWhiteSpace(model.DeviceItemTitle))
            {
                result.ModelErrors.Add(new PairItem <string, string>("DeviceItemTitle", "Введите название запчасти или выберите ее из склада"));
                return(null);
            }

            var entity = new DeviceItem
            {
                Price           = model.DeviceItemPrice,
                RepairOrderID   = model.DeviceItemRepairOrderID,
                Title           = model.DeviceItemTitle,
                CostPrice       = model.DeviceItemCostPrice,
                Count           = model.DeviceItemCount,
                DeviceItemID    = model.Id,
                EventDate       = model.DeviceItemEventDate,
                UserID          = model.DeviceItemUserID,
                WarehouseItemID = model.WarehouseItemID
            };

            DeviceItem oldItem = null;

            if (isEdit)
            {
                oldItem = RemontinkaServer.Instance.DataStore.GetDeviceItem(entity.DeviceItemID);
            } //if

            if (entity.WarehouseItemID != null)//денормализуем данные
            {
                var item = RemontinkaServer.Instance.EntitiesFacade.GetWarehouseItem(token, entity.WarehouseItemID);

                RiseExceptionIfNotFound(item, entity.WarehouseItemID, "Остаток на складе");

                entity.Title     = item.GoodsItemTitle;
                entity.Price     = item.RepairPrice;
                entity.CostPrice = item.StartPrice;
            }

            RemontinkaServer.Instance.EntitiesFacade.SaveDeviceItem(token, entity);

            if (!isEdit)
            {
                RemontinkaServer.Instance.OrderTimelineManager.TrackNewDeviceItem(token, entity);
            } //if

            if (oldItem != null)
            {
                RemontinkaServer.Instance.OrderTimelineManager.TrackDeviceItemChanges(token, oldItem, entity);
            } //if

            return(CreateItem(entity));
        }
Beispiel #20
0
 public void Assign(DeviceItem device)
 {
     this.deviceId        = device.deviceId;
     this.model           = device.model;
     this.modelId         = device.modelId;
     this.name            = device.name;
     this.secret          = device.secret;
     this.serialCode      = device.serialCode;
     this.softwareVersion = device.softwareVersion;
     this.hardwareVersion = device.hardwareVersion;
     this.remark          = device.remark;
 }
        /// <summary>
        /// 	Checks to see if an item has presentation settings for the passed in device
        /// </summary>
        /// <param name = "theItem">The item to check.</param>
        /// <param name = "device">The device to check for.</param>
        /// <returns>True if the item contains the device in it's presentation settings, false otherwise.</returns>
        public static bool ItemHasPresentationSettingsForDevice(Item theItem, DeviceItem device)
        {
            if (theItem == null || device == null) return false;

            //Try and get the device definition from the layout definition
            DeviceDefinition deviceDef = GetDeviceDefinition(theItem, device);
            if (deviceDef == null) return false;

            //IF the device defintion layout or renderings are null, then the device does not have presentation
            // settings for this item
            return !(deviceDef.Layout == null || deviceDef.Renderings == null);
        }
        /// <summary>
        /// Gets the cookie device.
        /// </summary>
        /// <param name="database">The database.</param>
        /// <returns>Resolved device</returns>
        private static DeviceItem GetCookieDevice(Database database)
        {
            var deviceCookie = HttpContext.Current.Request.Cookies[DeviceCookieName];

            if (deviceCookie != null && !String.IsNullOrEmpty(deviceCookie.Value))
            {
                DeviceItem item = database.Resources.Devices[deviceCookie.Value];
                return(item);
            }

            return(null);
        }
Beispiel #23
0
 private void gridDeviceSelection_SelectionChanged(object sender, EventArgs e)
 {
     if (gridDeviceSelection.SelectedRows.Count > 0)
     {
         mCurrentDeviceItem      = (DeviceItem)gridDeviceSelection.CurrentRow.Tag;
         wizMain.NextEnabled     = true;
         cmdRemoveDevice.Enabled = true;
         return;
     }
     wizMain.NextEnabled     = false;
     cmdRemoveDevice.Enabled = false;
 }
 public async Task <bool> ConnectDeviceAsync(DeviceItem device)
 {
     try
     {
         await adapter.ConnectToDeviceAsync(device.Device);
     }
     catch (DeviceConnectionException ex)
     {
         Debug.WriteLine("Error ConnectDeviceAsync : " + ex);
     }
     return(true);
 }
        private static bool HasLayout(Item item, DeviceItem device)
        {
            bool hasLayout = false;

            if (item != null && item.Visualization != null)
            {
                ID layoutId = item.Visualization.GetLayoutID(device);
                hasLayout = Guid.Empty != layoutId.Guid;
            }

            return(hasLayout);
        }
        /// <summary>
        /// Сохраняет в базе модель создания элемента.
        /// </summary>
        /// <param name="token">Токен безопасности.</param>
        /// <param name="model">Модель создания сущности для сохранения.</param>
        /// <param name="result">Результат выполнения..</param>
        /// <param name="isEdit">Признак редактирования модели. </param>
        private void SaveModel(SecurityToken token, DeviceItemEditModel model, SaveModelResult result, bool isEdit)
        {
            if (model.WarehouseItemID == null && string.IsNullOrWhiteSpace(model.DeviceItemTitle))
            {
                result.ModelErrors.Add(new PairItem <string, string>("DeviceItemTitle", "Введите название запчасти или выберите ее из склада"));
                return;
            }

            var entity = new DeviceItem
            {
                Price               = (double)WpfUtils.StringToDecimal(model.DeviceItemPrice),
                RepairOrderIDGuid   = model.RepairOrderID,
                Title               = model.DeviceItemTitle,
                CostPrice           = (double)WpfUtils.StringToDecimal(model.DeviceItemCostPrice),
                Count               = (double)WpfUtils.StringToDecimal(model.DeviceItemCount),
                DeviceItemIDGuid    = model.Id,
                EventDateDateTime   = model.DeviceItemEventDate,
                UserIDGuid          = model.DeviceItemUserID,
                WarehouseItemIDGuid = model.WarehouseItemID
            };

            DeviceItem oldItem = null;

            if (isEdit)
            {
                oldItem = ClientCore.Instance.DataStore.GetDeviceItem(entity.DeviceItemIDGuid);
            } //if

            if (entity.WarehouseItemID != null)//денормализуем данные
            {
                var item = ClientCore.Instance.DataStore.GetWarehouseItem(entity.WarehouseItemIDGuid);

                RiseExceptionIfNotFound(item, entity.WarehouseItemIDGuid, "Остаток на складе");

                entity.Title     = item.GoodsItemTitle;
                entity.Price     = item.RepairPrice;
                entity.CostPrice = item.StartPrice;
            }

            ClientCore.Instance.DataStore.SaveDeviceItem(entity);

            if (!isEdit)
            {
                ClientCore.Instance.OrderTimelineManager.TrackNewDeviceItem(token, entity);
                model.Id = entity.DeviceItemIDGuid;
            } //if

            if (oldItem != null)
            {
                ClientCore.Instance.OrderTimelineManager.TrackDeviceItemChanges(token, oldItem, entity);
            } //if
        }
Beispiel #27
0
        public void ReloadListDeviceItems()
        {
            try
            {
                int index = 0;
                Int32.TryParse(mainWindow.DeviceItemsListDg.SelectedIndex.ToString(), out index);
                if (mainWindow.unityService.deviceRegistrationService.deviceItemList.Count > 0)
                {
                    deviceItemsList.Clear();
                    foreach (DeviceItem device in mainWindow.unityService.deviceRegistrationService.deviceItemList)
                    {
                        deviceItemsList.Add(device);
                    }
                    if (GroupedDeviceItems.IsEditingItem)
                    {
                        GroupedDeviceItems.CommitEdit();
                    }
                    if (GroupedDeviceItems.IsAddingNew)
                    {
                        GroupedDeviceItems.CommitNew();
                    }
                    GroupedDeviceItems.Refresh();


                    if (mainWindow.DeviceItemsListDg.HasItems)
                    {
                        mainWindow.DeviceItemsListDg.SelectedItem = mainWindow.DeviceItemsListDg.Items[(index > -1) ? index : 0];
                        if (mainWindow.DeviceItemsListDg.SelectedItem != null)
                        {
                            DeviceItem temp = mainWindow.DeviceItemsListDg.SelectedItem as DeviceItem;
                            mainWindow.canvasControlService.ReloadListOrderItems(temp);
                        }
                    }

                    #region Khanh added 3
                    ALL_orderItemsList.Clear();
                    foreach (DeviceItem device in mainWindow.unityService.deviceRegistrationService.deviceItemList)
                    {
                        //deviceItemsList.Add(device);
                        foreach (DeviceItem.OrderItem item in device.OrderedItemList)
                        {
                            ALL_orderItemsList.Add(item);
                        }
                    }
                    ALL_OrderItems.Refresh();
                    //ALL_OrderItems.SortDescriptions.Clear();
                    //ALL_OrderItems.SortDescriptions.Add(new SortDescription("dateTime", ListSortDirection.Descending));
                    #endregion
                }
            }
            catch { Console.WriteLine("Error in ReloadListDeviceItems"); }
        }
        public static bool HasPresentation(this Item item, DeviceItem device)
        {
            if (item == null || device == null)
            {
                return(false);
            }
            if (item.Visualization.Layout == null)
            {
                return(false);
            }

            return(item.Visualization.GetLayout(device) != null);
        }
Beispiel #29
0
        private void SetAmp()
        {
            DeviceRecords devices = Sitecore.Context.Item?.Database.Resources.Devices;

            if (devices != null)
            {
                DeviceItem defaultDevice = devices?.GetAll()?.Where(d => d.Name.ToLower() == "amp").FirstOrDefault();
                if (defaultDevice != null)
                {
                    Sitecore.Context.Device = defaultDevice;
                }
            }
        }
 private void CkbEnable_Changed(object sender, RoutedEventArgs e)
 {
     if (ckbEnable.IsChecked == true)
     {
         DeviceItem.Start();
         spcDev.enable();
     }
     else
     {
         DeviceItem.Stop();
         spcDev.disable();
     }
 }
Beispiel #31
0
 public void RefreshDeviceBaseInforListView(DeviceItem device)
 {
     this.listViewDevice.Items[0].SubItems[1].Text = device.model;
     this.listViewDevice.Items[1].SubItems[1].Text = device.name;
     this.listViewDevice.Items[2].SubItems[1].Text = device.modelId;
     this.listViewDevice.Items[3].SubItems[1].Text = device.deviceId;
     this.listViewDevice.Items[4].SubItems[1].Text = device.hardwareVersion;
     this.listViewDevice.Items[5].SubItems[1].Text = device.softwareVersion;
     this.listViewDevice.Items[6].SubItems[1].Text = device.mcuBinVersion;
     this.listViewDevice.Items[7].SubItems[1].Text = device.onlineText;
     this.listViewDevice.Items[8].SubItems[1].Text = device.registedText;
     this.listViewDevice.Items[9].SubItems[1].Text = DateTime.Now.ToString();
 }
Beispiel #32
0
 private void RefreshlistViewRealDevicesSelectedItem()
 {
     if (this.listViewRealDevices.SelectedItems.Count == 1)
     {
         DeviceItem device = (DeviceItem)this.listViewRealDevices.SelectedItems[0].Tag;
         Program.TestManager.UpdateActiveDevice(device);
         Program.TestManager.projectService.GenerateLabelContent(device);
         this.RefreshDevicePropertysListView(device);
         this.textBoxDeviceId.Text     = device.deviceId;
         this.buttonAutoTest.Enabled   = device.online;
         this.buttonManualTest.Enabled = device.online;
     }
 }
Beispiel #33
0
            // Device items
            private static void handleDeviceItem(IList <HmiTarget> hmi, DeviceItem item)
            {
                SoftwareContainer sw_cont = item.GetService <SoftwareContainer>();

                if (sw_cont != null)
                {
                    if (sw_cont.Software is HmiTarget hmi_target)
                    {
                        hmi.Add(hmi_target);
                    }
                }
                IterDeviceItem(hmi, item.DeviceItems);
            }
        /// <summary>
        /// 	Gets the device definition for a given item and device.
        /// </summary>
        /// <param name = "theItem">The item.</param>
        /// <param name = "device">The device.</param>
        /// <returns>The device definition if it was found, null otherwise</returns>
        public static DeviceDefinition GetDeviceDefinition(Item theItem, DeviceItem device)
        {
            if (theItem == null || device == null) return null;

            //Make sure there is a renderings string
            string renderingString = theItem.Fields["__renderings"].Value;
            if (string.IsNullOrEmpty(renderingString)) return null;

            //Try and retrieve the layout definition by parsing the rendering string
            LayoutDefinition layout = LayoutDefinition.Parse(renderingString);
            if (layout == null) return null;

            //Try and get the device definition from the layout definition
            return layout.GetDevice(device.ID.ToString());
        }
Beispiel #35
0
        public MainWindow()
        {
            InitializeComponent();

            _defaultCodeTypeItems = new List<CodeTypeItem>
                {
                    new CodeTypeItem {DisplayName = "C# Expresssion", CodeType = CodeTypes.Expression},
                    new CodeTypeItem {DisplayName = "C# Statements", CodeType = CodeTypes.Statements},
                    new CodeTypeItem {DisplayName = "C# Program", CodeType = CodeTypes.Program}
                };

            _currentDevice = new DeviceItem
            {
                DeviceAddress = "__LOCAL__",
                DeviceType = DeviceTypes.Local,
                DeviceName = "Local"
            };
            _currentCodeType = _defaultCodeTypeItems[1];
        }
        /// <summary>
        /// Returns the url for a specified item and a specific device.  UrlOptions will be used
        /// if they are provided, but are not required.  If successful, a url for the item will be
        /// returned.  If not successfully, an empty string will be returned.
        /// </summary>
        /// <param name="item">The item to get the url for.</param>
        /// <param name="device">[optional] The device for the url.</param>
        /// <param name="urlOptions">[optional] The url parameters for the url.</param>
        /// <returns>The url to the item provided.</returns>
        public static string GetDeviceUrlForItem(Item item, DeviceItem device, UrlOptions urlOptions)
        {
            //if an item was not provided then just return empty string
            if (item == null)
            {
                return string.Empty;
            }

            //get our item url depending on if url options were provided or not
            string itemUrl = string.Empty;
            if (urlOptions != null)
            {
                itemUrl = LinkManager.GetItemUrl(item, urlOptions);
            }
            else
            {
                itemUrl = LinkManager.GetItemUrl(item);
            }

            //if our item url is null or empty then just return empty string
            if (string.IsNullOrEmpty(itemUrl))
            {
                return string.Empty;
            }

            //get our device url parameter
            string deviceUrlParam = string.Empty;
            if (device != null)
            {
                deviceUrlParam = device.QueryString;
            }

            //if we don't have a device url parameter then return our item url
            //this could be the default device, which does not have a url parameter.
            if (string.IsNullOrEmpty(deviceUrlParam))
            {
                return itemUrl;
            }

            //return our item url with the device url parameter attached
            return string.Concat(itemUrl, "?", deviceUrlParam);
        }
Beispiel #37
0
        private void DevicesComboBox_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            _currentDevice = DevicesComboBox.SelectedItem as DeviceItem;
            if (_currentDevice == null) return;
            _currentDevice.DeviceAddress = _currentDevice.DeviceAddress;
            _htmlHolder.innerHTML = String.Format("Connected to device '{0}' on [{1}]", _currentDevice.DeviceName, _currentDevice.DeviceAddress);
            Title = String.Format("ProtoPad - {0}", DevicesComboBox.Text);

            _projectAssembly.AssemblyReferences.Clear();

            var assemblyLoader = new BackgroundWorker();
            assemblyLoader.DoWork += DotNetProjectAssemblyReferenceLoader;
            assemblyLoader.RunWorkerAsync();

            _referencedAssemblies.Clear();

            SetText();

            SendCodeButton.IsEnabled = true;
            LoadAssemblyButton.IsEnabled = true;

            var wrapText = EditorHelpers.GetWrapText(EditorHelpers.CodeType.Expression, _currentDevice.DeviceType);
            var getFolderCode = wrapText.Replace("__STATEMENTSHERE__", _currentDevice.DeviceType == DeviceTypes.iOS
                                                       ? "Environment.GetFolderPath(Environment.SpecialFolder.Personal)"
                                                       : ""); //todo: Android
            var result = SendCode(_currentDevice.DeviceAddress, false, getFolderCode);
            if (result == null) return;
            var folder = result.Results.FirstOrDefault();
            if (folder != null)
            {
                StatusLabel.Content = folder.Item2.PrimitiveValue.ToString();
            }
        }
        private void BuildDevice(GridPanel grid, LayoutDefinition layout, DeviceItem deviceItem)
        {
            Assert.ArgumentNotNull(grid, "grid");
            Assert.ArgumentNotNull(deviceItem, "deviceItem");

            var xmlControl = string.IsNullOrEmpty(OpenDeviceClick)
                ? Resource.GetWebControl("LayoutFieldDeviceReadOnly") as XmlControl
                : Resource.GetWebControl("LayoutFieldDevice") as XmlControl;

            Assert.IsNotNull(xmlControl, typeof(XmlControl));

            grid.Controls.Add(xmlControl);

            string str1 = StringUtil.GetString(OpenDeviceClick).Replace("$Device", deviceItem.ID.ToString());
            string str2 = StringUtil.GetString(CopyToClick).Replace("$Device", deviceItem.ID.ToString());

            ReflectionUtil.SetProperty(xmlControl, "DeviceName", deviceItem.DisplayName);
            ReflectionUtil.SetProperty(xmlControl, "DeviceIcon", deviceItem.InnerItem.Appearance.Icon);
            ReflectionUtil.SetProperty(xmlControl, "DblClick", str1);
            ReflectionUtil.SetProperty(xmlControl, "Copy", str2);

            string str3 = string.Format("<span style=\"color:#999999\">{0}</span>", Translate.Text("[No layout specified]"));

            int index = 0;
            int num = 0;
            var parent1 = xmlControl["ControlsPane"] as System.Web.UI.Control;
            var parent2 = xmlControl["PlaceholdersPane"] as System.Web.UI.Control;

            if (layout != null)
            {
                DeviceDefinition device = layout.GetDevice(deviceItem.ID.ToString());
                string layout1 = device.Layout;

                if (!string.IsNullOrEmpty(layout1))
                {
                    Item obj = Client.ContentDatabase.GetItem(layout1);
                    if (obj != null)
                    {
                        str3 = Images.GetImage(obj.Appearance.Icon, 16, 16, "absmiddle", "0px 4px 0px 0px", obj.ID.ToString()) + obj.DisplayName;
                    }
                }

                ArrayList renderings = device.Renderings;
                if (renderings != null && renderings.Count > 0)
                {
                    Border border = new Border();
                    Context.ClientPage.AddControl(parent1, border);
                    foreach (RenderingDefinition renderingDefinition in renderings)
                    {
                        int conditionsCount = 0;

                        if (renderingDefinition.Rules != null && !renderingDefinition.Rules.IsEmpty)
                        {
                            conditionsCount = Enumerable.Count(renderingDefinition.Rules.Elements("rule"));
                        }

                        BuildRendering(border, device, renderingDefinition, index, conditionsCount);
                        ++index;
                    }
                }

                ArrayList placeholders = device.Placeholders;
                if (placeholders != null && placeholders.Count > 0)
                {
                    Border border = new Border();
                    Context.ClientPage.AddControl(parent2, border);

                    foreach (PlaceholderDefinition placeholderDefinition in placeholders)
                    {
                        BuildPlaceholder(border, device, placeholderDefinition);
                        ++num;
                    }
                }
            }

            ReflectionUtil.SetProperty(xmlControl, "LayoutName", str3);

            if (index == 0)
            {
                var noRenderingsLabel = string.Format("<span style=\"color:#999999\">{0}</span>", Translate.Text("[No renderings specified.]"));
                Context.ClientPage.AddControl(parent1, new LiteralControl(noRenderingsLabel));
            }

            if (num != 0)
            {
                return;
            }

            var noPlaceholdersLabel = string.Format("<span style=\"color:#999999\">{0}</span>", Translate.Text("[No placeholder settings were specified]"));
            Context.ClientPage.AddControl(parent2, new LiteralControl(noPlaceholdersLabel));
        }
Beispiel #39
0
    /// <summary>
    /// Chekcs if current sitecore item has print layout
    /// </summary>
    /// <returns>The result.</returns>
    public static bool CurrentItemHasPrintLayout()
    {
      Item item = Sitecore.Context.Item;
      if (item == null)
      {
        return false;
      }

      Item print = Sitecore.Context.Device.InnerItem.Axes.SelectSingleItem("../*[@@name='Print']");
      if (print != null)
      {
        var device = new DeviceItem(print);
        RenderingReference[] renderings = item.Visualization.GetRenderings(device, false);
        return renderings != null && renderings.Length != 0;
      }

      return false;
    }
Beispiel #40
0
        public MainWindow()
        {
            InitializeComponent();

            _currentDevice = new DeviceItem
                {
                    DeviceAddress = "http://192.168.1.104:8080/",
                    DeviceName = "Yarvik",
                    DeviceType = DeviceTypes.Android
                };
            // NOTE: Make sure that you've read through the add-on language's 'Getting Started' topic
            //   since it tells you how to set up an ambient parse request dispatcher and an ambient
            //   code repository within your application OnStartup code, and add related cleanup in your
            //   application OnExit code.  These steps are essential to having the add-on perform well.

            // Initialize the project assembly (enables support for automated IntelliPrompt features)
            _projectAssembly = new CSharpProjectAssembly("SampleBrowser");
            var assemblyLoader = new BackgroundWorker();
            assemblyLoader.DoWork += DotNetProjectAssemblyReferenceLoader;
            assemblyLoader.RunWorkerAsync();

            // Load the .NET Languages Add-on C# language and register the project assembly on it
            var language = new CSharpSyntaxLanguage();
            language.RegisterProjectAssembly(_projectAssembly);

            CodeEditor.Document.Language = language;

            CodeEditor.Document.Language.RegisterService(new IndicatorQuickInfoProvider());

            CodeEditor.PreviewKeyDown += (sender, args) =>
                {
                    if (args.Key != Key.Enter || (Keyboard.Modifiers & ModifierKeys.Control) != ModifierKeys.Control) return;
                    SendCodeButton_Click(null,null);
                    args.Handled = true;
                };

            _udpDiscoveryClient = new UdpDiscoveryClient(
            //                ready => Dispatcher.Invoke((Action) (() => SendCodeButton.IsEnabled = ready)),
                ready => { },
                (name, address) => Dispatcher.Invoke(() =>
                    {
                        if (address.Contains("?")) address = address.Replace("?", AndroidPort);
                        var deviceItem = new DeviceItem
                            {
                                DeviceAddress = address,
                                DeviceName = name,
                                DeviceType = name.StartsWith("ProtoPad Service on ANDROID Device ") ? DeviceTypes.Android : DeviceTypes.iOS
                            };
                        if (!DevicesComboBox.Items.Cast<object>().Any(i => (i as DeviceItem).DeviceAddress == deviceItem.DeviceAddress))
                        {
                            DevicesComboBox.Items.Add(deviceItem);
                        }
                        DevicesComboBox.IsEnabled = true;
                        //ResultTextBox.Text += String.Format("Found '{0}' on {1}", name, address);
                    }));
            ResultTextBox.Navigated += (sender, args) =>
                {
                    var htmlDocument = ResultTextBox.Document as HTMLDocument;
                    _htmlHolder = htmlDocument.getElementById("wrapallthethings") as HTMLDivElementClass;
                    _htmlWindow = htmlDocument.parentWindow;
                    _udpDiscoveryClient.SendServerPing();
                    var ticksPassed = 0;
                    var dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
                    dispatcherTimer.Tick += (s, a) =>
                        {
                            if (ticksPassed > 2)
                            {
                                dispatcherTimer.Stop();
                                if (DevicesComboBox.Items.Count == 1)
                                {
                                    DevicesComboBox.SelectedIndex = 0;
                                }
                            }
                            _udpDiscoveryClient.SendServerPing();
                            ticksPassed++;
                        };
                    dispatcherTimer.Interval = TimeSpan.FromMilliseconds(200);
                    dispatcherTimer.Start();
                };
            ResultTextBox.NavigateToString(Properties.Resources.ResultHtmlWrap);
        }
 /// <summary>
 /// Return the Url for for a specified item to show a certain device.  If successful
 /// this method will return the url to the item with the proper device url parameter
 /// appended.  If not successful return an empty string.
 /// </summary>
 /// <param name="item">The item.</param>
 /// <param name="device">The device.</param>
 /// <returns></returns>
 public static string GetDeviceUrlForItem(Item item, DeviceItem device)
 {
     //call over loaded method with null url options
     return GetDeviceUrlForItem(item, device, null);
 }
Beispiel #42
0
        private void ConnectToApp(DeviceItem deviceItem)
        {
            _currentDevice = deviceItem;

            var isLocal = _currentDevice.DeviceType == DeviceTypes.Local;

            ClearSimulatorWindowButton.IsEnabled = !isLocal;

            if (isLocal)
            {
                LogToResultsWindow("Running locally (regular .Net)");
            }
            else
            {
                _currentDevice.MainXamarinAssemblyName = SimpleHttpServer.SendCustomCommand(_currentDevice.DeviceAddress, "GetMainXamarinAssembly");
                if (_currentDevice.DeviceType == DeviceTypes.iOS)
                {
                    var cssFilesJson = SimpleHttpServer.SendCustomCommand(_currentDevice.DeviceAddress, "GetPixateCssFiles");
                    _currentDevice.PixateCssPaths = UtilityMethods.JsonDecode<string[]>(cssFilesJson);
                }
                LogToResultsWindow("Connected to device '{0}' on [{1}]", _currentDevice.DeviceName, _currentDevice.DeviceAddress);
            }

            UpdateCodeTypesComboBox();

            Title = String.Format("ProtoPad - {0}", _currentDevice.DeviceName);

            SetText(true);

            SendCodeButton.IsEnabled = true;
            LoadAssemblyButton.IsEnabled = true;

            StatusLabel.Content = "";

            if (_currentDevice.DeviceType != DeviceTypes.iOS)
            {
                return; // todo: locate and provide Android Emulator file path if applicable
            }

            var wrapText = EditorHelpers.GetWrapText(CodeTypes.Expression, _currentDevice.DeviceType, null);
            var getFolderCode = wrapText.Replace("__STATEMENTSHERE__", "Environment.GetFolderPath(Environment.SpecialFolder.Personal)");
            var result = SendCode(_currentDevice.DeviceAddress, false, getFolderCode);
            if (result == null || result.Results == null) return;
            var folder = result.Results.FirstOrDefault();
            if (folder == null) return;
            StatusLabel.Content = folder.ResultValue.PrimitiveValue.ToString();
        }
        /// <summary>
        /// 	Checks to see if the passed in item has presentation settings for the provided device and sublayout.
        /// </summary>
        /// <param name = "theItem">The item.</param>
        /// <param name = "device">The device.</param>
        /// <param name = "sublayoutItem">The sublayout item.</param>
        /// <returns>True if the item contains the device and sublayout in it's presentation settings, false otherwise.</returns>
        public static bool ItemHasPresentationSettingsForSublayout(Item theItem, DeviceItem device,
		                                                           SublayoutItem sublayoutItem)
        {
            if (theItem == null || device == null || sublayoutItem == null) return false;

            //If the item does not contain settings for the passed in device do not bother with the
            // rest of the check.
            if (!ItemHasPresentationSettingsForDevice(theItem, device)) return false;

            //Try and get the device definition from the layout definition
            DeviceDefinition deviceDef = GetDeviceDefinition(theItem, device);
            if (deviceDef == null) return false;

            //Try and get the rendering for the passed in display item
            RenderingDefinition rendering = deviceDef.GetRendering(sublayoutItem.ID.ToString());

            return !(rendering == null);
        }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="deviceItem"></param>
 public string DeviceQuery(DeviceItem deviceItem)
 {
     return deviceItem.QueryString;
 }
        /// <summary>
        /// 	Checks to see if the passed in item has presentation settings for the provided device and layout.
        /// </summary>
        /// <param name = "theItem">The item.</param>
        /// <param name = "device">The device.</param>
        /// <param name = "layoutItem">The layout item.</param>
        /// <returns>True if the item contains the device and layout in it's presentation settings, false otherwise.</returns>
        public static bool ItemHasPresentationSettingsForLayout(Item theItem, DeviceItem device, LayoutItem layoutItem)
        {
            if (theItem == null || device == null || layoutItem == null) return false;

            //If the item does not contain settings for the passed in device do not bother with the
            // rest of the check.
            if (!ItemHasPresentationSettingsForDevice(theItem, device)) return false;

            //Try and get the device definition from the layout definition
            DeviceDefinition deviceDef = GetDeviceDefinition(theItem, device);
            if (deviceDef == null) return false;
            if (deviceDef.Layout == null || deviceDef.Renderings == null) return false;

            return (deviceDef.Layout == layoutItem.ID.ToString());
        }