internal static void HandleCommandProp(Command command, PropertyInfo prop, out ICommandParameter parameter) { parameter = null; var definedArgument = prop.IsDefined(typeof(CommandArgumentAttribute), false); var definedProperty = prop.IsDefined(typeof(CommandPropertyAttribute), false); if (definedArgument && definedProperty) { var message = "Command parameter cannot be defined as argument and property simultaneously"; throw new CommandParameterException(message, prop.Name); } if (definedArgument) { var attribute = prop.GetCustomAttribute <CommandArgumentAttribute>(); parameter = GetCommandParameter(command, prop, attribute); command.Context.arguments[prop.Name] = parameter; } if (definedProperty) { var attribute = prop.GetCustomAttribute <CommandPropertyAttribute>(); parameter = GetCommandParameter(command, prop, attribute); command.Context.properties[prop.Name] = parameter; } }
/// <summary> /// Command handler which adds a new gtype to the project that is derived from the gtype currently being edited /// </summary> public static void OnAddNewDerviedType(ICommandParameter parameter, ICompositionHost host, DocumentEditSite site) { // Check to see that the user is currently editing a type and if not do nothing. // The edit site provides access to the state of the editor. Here we are checking to see of the active document // is a gtype by looking at the definition that is being edited. The definition is the model of the object being // edited var gType = (GTypeDefinition)site?.ActiveDocument?.Envoy?.ReferenceDefinition; if (gType == null) { return; } // Get the project being edited var project = host.GetSharedExportedValue <IDocumentManager>().ActiveProject; // Setup the create info for a gtype. var createInfo = EnvoyCreateInfo.CreateForNew(GTypeDefinition.ModelDefinitionTypeString, new QualifiedName("New Derived Type.gtype")); // The LockedSourceFile is an object which holds a document in memory ILockedSourceFile lockSourceFile; // Always perform modifications from within a transaction // Here we are creating a user transaction which means it is undoable using (var transaction = project.TransactionManager.BeginTransaction("Add A Type", TransactionPurpose.User)) { lockSourceFile = project.CreateNewFile(null, createInfo); transaction.Commit(); } // Here we are setting the base type based on the type that is currently being edited. using (var transaction = lockSourceFile.Envoy.ReferenceDefinition.TransactionManager.BeginTransaction("Make Type A Class", TransactionPurpose.NonUser)) { ((GTypeDefinition)lockSourceFile.Envoy.ReferenceDefinition).BaseTypeQualifiedName = gType.Name; transaction.Commit(); } }
/// <summary> /// Release lock /// </summary> /// <param name="parameter"></param> /// <param name="host"></param> /// <param name="site"></param> public static void ReleaseLock(ICommandParameter parameter, ICompositionHost host, DocumentEditSite site) { var debugHost = host.GetSharedExportedValue <IDebugHost>(); try { var filePath = ((Envoy)parameter.Parameter).GetFilePath(); var svnManager = host.GetSharedExportedValue <SvnManagerPlugin>(); var success = svnManager.ReleaseLock(filePath); if (success) { var envoy = ((Envoy)parameter.Parameter); var projectItem = envoy.GetProjectItemViewModel(site); if (null != projectItem) { projectItem.RefreshIcon(); } debugHost.LogMessage(new DebugMessage("Viewpoint.Svn", DebugMessageSeverity.Information, $"Release Lock {filePath}")); } } catch (Exception e) { debugHost.LogMessage(new DebugMessage("Viewpoint.Svn", DebugMessageSeverity.Error, $"Failed to Release Lock {e.Message}")); Console.WriteLine(e); const string caption = "Error SVN"; var result = MessageBox.Show(e.Message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
internal static void BuildParameterDictionary(Command command) { var propertyType = command.GetType(); var props = propertyType.GetProperties() .Where((prop) => prop.CanWrite && prop.CanRead); ICommandParameter previousParameter = null; foreach (var prop in props) { HandleCommandProp(command, prop, out var parameter); if (parameter != null) { if (previousParameter != null) { var prevRequired = previousParameter.Context.Required; var currRequired = parameter.Context.Required; if (!prevRequired && currRequired) { var prevName = previousParameter.Context.Name; var message = $"Required parameter: \"{prop.Name}\" is preceded by a non required parameter: \"{prevName}\""; throw new CommandParameterException(message, prop.Name); } } previousParameter = parameter; } } }
protected virtual void AssignDynamicValue(ICommandParameter parameter, string value, Parameter model) { var expressions = model.Expressions.Select(e => e.Text); var dynamicValue = new DynamicValue(Command.PlaybackSpot, value, expressions); parameter.SetValue(dynamicValue); }
/// <summary> /// This is the command handler that will add the code to multiple the output of the random number primitive by 10 /// This is called when the user presses the Multiply By 10 button /// </summary> /// <param name="parameter">The command parameter associated with instance of the command</param> /// <param name="selection">The current selection</param> /// <param name="host">The Composition host for the session</param> /// <param name="site">The document edit site which is managing the edit session</param> public static void OnMultipleBy10(ICommandParameter parameter, IEnumerable <IViewModel> selection, ICompositionHost host, DocumentEditSite site) { // The selected item will be the random number node since we only add this command for random numbers var node = selection.First().Model as Node; if (node == null) { return; } // Start a transaction and add content to multiply the output by 10 using (var transaction = node.TransactionManager.BeginTransaction("Multiple By 10", TransactionPurpose.User)) { // Create a multiple node, position it nicely to the right ot the random number, and add it to the same diagram var multiply = Multiply.Create(ElementCreateInfo.ForNew); multiply.TopLeft = new SMPoint(node.Bounds.Right + StockDiagramGeometries.StandardNodeWidth, node.Top + (2 * StockDiagramGeometries.GridSize)); node.Diagram.AddNode(multiply); // Wire the random number output to the first input on the multiple node node.Diagram.WireWithin((NodeTerminal)node.OutputTerminals.First(), (NodeTerminal)multiply.InputTerminals.First()); // Create a Double Numeric Constant with an initial value of 10.0 var literal = Literal.Create(NITypes.Double, 10.0); // Position the constant nicely and add it to the diagram literal.TopLeft = new SMPoint(node.Left + StockDiagramGeometries.TinyNodeWidth, node.Bounds.Bottom + (2 * StockDiagramGeometries.GridSize)); node.Diagram.AddNode(literal); // Wire the constant to the multiply node node.Diagram.WireWithin(literal.OutputTerminal, (NodeTerminal)multiply.InputTerminals.ElementAt(1)); // Commit the transaction to finish the operation transaction.Commit(); } }
private static void ChangeHeader(ICommandParameter parameter, ICompositionHost host, DocumentEditSite site) { var document = (FunctionDocument)site.ActiveDocument; bool showHeader = true; switch ((string)parameter.Parameter) { case "ToggleHeader": showHeader = document._alertId == Guid.Empty; break; case "ToggleDone": document._showHideDoneButton ^= true; break; case "ChangeText": document._headerText = TextCommandParameter.GetText(parameter); break; } site.ActiveDocumentEditor.RemoveAlert(document._alertId); document._alertId = Guid.Empty; if (showHeader) { string tooltip = "Here you will see additional information"; document._alertId = site.ActiveDocumentEditor.AddAlert(null, document._headerText, tooltip, null, document._showHideDoneButton); } }
/// <summary> /// Command handler which adds a new gtype to the project /// </summary> public static void OnAddNewType(ICommandParameter parameter, ICompositionHost host, DocumentEditSite site) { var project = host.GetSharedExportedValue <IDocumentManager>().ActiveProject; var createInfo = EnvoyCreateInfo.CreateForNew(GTypeDefinition.ModelDefinitionTypeString, new QualifiedName("New Type.gtype")); ILockedSourceFile lockSourceFile; using (var transaction = project.TransactionManager.BeginTransaction("Add A Type", TransactionPurpose.User)) { lockSourceFile = project.CreateNewFile(null, createInfo); lockSourceFile.Envoy.UpdateStoragePath("Classes\\New Member VI.gvi"); transaction.Commit(); } // To create a class we need to set the base type to whatever we want. The default base type for a class is GObject // We don't point to the base directly and instead we set the QualifiedName of the base class we want. The linker will then // find the base type by name and hook everything up based on the project configuration. using (var transaction = lockSourceFile.Envoy.ReferenceDefinition.TransactionManager.BeginTransaction("Make Type A Class", TransactionPurpose.NonUser)) { ((GTypeDefinition)lockSourceFile.Envoy.ReferenceDefinition).BaseTypeQualifiedName = TargetCommonTypes.GObjectQualifiedName; transaction.Commit(); } lockSourceFile?.Envoy?.Edit(); // After editing dispose our lock in the file lockSourceFile?.Dispose(); }
/// <summary> /// This will be called in response to a user making a selection in the command bar/popup menu, which is were we want to update the model. We have provided /// some extensions that encapsulate this process which involves transactions. /// </summary> private static void ChangeTemperatureScale(ICommandParameter parameter, IEnumerable <IViewModel> selection, ICompositionHost host, DocumentEditSite site) { var fanSpeed = (FanSpeed)parameter.QueryService <ControlCommandParameter>().FirstOrDefault().Parameter; var models = selection.GetSelectedModels <FanModel>(); // useful extension to easily perform updates on models through transactions ITransactionManagerExtensions.TransactOnElements(models, "Change fan speed", model => model.FanSpeed = fanSpeed); }
public static void OnOpenInNotepad(ICommandParameter parameter, ICompositionHost host, DocumentEditSite site) { var text = (site.EditControl.Document.Envoy.ReferenceDefinition as TextDocumentDefinition).Text; var fileName = Path.GetTempFileName(); File.WriteAllText(fileName, text); Process.Start("Notepad.exe", fileName); }
protected virtual void AssignValue(ICommandParameter parameter, string value) { parameter.SetValue(value, out var errors); if (!string.IsNullOrEmpty(errors)) { AddError(errors); } }
private void init() { _empty = CommandParameter.CreateEmpty(Constants.BasicSuccessfulResponse); _generalInfo = new SimpleATCommand(ATCommand.DefaultInfo.Command(), _empty); _rssi = new SimpleATCommand(ATCommand.ReceivedSignalStrengthInfo.Command(), _empty); _rscp = new SimpleATCommand(ATCommand.ReceivedSignalCodePowerInfo.Command(), _empty); _sysInfo = new SimpleATCommand(ATCommand.SystemInfo.Command(), _empty); }
/// <summary> /// Command handler which shows the data type of the selected terminal /// </summary> public static void OnShowTerminalType(ICommandParameter parameter, ICompositionHost host, DocumentEditSite site) { var viewModel = parameter.QueryService <NodeTerminalViewModel>().FirstOrDefault(); if (viewModel != null) { NIMessageBox.Show("The terminal type is: " + viewModel.DataType.ToString()); } }
private static void OnSoundCommand(ICommandParameter parameter, IEnumerable <IViewModel> selection, ICompositionHost host, DocumentEditSite site) { var viewModel = selection.FirstOrDefault() as InteractiveNodeViewModel; if (viewModel != null) { viewModel.Sound = string.Concat(parameter.LabelTitle.Split(new[] { ' ' }, 3).Skip(2)); } }
protected virtual bool TryCreateParameter(FieldInfo field, out ICommandParameter parameter) { parameter = Activator.CreateInstance(field.FieldType) as ICommandParameter; if (parameter is null) { AddError($"Failed to create instance of `{field.FieldType}` parameter for `{CommandId}` command."); } return(parameter != null); }
private static void FanSpeedHighAttach(PlatformVisual visual, ICommandParameter parameter, IEnumerable <IViewModel> selection, ICompositionHost host, DocumentEditSite site) { if (!parameter.QueryService <ControlCommandParameter>().Any()) { parameter.AttachService(new ControlCommandParameter() { Parameter = FanSpeed.High }); } }
public static bool UpdateIsActive(ICommandParameter parameter, IEnumerable <IViewModel> selection, ICompositionHost host, DocumentEditSite site) { var checkableParameter = parameter as ICheckableCommandParameter; if (checkableParameter != null) { checkableParameter.IsChecked = CommandHelpers.GetCheckedState(selection.OfType <InteractiveNodeViewModel>(), vm => vm.IsActive); } return(true); }
/// <summary> /// Command handler which writes the active definition to a temporary merge script and opens that script in notepad. /// </summary> public static void OnOpenInNotepad(ICommandParameter parameter, ICompositionHost host, DocumentEditSite site) { var activeDefinition = site?.EditControl?.Document?.Envoy?.ReferenceDefinition; if (activeDefinition != null) { var fileName = Path.GetTempFileName(); File.WriteAllText(fileName, MergeScriptBuilder.Create(activeDefinition.ToEnumerable(), host).ToString()); Process.Start("Notepad.exe", fileName); } }
private async Task <bool> executeStep(ICommandParameter step, IPortPlug port) { _currentCommand = step.IsNextParameter ? string.Empty : Command; _currentOperator = step.IsNextParameter ? string.Empty : "="; _currentParam = step.Value; Parameter = step; await base.ExecuteAsync(port); return(base.Succeeded()); }
public SimpleATCommand(string command, ICommandParameter emptyParameter) { init(command); if (emptyParameter == null || !emptyParameter.IsEmpty || string.IsNullOrWhiteSpace(emptyParameter.SuccessfulResponsePattern)) { throw new ArgumentException("Parameter not empty or not specified."); } Parameter = emptyParameter; }
private static void FanSpeedLowAttach(PlatformVisual visual, ICommandParameter parameter, IEnumerable <IViewModel> selection, ICompositionHost host, DocumentEditSite site) { // This allows us to pass specific information to a common handler used by multiple commands. Otherwise, we would have redundant code for // three different commands if (!parameter.QueryService <ControlCommandParameter>().Any()) { parameter.AttachService(new ControlCommandParameter() { Parameter = FanSpeed.Low }); } }
public ParamATCommand(string command, ICommandParameter parameter) : base(command) { if (parameter == null || parameter.IsEmpty || string.IsNullOrWhiteSpace(parameter.Value) || string.IsNullOrWhiteSpace(parameter.SuccessfulResponsePattern)) { throw new ArgumentException("Parameter not specified or empty."); } Command = Command.TrimEnd('='); Parameter = parameter; HasParameters = true; }
private ICommandParameter <TDynamic>[] createColumn() { var type = typeof(TDynamic); var properties = type.GetProperties(); var array = new ICommandParameter <TDynamic> [properties.Length]; for (var i = 0; i < properties.Length; i++) { array[i] = createParameter(properties[i]); } return(array); }
private static bool UpdateParameterFromModeValue(ICommandParameter parameter, IEnumerable <IViewModel> selection, SelfTypeMode mode) { var selfType = FindSelfType(selection); if (selfType == null) { return(false); } ((ICheckableCommandParameter)parameter).IsChecked = selfType.Mode == mode; return(mode != SelfTypeMode.Variant || RebarFeatureToggles.IsVariantTypesEnabled); }
private void init() { _empty = CommandParameter.CreateEmpty(Constants.BasicSuccessfulResponse); _storageQuery = new SimpleATCommand(ATCommand.MessageStorageInfo.Command(), _empty); var listParam = new CommandParameter(Constants.MessageStatus.Any.ToValueString(), Constants.BasicSuccessfulResponse); _listQuery = new ParamATCommand(ATCommand.MessageList.Command(), listParam); var mfParam = new CommandParameter(Constants.MessageFormat.Pdu.ToValueString(), Constants.BasicSuccessfulResponse); _mfCmd = new ParamATCommand(ATCommand.MessageFormat.Command(), mfParam); }
private static void ChangeFanSpeedCombo(ICommandParameter parameter, IEnumerable <IViewModel> selection, ICompositionHost host, DocumentEditSite site) { var choiceParameter = parameter.QueryService <ChoiceCommandParameter>().FirstOrDefault(); if (choiceParameter != null) { var model = ((FanModel)((FanViewModel)selection.First()).Model); using (var transaction = model.TransactionManager.BeginTransaction("Change Spped", TransactionPurpose.User)) { model.FanSpeed = (FanSpeed)choiceParameter.Chosen; transaction.Commit(); } } }
/// <summary> /// </summary> public static void OnSaveBetter(ICommandParameter parameter, ICompositionHost host, DocumentEditSite site) { var path = parameter.Parameter as string; Process saveBetter = new Process(); saveBetter.StartInfo.UseShellExecute = false; saveBetter.StartInfo.CreateNoWindow = true; saveBetter.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; saveBetter.StartInfo.Arguments = path; saveBetter.StartInfo.FileName = "SaveBetter.jar"; saveBetter.Start(); saveBetter.WaitForExit(); /// NIMessageBox.Show(path); }
/// <summary> /// This command create a merge script string from the selection of the active editor. Merge scripts are what are used /// for the clipboard, palette entries, and drag drop. Merge scripts are basically mini versions of our persisted source /// file format. Merge scripts are also useful for scripting use cases where merge scripts can be pased onto a diagram, /// wired together and modified. Using merge scripts as templates is easier than writing a bunch on scripting code by hand. /// </summary> public static void OnCreateMergeScriptFromSelection(ICommandParameter parameter, ICompositionHost host, DocumentEditSite site) { var selection = site.ActiveSelection.OfType <IElementViewModel>(); if (!selection.Any()) { return; } // Create an Element selection is which a selection model for the selected view models var elementSelection = SelectionToolViewModel.CreateElementSelection(selection, true); // Get the text from the merge script _lastMergeScript = elementSelection.CopyMergeScript(host); }
/// <summary> /// SVN Commit /// </summary> /// <param name="parameter"></param> /// <param name="host"></param> /// <param name="site"></param> public static void Commit(ICommandParameter parameter, ICompositionHost host, DocumentEditSite site) { var debugHost = host.GetSharedExportedValue <IDebugHost>(); try { var filePath = ((Envoy)parameter.Parameter).GetFilePath(); //moved up here, after ShowDialog() envoy returns null var envoy = ((Envoy)parameter.Parameter); var projectItem = envoy.GetProjectItemViewModel(site); //note - no built in service to manage creating view/viewmodels, done by hand var commitViewModel = new CommitViewModel(); commitViewModel.FilePath = filePath; var commitView = new CommitView(commitViewModel); commitView.Owner = (Window)site.RootVisual; commitView.ShowDialog(); if (commitViewModel.OkButtonClicked) { var svnManager = host.GetSharedExportedValue <SvnManagerPlugin>(); var success = svnManager.Commit(filePath, commitViewModel.CommitMessage); if (success) { //if uncommented and done here null ref //var envoy = ((Envoy)parameter.Parameter); //var projectItem = envoy.GetProjectItemViewModel(site); if (null != projectItem) { projectItem.RefreshIcon(); } debugHost.LogMessage(new DebugMessage("Svn", DebugMessageSeverity.Information, $"Commit {filePath}")); } } } catch (Exception e) { Console.WriteLine(e); debugHost.LogMessage(new DebugMessage("Svn", DebugMessageSeverity.Error, $"Failed to Commit {e.Message}")); const string caption = "Error SVN"; var result = MessageBox.Show(e.Message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private static void SelectChannels(ICommandParameter parameter, IEnumerable <IViewModel> selection, ICompositionHost host, DocumentEditSite site) { IEnumerable <string> frequencyChannels = selection.Select(item => item.Model) .OfType <PulseWidthModulationControlModel>() .Select(model => model.FrequencyChannel) .Where(channel => !string.IsNullOrEmpty(channel)) .ToList(); IEnumerable <string> dutyCycleChannels = selection.Select(item => item.Model) .OfType <PulseWidthModulationControlModel>() .Select(model => model.DutyCycleChannel) .Where(channel => !string.IsNullOrEmpty(channel)) .ToList(); var systemDefinitionPalette = SystemDefinitionPaletteControl.Activate(site); systemDefinitionPalette.SelectNodes(dutyCycleChannels.Concat(frequencyChannels)); }