public ScriptModel BuildModel(string path)
        {
            var code = GenerateCode(path);
            var assembly = CSScript.LoadCode(code);
            var type = assembly.GetType("Scripting.DynamicClass");
            var model = new ScriptModel();

            if(type == null) {
                throw new InvalidOperationException("Could not load the script. No generated classes were found.");
            }

            var scriptInstance = Activator.CreateInstance(type);

            var targets = from field in type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
                          let isTarget = field.FieldType.Name == "Target"
                          where isTarget
                          let target = (Delegate)field.GetValue(scriptInstance)
                          let targetAction = new Action(() => target.DynamicInvoke())
                          let description = GetDescription(field)
                          let dependencies = GetDependencies(field)
                          select new { action = targetAction, name = field.Name, description, dependencies };

            foreach(var target in targets) {
                model.AddTarget(target.name, target.dependencies, target.action, target.description);
            }

            return model;
        }
Exemple #2
0
 public Target(string name, Action block, string[] dependencies, string description, ScriptModel parentScript)
 {
     Name = name;
     Description = description;
     this.block = block;
     this.parentScript = parentScript;
     dependencyNames = dependencies ?? new string[0];
 }
        public void SetFileType(object param)
        {
            File = null;
            ListViewItem item = param as ListViewItem;

            if (item == null)
            {
                return;
            }
            switch (item.Tag as string)
            {
            case "FocusTreeItem":
                File = new FocusGridModel("New file");
                Messenger.Default.Send(new NotificationMessage(this,
                                                               new ViewModelLocator().Tutorial, "NewFocusTreeFile"));
                break;

            case "LocalisationItem":
                File = new LocalisationModel("New file");
                Messenger.Default.Send(new NotificationMessage(this,
                                                               new ViewModelLocator().Tutorial, "NewLocalizationFile"));
                break;

            case "EventItem":
                File = new EventTabModel("New file");
                Messenger.Default.Send(new NotificationMessage(this,
                                                               new ViewModelLocator().Tutorial, "NewEventFile"));
                break;

            case "GenericItem":
                File = new ScriptModel("New file");
                Messenger.Default.Send(new NotificationMessage(this,
                                                               new ViewModelLocator().Tutorial, "NewScriptFile"));
                break;
            }
        }
        // save the script at the current tab
        public bool saveCertainScript(int scriptTabIdx = -1)
        {
            if (scriptTabIdx == -1)
            {
                scriptTabIdx = scriptsTabControl.SelectedIndex;
            }

            if (scriptTabIdx < 0 || SimulationManager.checkSimulating())
            {
                return(false);
            }

            // get the current tab text w/o asterisk
            string currentTabTextWithoutAsterisk = scriptsTabControl.SelectedTab.Text.ToString();

            currentTabTextWithoutAsterisk = currentTabTextWithoutAsterisk.TrimEnd('*');

            // get the script-model
            ScriptModel scriptModel = ModelManager.getScriptModelByIndex();

            // if it's the twice or more times to save the file,
            // no need to prompt a save-dialog
            if (scriptModel.hasBeenSavedAtLeastOneTime())
            {
                // have unsaved changes
                if (scriptModel.HaveUnsavedChanges)
                {
                    // build the new path, including path, file name, and extension
                    int    lastIdxOfSeperator = scriptModel.SavedFilePath.LastIndexOf('\\');
                    string newPath;
                    if (lastIdxOfSeperator >= 0)
                    {
                        newPath = scriptModel.SavedFilePath.Substring(0, lastIdxOfSeperator + 1) + currentTabTextWithoutAsterisk + ".sms";
                    }
                    else
                    {
                        newPath = currentTabTextWithoutAsterisk + ".sms";
                    }

                    // store the file path to the script-model
                    scriptModel.SavedFilePath      = newPath;
                    scriptModel.HaveUnsavedChanges = false;

                    // serialize
                    SerializationManager.serialize(scriptModel, newPath);

                    // trim the asterisk at the end
                    scriptsTabControl.SelectedTab.Text = scriptsTabControl.SelectedTab.Text.TrimEnd('*');

                    return(true);
                }

                return(false);
            }



            /* prompt a save-dialog */

            // create a save-file-dialog
            SaveFileDialog saveScriptDialog = new SaveFileDialog();

            saveScriptDialog.DefaultExt       = "sms";
            saveScriptDialog.RestoreDirectory = true;
            saveScriptDialog.FileName         = currentTabTextWithoutAsterisk;

            // save the file succesfully
            if (saveScriptDialog.ShowDialog() == DialogResult.OK)
            {
                // get the file name with the path and an extension "sms"
                string fileNameWithPath = saveScriptDialog.FileName;
                if (!fileNameWithPath.EndsWith(".sms"))
                {
                    fileNameWithPath += ".sms";
                }

                // the pre-saving file path, possible as null
                string origPathOrNull = scriptModel.SavedFilePath;

                // do serialization for saving the file
                try {
                    // store the file path to the script-model
                    scriptModel.SavedFilePath      = fileNameWithPath;
                    scriptModel.HaveUnsavedChanges = false;

                    // get the file name w/o path and extension
                    int    lastIdxOfDot              = fileNameWithPath.LastIndexOf('.');
                    int    lastIdxOfSeperator        = fileNameWithPath.LastIndexOf('\\');
                    string fileNameWithoutPathAndExt = fileNameWithPath.Substring(lastIdxOfSeperator + 1, lastIdxOfDot - lastIdxOfSeperator - 1);

                    // rename the script
                    ModelManager.renameScript(fileNameWithoutPathAndExt, true);
                    scriptsTabControl.SelectedTab.Text = fileNameWithoutPathAndExt;

                    // serialize
                    SerializationManager.serialize(scriptModel, fileNameWithPath);
                } catch (Exception) {
                    new AlertForm("Error happened", "Unfortunately, errors happened when saving the file. Operation failed.").ShowDialog();
                    scriptModel.SavedFilePath = origPathOrNull;
                    throw;
                    return(false);
                }

                return(true);
            }

            // no saving
            return(false);
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            Log.Debug(TAG, "OnCreate");
            base.OnCreate(savedInstanceState);

            lock (DatabaseContext.DbLocker)
            {
                using (DatabaseContext db = new DatabaseContext(gs.DatabasePathBase))
                {
                    scriptHardware = db.Scripts.Include(x => x.Commands).Include(x => x.TriggerPort).FirstOrDefault(x => x.Id == Intent.Extras.GetInt(nameof(ScriptModel.Id), 0));
                }
            }

            TopLayout    = FindViewById <LinearLayoutCompat>(Resource.Id.script_top_layout);
            FooterLayout = FindViewById <LinearLayoutCompat>(Resource.Id.script_footer_layout);

            CardTitle.Text    = GetText(Resource.String.script_edit_title);
            CardSubtitle.Text = GetText(Resource.String.script_edit_subtitle);

            DeleteScript = new AppCompatButton(this)
            {
                Text = GetText(Resource.String.delete_title)
            };
            DeleteScript.SetTextColor(Color.DarkRed);
            DeleteScript.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
            FooterLayout.AddView(DeleteScript);

            ButtonOk.Tag = scriptHardware.Id;

            CommandsScript = new AppCompatButton(this)
            {
                Text = $"{GetString(Resource.String.commands_title)} ({scriptHardware.Commands.Count})"
            };
            CommandsScript.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);
            TopLayout.AddView(CommandsScript);

            StartScript = new AppCompatButton(this)
            {
                Text    = GetText(Resource.String.run_the_script_title),
                Enabled = scriptHardware.Commands.Count > 0
            };
            StartScript.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent);


            TopLayout.AddView(StartScript);

            ScriptName.Text = scriptHardware.Name;
            if (scriptHardware.TriggerPort != null)
            {
                AutorunTrigger.Checked  = true;
                PortTrigger.Enabled     = true;
                HardwareTrigger.Enabled = true;
                StateTrigger.Enabled    = true;

                int indexPosition = Hardwares.Keys.ToList().IndexOf(scriptHardware.TriggerPort.HardwareId);
                HardwareTrigger.SetSelection(indexPosition);

                PortsList_UpdateSpinner(scriptHardware.TriggerPort.HardwareId, ref PortTrigger, scriptHardware.TriggerPort.Id);//, ref Ports

                string[] statuses = Resources.GetStringArray(Resource.Array.script_trigger_port_states_array);
                if (scriptHardware.TriggerPortState == true)
                {
                    indexPosition = Array.IndexOf(statuses, GetString(Resource.String.abc_capital_on));
                }
                else if (scriptHardware.TriggerPortState == false)
                {
                    indexPosition = Array.IndexOf(statuses, GetString(Resource.String.abc_capital_off));
                }
                else
                {
                    indexPosition = Array.IndexOf(statuses, GetString(Resource.String.abc_capital_switch));
                }
                StateTrigger.SetSelection(indexPosition);
            }
        }
Exemple #6
0
        public static String OperationModelsToCode(ScriptModel scriptModel, ref List <String> myContain)
        {
            //输入
            XmlDocument doc = new XmlDocument();

            doc.Load("Config/input.xml");
            XmlNode inputRoot = doc.DocumentElement;
            //格式
            XmlNode inputFormat             = inputRoot.SelectSingleNode("Format");
            XmlNode Delimiter               = inputFormat.SelectSingleNode("Delimiter");
            String  strInputFormatDelimiter = Delimiter.InnerText;
            XmlNode Range = inputFormat.SelectSingleNode("Range");
            String  strInputFormatRange = Range.InnerText;
            char    StrInputFormatDelimiter;

            if (strInputFormatDelimiter.Equals("Comma"))
            {
                StrInputFormatDelimiter = ',';
            }
            else if (strInputFormatDelimiter.Equals("Space"))
            {
                StrInputFormatDelimiter = ' ';
            }
            else
            {
                StrInputFormatDelimiter = ' ';
            }
            char StrInputFormatRange;

            if (strInputFormatRange.Equals("Shortbar"))
            {
                StrInputFormatRange = '-';
            }
            else if (strInputFormatRange.Equals("R"))
            {
                StrInputFormatRange = 'r';
            }
            else
            {
                StrInputFormatRange = '-';
            }

            //临时存放,即存放生成代码时会需要用到的变量
            //规则是Step前面加My,即MyStep1,MyStep2...
            //List<String> myContain = new List<string>();
            StringBuilder sb = new StringBuilder();
            //if (scriptModel.Value.Contains(scriptModel.Name + "LightGroup"))
            //{
            List <String> contains = new List <string>();

            foreach (var mItem in scriptModel.OperationModels)
            {
                String name = contains.Count == 0
                                  ? ""
                                  : contains[contains.Count - 1];

                if (mItem is ConditionJudgmentOperationModel)
                {
                    ConditionJudgmentOperationModel conditionJudgmentOperationModel = mItem as ConditionJudgmentOperationModel;
                    StringBuilder positionBuild = new StringBuilder();
                    positionBuild.Append("new List<int>(){");
                    for (int i = 0; i < conditionJudgmentOperationModel.IfPosition.Count; i++)
                    {
                        if (i != conditionJudgmentOperationModel.IfPosition.Count - 1)
                        {
                            positionBuild.Append(conditionJudgmentOperationModel.IfPosition[i] + ",");
                        }
                        else
                        {
                            positionBuild.Append(conditionJudgmentOperationModel.IfPosition[i]);
                        }
                    }
                    positionBuild.Append("}");
                    StringBuilder colorBuild = new StringBuilder();
                    colorBuild.Append("new List<int>(){");
                    for (int i = 0; i < conditionJudgmentOperationModel.IfColor.Count; i++)
                    {
                        if (i != conditionJudgmentOperationModel.IfColor.Count - 1)
                        {
                            colorBuild.Append(conditionJudgmentOperationModel.IfColor[i] + ",");
                        }
                        else
                        {
                            colorBuild.Append(conditionJudgmentOperationModel.IfColor[i]);
                        }
                    }
                    colorBuild.Append("}");
                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup.ConditionJudgment(ConditionJudgmentOperationModel.Operation." + conditionJudgmentOperationModel.MyOperator + ","
                              + conditionJudgmentOperationModel.IfTime + ","
                              + conditionJudgmentOperationModel.IfAction + ","
                              + positionBuild.ToString() + ","
                              + colorBuild.ToString() + ",\""
                              + conditionJudgmentOperationModel.ThenTime + "\",\""
                              + conditionJudgmentOperationModel.ThenPosition + "\",\""
                              + conditionJudgmentOperationModel.ThenColor
                              + "\");");
                }
                else if (mItem is SetAttributeOperationModel)
                {
                    SetAttributeOperationModel setAttributeOperationModel = mItem as SetAttributeOperationModel;
                    for (int i = 0; i < setAttributeOperationModel.AttributeOperationModels.Count; i++)
                    {
                        if (setAttributeOperationModel.AttributeOperationModels[i].attributeType == SetAttributeOperationModel.AttributeOperationModel.AttributeType.TIME)
                        {
                            sb.Append(Environment.NewLine + name + "LightGroup.SetAttribute(LightGroup.TIME,\"" + setAttributeOperationModel.AttributeOperationModels[i].Value + "\");");
                        }
                        else if (setAttributeOperationModel.AttributeOperationModels[i].attributeType == SetAttributeOperationModel.AttributeOperationModel.AttributeType.POSITION)
                        {
                            sb.Append(Environment.NewLine + name + "LightGroup.SetAttribute(LightGroup.POSITION,\"" + setAttributeOperationModel.AttributeOperationModels[i].Value + "\");");
                        }
                        else if (setAttributeOperationModel.AttributeOperationModels[i].attributeType == SetAttributeOperationModel.AttributeOperationModel.AttributeType.COLOR)
                        {
                            sb.Append(Environment.NewLine + name + "LightGroup.SetAttribute(LightGroup.COLOR,\"" + setAttributeOperationModel.AttributeOperationModels[i].Value + "\");");
                        }
                    }
                }
                else if (mItem is CreateFromStepOperationModel)
                {
                    String _name = GetUsableStepName(ref contains);
                    sb.Append(Environment.NewLine + "\tLightGroup " + _name + "LightGroup = " + (mItem as CreateFromStepOperationModel).StepName + "();");
                }
                else if (mItem is CreateFromFileOperationModel)
                {
                    String _name = GetUsableStepName(ref contains);
                    CreateFromFileOperationModel createFromFileOperationModel = mItem as CreateFromFileOperationModel;
                    if (createFromFileOperationModel.FileName.EndsWith(".light"))
                    {
                        sb.Append(Environment.NewLine + "\tLightGroup " + _name + "LightGroup = Create.CreateFromLightFile(\"" + createFromFileOperationModel.FileName + "\");");
                    }
                    else if (createFromFileOperationModel.FileName.EndsWith(".mid"))
                    {
                        sb.Append(Environment.NewLine + "\tLightGroup " + _name + "LightGroup = Create.CreateFromMidiFile(\"" + createFromFileOperationModel.FileName + "\");");
                    }
                    else if (createFromFileOperationModel.FileName.EndsWith(".limitlessLamp"))
                    {
                        sb.Append(Environment.NewLine + "\tLightGroup " + _name + "LightGroup = Create.CreateFromLimitlessLampFile(\"" + createFromFileOperationModel.FileName + "\");");
                    }
                    else if (createFromFileOperationModel.FileName.EndsWith(".lightScript"))
                    {
                        sb.Append(Environment.NewLine + "\tLightGroup " + _name + "LightGroup = Create.CreateFromLightScriptFile(\"" + createFromFileOperationModel.FileName + "\",\"" + createFromFileOperationModel.StepName + "\");");
                    }
                }
                else if (mItem is CreateFromQuickOperationModel)
                {
                    CreateFromQuickOperationModel createFromQuickOperationModel = mItem as CreateFromQuickOperationModel;
                    StringBuilder positionBuild = new StringBuilder();
                    positionBuild.Append("new List<int>(){");
                    for (int i = 0; i < createFromQuickOperationModel.PositionList.Count; i++)
                    {
                        if (i != createFromQuickOperationModel.PositionList.Count - 1)
                        {
                            positionBuild.Append(createFromQuickOperationModel.PositionList[i] + ",");
                        }
                        else
                        {
                            positionBuild.Append(createFromQuickOperationModel.PositionList[i] + "}");
                        }
                    }
                    StringBuilder colorBuild = new StringBuilder();
                    colorBuild.Append("new List<int>(){");
                    for (int i = 0; i < createFromQuickOperationModel.ColorList.Count; i++)
                    {
                        if (i != createFromQuickOperationModel.ColorList.Count - 1)
                        {
                            colorBuild.Append(createFromQuickOperationModel.ColorList[i] + ",");
                        }
                        else
                        {
                            colorBuild.Append(createFromQuickOperationModel.ColorList[i] + "}");
                        }
                    }
                    sb.Append(Environment.NewLine + "\tCreateFromQuickOperationModel createFromQuickOperationModel = new CreateFromQuickOperationModel("
                              + createFromQuickOperationModel.Time + ","
                              + positionBuild.ToString() + ","
                              + createFromQuickOperationModel.Interval + ","
                              + createFromQuickOperationModel.Continued + ","
                              + colorBuild.ToString() + ","
                              + createFromQuickOperationModel.Type + ","
                              + createFromQuickOperationModel.Action + ");");

                    String _name = GetUsableStepName(ref contains);
                    sb.Append(Environment.NewLine + "\tLightGroup " + _name + "LightGroup = Create.CreateLightGroup(createFromQuickOperationModel);");
                }
                else if (mItem is VerticalFlippingOperationModel)
                {
                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup.VerticalFlipping();");
                }
                else if (mItem is HorizontalFlippingOperationModel)
                {
                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup.HorizontalFlipping();");
                }
                else if (mItem is LowerLeftSlashFlippingOperationModel)
                {
                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup.LowerLeftSlashFlipping();");
                }
                else if (mItem is LowerRightSlashFlippingOperationModel)
                {
                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup.LowerRightSlashFlipping();");
                }
                else if (mItem is ClockwiseOperationModel)
                {
                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup.Clockwise();");
                }
                else if (mItem is AntiClockwiseOperationModel)
                {
                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup.AntiClockwise();");
                }
                else if (mItem is RemoveBorderOperationModel)
                {
                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup.RemoveBorder();");
                }
                else if (mItem is ReversalOperationModel)
                {
                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup.Reversal();");
                }
                else if (mItem is ChangeTimeOperationModel)
                {
                    ChangeTimeOperationModel changeTimeOperationModel = mItem as ChangeTimeOperationModel;
                    if (changeTimeOperationModel.MyOperator == ChangeTimeOperationModel.Operation.MULTIPLICATION)
                    {
                        sb.Append(Environment.NewLine + "\t" + name + "LightGroup.ChangeTime(LightGroup.MULTIPLICATION," + changeTimeOperationModel.Multiple.ToString() + ");");
                    }
                    else if (changeTimeOperationModel.MyOperator == ChangeTimeOperationModel.Operation.DIVISION)
                    {
                        sb.Append(Environment.NewLine + "\t" + name + "LightGroup.ChangeTime(LightGroup.DIVISION," + changeTimeOperationModel.Multiple.ToString() + ");");
                    }
                }
                else if (mItem is CreateFromAutomaticOperationModel)
                {
                    String _name = GetUsableStepName(ref contains);
                    CreateFromAutomaticOperationModel createFromAutomaticOperationModel = mItem as CreateFromAutomaticOperationModel;
                    if (createFromAutomaticOperationModel.MyBaseAutomatic is CreateFromAutomaticOperationModel.RhombusDiffusionAutomaticOperationModel)
                    {
                        sb.Append(Environment.NewLine + "\tLightGroup " + _name + "LightGroup = Create.Automatic(Create.RHOMBUSDIFFUSION," + (createFromAutomaticOperationModel.MyBaseAutomatic as CreateFromAutomaticOperationModel.RhombusDiffusionAutomaticOperationModel).Position +
                                  "," + (createFromAutomaticOperationModel.MyBaseAutomatic as CreateFromAutomaticOperationModel.RhombusDiffusionAutomaticOperationModel).Continued + ");");
                    }
                    else if (createFromAutomaticOperationModel.MyBaseAutomatic is CreateFromAutomaticOperationModel.CrossAutomaticOperationModel)
                    {
                        sb.Append(Environment.NewLine + "\tLightGroup " + _name + "LightGroup = Create.Automatic(Create.CROSS," + (createFromAutomaticOperationModel.MyBaseAutomatic as CreateFromAutomaticOperationModel.CrossAutomaticOperationModel).Position +
                                  "," + (createFromAutomaticOperationModel.MyBaseAutomatic as CreateFromAutomaticOperationModel.CrossAutomaticOperationModel).Continued + ");");
                    }
                    else if (createFromAutomaticOperationModel.MyBaseAutomatic is CreateFromAutomaticOperationModel.RandomFountainAutomaticOperationModel)
                    {
                        StringBuilder positionBuild = new StringBuilder();
                        positionBuild.Append("new List<int>(){");

                        List <int> PositionList = (createFromAutomaticOperationModel.MyBaseAutomatic as CreateFromAutomaticOperationModel.RandomFountainAutomaticOperationModel).Position;
                        for (int i = 0; i < PositionList.Count; i++)
                        {
                            if (i != PositionList.Count - 1)
                            {
                                positionBuild.Append(PositionList[i] + ",");
                            }
                            else
                            {
                                positionBuild.Append(PositionList[i] + "}");
                            }
                        }
                        sb.Append(Environment.NewLine + "\tLightGroup " + _name + "LightGroup = Create.Automatic(Create.RANDOMFOUNTAIN," + positionBuild.ToString() + ".ToArray());");
                    }
                    else if (createFromAutomaticOperationModel.MyBaseAutomatic is CreateFromAutomaticOperationModel.BilateralDiffusionAutomaticOperationModel)
                    {
                        sb.Append(Environment.NewLine + "\tLightGroup " + _name + "LightGroup = Create.Automatic(Create.BILATERALDIFFUSION," + (createFromAutomaticOperationModel.MyBaseAutomatic as CreateFromAutomaticOperationModel.BilateralDiffusionAutomaticOperationModel).Position +
                                  "," + (createFromAutomaticOperationModel.MyBaseAutomatic as CreateFromAutomaticOperationModel.BilateralDiffusionAutomaticOperationModel).Continued + ");");
                    }
                }
                else if (mItem is FoldOperationModel)
                {
                    FoldOperationModel foldOperationModel = mItem as FoldOperationModel;
                    if (foldOperationModel.MyOrientation == FoldOperationModel.Orientation.VERTICAL)
                    {
                        sb.Append(Environment.NewLine + "\t" + name + "LightGroup.Fold(LightGroup.VERTICAL," + foldOperationModel.StartPosition.ToString() + "," + foldOperationModel.Span.ToString() + ");");
                    }
                    else if (foldOperationModel.MyOrientation == FoldOperationModel.Orientation.HORIZONTAL)
                    {
                        sb.Append(Environment.NewLine + "\t" + name + "LightGroup.Fold(LightGroup.HORIZONTAL," + foldOperationModel.StartPosition.ToString() + "," + foldOperationModel.Span.ToString() + ");");
                    }
                }
                else if (mItem is SetEndTimeOperationModel)
                {
                    SetEndTimeOperationModel setEndTimeOperationModel = mItem as SetEndTimeOperationModel;
                    if (setEndTimeOperationModel.MyType == SetEndTimeOperationModel.Type.ALL)
                    {
                        sb.Append(Environment.NewLine + "\t" + name + "LightGroup.SetEndTime(LightGroup.ALL,\"" + setEndTimeOperationModel.Value.ToString() + "\");");
                    }
                    else if (setEndTimeOperationModel.MyType == SetEndTimeOperationModel.Type.END)
                    {
                        sb.Append(Environment.NewLine + "\t" + name + "LightGroup.SetEndTime(LightGroup.END,\"" + setEndTimeOperationModel.Value.ToString() + "\");");
                    }
                    else if (setEndTimeOperationModel.MyType == SetEndTimeOperationModel.Type.ALLANDEND)
                    {
                        sb.Append(Environment.NewLine + "\t" + name + "LightGroup.SetEndTime(LightGroup.ALLANDEND,\"" + setEndTimeOperationModel.Value.ToString() + "\");");
                    }
                }
                else if (mItem is InterceptTimeOperationModel)
                {
                    InterceptTimeOperationModel interceptTimeOperationModel = mItem as InterceptTimeOperationModel;
                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup.InterceptTime(" + interceptTimeOperationModel.Start.ToString() + "," + interceptTimeOperationModel.End.ToString() + ");");
                }
                else if (mItem is AnimationDisappearOperationModel)
                {
                    AnimationDisappearOperationModel animationDisappearOperationModel = mItem as AnimationDisappearOperationModel;
                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup = Animation.Serpentine(" + scriptModel.Name + "LightGroup," + animationDisappearOperationModel.StartTime.ToString() + ", " + animationDisappearOperationModel.Interval.ToString() + ");");
                }
                else if (mItem is OneNumberOperationModel)
                {
                    OneNumberOperationModel oneNumberOperationModel = mItem as OneNumberOperationModel;
                    if (oneNumberOperationModel.Identifier.Equals("Animation.Windmill"))
                    {
                        sb.Append(Environment.NewLine + "\t" + name + "LightGroup = Animation.Windmill(" + scriptModel.Name + "LightGroup," + oneNumberOperationModel.Number.ToString() + ");");
                    }
                    else
                    {
                        sb.Append(Environment.NewLine + "\t" + name + "LightGroup." + oneNumberOperationModel.Identifier + "(" + oneNumberOperationModel.Number.ToString() + ");");
                    }
                }
                else if (mItem is ChangeColorOperationModel ||
                         mItem is CopyToTheEndOperationModel ||
                         mItem is CopyToTheFollowOperationModel ||
                         mItem is AccelerationOrDecelerationOperationModel
                         )
                {
                    String rangeGroupName = String.Empty;
                    int    i = 1;
                    while (i <= 100000)
                    {
                        if (!myContain.Contains("Step" + i))
                        {
                            myContain.Add("Step" + i);
                            rangeGroupName = "MyStep" + i + "ColorGroup";
                            break;
                        }
                        i++;
                    }
                    if (i > 100000)
                    {
                        //new MessageDialog(StaticConstant.mw, "ThereIsNoProperName").ShowDialog();
                    }
                    else
                    {
                        sb.Append(Environment.NewLine + "\tColorGroup " + rangeGroupName + " = new ColorGroup(");
                        ColorOperationModel changeColorOperationModel = mItem as ColorOperationModel;
                        if (changeColorOperationModel.Colors.Count == 1)
                        {
                            sb.Append("\"" + changeColorOperationModel.Colors[0] + "\",'" + StrInputFormatDelimiter.ToString() + "','" + StrInputFormatRange.ToString() + "');");
                        }
                        else
                        {
                            for (int count = 0; count < changeColorOperationModel.Colors.Count; count++)
                            {
                                if (count == 0)
                                {
                                    sb.Append("\"");
                                }
                                if (count != changeColorOperationModel.Colors.Count - 1)
                                {
                                    sb.Append(changeColorOperationModel.Colors[count] + StrInputFormatDelimiter.ToString());
                                }
                                else
                                {
                                    sb.Append(changeColorOperationModel.Colors[count] + "\",'" + StrInputFormatDelimiter.ToString() + "','" + StrInputFormatRange.ToString() + "');");
                                }
                            }
                        }
                        if (mItem is ChangeColorOperationModel)
                        {
                            sb.Append(Environment.NewLine + "\t" + name + "LightGroup.SetColor(" + rangeGroupName + ");");
                        }
                        else if (mItem is CopyToTheEndOperationModel)
                        {
                            sb.Append(Environment.NewLine + "\t" + name + "LightGroup.CopyToTheEnd(" + rangeGroupName + ");");
                        }
                        else if (mItem is CopyToTheFollowOperationModel)
                        {
                            sb.Append(Environment.NewLine + "\t" + name + "LightGroup.CopyToTheFollow(" + rangeGroupName + ");");
                        }
                        else if (mItem is AccelerationOrDecelerationOperationModel)
                        {
                            sb.Append(Environment.NewLine + "\t" + name + "LightGroup.AccelerationOrDeceleration(" + rangeGroupName + ");");
                        }
                        else if (mItem is ColorWithCountOperationModel)
                        {
                            sb.Append(Environment.NewLine + "\t" + name + "LightGroup.ColorWithCount(" + rangeGroupName + ");");
                        }
                    }
                }
                else if (mItem is ShapeColorOperationModel)
                {
                    String rangeGroupName = String.Empty;
                    int    i = 1;
                    while (i <= 100000)
                    {
                        if (!myContain.Contains("Step" + i))
                        {
                            myContain.Add("Step" + i);
                            rangeGroupName = "MyStep" + i + "ColorGroup";
                            break;
                        }
                        i++;
                    }
                    if (i > 100000)
                    {
                        //new MessageDialog(StaticConstant.mw, "ThereIsNoProperName").ShowDialog();
                    }
                    else
                    {
                        sb.Append(Environment.NewLine + "\tColorGroup " + rangeGroupName + " = new ColorGroup(");
                        ShapeColorOperationModel shapeColorOperationModel = mItem as ShapeColorOperationModel;
                        if (shapeColorOperationModel.Colors.Count == 1)
                        {
                            sb.Append("\"" + shapeColorOperationModel.Colors[0] + "\",'" + StrInputFormatDelimiter.ToString() + "','" + StrInputFormatRange.ToString() + "');");
                        }
                        else
                        {
                            for (int count = 0; count < shapeColorOperationModel.Colors.Count; count++)
                            {
                                if (count == 0)
                                {
                                    sb.Append("\"");
                                }
                                if (count != shapeColorOperationModel.Colors.Count - 1)
                                {
                                    sb.Append(shapeColorOperationModel.Colors[count] + StrInputFormatDelimiter.ToString());
                                }
                                else
                                {
                                    sb.Append(shapeColorOperationModel.Colors[count] + "\",'" + StrInputFormatDelimiter.ToString() + "','" + StrInputFormatRange.ToString() + "');");
                                }
                            }
                        }
                        if (shapeColorOperationModel.MyShapeType == ShapeColorOperationModel.ShapeType.SQUARE)
                        {
                            sb.Append(Environment.NewLine + "\t" + name + "LightGroup.ShapeColor(LightGroup.SQUARE, " + rangeGroupName + "); ");
                        }
                        else if (shapeColorOperationModel.MyShapeType == ShapeColorOperationModel.ShapeType.RADIALVERTICAL)
                        {
                            sb.Append(Environment.NewLine + "\t" + name + "LightGroup.ShapeColor(LightGroup.RADIALVERTICAL, " + rangeGroupName + "); ");
                        }
                        else if (shapeColorOperationModel.MyShapeType == ShapeColorOperationModel.ShapeType.RADIALHORIZONTAL)
                        {
                            sb.Append(Environment.NewLine + "\t" + name + "LightGroup.ShapeColor(LightGroup.RADIALHORIZONTAL, " + rangeGroupName + "); ");
                        }
                    }
                }
                else if (mItem is ThirdPartyOperationModel)
                {
                    ThirdPartyOperationModel thirdPartyOperationModel = mItem as ThirdPartyOperationModel;
                    StringBuilder            _sb = new StringBuilder();
                    _sb.Append("new List<String> {");
                    for (int i = 0; i < thirdPartyOperationModel.Parameters.Count; i++)
                    {
                        if (i != thirdPartyOperationModel.Parameters.Count - 1)
                        {
                            _sb.Append("\"" + thirdPartyOperationModel.Parameters[i] + "\",");
                        }
                        else
                        {
                            _sb.Append("\"" + thirdPartyOperationModel.Parameters[i] + "\"}");
                        }
                    }

                    sb.Append(Environment.NewLine + "\t" + name + "LightGroup.ThirdParty(" + "\"" + thirdPartyOperationModel.ThirdPartyName + "\",\"" + thirdPartyOperationModel.DllFileName + "\"," +
                              _sb.ToString() + ");");
                }
            }
            //}
            return(sb.ToString());
        }
Exemple #7
0
 private void NotificationMessageReceived(NotificationMessage msg)
 {
     //If this is not the intended target
     if (msg.Target != null && msg.Target != this)
     {
         return;
     }
     if (msg.Notification == "OpenFocusTree")
     {
         FocusGridModel container = msg.Sender as FocusGridModel;
         if (TabsModelList.Contains(container))
         {
             return;
         }
         CheckForChanges(container);
         TabsModelList.Add(container);
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Notification == "OpenLocalisation")
     {
         LocalisationModel container = msg.Sender as LocalisationModel;
         if (TabsModelList.Contains(container))
         {
             return;
         }
         CheckForChanges(container);
         TabsModelList.Add(container);
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Notification == "OpenEventList")
     {
         EventTabModel container = msg.Sender as EventTabModel;
         if (TabsModelList.Contains(container))
         {
             return;
         }
         CheckForChanges(container);
         TabsModelList.Add(container);
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Notification == "OpenScriptList")
     {
         ScriptModel container = msg.Sender as ScriptModel;
         if (TabsModelList.Contains(container))
         {
             return;
         }
         CheckForChanges(container);
         TabsModelList.Add(container);
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Notification == "SaveProject")
     {
         saveProject();
     }
     if (msg.Notification == "RefreshProjectViewer")
     {
         TabsModelList.Clear();
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Notification == "SendDeleteItemSignal")
     {
         ObservableObject Model = null;
         if (msg.Sender is FocusGridModel)
         {
             Model = TabsModelList.FirstOrDefault((m) => m is FocusGridModel &&
                                                  ((FocusGridModel)m).UniqueID == ((FocusGridModel)msg.Sender).UniqueID);
         }
         else if (msg.Sender is LocalisationModel)
         {
             Model = TabsModelList.FirstOrDefault((m) => m is LocalisationModel &&
                                                  ((LocalisationModel)m).UniqueID == ((LocalisationModel)msg.Sender).UniqueID);
         }
         else if (msg.Sender is EventTabModel)
         {
             Model = TabsModelList.FirstOrDefault((m) => m is EventTabModel &&
                                                  ((EventTabModel)m).UniqueID == ((EventTabModel)msg.Sender).UniqueID);
         }
         else if (msg.Sender is ScriptModel)
         {
             Model = TabsModelList.FirstOrDefault((m) => m is ScriptModel &&
                                                  ((ScriptModel)m).UniqueID == ((ScriptModel)msg.Sender).UniqueID);
         }
         TabsModelList.Remove(Model);
         RaisePropertyChanged("TabsModelList");
     }
     if (msg.Target == this)
     {
         //Resend to the tutorial View model if this was the target
         Messenger.Default.Send(new NotificationMessage(msg.Sender,
                                                        new ViewModelLocator().Tutorial, msg.Notification));
     }
 }
Exemple #8
0
        private void EditElement(object obj)
        {
            UndoService.Current[GetUndoRoot()].BeginChangeSetBatch("EditAnyFile", false);
            FileManager dialog = new FileManager(ModeType.Edit);

            if (obj is FocusGridModel)
            {
                FocusGridModel item = (FocusGridModel)obj;
                new ViewModelLocator().FileManager.File = new FocusGridModel(item.VisibleName)
                {
                    TAG             = item.TAG,
                    AdditionnalMods = item.AdditionnalMods
                };
                dialog.ShowDialog();
                if (new ViewModelLocator().FileManager.File == null)
                {
                    return;
                }
                FocusGridModel newItem = new ViewModelLocator().FileManager.File as FocusGridModel;
                if (newItem == null)
                {
                    return;
                }
                item.VisibleName     = newItem.VisibleName;
                item.TAG             = newItem.TAG;
                item.AdditionnalMods = newItem.AdditionnalMods;
            }
            else if (obj is LocalisationModel)
            {
                LocalisationModel item = (LocalisationModel)obj;
                new ViewModelLocator().FileManager.File = new LocalisationModel(item.VisibleName)
                {
                    LanguageName = item.LanguageName
                };
                dialog.ShowDialog();
                if (new ViewModelLocator().FileManager.File == null)
                {
                    return;
                }
                LocalisationModel newItem = new ViewModelLocator().FileManager.File as LocalisationModel;
                if (newItem == null)
                {
                    return;
                }
                item.VisibleName  = newItem.VisibleName;
                item.LanguageName = newItem.LanguageName;
            }
            else if (obj is EventTabModel)
            {
                EventTabModel item = (EventTabModel)obj;
                new ViewModelLocator().FileManager.File = new EventTabModel(item.VisibleName)
                {
                    EventNamespace = item.EventNamespace
                };
                dialog.ShowDialog();
                if (new ViewModelLocator().FileManager.File == null)
                {
                    return;
                }
                EventTabModel newItem = (new ViewModelLocator()).FileManager.File as EventTabModel;
                if (newItem == null)
                {
                    return;
                }
                item.VisibleName    = newItem.VisibleName;
                item.EventNamespace = newItem.EventNamespace;
            }
            else if (obj is ScriptModel)
            {
                ScriptModel item = (ScriptModel)obj;
                new ViewModelLocator().FileManager.File = new ScriptModel(item.VisibleName);
                dialog.ShowDialog();
                if (new ViewModelLocator().FileManager.File == null)
                {
                    return;
                }
                ScriptModel newItem = new ViewModelLocator().FileManager.File as ScriptModel;
                if (newItem != null)
                {
                    item.VisibleName = newItem.VisibleName;
                }
            }
            UndoService.Current[GetUndoRoot()].EndChangeSetBatch();
        }
        /// <summary>
        ///
        /// </summary>
        protected void CalculateRunways(ScriptModel scriptModel)
        {
            int i = 0;

            foreach (var runway in this.datFile.LandRunways)
            {
                var scriptRunway = new ScriptRunway();

                double runwayShoulderSize = 0;

                // Might be wrong but X-Plane seems to use around 1/5th of the runway width as a shoulder
                if (runway.ShoulderType != ShoulderType.NoShoulder)
                {
                    runwayShoulderSize = runway.Width / 5;
                }

                scriptRunway.Width = runway.Width + (runwayShoulderSize * 2);

                var end1Coord = new GeoCoordinate(runway.End1.Latitude, runway.End1.Longitude);
                var end2Coord = new GeoCoordinate(runway.End2.Latitude, runway.End2.Longitude);

                var runwayLength = end1Coord.GetDistanceTo(end2Coord);
                scriptRunway.Length = runwayLength + (runwayShoulderSize * 2);

                var angle = GeoHelper.DegreeBearing(end1Coord, end2Coord);
                scriptRunway.Angle = -angle;

                var runwayMidPoint = GeoHelper.MidPoint(end1Coord, end2Coord);
                var runwayPosition = GeoCoordinateToPoint(tscFile.Location, runwayMidPoint);
                scriptRunway.X     = runwayPosition.X;
                scriptRunway.Y     = runwayPosition.Y;
                scriptRunway.Index = i;

                switch (runway.ShoulderType)
                {
                case ShoulderType.AsphaltShoulder:
                    scriptRunway.ShoulderType = "asphalt";
                    break;

                case ShoulderType.ConcreneShoulder:
                    scriptRunway.ShoulderType = "concrete";
                    break;

                case ShoulderType.NoShoulder:
                    scriptRunway.ShoulderType = "none";
                    break;
                }

                switch (runway.SurfaceType)
                {
                case SurfaceType.Asphalt:
                    scriptRunway.SurfaceType = "asphalt";
                    break;

                case SurfaceType.Concrete:
                    scriptRunway.SurfaceType = "concrete";
                    break;

                case SurfaceType.Grass:
                case SurfaceType.Dirt:
                case SurfaceType.Gravel:
                case SurfaceType.DryLakeBed:
                case SurfaceType.Water:
                case SurfaceType.SnowOrIce:
                case SurfaceType.Transparent:
                    scriptRunway.SurfaceType = "transparent";
                    break;
                }

                scriptModel.Runways.Add(scriptRunway);
                i++;
            }
        }
        protected void CalculateDSFFileBuildings(ScriptModel scriptModel)
        {
            int i = 0;

            foreach (var polygon in this.dsfFile.Polygons)
            {
                // Don't bother with fences or hedges for the moment
                if (!polygon.Reference.ToLower().Contains("fence") &&
                    !polygon.Reference.ToLower().Contains("hedge"))
                {
                    if (polygon.WindingCollections != null)
                    {
                        foreach (var polygonWindingCollection in polygon.WindingCollections)
                        {
                            if (polygonWindingCollection.HeightMeters.HasValue)
                            {
                                foreach (var winding in polygonWindingCollection.Windings)
                                {
                                    ScriptBuilding scriptBuilding = new ScriptBuilding();
                                    scriptBuilding.Height = polygonWindingCollection.HeightMeters.Value;
                                    scriptBuilding.Index  = i;
                                    scriptBuilding.Nodes  = new List <ScriptNode>();

                                    var polyRefFileInfo = new FileInfo(polygon.Reference);
                                    scriptBuilding.Name = polyRefFileInfo.Name.Replace(polyRefFileInfo.Extension, "");

                                    for (int j = 0; j < winding.Points.Count; j++)
                                    {
                                        var node       = winding.Points[j];
                                        var scriptNode = new ScriptNode();

                                        var nodeCoord    = new GeoCoordinate(node.Latitude, node.Longitude);
                                        var nodePosition = GeoCoordinateToPoint(tscFile.Location, nodeCoord);

                                        scriptNode.X = nodePosition.X;
                                        scriptNode.Y = nodePosition.Y;

                                        scriptNode.Render = true;

                                        if (j == 0)
                                        {
                                            scriptNode.OpenLoop = true;
                                        }

                                        if (j == winding.Points.Count - 1)
                                        {
                                            scriptNode.CloseLoop = true;
                                        }

                                        scriptBuilding.Nodes.Add(scriptNode);
                                    }

                                    scriptModel.Buildings.Add(scriptBuilding);
                                    i++;
                                }
                            }
                        }
                    }
                }
            }
        }
Exemple #11
0
        public void TestScriptParser()
        {
            ScriptModel model = TestScriptToScript();

            TestScriptToScript(model);
        }
Exemple #12
0
 public RedirectResult Shared(int id)
 {
     ScriptModel.Shared(id);
     return(Redirect(Request.UrlReferrer.ToString()));
 }
Exemple #13
0
 public ActionResult Lock(int id)
 {
     ScriptModel.Lock(id);
     return(Redirect(Request.UrlReferrer.ToString()));
 }
Exemple #14
0
 public ActionResult Remove(int id)
 {
     ScriptModel.Remove(id);
     return(new EmptyResult());
 }
Exemple #15
0
 public ScriptModel Save(ScriptModel scriptModel, IEnumerable <DescriptCommand> commands)
 {
     scriptModel.DescriptCommands.Clear();
     scriptModel.DescriptCommands.AddRange(commands);
     return(_scriptRepository.AddOrUpdate(scriptModel));
 }
 private void RunEditScript(ScriptModel script)
 {
     Controller.Run <EditScenarioPresenter, ScriptModel>(script);
     SetSourceScripts();
 }
Exemple #17
0
        public static Dictionary <String, ScriptModel> GetScriptModelDictionary(String filePath, out String introduce, out String audioResources)
        {
            Dictionary <String, ScriptModel> scriptModelDictionary = new Dictionary <string, ScriptModel>();
            XDocument xDoc       = XDocument.Load(filePath);
            XElement  xRoot      = xDoc.Element("Root");
            XElement  xIntroduce = xRoot.Element("Introduce");

            if (xIntroduce != null)
            {
                introduce = xIntroduce.Value;
            }
            else
            {
                introduce = "";
            }
            XElement xAudioResources = xRoot.Element("AudioResources");

            if (xAudioResources != null)
            {
                audioResources = xAudioResources.Value;
            }
            else
            {
                audioResources = "";
            }
            XElement xScripts = xRoot.Element("Scripts");

            foreach (var xScript in xScripts.Elements("Script"))
            {
                ScriptModel scriptModel = new ScriptModel
                {
                    Name  = xScript.Attribute("name").Value,
                    Value = Base2String(xScript.Attribute("value").Value)
                };
                if (xScript.Attribute("intersection") != null && !xScript.Attribute("intersection").Value.ToString().Trim().Equals(String.Empty))
                {
                    scriptModel.Intersection = xScript.Attribute("intersection").Value.Trim().Split(' ').ToList();
                }
                else
                {
                    scriptModel.Intersection = new List <String>();
                }
                if (xScript.Attribute("complement") != null && !xScript.Attribute("complement").Value.Equals(String.Empty))
                {
                    scriptModel.Complement = xScript.Attribute("complement").Value.Trim().Split(' ').ToList();
                }
                else
                {
                    scriptModel.Complement = new List <String>();
                }
                String visible = xScript.Attribute("visible").Value;
                if (visible.Equals("true"))
                {
                    scriptModel.Visible = true;
                }
                else
                {
                    scriptModel.Visible = false;
                }
                //scriptModel.Contain = xScript.Attribute("contain").Value.Split(' ').ToList();
                //command = fileBusiness.Base2String(xScript.Attribute("value").Value);

                foreach (var xEdit in xScript.Elements())
                {
                    BaseOperationModel baseOperationModel = null;
                    if (xEdit.Name.ToString().Equals("ConditionJudgment"))
                    {
                        baseOperationModel = new ConditionJudgmentOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("SetAttribute"))
                    {
                        baseOperationModel = new SetAttributeOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("CreateFromAutomatic"))
                    {
                        baseOperationModel = new CreateFromAutomaticOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("CreateFromFile"))
                    {
                        baseOperationModel = new CreateFromFileOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("CreateFromStep"))
                    {
                        baseOperationModel = new CreateFromStepOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("CreateFromQuick"))
                    {
                        baseOperationModel = new CreateFromQuickOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("VerticalFlipping"))
                    {
                        baseOperationModel = new VerticalFlippingOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("HorizontalFlipping"))
                    {
                        baseOperationModel = new HorizontalFlippingOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("LowerLeftSlashFlipping"))
                    {
                        baseOperationModel = new LowerLeftSlashFlippingOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("LowerRightSlashFlipping"))
                    {
                        baseOperationModel = new LowerRightSlashFlippingOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("Clockwise"))
                    {
                        baseOperationModel = new ClockwiseOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("AntiClockwise"))
                    {
                        baseOperationModel = new AntiClockwiseOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("RemoveBorder"))
                    {
                        baseOperationModel = new RemoveBorderOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("Reversal"))
                    {
                        baseOperationModel = new ReversalOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("SetEndTime"))
                    {
                        baseOperationModel = new SetEndTimeOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("ChangeTime"))
                    {
                        baseOperationModel = new ChangeTimeOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("AnimationDisappear"))
                    {
                        baseOperationModel = new AnimationDisappearOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("InterceptTime"))
                    {
                        baseOperationModel = new InterceptTimeOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("FillColor") ||
                             xEdit.Name.ToString().Equals("SetAllTime") ||
                             xEdit.Name.ToString().Equals("SetStartTime") ||
                             xEdit.Name.ToString().Equals("MatchTotalTimeLattice") ||
                             xEdit.Name.ToString().Equals("Animation.Windmill"))
                    {
                        baseOperationModel = new OneNumberOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("Fold"))
                    {
                        baseOperationModel = new FoldOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("ChangeColor") ||
                             xEdit.Name.ToString().Equals("CopyToTheEnd") ||
                             xEdit.Name.ToString().Equals("CopyToTheFollow") ||
                             xEdit.Name.ToString().Equals("AccelerationOrDeceleration") ||
                             xEdit.Name.ToString().Equals("ColorWithCount"))
                    {
                        if (xEdit.Name.ToString().Equals("ChangeColor"))
                        {
                            baseOperationModel = new ChangeColorOperationModel();
                        }
                        else if (xEdit.Name.ToString().Equals("CopyToTheEnd"))
                        {
                            baseOperationModel = new CopyToTheEndOperationModel();
                        }
                        else if (xEdit.Name.ToString().Equals("CopyToTheFollow"))
                        {
                            baseOperationModel = new CopyToTheFollowOperationModel();
                        }
                        else if (xEdit.Name.ToString().Equals("AccelerationOrDeceleration"))
                        {
                            baseOperationModel = new AccelerationOrDecelerationOperationModel();
                        }
                        else
                        {
                            baseOperationModel = new ColorWithCountOperationModel();
                        }
                    }
                    else if (xEdit.Name.ToString().Equals("ShapeColor"))
                    {
                        baseOperationModel = new ShapeColorOperationModel();
                    }
                    else if (xEdit.Name.ToString().Equals("ThirdParty"))
                    {
                        baseOperationModel = new ThirdPartyOperationModel();
                    }
                    baseOperationModel.SetXElement(xEdit);
                    scriptModel.OperationModels.Add(baseOperationModel);
                }
                scriptModelDictionary.Add(scriptModel.Name, scriptModel);
            }
            return(scriptModelDictionary);
        }
Exemple #18
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="script">脚本模型</param>
 public TaskRuner(ScriptModel script)
 {
     _Script = script;
 }
Exemple #19
0
        public ActionResult PyScript(string name, string p1, string p2, string v1, string v2)
        {
#if DEBUG
#else
            try
            {
#endif
            var script = CurrentDatabase.ContentOfTypePythonScript(name);
            if (!script.HasValue())
            {
                return(Message("no script named " + name));
            }

            if (!ScriptModel.CanRunScript(script))
            {
                return(Message("Not Authorized to run this script"));
            }

            if (Regex.IsMatch(script, @"model\.Form\b"))
            {
                return(Redirect("/PyScriptForm/" + name));
            }

            script = script.Replace("@P1", p1 ?? "NULL")
                     .Replace("@P2", p2 ?? "NULL")
                     .Replace("V1", v1 ?? "None")
                     .Replace("V2", v2 ?? "None");
            if (script.Contains("@qtagid"))
            {
                var id  = CurrentDatabase.FetchLastQuery().Id;
                var tag = CurrentDatabase.PopulateSpecialTag(id, DbUtil.TagTypeId_Query);
                script = script.Replace("@qtagid", tag.Id.ToString());
            }

            ViewBag.report = name;
            ViewBag.url    = Request.Url?.PathAndQuery;
            if (script.Contains("Background Process Completed"))
            {
                var logFile = $"RunPythonScriptInBackground.{DateTime.Now:yyyyMMddHHmmss}";
                ViewBag.LogFile = logFile;
                var qs   = Request.Url?.Query;
                var host = Util.Host;

                HostingEnvironment.QueueBackgroundWorkItem(ct =>
                {
                    var qsa = HttpUtility.ParseQueryString(qs ?? "");
                    var pm  = new PythonModel(CurrentDatabase);
                    pm.DictionaryAdd("LogFile", logFile);
                    foreach (string key in qsa)
                    {
                        pm.DictionaryAdd(key, qsa[key]);
                    }
                    string result = pm.RunScript(script);
                    if (result.HasValue())
                    {
                        pm.LogToContent(logFile, result);
                    }
                });
                return(View("RunPythonScriptProgress"));
            }
            var pe = new PythonModel(CurrentDatabase);
            if (script.Contains("@BlueToolbarTagId"))
            {
                var id = CurrentDatabase.FetchLastQuery().Id;
                pe.DictionaryAdd("BlueToolbarGuid", id.ToCode());
            }

            foreach (var key in Request.QueryString.AllKeys)
            {
                pe.DictionaryAdd(key, Request.QueryString[key]);
            }

            pe.Output = ScriptModel.Run(name, pe);
            if (pe.Output.StartsWith("REDIRECT="))
            {
                var a = pe.Output.SplitStr("=", 2);
                return(Redirect(a[1].TrimEnd()));
            }

            return(View(pe));

#if DEBUG
#else
        }

        catch (Exception ex)
        {
            return(RedirectShowError(ex.Message));
        }
#endif
        }
Exemple #20
0
        protected override void ButtonOk_Click(object sender, EventArgs e)
        {
            Log.Debug(TAG, $"ButtonOk_Click");

            string obj_id_tag = ButtonOk.Tag?.ToString() ?? "0";
            int    obj_id     = 0;

            if (Regex.IsMatch(obj_id_tag, @"^\d+$"))
            {
                obj_id = int.Parse(obj_id_tag);
            }

            string errMsg = ReadView(obj_id);

            if (!string.IsNullOrWhiteSpace(errMsg))
            {
                Log.Error(TAG, $"ButtonOk_Click - {errMsg}");
                CardSubtitle.Text = errMsg;
                CardSubtitle.SetTextColor(Android.Graphics.Color.Red);
                Toast.MakeText(this, errMsg, ToastLength.Short).Show();
                return;
            }

            ScriptModel scriptHardware = null;

            if (obj_id > 0)
            {
                lock (DatabaseContext.DbLocker)
                {
                    using (DatabaseContext db = new DatabaseContext(gs.DatabasePathBase))
                    {
                        scriptHardware = db.Scripts.FirstOrDefault(x => x.Id == obj_id);
                    }
                }
                scriptHardware.Name = ScriptName.Text.Trim();
            }
            if (scriptHardware == null)
            {
                scriptHardware = new ScriptModel()
                {
                    Name = ScriptName.Text
                };
            }
            if (AutorunTrigger.Checked)
            {
                scriptHardware.TriggerPortId = Ports.Keys.ElementAt(PortTrigger.SelectedItemPosition);

                string[] statuses           = Resources.GetStringArray(Resource.Array.script_trigger_port_states_array);
                string   selectedPortStatus = statuses[StateTrigger.SelectedItemPosition];
                if (selectedPortStatus == GetString(Resource.String.abc_capital_on))
                {
                    scriptHardware.TriggerPortState = true;
                }
                else if (selectedPortStatus == GetString(Resource.String.abc_capital_off))
                {
                    scriptHardware.TriggerPortState = false;
                }
                else
                {
                    scriptHardware.TriggerPortState = null;
                }
            }

            lock (DatabaseContext.DbLocker)
            {
                using (DatabaseContext db = new DatabaseContext(gs.DatabasePathBase))
                {
                    if (scriptHardware.Id > 0)
                    {
                        db.Scripts.Update(scriptHardware);
                    }
                    else
                    {
                        db.Scripts.Add(scriptHardware);
                    }
                    db.SaveChanges();
                }
            }

            StartActivity(typeof(ScriptsListActivity));
        }