private static void TestGeneratedXml(string classFileName, string xmlFileName, string contentTypeName, ParserFactory factory)
        {
            ContentType contentType;
            string expectedOutput;

            using (var goldReader = File.OpenText(@"..\..\TestFiles\" + xmlFileName + ".xml"))
            {
                expectedOutput = goldReader.ReadToEnd();
            }

            var contentTypeConfig = CodeGeneratorConfiguration.Create().Get(contentTypeName);
            contentTypeConfig.BaseClass = "Umbraco.Core.Models.TypedModelBase";

            using (var inputReader = File.OpenText(@"..\..\TestFiles\" + classFileName + ".cs"))
            {
                var codeParser = new CodeParser(contentTypeConfig, TestDataTypeProvider.All, factory);
                contentType = codeParser.Parse(inputReader).Single();
            }

            var serializer = new ContentTypeSerializer();
            var xml = serializer.Serialize(contentType);

            Console.WriteLine(xml);

            Assert.AreEqual(expectedOutput, xml);
        }
		private static void TestGeneratedXml(string fileName, string contentTypeName)
		{
			ContentType contentType;
			string expectedOutput;

            using (var goldReader = File.OpenText(@"..\..\TestFiles\" + fileName + ".xml"))
			{
				expectedOutput = goldReader.ReadToEnd();
			}

		    var contentTypeConfig = new CodeGeneratorConfiguration().Get(contentTypeName);
		    contentTypeConfig.BaseClass = "DocumentTypeBase";

            using (var inputReader = File.OpenText(@"..\..\TestFiles\" + fileName + ".cs"))
			{
                var codeParser = new CodeParser(contentTypeConfig, TestDataTypeProvider.All, new DefaultParserFactory());
			    contentType = codeParser.Parse(inputReader).Single();
			}
            
		    var serializer = new ContentTypeSerializer();
		    var xml = serializer.Serialize(contentType);

            Console.WriteLine(xml);

		    Assert.AreEqual(expectedOutput, xml);
		}
		private void GenerateXml(ContentTypeConfiguration contentTypeConfiguration)
		{
			var parser = new CodeParser(contentTypeConfiguration, dataTypes, new DefaultParserFactory());
		    var modelPath = HttpContext.Current.Server.MapPath(contentTypeConfiguration.ModelPath);
			if (!Directory.Exists(modelPath))
				Directory.CreateDirectory(modelPath);
			var files = Directory.GetFiles(modelPath, "*.cs");
			var documents = new List<XDocument>();
			foreach(var file in files)
			{
				using (var reader = File.OpenText(file))
				{
				    var contentType = parser.Parse(reader).FirstOrDefault();
                    if (contentType != null)
					    documents.Add(XDocument.Parse(serializer.Serialize(contentType)));
				}
			}

			var documentTypeRoot = Path.Combine(uSyncConfiguration.USyncFolder, contentTypeConfiguration.ContentTypeName);
			if (!Directory.Exists(documentTypeRoot))
				Directory.CreateDirectory(documentTypeRoot);
			WriteDocuments(contentTypeConfiguration, documents, documentTypeRoot, "");
		}
        public static string GetRightSideAssignmentValueAsString(IElement element, InstructionSave instruction)
        {
            CustomVariable customVariable = element.GetCustomVariableRecursively(instruction.Member);

            IElement referencedElement = null;

            #region Determine if the assignment is a file

            bool isFile = false;

            if (customVariable != null)
            {
                referencedElement =
                    BaseElementTreeNode.GetElementIfCustomVariableIsVariableState(customVariable, element);

                isFile = customVariable.GetIsFile();
            }

            #endregion

            string valueAsString = "";

            if (referencedElement == null)
            {
                valueAsString = CodeParser.ParseObjectValue(instruction.Value);

                if (isFile)
                {
                    valueAsString = valueAsString.Replace("\"", "");

                    if (valueAsString == "<NONE>")
                    {
                        valueAsString = "null";
                    }
                }
                else if (CustomVariableCodeGenerator.ShouldAssignToCsv(customVariable, valueAsString))
                {
                    valueAsString = CustomVariableCodeGenerator.GetAssignmentToCsvItem(customVariable, element, valueAsString);
                }
                else if (customVariable != null && customVariable.Type == "Color")
                {
                    valueAsString = "Color." + valueAsString.Replace("\"", "");
                }
                if (customVariable != null && !string.IsNullOrEmpty(customVariable.SourceObject) && !isFile)
                {
                    NamedObjectSave namedObject = element.GetNamedObjectRecursively(customVariable.SourceObject);

                    bool isVariableState = customVariable.GetIsVariableState();

                    IElement objectElement = null;

                    if (namedObject != null)
                    {
                        ObjectFinder.Self.GetIElement(namedObject.SourceClassType);
                    }

                    if (objectElement != null)
                    {
                        if (isVariableState)
                        {
                            string typeName = "VariableState";

                            StateSaveCategory category = objectElement.GetStateCategoryRecursively(customVariable.Type);

                            if (category != null && category.SharesVariablesWithOtherCategories == false)
                            {
                                typeName = category.Name;
                            }
                            valueAsString = objectElement.Name.Replace("/", ".").Replace("\\", ".") + "." + typeName + "." + valueAsString.Replace("\"", "");
                        }
                    }

                    valueAsString = CodeWriter.MakeLocalizedIfNecessary(
                        namedObject,
                        instruction.Member,
                        instruction.Value,
                        valueAsString,
                        customVariable);
                }
            }
            else
            {
                string enumValue = (string)instruction.Value;

                if (!string.IsNullOrEmpty(enumValue) && enumValue != "<NONE>")
                {
                    string variableType = "VariableState";

                    if (customVariable != null && customVariable.Type.ToLower() != "string")
                    {
                        variableType = customVariable.Type;
                    }
                    valueAsString = FullyQualifyStateValue(referencedElement, enumValue, variableType);
                }
            }
            return(valueAsString);
        }
Example #5
0
        public static ExpressionNode Read(ReadParams p, DataType refDataType, bool stayOnSameLine, params string[] stopStrings)
        {
            ExpressionNode exp           = null;
            var            code          = p.Code;
            var            lastPos       = code.Position;
            var            parseDataType = refDataType;

            while (!code.EndOfFile)
            {
                switch (code.PeekChar())
                {
                case ';':
                case '{':
                case '}':
                    return(exp);
                }

                if (stopStrings != null)
                {
                    foreach (var str in stopStrings)
                    {
                        if (str.IsWord())
                        {
                            if (code.PeekExactWholeWord(str))
                            {
                                return(exp);
                            }
                        }
                        else
                        {
                            if (code.PeekExact(str))
                            {
                                return(exp);
                            }
                        }
                    }
                }

                if (!code.Read())
                {
                    break;
                }

                if (stayOnSameLine)
                {
                    if (code.PositionsAreOnDifferentLines(lastPos, code.TokenStartPostion))
                    {
                        code.Position = code.TokenStartPostion;
                        break;
                    }
                    lastPos = code.Position;
                }

                if (exp == null)
                {
                    exp = new ExpressionNode(p.Statement);
                }

                switch (code.Type)
                {
                case CodeType.Number:
                    exp.AddChild(new NumberNode(p.Statement, code.Span, code.Text));
                    break;

                case CodeType.StringLiteral:
                    if (code.Text.StartsWith("'"))
                    {
                        exp.AddChild(new CharLiteralNode(p.Statement, code.Span, CodeParser.StringLiteralToString(code.Text)));
                    }
                    else
                    {
                        exp.AddChild(new StringLiteralNode(p.Statement, code.Span, CodeParser.StringLiteralToString(code.Text)));
                    }
                    break;

                case CodeType.Word:
                    exp.AddChild(exp.ReadWord(p, parseDataType));
                    break;

                case CodeType.Operator:
                    switch (code.Text)
                    {
                    case "(":
                    {
                        var opText    = code.Text;
                        var startPos  = code.Span.Start;
                        var resumePos = code.Position;
                        var dataType  = DataType.TryParse(new DataType.ParseArgs
                            {
                                Code             = code,
                                Flags            = DataType.ParseFlag.Strict,
                                DataTypeCallback = name =>
                                {
                                    return(p.Statement.CodeAnalyzer.PreprocessorModel.DefinitionProvider.
                                           GetAny <DataTypeDefinition>(startPos + p.FuncOffset, name).FirstOrDefault());
                                },
                                VariableCallback = name =>
                                {
                                    return(p.Statement.CodeAnalyzer.PreprocessorModel.DefinitionProvider.
                                           GetAny <VariableDefinition>(startPos + p.FuncOffset, name).FirstOrDefault());
                                },
                                TableFieldCallback = (tableName, fieldName) =>
                                {
                                    foreach (var tableDef in p.Statement.CodeAnalyzer.PreprocessorModel.DefinitionProvider.GetGlobalFromFile(tableName))
                                    {
                                        if (tableDef.AllowsChild)
                                        {
                                            foreach (var fieldDef in tableDef.GetChildDefinitions(fieldName))
                                            {
                                                return(new Definition[] { tableDef, fieldDef });
                                            }
                                        }
                                    }

                                    return(null);
                                },
                                VisibleModel = false
                            });
                        if (dataType != null && code.ReadExact(')'))
                        {
                            // This is a cast
                            var span = new Span(startPos, code.Span.End);
                            exp.AddChild(new CastNode(p.Statement, span, dataType, ExpressionNode.Read(p, dataType, stayOnSameLine, stopStrings)));
                        }
                        else
                        {
                            code.Position = resumePos;
                            exp.AddChild(exp.ReadNestable(p, parseDataType, code.Span, opText, null));
                        }
                    }
                    break;

                    //case "[":
                    //	exp.AddChild(exp.ReadNestable(p, code.Span, code.Text, stopStrings));
                    //	break;
                    case "-":
                    {
                        var lastNode = exp.LastChild;
                        if (lastNode == null || lastNode is OperatorNode)
                        {
                            exp.AddChild(new OperatorNode(p.Statement, code.Span, code.Text, SpecialOperator.UnaryMinus));
                        }
                        else
                        {
                            exp.AddChild(new OperatorNode(p.Statement, code.Span, code.Text, null));
                        }
                    }
                    break;

                    case "?":
                        parseDataType = refDataType;
                        exp.AddChild(ConditionalNode.Read(p, parseDataType, code.Span, stopStrings));
                        break;

                    case "=":
                    {
                        var rDataType = exp.NumChildren > 0 ? exp.LastChild.DataType : null;
                        exp.AddChild(new OperatorNode(p.Statement, code.Span, code.Text, null));
                        exp.AddChild(ExpressionNode.Read(p, rDataType, stopStrings));
                    }
                    break;

                    case "==":
                    case "!=":
                    case "<":
                    case "<=":
                    case ">":
                    case ">=":
                    {
                        if (exp.NumChildren > 0)
                        {
                            var dt = exp.LastChild.DataType;
                            if (dt != null)
                            {
                                parseDataType = dt;
                            }
                        }
                        exp.AddChild(new OperatorNode(p.Statement, code.Span, code.Text, null));
                    }
                    break;

                    default:
                        exp.AddChild(new OperatorNode(p.Statement, code.Span, code.Text, null));
                        break;
                    }
                    break;

                default:
                    exp.ReportError(code.Span, CAError.CA0001, code.Text);                              // Unknown '{0}'.
                    exp.AddChild(new UnknownNode(p.Statement, code.Span, code.Text));
                    break;
                }
            }

            return(exp);
        }
Example #6
0
 public WhileToken(CodeParser Parser, String Content)
     : base(Parser, Content)
 {
 }
Example #7
0
 public void StellarisDetectDuplicatesAndGenerateParserMap()
 {
     var codeParser  = new CodeParser(new Logger());
     var quotesRegex = new Regex("\".*?\"", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Example #8
0
 public ATan2Token(CodeParser Parser, String Content) : base(Parser, Content)
 {
 }
Example #9
0
 private static JToken GetDefaultValue(object obj, PropertyInfo property)
 {
     object value = null;
     try
     {
         value = property.GetValue(obj, null);
     }
     catch { }
     if (value == null)
     {
         return new JValue("");
     }
     else if (property.PropertyType == typeof(int))
     {
         return new JValue((int)value);
     }
     else if (property.PropertyType == typeof(bool))
     {
         return new JValue(value.ToString().ToLower());
     }
     else if (property.PropertyType == typeof(System.Drawing.Font))
     {
         var font = (System.Drawing.Font)value;
         var fontValue = new List<string>();
         fontValue.Add(font.OriginalFontName);
         fontValue.Add(string.Format("{0}pt", font.Size));
         if (font.Style != System.Drawing.FontStyle.Regular)
         {
             fontValue.Add(font.Style.ToString());
         }
         return new JValue(string.Join(",", fontValue));
     }
     else if (typeof(System.Collections.IList).IsAssignableFrom(property.PropertyType))
     {
         var items = new JArray();
         if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericArguments().Length == 1)
         {
             var itemType = property.PropertyType.GetGenericArguments()[0];
             var toolItems = new ArrayList();
             if (itemType == typeof(JQClientTools.JQToolItem))
             {
                 //增加grid的默认toolitems
                 toolItems.AddRange(new JQClientTools.JQToolItem[] { JQClientTools.JQToolItem.InsertItem, JQClientTools.JQToolItem.UpdateItem, JQClientTools.JQToolItem.DeleteItem
                     , JQClientTools.JQToolItem.ApplyItem, JQClientTools.JQToolItem.CancelItem, JQClientTools.JQToolItem.QueryItem });
             }
             else if (itemType == typeof(JQMobileTools.JQToolItem))
             {
                 //增加grid的默认toolitems
                 toolItems.AddRange(new JQMobileTools.JQToolItem[] { JQMobileTools.JQToolItem.InsertItem, JQMobileTools.JQToolItem.PreviousPageItem,  JQMobileTools.JQToolItem.NextPageItem
                     , JQMobileTools.JQToolItem.QueryItem, JQMobileTools.JQToolItem.RefreshItem, JQMobileTools.JQToolItem.BackItem });
             }
             foreach (var toolItem in toolItems)
             {
                 var item = new JObject();
                 var itemProperties = toolItem.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
                 foreach (var itemProperty in itemProperties)
                 {
                     if (CanEdit(itemProperty))
                     {
                         item[itemProperty.Name] = GetDefaultValue(toolItem, itemProperty);
                     }
                 }
                 items.Add(item);
             }
         }
         else if (typeof(System.Collections.IList).IsAssignableFrom(property.PropertyType))
         {
             CodeParser helper = new CodeParser();
             foreach (var collectionItem in (IEnumerable)value)
             {
                 items.Add(helper.GetItemProperties(collectionItem));
             }
         }
         return items;
     }
     else
     {
         return new JValue(value.ToString());
     }
 }
Example #10
0
 public StringVariableToken(CodeParser Parser, String Content) : base(Parser, Content)
 {
 }
Example #11
0
        /// <summary>
        /// Examines a source code file, looking for references in the comments at the top.
        /// </summary>
        /// <param name="cp">A CodeParser object used to parse the text.</param>
        /// <returns>True if successful; otherwise false.</returns>
        private bool ProcessSource(CodeParser cp)
        {
            Regex rxRef = new Regex(@"^//\s*\#ref(erence)?\:\s*(.+)$");
            Match match;
            string line;

            while (!cp.EndOfFile)
            {
                line = cp.ReadLine().Trim();

                if (!string.IsNullOrEmpty(line))
                {
                    if ((match = rxRef.Match(line)).Success)
                    {
                        _references.Add(match.Groups[2].Value);
                    }
                    else if (!line.StartsWith("//")) break;
                }
            }

            return true;
        }
Example #12
0
        public LogInfo SetMacro(string macroName, string macroCommand, SectionAddress addr, bool global, bool permanent)
        {
            if (Regex.Match(macroName, Macro.MacroNameRegex, RegexOptions.Compiled).Success == false) // Macro Name Validation
            {
                return(new LogInfo(LogState.Error, $"Invalid macro name [{macroName}]"));
            }

            if (macroCommand != null)
            { // Insert
                // Try parsing
                CodeCommand cmd = CodeParser.ParseStatement(macroCommand, addr);
                if (cmd.Type == CodeType.Error)
                {
                    Debug.Assert(cmd.Info.GetType() == typeof(CodeInfo_Error));
                    CodeInfo_Error info = cmd.Info as CodeInfo_Error;

                    return(new LogInfo(LogState.Error, info.ErrorMessage));
                }

                // Put into dictionary
                if (permanent) // MacroDict
                {
                    MacroDict[macroName] = cmd;
                    if (Ini.SetKey(addr.Project.MainPlugin.FullPath, "Variables", macroName, cmd.RawCode))
                    {
                        return(new LogInfo(LogState.Success, $"Permanent Macro [{macroName}] set to [{cmd.RawCode}]"));
                    }
                    else
                    {
                        return(new LogInfo(LogState.Error, $"Could not write macro into [{addr.Project.MainPlugin.FullPath}]"));
                    }
                }
                else if (global) // MacroDict
                {
                    MacroDict[macroName] = cmd;
                    return(new LogInfo(LogState.Success, $"Global Macro [{macroName}] set to [{cmd.RawCode}]"));
                }
                else
                {
                    LocalDict[macroName] = cmd;
                    return(new LogInfo(LogState.Success, $"Local Macro [{macroName}] set to [{cmd.RawCode}]"));
                }
            }
            else
            {                  // Delete
                // Put into dictionary
                if (permanent) // MacroDict
                {
                    if (MacroDict.ContainsKey(macroName))
                    {
                        MacroDict.Remove(macroName);
                        Ini.DeleteKey(addr.Project.MainPlugin.FullPath, "Variables", macroName);
                        return(new LogInfo(LogState.Success, $"Permanent Macro [{macroName}] deleted"));
                    }
                    else
                    {
                        return(new LogInfo(LogState.Error, $"Permanent Macro [{macroName}] not found"));
                    }
                }
                else if (global) // MacroDict
                {
                    if (MacroDict.ContainsKey(macroName))
                    {
                        MacroDict.Remove(macroName);
                        return(new LogInfo(LogState.Success, $"Global Macro [{macroName}] deleted"));
                    }
                    else
                    {
                        return(new LogInfo(LogState.Error, $"Global Macro [{macroName}] not found"));
                    }
                }
                else // LocalDict
                {
                    if (LocalDict.ContainsKey(macroName))
                    {
                        LocalDict.Remove(macroName);
                        return(new LogInfo(LogState.Success, $"Local Macro [{macroName}] deleted"));
                    }
                    else
                    {
                        return(new LogInfo(LogState.Error, $"Local Macro [{macroName}] not found"));
                    }
                }
            }
        }
Example #13
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState, Resource.Layout.frmReceivingDetails);

            translateScreen();

            // Récupération de la réception
            ReceptionWS reception = (ReceptionWS)ReceivingActivity.data;

            // Action clic pour clear le EditText
            clearTextOnClick(FindViewById <ImageButton>(Resource.Id.imClear), FindViewById <EditText>(Resource.Id.tfLicenseReceivingDetails));

            // Remplir champs de données par rapport à la réception
            FindViewById <TextView>(Resource.Id.tvNumRecieving).Text = reception.ReceptionNRI.ToString();
            FindViewById <TextView>(Resource.Id.tvnameProvider).Text = reception.SupplierCode;

            // Affichage de la dernière licence créer, si pas de licence alors on n'affiche rien
            if (licence != null)
            {
                if (licence.productNRI != 0)
                {
                    // Creation liste de nom produit
                    List <ProductDetailsWS> listProduct = OperationsWebService.getReceptionProductDetails(Configuration.securityToken, reception.ReceptionNRI, (int)Configuration.currentLanguage, Configuration.userInfos.NRI, null).OfType <ProductDetailsWS>().ToList();

                    // On parcourt la liste de produit pour trouver le produit qui correspond à la licence
                    foreach (ProductDetailsWS p in listProduct)
                    {
                        // Puis on affichage les information dans les TextView
                        if (licence.productNRI == p.NRI)
                        {
                            FindViewById <TextView>(Resource.Id.tvNameProduct).Text = p.code;
                            FindViewById <TextView>(Resource.Id.tvAmountQte).Text   = p.qtyPicked.ToString() + "/" + p.qtyToPick.ToString();
                            FindViewById <TextView>(Resource.Id.tvAmountPoids).Text = licence.weightKG.ToString() + " kg";
                        }
                    }
                }
            }

            // Action touche "Enter" pour accèder à la création d'une nouvelle licence
            EditText urlEditText = FindViewById <EditText>(Resource.Id.tfLicenseReceivingDetails);

            urlEditText.KeyPress += (object sender, View.KeyEventArgs e) => {
                e.Handled = false;
                CodeParser parser = new CodeParser();

                if (e.Event.Action == KeyEventActions.Down && e.KeyCode == Keycode.Enter)
                {
                    if (urlEditText.Text.ToString() != "")
                    {
                        urlEditText.Text.Replace(" ", "");
                        licence = new LicenseWS();

                        ParsedLicence parsedLicence = parser.getLicense(urlEditText.Text);
                        licence = Converts.ParsedLicToLicenceWS(parsedLicence);

                        if (licence.licenseCode == null)
                        {
                            licence.licenseCode = urlEditText.Text;
                            licence.parentNRI   = reception.ReceptionNRI;
                            data = reception;
                            StartActivity(new Intent(this, typeof(NewLicenseActivity)));
                        }
                        else
                        {
                            licence.parentNRI = reception.ReceptionNRI;
                            // Creation liste de nom produit
                            List <ProductDetailsWS> listProduct = OperationsWebService.getReceptionProductDetails(Configuration.securityToken, reception.ReceptionNRI, (int)Configuration.currentLanguage, Configuration.userInfos.Udp_NRI, Configuration.userInfos.Udp_Label).OfType <ProductDetailsWS>().ToList();


                            foreach (ProductDetailsWS pro in listProduct)
                            {
                                if (pro.SSCC.Contains(licence.productSSCC))
                                {
                                    licence.productNRI = pro.NRI;
                                }
                            }

                            if (licence.productNRI != 0)
                            {
                                data = reception;
                                var produit = OperationsWebService.pickLicenseReception(Configuration.securityToken, licence, (int)Configuration.currentLanguage, Configuration.userInfos.Udp_NRI, Configuration.userInfos.Udp_Label);
                                if (produit == null)
                                {
                                    Toast.MakeText(this, OperationsWebService.errorMessage, ToastLength.Long).Show();
                                    Recreate();
                                }
                                else
                                {
                                    Recreate();
                                }
                            }
                            else
                            {
                                if (Configuration.currentLanguage == CR_TTLangue.French_Canada)
                                {
                                    Toast.MakeText(this, Activities.ResourceFR.errProductNotPresent, ToastLength.Long).Show();
                                }
                                else
                                {
                                    Toast.MakeText(this, Activities.ResourceEN.errProductNotPresent, ToastLength.Long).Show();
                                }
                            }
                        }

                        e.Handled = true;
                    }
                    else
                    {
                        urlEditText.Text = "";
                        switch (Configuration.currentLanguage)
                        {
                        case  CR_TTLangue.French_Canada:
                            Toast.MakeText(this, Activities.ResourceFR.errEmptyFieldLicense, ToastLength.Long).Show();
                            break;

                        case  CR_TTLangue.English:
                            Toast.MakeText(this, Activities.ResourceFR.errEmptyFieldLicense, ToastLength.Long).Show();
                            break;
                        }
                    }
                }
            };

            // Action clic sur détails pour accèder à la liste de produit d'une reception
            FindViewById <ImageButton>(Resource.Id.imDetails).Click += async(sender, e) => {
                data   = reception;
                IsBusy = true;
                await Task.Delay(50);

                StartActivity(new Intent(this, typeof(ProductDetailsActivity)));
                IsBusy = false;
            };

            // Ne peut pas fonctionner, il faudrait ajouter une méthode dans les web services afin d'ajouter des licences sur une palette.

            /*// Action clic sur palette pour mettre toutes les licences crées sur la palette
             * FindViewById<Button>(Resource.Id.btnPalette).Click += async (sender, e) => {
             *  if (licences != null)
             *  {
             *
             *      IsBusy = true;
             *      await Task.Delay(50);
             *      var test1 = "1302";
             *      var test2 = "111";
             *      var codePalette = OperationsWebService.createPalletCode(Configuration.securityToken, ref test1, ref test2);
             *      string msg = "Licence non transférée : ";
             *      bool isSucess = true;
             *      licences.Remove(licence);
             *
             *      foreach (LicenseWS lic in licences)
             *      {
             *          if (!(OperationsWebService.relocateLicense(Configuration.securityToken, lic.licenseCode, codePalette, RELOCATION_DESTINATION.Pallet, Configuration.userInfos.warehouseNRI)))
             *          {
             *              isSucess = false;
             *              msg += lic.licenseCode + ", ";
             *          }
             *      }
             *      IsBusy = false;
             *      if (isSucess)
             *      {
             *          Toast.MakeText(this, "Les licences ont été transférées", ToastLength.Long).Show();
             *
             *      }
             *      else
             *      {
             *          Toast.MakeText(this, msg, ToastLength.Long).Show();
             *
             *      }
             *      Recreate();
             *  }
             *  else
             *  {
             *      Toast.MakeText(this, "Veuillez insérer des licences", ToastLength.Long).Show();
             *  }
             * };*/

            // Action clic sur bouton pour completer une reception
            FindViewById <Button>(Resource.Id.btnEndReceiving).Click += async(sender, e) => {
                IsBusy = true;
                await Task.Delay(50);

                OperationsWebService.completeReception(Configuration.securityToken, reception.ReceptionNRI);
                IsBusy      = false;
                mustRefresh = true;

                Finish();
            };
        }
Example #14
0
 public EndOfInputToken(CodeParser Parser, String Content) : base(Parser, Content)
 {
 }
Example #15
0
        private async void SyntaxCheckCommand_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            if (_m.SyntaxInputCode.Length == 0)
            {
                _m.SyntaxCheckResult = "Please input code.";
                return;
            }

            SyntaxCheckButton.Focus();
            _m.CanExecuteCommand = false;
            try
            {
                _m.SyntaxCheckResult = "Checking...";

                await Task.Run(() =>
                {
                    Project p = _m.CurrentProject;

                    Script sc = p.MainScript;
                    ScriptSection section;
                    if (p.MainScript.Sections.ContainsKey(ScriptSection.Names.Process))
                    {
                        section = sc.Sections[ScriptSection.Names.Process];
                    }
                    else // Create dummy [Process] section instance
                    {
                        section = new ScriptSection(sc, ScriptSection.Names.Process, SectionType.Code, new string[0], 1);
                    }

                    // Split lines from SyntaxInputCode
                    List <string> lines = new List <string>();
                    using (StringReader r = new StringReader(_m.SyntaxInputCode))
                    {
                        string line;
                        while ((line = r.ReadLine()) != null)
                        {
                            line = line.Trim();
                            lines.Add(line);
                        }
                    }

                    // Run CodeParser to retrieve parsing errors
                    CodeParser parser = new CodeParser(section, Global.Setting, sc.Project.Compat);
                    (CodeCommand[] cmds, List <LogInfo> errorLogs) = parser.ParseStatements(lines);

                    // Check macro commands
                    Macro macro = new Macro(p, p.Variables, out _);
                    if (macro.MacroEnabled)
                    {
                        foreach (CodeCommand cmd in cmds.Where(x => x.Type == CodeType.Macro))
                        {
                            CodeInfo_Macro info = cmd.Info.Cast <CodeInfo_Macro>();

                            if (!macro.GlobalDict.ContainsKey(info.MacroType))
                            {
                                errorLogs.Add(new LogInfo(LogState.Error, $"Invalid CodeType or Macro [{info.MacroType}]", cmd));
                            }
                        }
                    }

                    // Print results
                    if (0 < errorLogs.Count)
                    {
                        StringBuilder b = new StringBuilder();
                        for (int i = 0; i < errorLogs.Count; i++)
                        {
                            LogInfo log = errorLogs[i];
                            b.AppendLine($"[{i + 1}/{errorLogs.Count}] {log.Message} ({log.Command})");
                        }
                        _m.SyntaxCheckResult = b.ToString();
                    }
                    else
                    {
                        _m.SyntaxCheckResult = "Error not found.";
                    }
                });
            }
            finally
            {
                _m.CanExecuteCommand = true;
                CommandManager.InvalidateRequerySuggested();

                SyntaxCheckResultTextBox.Focus();
            }
        }
Example #16
0
        public static UIControl ParseUIControl(List <string> rawLines, SectionAddress addr, ref int idx)
        {
            UIControlType type    = UIControlType.None;
            string        rawLine = rawLines[idx].Trim();

            // Check if rawCode is Empty
            if (rawLine.Equals(string.Empty))
            {
                return(null);
            }

            // Comment Format : starts with '//' or '#', ';'
            if (rawLine.StartsWith("//") || rawLine.StartsWith("#") || rawLine.StartsWith(";"))
            {
                return(null);
            }

            // Find key of interface control
            string key      = string.Empty;
            string rawValue = string.Empty;
            int    equalIdx = rawLine.IndexOf('=');

            if (equalIdx != -1 && equalIdx != 0)
            {
                key      = rawLine.Substring(0, equalIdx);
                rawValue = rawLine.Substring(equalIdx + 1);
            }
            else
            {
                throw new InvalidCommandException($"Interface control [{rawValue}] does not have a name defined", rawLine);
            }

            // Parse Arguments
            List <string> args = new List <string>();

            try
            {
                string remainder = rawValue;
                while (remainder != null)
                {
                    Tuple <string, string> tuple = CodeParser.GetNextArgument(remainder);
                    args.Add(tuple.Item1);
                    remainder = tuple.Item2;
                }
            }
            catch (InvalidCommandException e) { throw new InvalidCommandException(e.Message, rawLine); }

            // Check doublequote's occurence - must be 2n
            if (StringHelper.CountOccurrences(rawValue, "\"") % 2 == 1)
            {
                throw new InvalidCommandException($"Interface control [{rawValue}]'s doublequotes mismatch", rawLine);
            }

            // Check if last operand is \ - MultiLine check - only if one or more operands exists
            if (0 < args.Count)
            {
                while (args.Last().Equals(@"\", StringComparison.OrdinalIgnoreCase))
                {                              // Split next line and append to List<string> operands
                    if (rawLines.Count <= idx) // Section ended with \, invalid grammar!
                    {
                        throw new InvalidCommandException($@"Last interface control [{rawValue}] cannot end with '\' ", rawLine);
                    }
                    idx++;
                    args.AddRange(rawLines[idx].Trim().Split(','));
                }
            }

            // UIControl should have at least 7 operands
            //    Text, Visibility, Type, X, Y, width, height, [Optional]
            if (args.Count < 7)
            {
                throw new InvalidCommandException($"Interface control [{rawValue}] must have at least 7 arguments", rawLine);
            }

            // Parse opcode
            try { type = UIParser.ParseControlType(args[2]); }
            catch (InvalidCommandException e) { throw new InvalidCommandException(e.Message, rawLine); }

            // Remove UIControlType from operands
            //   Leftover : Text, Visibility, X, Y, width, height, [Optional]
            args.RemoveAt(2);

            // Forge UIControl
            string text       = StringEscaper.Unescape(args[0]);
            bool   visibility = args[1].Equals("1", StringComparison.Ordinal);

            bool intParse = true;

            intParse &= NumberHelper.ParseInt32(args[2], out int x);
            intParse &= NumberHelper.ParseInt32(args[3], out int y);
            intParse &= NumberHelper.ParseInt32(args[4], out int width);
            intParse &= NumberHelper.ParseInt32(args[5], out int height);
            if (intParse == false)
            {
                throw new InvalidCommandException($"Invalid integers in [{rawValue}]", rawLine);
            }

            Rect   rect = new Rect(x, y, width, height);
            UIInfo info;

            try { info = ParseUIControlInfo(type, args); }
            catch (InvalidCommandException e) { throw new InvalidCommandException(e.Message, rawLine); }
            return(new UIControl(rawLine, addr, key, text, visibility, type, rect, info));
        }
Example #17
0
        private static UIInfo ParseUIControlInfo(UIControlType type, List <string> fullArgs)
        {
            // Only use fields starting from 8th operand
            List <string> args = fullArgs.Skip(6).ToList(); // Remove Text, Visibility, X, Y, width, height

            switch (type)
            {
                #region TextBox
            case UIControlType.TextBox:
            {
                const int minOpCount = 1;
                const int maxOpCount = 1;
                if (CodeParser.CheckInfoArgumentCount(args, minOpCount, maxOpCount + 1))         // +1 for tooltip
                {
                    throw new InvalidCommandException($"[{type}] can have [{minOpCount}] ~ [{maxOpCount + 1}] arguments");
                }

                return(new UIInfo_TextBox(GetInfoTooltip(args, maxOpCount), StringEscaper.Unescape(args[0])));
            }

                #endregion
                #region TextLabel
            case UIControlType.TextLabel:
            {
                const int minOpCount = 1;
                const int maxOpCount = 2;
                if (CodeParser.CheckInfoArgumentCount(args, minOpCount, maxOpCount + 1))         // +1 for tooltip
                {
                    throw new InvalidCommandException($"[{type}] can have [{minOpCount}] ~ [{maxOpCount + 1}] arguments");
                }

                if (!NumberHelper.ParseInt32(args[0], out int fontSize))
                {
                    throw new InvalidCommandException($"FontSize {args[0]} is not a valid integer");
                }

                UIInfo_TextLabel_Style style = UIInfo_TextLabel_Style.Normal;
                if (args[1].Equals("Bold", StringComparison.OrdinalIgnoreCase))
                {
                    style = UIInfo_TextLabel_Style.Bold;
                }
                else if (args[1].Equals("Italic", StringComparison.OrdinalIgnoreCase))
                {
                    style = UIInfo_TextLabel_Style.Italic;
                }
                else if (args[1].Equals("Underline", StringComparison.OrdinalIgnoreCase))
                {
                    style = UIInfo_TextLabel_Style.Underline;
                }
                else if (args[1].Equals("Strike", StringComparison.OrdinalIgnoreCase))
                {
                    style = UIInfo_TextLabel_Style.Strike;
                }

                return(new UIInfo_TextLabel(GetInfoTooltip(args, maxOpCount), fontSize, style));
            }

                #endregion
                #region NumberBox
            case UIControlType.NumberBox:
            {
                const int minOpCount = 4;
                const int maxOpCount = 4;
                if (CodeParser.CheckInfoArgumentCount(args, minOpCount, maxOpCount + 1))         // +1 for tooltip
                {
                    throw new InvalidCommandException($"[{type}] can have [{minOpCount}] ~ [{maxOpCount + 1}] arguments");
                }

                NumberHelper.ParseInt32(args[0], out int value);
                NumberHelper.ParseInt32(args[1], out int min);
                NumberHelper.ParseInt32(args[2], out int max);
                NumberHelper.ParseInt32(args[3], out int interval);

                return(new UIInfo_NumberBox(GetInfoTooltip(args, maxOpCount), value, min, max, interval));
            }

                #endregion
                #region CheckBox
            case UIControlType.CheckBox:
            {
                const int minOpCount = 1;
                const int maxOpCount = 3;                                                // +2 for [RunOptional]
                if (CodeParser.CheckInfoArgumentCount(args, minOpCount, maxOpCount + 1)) // +1 for tooltip
                {
                    throw new InvalidCommandException($"[{type}] can have [{minOpCount}] ~ [{maxOpCount + 1}] arguments");
                }

                bool _checked = false;
                if (args[0].Equals("True", StringComparison.OrdinalIgnoreCase))
                {
                    _checked = true;
                }
                else if (args[0].Equals("False", StringComparison.OrdinalIgnoreCase) == false)
                {
                    throw new InvalidCommandException($"Invalid argument [{args[0]}], must be [True] or [False]");
                }

                string tooltip = null;
                if (args.Last().StartsWith("__", StringComparison.Ordinal))         // Has <ToolTip>
                {
                    tooltip = GetInfoTooltip(args, args.Count - 1);
                }

                string sectionName  = null;
                bool   hideProgress = false;
                if (3 <= args.Count &&
                    (args[2].Equals("True", StringComparison.OrdinalIgnoreCase) || args[2].Equals("False", StringComparison.OrdinalIgnoreCase)) &&
                    (args[1].StartsWith("_", StringComparison.Ordinal) && args[1].EndsWith("_", StringComparison.Ordinal)))
                {         // Has [RunOptinal] -> <SectionName>,<HideProgress>
                    if (args[2].Equals("True", StringComparison.OrdinalIgnoreCase))
                    {
                        hideProgress = true;
                    }
                    else if (args[2].Equals("False", StringComparison.OrdinalIgnoreCase) == false)
                    {
                        throw new InvalidCommandException($"Invalid argument [{args[2]}], must be [True] or [False]");
                    }

                    sectionName = args[1].Substring(1, args[1].Length - 2);
                }

                return(new UIInfo_CheckBox(tooltip, _checked, sectionName, hideProgress));
            }

                #endregion
                #region ComboBox
            case UIControlType.ComboBox:
            {         // Variable Length
                List <string> items = new List <string>();

                // Have ToolTip?
                string toolTip = null;
                int    cnt     = args.Count;
                if (args.Last().StartsWith("__", StringComparison.Ordinal))
                {
                    toolTip = args.Last();
                    cnt    -= 1;
                }

                string sectionName  = null;
                bool   hideProgress = false;
                if (2 <= cnt &&
                    (args[cnt - 1].Equals("True", StringComparison.OrdinalIgnoreCase) || args[cnt - 1].Equals("False", StringComparison.OrdinalIgnoreCase)) &&
                    (args[cnt - 2].StartsWith("_", StringComparison.Ordinal) && args[cnt - 2].EndsWith("_", StringComparison.Ordinal)))
                {         // Has [RunOptinal] -> <SectionName>,<HideProgress>
                    if (args[cnt - 1].Equals("True", StringComparison.OrdinalIgnoreCase))
                    {
                        hideProgress = true;
                    }
                    else if (args[cnt - 1].Equals("False", StringComparison.OrdinalIgnoreCase) == false)
                    {
                        throw new InvalidCommandException($"Invalid argument [{args[cnt - 1]}], must be [True] or [False]");
                    }

                    sectionName = args[cnt - 2].Substring(1, args[cnt - 2].Length - 2);
                    cnt        -= 2;
                }

                for (int i = 0; i < cnt; i++)
                {
                    items.Add(args[i]);
                }

                int idx = items.IndexOf(fullArgs[0]);
                if (idx == -1)
                {
                    throw new InvalidCommandException($"[{type}] has wrong selected value [{fullArgs[0]}]");
                }

                return(new UIInfo_ComboBox(toolTip, items, idx, sectionName, hideProgress));
            }

                #endregion
                #region Image
            case UIControlType.Image:
            {
                const int minOpCount = 0;
                const int maxOpCount = 1;                                                // [URL]
                if (CodeParser.CheckInfoArgumentCount(args, minOpCount, maxOpCount + 1)) // +1 for tooltip
                {
                    throw new InvalidCommandException($"[{type}] can have [{minOpCount}] ~ [{maxOpCount + 1}] arguments");
                }

                string url = null;
                if (1 <= args.Count)
                {
                    url = args[0];
                }

                return(new UIInfo_Image(GetInfoTooltip(args, maxOpCount), url));
            }

                #endregion
                #region TextFile
            case UIControlType.TextFile:
            {
                const int minOpCount = 0;
                const int maxOpCount = 0;
                if (CodeParser.CheckInfoArgumentCount(args, minOpCount, maxOpCount + 1))
                {
                    throw new InvalidCommandException($"[{type}] can have [{minOpCount}] ~ [{maxOpCount + 1}] arguments");
                }

                return(new UIInfo_TextFile(GetInfoTooltip(args, maxOpCount)));
            }

                #endregion
                #region Button
            case UIControlType.Button:
            {         // <SectionToRun>,<Picture>,[HideProgress]  +[UnknownBoolean] +[RunOptional]
                // Ex)
                // pButton1 =,1,8,382,47,24,24,Process-OpenDriver_x86,opendir.bmp,False,_Process-OpenDriver_x86,False,_Process-OpenDriver_x86_,False
                // Button_Download=,1,8,403,21,24,24,DownloadXXX,DoubleJDesignRavenna3dArrowDown0016016.bmp,False,False,_DownloadXXX_,False,"__DOWNLOAD Script"
                // OpendirSMFilesButton=,1,8,475,204,24,24,Opendir_SMFiles,opendir.bmp,"__Open Custom .ini Folder"
                // Button_HiveUnload_Target="HiveUnload: Target + ProjectTemp + MountFolders",1,8,15,17,293,46,HiveUnload_Launch_B,HiveUnload3232.bmp,0,"__UnLoad hives"
                // Button_Tools_Folder="Open Tools Folder",1,8,98,256,134,25,Open_Tools_Folder
                const int minOpCount = 1;
                if (CodeParser.CheckInfoArgumentCount(args, minOpCount, -1))
                {
                    throw new InvalidCommandException($"[{type}] must have at least [{minOpCount}] arguments");
                }

                int    cnt     = args.Count;
                string tooltip = null;
                if (args.Last().StartsWith("__", StringComparison.Ordinal))         // Has <ToolTip>
                {
                    tooltip = GetInfoTooltip(args, cnt - 1);
                    cnt    -= 1;
                }

                string sectionName = args[0];

                string picture = null;
                if (2 <= cnt)
                {
                    if (args[1].Equals("0", StringComparison.OrdinalIgnoreCase) == false)
                    {
                        picture = args[1];
                    }
                }

                bool hideProgress = false;
                if (3 <= cnt)
                {
                    if (args[2].Equals("True", StringComparison.OrdinalIgnoreCase))
                    {
                        hideProgress = true;
                    }
                    else if (args[2].Equals("False", StringComparison.OrdinalIgnoreCase) == false)
                    {
                        // WB082 Compability Shim
                        if (args[2].Equals("1", StringComparison.Ordinal))
                        {
                            hideProgress = true;
                        }
                        else if (args[2].Equals("0", StringComparison.Ordinal) == false)
                        {
                            throw new InvalidCommandException($"Invalid argument [{args[2]}], must be [True] or [False]");
                        }
                    }
                }

                // Ignore [UnknownBoolean] and [RunOptional]

                return(new UIInfo_Button(tooltip, args[0], picture, hideProgress));
            }

                #endregion
                #region WebLabel
            case UIControlType.WebLabel:
            {
                const int minOpCount = 1;
                const int maxOpCount = 1;
                if (CodeParser.CheckInfoArgumentCount(args, minOpCount, maxOpCount + 1))         // +1 for tooltip
                {
                    throw new InvalidCommandException($"[{type}] can have [{minOpCount}] ~ [{maxOpCount + 1}] arguments");
                }

                return(new UIInfo_WebLabel(GetInfoTooltip(args, maxOpCount), StringEscaper.Unescape(args[0])));
            }

                #endregion
                #region RadioButton
            case UIControlType.RadioButton:
            {
                const int minOpCount = 1;
                const int maxOpCount = 3;         // +2 for [RunOptional]
                if (CodeParser.CheckInfoArgumentCount(args, minOpCount, maxOpCount + 1))
                {
                    throw new InvalidCommandException($"[{type}] can have [{minOpCount}] ~ [{maxOpCount + 1}] arguments");
                }

                bool selected = false;
                if (args[0].Equals("True", StringComparison.OrdinalIgnoreCase))
                {
                    selected = true;
                }
                else if (args[0].Equals("False", StringComparison.OrdinalIgnoreCase) == false)
                {
                    throw new InvalidCommandException($"Invalid argument [{args[0]}], must be [True] or [False]");
                }

                string tooltip = null;
                if (args.Last().StartsWith("__", StringComparison.Ordinal))         // Has <ToolTip>
                {
                    tooltip = GetInfoTooltip(args, args.Count - 1);
                }

                string sectionName  = null;
                bool   hideProgress = false;
                if (3 <= args.Count &&
                    (args[2].Equals("True", StringComparison.OrdinalIgnoreCase) || args[2].Equals("False", StringComparison.OrdinalIgnoreCase)) &&
                    (args[1].StartsWith("_", StringComparison.Ordinal) && args[1].EndsWith("_", StringComparison.Ordinal)))
                {         // Has [RunOptinal] -> <SectionName>,<HideProgress>
                    if (args[2].Equals("True", StringComparison.OrdinalIgnoreCase))
                    {
                        hideProgress = true;
                    }
                    else if (args[2].Equals("False", StringComparison.OrdinalIgnoreCase) == false)
                    {
                        throw new InvalidCommandException($"Invalid argument [{args[2]}], must be [True] or [False]");
                    }

                    sectionName = args[1].Substring(1, args[1].Length - 2);
                }

                return(new UIInfo_RadioButton(tooltip, selected, sectionName, hideProgress));
            }

                #endregion
                #region Bevel
            case UIControlType.Bevel:
            {
                const int minOpCount = 0;
                const int maxOpCount = 2;
                if (CodeParser.CheckInfoArgumentCount(args, minOpCount, maxOpCount + 1))         // +1 for tooltip
                {
                    throw new InvalidCommandException($"[{type}] can have [{minOpCount}] ~ [{maxOpCount + 1}] arguments");
                }

                int?fontSize = null;
                UIInfo_BevelCaption_Style?style = null;

                if (1 <= args.Count)
                {
                    if (!NumberHelper.ParseInt32(args[0], out int fontSizeVal))
                    {
                        throw new InvalidCommandException($"FontSize {args[0]} is not a valid integer");
                    }
                    fontSize = fontSizeVal;
                }

                if (2 <= args.Count)
                {
                    if (args[1].Equals("Normal", StringComparison.OrdinalIgnoreCase))
                    {
                        style = UIInfo_BevelCaption_Style.Normal;
                    }
                    else if (args[1].Equals("Bold", StringComparison.OrdinalIgnoreCase))
                    {
                        style = UIInfo_BevelCaption_Style.Bold;
                    }
                }

                return(new UIInfo_Bevel(GetInfoTooltip(args, maxOpCount), fontSize, style));
            }

                #endregion
                #region FileBox
            case UIControlType.FileBox:
            {
                const int minOpCount = 0;
                const int maxOpCount = 1;
                if (CodeParser.CheckInfoArgumentCount(args, minOpCount, maxOpCount + 1))
                {
                    throw new InvalidCommandException($"[{type}] can have [{minOpCount}] ~ [{maxOpCount + 1}] arguments");
                }

                bool isFile = false;
                if (0 < args.Count)
                {
                    if (args[0].Equals("file", StringComparison.OrdinalIgnoreCase))
                    {
                        isFile = true;
                    }
                    else if (args[0].Equals("dir", StringComparison.OrdinalIgnoreCase))
                    {
                        isFile = false;
                    }
                    else
                    {
                        throw new InvalidCommandException($"Argument [{type}] should be either [file] or [dir]");
                    }
                }

                return(new UIInfo_FileBox(GetInfoTooltip(args, maxOpCount), isFile));
            }

                #endregion
                #region RadioGroup
            case UIControlType.RadioGroup:
            {         // Variable Length
                List <string> items = new List <string>();

                string sectionName  = null;
                bool   showProgress = false;

                int cnt = args.Count - 1;
                if (args.Last().StartsWith("__", StringComparison.Ordinal))         // Has <ToolTip>
                {
                    cnt -= 1;
                }

                if ((args[cnt].Equals("True", StringComparison.OrdinalIgnoreCase) || args[cnt].Equals("False", StringComparison.OrdinalIgnoreCase)) &&
                    (args[cnt - 1].StartsWith("_", StringComparison.Ordinal) && args[cnt - 1].EndsWith("_", StringComparison.Ordinal)))
                {         // Has [RunOptinal] -> <SectionName>,<HideProgress>
                    if (args[cnt].Equals("True", StringComparison.OrdinalIgnoreCase))
                    {
                        showProgress = true;
                    }
                    else if (args[cnt].Equals("False", StringComparison.OrdinalIgnoreCase) == false)
                    {
                        throw new InvalidCommandException($"Invalid argument [{args[cnt]}], must be [True] or [False]");
                    }

                    sectionName = args[cnt - 1].Substring(1, args[cnt - 1].Length - 2);

                    cnt -= 2;
                }

                for (int i = 0; i < cnt; i++)
                {
                    items.Add(args[i]);
                }

                if (NumberHelper.ParseInt32(args[cnt], out int idx) == false)
                {
                    throw new InvalidCommandException($"Invalid argument [{args[cnt]}], must be an integer");
                }

                return(new UIInfo_RadioGroup(GetInfoTooltip(args, args.Count), items, idx, sectionName, showProgress));
            }

                #endregion
                #region default
            default:
                Debug.Assert(false);
                break;
                #endregion
            }

            throw new InvalidCommandException($"Invalid interface control type [{type}]");
        }
Example #18
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState, Resource.Layout.frmPickingDetails);

            translateScreen();

            clearTextOnClick(FindViewById <ImageButton>(Resource.Id.imClear), FindViewById <EditText>(Resource.Id.tfLicensePickingDetails));

            SaleWS sale = (SaleWS)PickingListActivity.data;


            // Remplir champs de données par rapport à la réception
            FindViewById <TextView>(Resource.Id.tvNumPicking).Text = sale.saleNRI.ToString();
            FindViewById <TextView>(Resource.Id.tvnameClient).Text = sale.customerCode;

            // Action clic sur détails pour accèder à la liste de produit d'une reception
            FindViewById <ImageButton>(Resource.Id.imDetails).Click += async(sender, e) => {
                data   = sale;
                IsBusy = true;
                await Task.Delay(50);

                StartActivity(new Intent(this, typeof(ProductDetailsActivity)));
                IsBusy = false;
            };

            // Action clic sur bouton pour completer une reception
            FindViewById <Button>(Resource.Id.btnEndPicking).Click += async(sender, e) => {
                IsBusy = true;
                await Task.Delay(50);

                OperationsWebService.completeSale(Configuration.securityToken, sale.saleNRI);
                IsBusy      = false;
                mustRefresh = true;
                Finish();
            };

            // Affichage de la dernière licence créer, si pas de licence alors on n'affiche rien
            if (licence != null)
            {
                // Creation liste de nom produit
                List <ProductDetailsWS> listProduct = OperationsWebService.getSaleProductDetails(Configuration.securityToken, sale.saleNRI, (int)Configuration.currentLanguage, Configuration.userInfos.Udp_NRI).OfType <ProductDetailsWS>().ToList();

                foreach (ProductDetailsWS p in listProduct)
                {
                    // On parcourt la liste de produit pour trouver le produit qui correspond à la licence
                    foreach (PickedLicensesWS l in p.pickedProducts)
                    {
                        // Puis on affichage les information dans les TextView
                        if (licence.licenseCode == l.code)
                        {
                            FindViewById <TextView>(Resource.Id.tvNameProduct).Text = p.code;
                            FindViewById <TextView>(Resource.Id.tvAmountQte).Text   = p.qtyPicked.ToString();
                            FindViewById <TextView>(Resource.Id.tvAmountPoids).Text = l.weight.ToString() + " kg";
                        }
                    }
                }
            }

            EditText editText = FindViewById <EditText>(Resource.Id.tfLicensePickingDetails);

            editText.KeyPress += (object sender, View.KeyEventArgs e) => {
                e.Handled = false;

                CodeParser parser = new CodeParser();


                if (e.Event.Action == KeyEventActions.Down && e.KeyCode == Keycode.Enter)
                {
                    if (editText.Text.ToString() != "")
                    {
                        editText.Text.Replace(" ", "");
                        licence = new LicenseWS();

                        ParsedLicence parsedLicence = parser.getLicense(editText.Text);
                        licence = Converts.ParsedLicToLicenceWS(parsedLicence);

                        if (licence.licenseCode == null)
                        {
                            licence.licenseCode = editText.Text;
                        }

                        licence.parentNRI = sale.saleNRI;

                        var productResult = OperationsWebService.PickLicenseSale(Configuration.securityToken, licence, Configuration.userInfos.warehouseNRI, Configuration.userInfos.warehouseNRI, Configuration.userInfos.Udp_NRI);
                        if (productResult == null)
                        {
                            Toast.MakeText(this, OperationsWebService.errorMessage, ToastLength.Long).Show();
                            OperationsWebService.errorMessage = "";
                        }
                        else
                        {
                            switch (Configuration.currentLanguage)
                            {
                            case CR_TTLangue.French_Canada:
                            {
                                Toast.MakeText(this, "Licence ajoutée", ToastLength.Long).Show();

                                break;
                            }

                            case CR_TTLangue.English:
                            {
                                Toast.MakeText(this, "License added", ToastLength.Long).Show();
                                break;
                            }
                            }
                        }
                        data = sale;

                        Recreate();
                        e.Handled = true;
                    }
                    else
                    {
                        editText.Text = "";
                        switch (Configuration.currentLanguage)
                        {
                        case CR_TTLangue.French_Canada:
                        {
                            Toast.MakeText(this, Activities.ResourceFR.errEmptyFieldLicense, ToastLength.Long).Show();

                            break;
                        }

                        case CR_TTLangue.English:
                        {
                            Toast.MakeText(this, Activities.ResourceEN.errEmptyFieldLicense, ToastLength.Long).Show();
                            break;
                        }
                        }
                    }
                }
            };
        }
Example #19
0
        public static async Task <IDictionary <string, string> > Run(IDictionary <string, Task <WcfServiceClassInfo> > wcfClasses)
        {
            var codes = new Dictionary <string, string>();

            // create service code files for web api controllers
            foreach (string wcfClassName in wcfClasses.Keys)
            {
                // wcf class info
                var wcfInfo = await wcfClasses[wcfClassName];

                var controllerName       = wcfInfo.ControllerName;
                var controllerNamespace  = wcfInfo.ControllerNamespace;
                var wcfServiceSourceCode = wcfInfo.WcfServiceSourceCode;
                var wcfMethods           = wcfInfo.WcfMethods;
                var isAsmx = wcfInfo.IsAsmx;

                // check if has wcf code
                if (string.IsNullOrEmpty(wcfServiceSourceCode))
                {
                    codes.Add(controllerName, wcfServiceSourceCode);

                    continue;
                }

                // parse wcf code
                var wcfUnit = await CodeParser.ConvertToCompilationUnit(wcfServiceSourceCode);

                // initialize web api code gen
                var unit = SyntaxFactory.CompilationUnit();

                // create using directives for api controller
                var apiUsings = CreateApiControllerUsings();

                // create file header comments
                var fileHeaderComments = CreateFileHeaderComments();
                apiUsings[0] = apiUsings[0].WithUsingKeyword(fileHeaderComments);

                // create using directives for method parameters
                //   all 'usings directives' from wcf file are added regardless if actually used or not (a bit of a hack)
                //   a better way is to use roslyn's semantic model/analysis to determine which 'usings' are truly used by the method parameters
                var wcfUsings = wcfUnit.Usings;

                // add all usings & header comments
                var usingDirectives = BuildUsingDirectives(apiUsings, wcfUsings);
                unit = unit.AddUsings(usingDirectives.ToArray());

                // create namespace
                var namespaceDeclaration = CreateNamespaceDeclaration(controllerNamespace);

                // create field for wcf class instance
                var fieldDeclaration = CreateFieldDeclaration(wcfClassName);

                // create class
                var classDeclaration = CreateClassDeclaration(controllerName);
                classDeclaration = classDeclaration.AddMembers(fieldDeclaration);

                // create methods
                var methodDeclarations = await ServiceCodeMethodsGenerator.CreateMethodDeclarations(controllerName, wcfUnit, wcfMethods, isAsmx);

                classDeclaration = classDeclaration.AddMembers(methodDeclarations.ToArray());

                // finalize & format generated code
                namespaceDeclaration = namespaceDeclaration.AddMembers(classDeclaration);
                unit = unit.AddMembers(namespaceDeclaration);

                var code = unit
                           .NormalizeWhitespace()
                           .ToFullString();

                codes.Add(controllerName, code);
            }

            return(codes);
        }
Example #20
0
        /// <summary>
        /// Compiles a .cs script file, and processes the assembly.
        /// </summary>
        /// <returns>If the script could be compiled and contains command methods, then true.
        /// Otherwise false.</returns>
        private bool Compile()
        {
            Plugin.Output.WriteLine(OutputStyle.NotImportant, Res.script_Compiling, _fileName);

            string source = File.ReadAllText(_fileName);
            CodeParser parser = new CodeParser(source);
            if (!ProcessSource(parser)) return false;

            CodeDomProvider compiler = CodeDomProvider.CreateProvider("CSharp");
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateExecutable = false;
            parameters.GenerateInMemory = true;
            parameters.WarningLevel = 3;
            parameters.TreatWarningsAsErrors = false;
            parameters.CompilerOptions = "/optimize";

            // References
            parameters.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            foreach (string r in _references) parameters.ReferencedAssemblies.Add(r);

            CompilerResults results = compiler.CompileAssemblyFromSource(parameters, source);
            if (results.Errors.Count > 0)
            {
                StringBuilder sbErr = new StringBuilder();
                bool failed = false;
                foreach (CompilerError err in results.Errors)
                {
                    if (sbErr.Length != 0) sbErr.AppendLine();
                    if (err.IsWarning)
                    {
                        sbErr.AppendFormat(Res.script_CompileWarning, err.Line, err.ErrorNumber, err.ErrorText);
                    }
                    else
                    {
                        sbErr.AppendFormat(Res.script_CompileError, err.Line, err.ErrorNumber, err.ErrorText);
                        failed = true;
                    }
                }

                OutputStyle outStyle;
                if (failed)
                {
                    sbErr.Insert(0, string.Format(Res.script_CompileErrors + "\r\n", _fileName));
                    outStyle = OutputStyle.Error;
                }
                else
                {
                    sbErr.Insert(0, string.Format(Res.script_CompileWarnings + "\r\n", _fileName));
                    outStyle = OutputStyle.Warning;
                }

                if (failed) Plugin.Output.Show();
                Plugin.Output.WriteLine(outStyle, sbErr.ToString());

                if (failed) return false;
            }

            //_plugin.Log("  Script compiled successfully.");

            _assembly = results.CompiledAssembly;
            if (!ProcessAssembly()) return false;

            return true;
        }
Example #21
0
 /// <summary>
 /// Instantiate a new Token
 /// </summary>
 /// <param name="Type">Type of Token</param>
 /// <param name="Content">Contents of Token</param>
 public Token(CodeParser Parser, String Content)
 {
     this.Parser = Parser;
     //this.Content = Content;
 }
Example #22
0
        private void SetPorts(ClassDeclarationSyntax classNode, AbstractionModel model, bool isInputPort = false)
        {
            try
            {
                if (isInputPort)
                {
                    var parser = new CodeParser();

                    var baseList     = (parser.GetBaseObjects(classNode));
                    var portNodeList = (baseList.First() as BaseListSyntax)?.Types.ToList();

                    if (portNodeList == null)
                    {
                        return;
                    }
                    var portSyntaxNodes = portNodeList.Where(n => MatchStartOfString(n.ToString(), ProgrammingParadigms));

                    var docLines         = model.SourceCode.Split(new [] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
                    var classDeclaration = docLines.First(line => line.Trim().Contains($"class {model.Type}"));

                    var implementedPortNames = new List <string>();
                    if (classDeclaration.Contains("//"))
                    {
                        // Get implemented port names
                        // string implementedPortsInlineComment = baseList.LastOrDefault()?.GetTrailingTrivia().ToString().Trim(new []{' ', '/', '\r', '\n'}) ?? "";
                        var implementedPortsInlineComment =
                            classDeclaration.Split(new[] { "//" }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault();

                        if (!string.IsNullOrEmpty(implementedPortsInlineComment))
                        {
                            implementedPortNames = implementedPortsInlineComment.Split(new[] { ", " }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();
                        }
                    }

                    var modelGenerics = model.GetGenerics();

                    var implementedPortCount = 0;
                    foreach (var portSyntaxNode in portSyntaxNodes)
                    {
                        var port = new Port()
                        {
                            Type = portSyntaxNode.Type.ToString()
                        };

                        if (implementedPortCount < implementedPortNames.Count)
                        {
                            port.Name = implementedPortNames[implementedPortCount];
                        }
                        else
                        {
                            port.Name = "?" + port.Type;
                        }

                        // Handle reverse ports (e.g. IDataFlowB and IEventB)
                        // var typeWithoutGenerics = TypeWithoutGenerics(port.Type);
                        // port.IsReversePort = typeWithoutGenerics.EndsWith("B");
                        port.IsReversePort = IsReversePort(port.Type);

                        if (port.IsReversePort)
                        {
                            port.IsInputPort = false;
                            model.AddAcceptedPort(port.Type, port.Name, true);
                        }
                        else
                        {
                            port.IsInputPort = true;
                            model.AddImplementedPort(port.Type, port.Name);
                        }

                        var indexList = new List <int>();

                        if (portSyntaxNode.Type is GenericNameSyntax gen)
                        {
                            var portGenerics = gen
                                               .DescendantNodesAndSelf().OfType <GenericNameSyntax>()
                                               .SelectMany(n => n.TypeArgumentList.Arguments.Select(a => a.ToString()))
                                               .ToHashSet();

                            foreach (var portGeneric in portGenerics)
                            {
                                var index = modelGenerics.IndexOf(portGeneric);
                                if (index != -1)
                                {
                                    indexList.Add(index);
                                }
                            }
                        }

                        model.AddPortGenericIndices(port.Name, indexList);
                        implementedPortCount++;
                    }
                }
                else
                {
                    var parser = new CodeParser()
                    {
                        AccessLevel = "private"
                    };

                    var privateFields   = parser.GetFields(classNode);
                    var portSyntaxNodes = privateFields.Where(n =>
                                                              n is FieldDeclarationSyntax field &&
                                                              (MatchStartOfString(field.Declaration.Type.ToString(), ProgrammingParadigms) ||
                                                               MatchStartOfString(field.Declaration.Type.ToString(), ProgrammingParadigms, prefix: "List<")))
                                          .Select(s => s as FieldDeclarationSyntax);


                    var modelGenerics = model.GetGenerics();
                    foreach (var portSyntaxNode in portSyntaxNodes)
                    {
                        var port = new Port()
                        {
                            Type = portSyntaxNode.Declaration.Type.ToString(),
                            Name = portSyntaxNode.Declaration.Variables.First().Identifier.ToString(),
                        };

                        port.Description = portSyntaxNode.HasLeadingTrivia ? ParsePortDocumentation(portSyntaxNode.GetLeadingTrivia().ToString()) : "";

                        // Handle reverse ports (e.g. IDataFlowB and IEventB)
                        // var typeWithoutGenerics = TypeWithoutGenerics(port.Type);
                        // port.IsReversePort = typeWithoutGenerics.EndsWith("B");
                        port.IsReversePort = IsReversePort(port.Type);

                        if (port.IsReversePort)
                        {
                            port.IsInputPort = true;
                            model.AddImplementedPort(port.Type, port.Name, isReversePort: true, description: port.Description);
                        }
                        else
                        {
                            port.IsInputPort = false;
                            model.AddAcceptedPort(port.Type, port.Name, description: port.Description);
                        }

                        var indexList = new List <int>();

                        if (portSyntaxNode.Declaration.Type is GenericNameSyntax gen)
                        {
                            var portGenerics = gen
                                               .DescendantNodesAndSelf().OfType <GenericNameSyntax>()
                                               .SelectMany(n => n.TypeArgumentList.Arguments.Select(a => a.ToString()).Where(a => modelGenerics.Contains(a)))
                                               .ToHashSet();

                            foreach (var portGeneric in portGenerics)
                            {
                                var index = modelGenerics.IndexOf(portGeneric);
                                if (index != -1)
                                {
                                    indexList.Add(index);
                                }
                            }
                        }

                        model.AddPortGenericIndices(port.Name, indexList);
                    }
                }
            }
            catch (Exception e)
            {
                Logging.Log($"Failed to set {(isInputPort ? "implemented" : "accepted")} ports in AbstractionModelManager.\nError: {e}");
            }
        }
Example #23
0
 public ToUpper__Token(CodeParser Parser, String Content) : base(Parser, Content)
 {
 }
Example #24
0
        public Macro(Project project, Variables variables, out List <LogInfo> logs)
        {
            macroEnabled = true;
            logs         = new List <LogInfo>();
            if (project.MainPlugin.Sections.ContainsKey("Variables") == false)
            {
                macroEnabled = false;
                logs.Add(new LogInfo(LogState.Info, "Macro not defined"));
                return;
            }

            Dictionary <string, string> varDict = Ini.ParseIniLinesVarStyle(project.MainPlugin.Sections["Variables"].GetLines());

            if ((varDict.ContainsKey("API") && varDict.ContainsKey("APIVAR")) == false)
            {
                macroEnabled = false;
                logs.Add(new LogInfo(LogState.Info, "Macro not defined"));
                return;
            }

            // Get macroPlugin
            string rawPluginPath   = varDict["API"];
            string macroPluginPath = variables.Expand(varDict["API"]); // Need Expansion

            macroPlugin = project.AllPlugins.Find(x => string.Equals(x.FullPath, macroPluginPath, StringComparison.OrdinalIgnoreCase));
            if (macroPlugin == null)
            {
                macroEnabled = false;
                logs.Add(new LogInfo(LogState.Error, $"Macro defined but unable to find macro plugin [{rawPluginPath}"));
                return;
            }

            // Get macroPlugin
            if (macroPlugin.Sections.ContainsKey(varDict["APIVAR"]) == false)
            {
                macroEnabled = false;
                logs.Add(new LogInfo(LogState.Error, $"Macro defined but unable to find macro section [{varDict["APIVAR"]}"));
                return;
            }
            macroSection = macroPlugin.Sections[varDict["APIVAR"]];
            variables.SetValue(VarsType.Global, "API", macroPluginPath);
            if (macroPlugin.Sections.ContainsKey("Variables"))
            {
                variables.AddVariables(VarsType.Global, macroPlugin.Sections["Variables"]);
            }

            // Import Section [APIVAR]'s variables, such as '%Shc_Mode%=0'
            variables.AddVariables(VarsType.Global, macroSection);

            // Parse Section [APIVAR] into MacroDict
            {
                SectionAddress addr = new SectionAddress(macroPlugin, macroSection);
                Dictionary <string, string> rawDict = Ini.ParseIniLinesIniStyle(macroSection.GetLines());
                foreach (var kv in rawDict)
                {
                    try
                    {
                        if (Regex.Match(kv.Key, Macro.MacroNameRegex, RegexOptions.Compiled).Success) // Macro Name Validation
                        {
                            macroDict[kv.Key] = CodeParser.ParseStatement(kv.Value, addr);
                        }
                        else
                        {
                            logs.Add(new LogInfo(LogState.Error, $"Invalid macro name [{kv.Key}]"));
                        }
                    }
                    catch (Exception e)
                    {
                        logs.Add(new LogInfo(LogState.Error, e));
                    }
                }
            }

            // Parse MainPlugin's section [Variables] into MacroDict
            // (Written by SetMacro, ... ,PERMANENT
            if (project.MainPlugin.Sections.ContainsKey("Variables"))
            {
                PluginSection  permaSection         = project.MainPlugin.Sections["Variables"];
                SectionAddress addr                 = new SectionAddress(project.MainPlugin, permaSection);
                Dictionary <string, string> rawDict = Ini.ParseIniLinesIniStyle(permaSection.GetLines());
                foreach (var kv in rawDict)
                {
                    try
                    {
                        if (Regex.Match(kv.Key, Macro.MacroNameRegex, RegexOptions.Compiled).Success) // Macro Name Validation
                        {
                            macroDict[kv.Key] = CodeParser.ParseStatement(kv.Value, addr);
                        }
                        else
                        {
                            logs.Add(new LogInfo(LogState.Error, $"Invalid macro name [{kv.Key}]"));
                        }
                    }
                    catch (Exception e)
                    {
                        logs.Add(new LogInfo(LogState.Error, e));
                    }
                }
            }
        }
Example #25
0
        public (List <LogInfo>, Result) CheckScript()
        {
            List <LogInfo> logs = new List <LogInfo>();

            // Codes
            if (_sc.Sections.ContainsKey(ScriptSection.Names.Process))
            {
                logs.AddRange(CheckCodeSection(_sc.Sections[ScriptSection.Names.Process]));
            }

            // UICtrls - [Interface]
            List <string> processedInterfaces = new List <string>();

            if (_sc.Sections.ContainsKey(ScriptSection.Names.Interface))
            {
                processedInterfaces.Add(ScriptSection.Names.Interface);
                logs.AddRange(CheckInterfaceSection(_sc.Sections[ScriptSection.Names.Interface]));
            }
            // UICtrls - Interface=
            if (_sc.MainInfo.ContainsKey(ScriptSection.Names.Interface))
            {
                string ifaceSection = _sc.MainInfo[ScriptSection.Names.Interface];
                processedInterfaces.Add(ifaceSection);
                if (_sc.Sections.ContainsKey(ifaceSection))
                {
                    logs.AddRange(CheckInterfaceSection(_sc.Sections[ifaceSection]));
                }
                else
                {
                    logs.Add(new LogInfo(LogState.Error, $"Section [{ifaceSection}] does not exist (Interface={ifaceSection})"));
                }
            }
            // UICtrls - InterfaceList= (Stage 1)
            if (_sc.MainInfo.ContainsKey(Script.Const.InterfaceList))
            {
                // Check if InterfaceList contains proper sections
                string interfaceList = _sc.MainInfo[Script.Const.InterfaceList];
                try
                {
                    string remainder = interfaceList;
                    while (remainder != null)
                    {
                        string next;
                        (next, remainder) = CodeParser.GetNextArgument(remainder);

                        // Does section exist?
                        if (!_sc.Sections.ContainsKey(next))
                        {
                            logs.Add(new LogInfo(LogState.Error, $"Section [{next}] does not exist (InterfaceList={interfaceList})"));
                        }
                    }
                }
                catch (InvalidCommandException e)
                {
                    logs.Add(new LogInfo(LogState.Error, e));
                }
            }
            // UICtrls - InterfaceList= (Stage 2)
            // Do not enable deepScan, SyntaxChecker have its own implementation of `IniWrite` pattern scanning
            foreach (string ifaceSection in _sc.GetInterfaceSectionNames(false)
                     .Where(x => !processedInterfaces.Contains(x, StringComparer.OrdinalIgnoreCase)))
            {
                if (_sc.Sections.ContainsKey(ifaceSection))
                {
                    logs.AddRange(CheckInterfaceSection(_sc.Sections[ifaceSection]));
                }
            }

            // Result
            Result result = Result.Clean;

            if (logs.Any(x => x.State == LogState.Error || x.State == LogState.CriticalError))
            {
                result = Result.Error;
            }
            else if (logs.Any(x => x.State == LogState.Warning))
            {
                result = Result.Warning;
            }

            return(logs, result);
        }
Example #26
0
 public void SetUp()
 {
     parser = new CodeParser();
 }
Example #27
0
        private void RecursiveFindCodeSection(IReadOnlyList <CodeCommand> codes, List <LogInfo> logs)
        {
            string targetCodeSection      = null;
            string targetInterfaceSection = null;

            foreach (CodeCommand cmd in codes)
            {
                switch (cmd.Type)
                {
                    #region Check CodeSections
                case CodeType.If:
                {
                    CodeInfo_If info = cmd.Info.Cast <CodeInfo_If>();

                    if (info.Condition.Type == BranchConditionType.ExistSection)
                    {
                        // For recursive section call
                        // Ex) If,ExistSection,%ScriptFile%,DoWork,Run,%ScriptFile%,DoWork
                        if (info.Condition.Arg1.Equals(Script.Const.ScriptFile, StringComparison.OrdinalIgnoreCase) &&
                            info.Embed.Type == CodeType.Run || info.Embed.Type == CodeType.RunEx || info.Embed.Type == CodeType.Exec)
                        {
                            CodeInfo_RunExec subInfo = info.Embed.Info.Cast <CodeInfo_RunExec>();
                            if (subInfo.ScriptFile.Equals(Script.Const.ScriptFile, StringComparison.OrdinalIgnoreCase))
                            {
                                if (info.Condition.Arg2.Equals(subInfo.SectionName, StringComparison.OrdinalIgnoreCase))
                                {
                                    continue;
                                }
                            }
                        }
                    }

                    RecursiveFindCodeSection(info.Link, logs);
                }
                break;

                case CodeType.Else:
                {
                    CodeInfo_Else info = cmd.Info.Cast <CodeInfo_Else>();

                    RecursiveFindCodeSection(info.Link, logs);
                }
                break;

                case CodeType.Run:
                case CodeType.Exec:
                case CodeType.RunEx:
                {
                    CodeInfo_RunExec info = cmd.Info.Cast <CodeInfo_RunExec>();

                    // CodeValidator does not have Variable information, so just check with predefined literal
                    if (info.ScriptFile.Equals(Script.Const.ScriptFile, StringComparison.OrdinalIgnoreCase) &&
                        !CodeParser.StringContainsVariable(info.SectionName))
                    {
                        targetCodeSection = info.SectionName;
                    }
                }
                break;

                case CodeType.Loop:
                case CodeType.LoopLetter:
                case CodeType.LoopEx:
                case CodeType.LoopLetterEx:
                {
                    CodeInfo_Loop info = cmd.Info.Cast <CodeInfo_Loop>();

                    if (info.Break)
                    {
                        continue;
                    }

                    // CodeValidator does not have Variable information, so just check with predefined literal
                    if (info.ScriptFile.Equals(Script.Const.ScriptFile, StringComparison.OrdinalIgnoreCase) &&
                        !CodeParser.StringContainsVariable(info.SectionName))
                    {
                        targetCodeSection = info.SectionName;
                    }
                }
                break;

                    #endregion
                    #region Check InterfaceSections
                case CodeType.AddInterface:
                {
                    CodeInfo_AddInterface info = cmd.Info.Cast <CodeInfo_AddInterface>();

                    // CodeValidator does not have Variable information, so just check with predefined literal
                    if (info.ScriptFile.Equals(Script.Const.ScriptFile, StringComparison.OrdinalIgnoreCase) &&
                        !CodeParser.StringContainsVariable(info.Section))
                    {
                        targetInterfaceSection = info.Section;
                    }
                }
                break;

                case CodeType.ReadInterface:
                {
                    CodeInfo_ReadInterface info = cmd.Info.Cast <CodeInfo_ReadInterface>();

                    // CodeValidator does not have Variable information, so just check with predefined literal
                    if (info.ScriptFile.Equals(Script.Const.ScriptFile, StringComparison.OrdinalIgnoreCase) &&
                        !CodeParser.StringContainsVariable(info.Section))
                    {
                        targetInterfaceSection = info.Section;
                    }
                }
                break;

                case CodeType.WriteInterface:
                {
                    CodeInfo_WriteInterface info = cmd.Info.Cast <CodeInfo_WriteInterface>();

                    // CodeValidator does not have Variable information, so just check with predefined literal
                    if (info.ScriptFile.Equals(Script.Const.ScriptFile, StringComparison.OrdinalIgnoreCase) &&
                        !CodeParser.StringContainsVariable(info.Section))
                    {
                        targetInterfaceSection = info.Section;
                    }
                }
                break;

                case CodeType.IniWrite:
                {
                    // To detect multi-interface without `InterfaceList=`,
                    // Inspect pattern `IniWrite,%ScriptFile%,Main,Interface,<NewInterfaceSection>`
                    CodeInfo_IniWrite info = cmd.Info.Cast <CodeInfo_IniWrite>();

                    // CodeValidator does not have Variable information, so just check with predefined literal
                    if (info.FileName.Equals(Script.Const.ScriptFile, StringComparison.OrdinalIgnoreCase) &&
                        info.Section.Equals(ScriptSection.Names.Main, StringComparison.OrdinalIgnoreCase) &&
                        info.Key.Equals(ScriptSection.Names.Interface, StringComparison.OrdinalIgnoreCase) &&
                        !CodeParser.StringContainsVariable(info.Value))
                    {
                        targetInterfaceSection = info.Value;
                    }
                }
                break;
                    #endregion
                }

                if (targetCodeSection != null)
                {
                    if (_sc.Sections.ContainsKey(targetCodeSection))
                    {
                        logs.AddRange(CheckCodeSection(_sc.Sections[targetCodeSection], cmd.RawCode, cmd.LineIdx));
                    }
                    else
                    {
                        logs.Add(new LogInfo(LogState.Error, $"Section [{targetCodeSection}] does not exist", cmd));
                    }
                }

                if (targetInterfaceSection != null)
                {
                    if (_sc.Sections.ContainsKey(targetInterfaceSection))
                    {
                        logs.AddRange(CheckInterfaceSection(_sc.Sections[targetInterfaceSection], cmd.RawCode, cmd.LineIdx));
                    }
                    else
                    {
                        logs.Add(new LogInfo(LogState.Error, $"Section [{targetInterfaceSection}] does not exist", cmd));
                    }
                }
            }
        }
 public void StatndartCodeParserShouldReturnTrueForCorrectString()
 {
     Assert.Equal(true, CodeParser.TryParseStandartCode("FIA standard 8858-2010"));
 }
Example #29
0
 public RightParenToken(CodeParser Parser, String Content) : base(Parser, Content)
 {
 }
Example #30
0
 public PrintToken(CodeParser Parser, String Content) : base(Parser, Content)
 {
 }
Example #31
0
 protected Language(string displayName, List <string> fileExtensions, string langFileDescription,
                    CodeCleaner codeCleaner, CodeTokenizer codeTokenizer, TokenFilterChain tokenFilterChain, CodeParser codeParser,
                    ThreeTextController textController, ThreeStructureController threeStructureController)
 {
     DisplayName              = displayName;
     FileExtensions           = fileExtensions;
     LangFileDescription      = langFileDescription;
     CodeCleaner              = codeCleaner;
     CodeTokenizer            = codeTokenizer;
     TokenFilterChain         = tokenFilterChain;
     CodeParser               = codeParser;
     TextController           = textController;
     ThreeStructureController = threeStructureController;
 }
Example #32
0
 public LessThenToken(CodeParser Parser, String Content) : base(Parser, Content)
 {
 }
Example #33
0
 public NumericFunctionToken(CodeParser Parser, String Content) : base(Parser, Content)
 {
 }
Example #34
0
        private string ParseContent(DataRow dr, string tempate, int rowcount)
        {
            var sOutput = tempate;

            var replyId = dr.GetInt("ReplyId");
            var topicId = dr.GetInt("TopicId");
            var postId = replyId == 0 ? topicId : replyId;
            var contentId = dr.GetInt("ContentId");
            var dateCreated = dr.GetDateTime("DateCreated");
            var dateUpdated = dr.GetDateTime("DateUpdated");
            var authorId = dr.GetInt("AuthorId");
            var username = dr.GetString("Username");
            var firstName = dr.GetString("FirstName");
            var lastName = dr.GetString("LastName");
            var displayName = dr.GetString("DisplayName");
            var userTopicCount = dr.GetInt("TopicCount");
            var userReplyCount = dr.GetInt("ReplyCount");
            var postCount = userTopicCount + userReplyCount;
            var userCaption = dr.GetString("UserCaption");
            var body = dr.GetString("Body");
            var subject = dr.GetString("Subject");
            var tags = dr.GetString("Tags");
            var signature = dr.GetString("Signature");
            var ipAddress = dr.GetString("IPAddress");
            var memberSince = dr.GetDateTime("MemberSince");
            var avatarDisabled = dr.GetBoolean("AvatarDisabled");
            var userRoles = dr.GetString("UserRoles");
            var isUserOnline = dr.GetBoolean("IsUserOnline");
            var replyStatusId = dr.GetInt("StatusId");
            var totalPoints = _enablePoints ? dr.GetInt("UserTotalPoints") : 0;
            var answerCount = dr.GetInt("AnswerCount");
            var rewardPoints = dr.GetInt("RewardPoints");
            var dateLastActivity = dr.GetDateTime("DateLastActivity");
            var signatureDisabled = dr.GetBoolean("SignatureDisabled");

            // Populate the user object with the post author info.
            var up = new User
            {
                UserId = authorId,
                UserName = username,
                FirstName = firstName.Replace("&amp;#", "&#"),
                LastName = lastName.Replace("&amp;#", "&#"),
                DisplayName = displayName.Replace("&amp;#", "&#"),
                Profile =
                    {
                        UserCaption = userCaption,
                        Signature = signature,
                        DateCreated = memberSince,
                        AvatarDisabled = avatarDisabled,
                        Roles = userRoles,
                        ReplyCount = userReplyCount,
                        TopicCount = userTopicCount,
                        AnswerCount = answerCount,
                        RewardPoints = rewardPoints,
                        DateLastActivity = dateLastActivity,
                        PrefBlockAvatars = UserPrefHideAvatars,
                        PrefBlockSignatures = UserPrefHideSigs,
                        IsUserOnline = isUserOnline,
                        SignatureDisabled = signatureDisabled
                    }
            };

            //Perform Profile Related replacements
            sOutput = TemplateUtils.ParseProfileTemplate(sOutput, up, PortalId, ModuleId, ImagePath, CurrentUserType, true, UserPrefHideAvatars, UserPrefHideSigs, ipAddress, UserId, TimeZoneOffset);

            // Replace Tags Control
            if (string.IsNullOrWhiteSpace(tags))
                sOutput = TemplateUtils.ReplaceSubSection(sOutput, string.Empty, "[AF:CONTROL:TAGS]", "[/AF:CONTROL:TAGS]");
            else
            {
                sOutput = sOutput.Replace("[AF:CONTROL:TAGS]", string.Empty);
                sOutput = sOutput.Replace("[/AF:CONTROL:TAGS]", string.Empty);
                var tagList = string.Empty;
                foreach (var tag in tags.Split(','))
                {
                    if (tagList != string.Empty)
                        tagList += ", ";

                    tagList += "<a href=\"" + Utilities.NavigateUrl(TabId, string.Empty, new[] { ParamKeys.ViewType + "=search", ParamKeys.Tags + "=" + HttpUtility.UrlEncode(tag) }) + "\">" + tag + "</a>";
                }
                sOutput = sOutput.Replace("[AF:LABEL:TAGS]", tagList);
            }

            // Use a string builder from here on out.

            var sbOutput = new StringBuilder(sOutput);

            // Row CSS Classes
            if (rowcount % 2 == 0)
            {
                sbOutput.Replace("[POSTINFOCSS]", "afpostinfo afpostinfo1");
                sbOutput.Replace("[POSTTOPICCSS]", "afposttopic afpostreply1");
                sbOutput.Replace("[POSTREPLYCSS]", "afpostreply afpostreply1");
            }
            else
            {
                sbOutput.Replace("[POSTTOPICCSS]", "afposttopic afpostreply2");
                sbOutput.Replace("[POSTINFOCSS]", "afpostinfo afpostinfo2");
                sbOutput.Replace("[POSTREPLYCSS]", "afpostreply afpostreply2");
            }

            // Description
            if (replyId == 0)
            {
                sbOutput.Replace("[POSTID]", topicId.ToString());
                _topicDescription = Utilities.StripHTMLTag(body).Trim();
                _topicDescription = _topicDescription.Replace(System.Environment.NewLine, string.Empty);
                if (_topicDescription.Length > 255)
                    _topicDescription = _topicDescription.Substring(0, 255);
            }
            else
            {
                sbOutput.Replace("[POSTID]", replyId.ToString());
            }

            sbOutput.Replace("[FORUMID]", ForumId.ToString());
            sbOutput.Replace("[REPLYID]", replyId.ToString());
            sbOutput.Replace("[TOPICID]", topicId.ToString());
            sbOutput.Replace("[POSTDATE]", GetDate(dateCreated));
            sbOutput.Replace("[DATECREATED]", GetDate(dateCreated));

            // Parse Roles -- This should actually be taken care of in ParseProfileTemplate
            //if (sOutput.Contains("[ROLES:"))
            //    sOutput = TemplateUtils.ParseRoles(sOutput, (up.UserId == -1) ? string.Empty : up.Profile.Roles);

            // Delete Action
            if (_bModDelete || ((_bDelete && authorId == UserId && !_bLocked) && ((replyId == 0 && _replyCount == 0) || replyId > 0)))
            {
                if (_useListActions)
                    sbOutput.Replace("[ACTIONS:DELETE]", "<li class=\"af-delete\" onclick=\"amaf_postDel(" + topicId + "," + replyId + ");\" title=\"[RESX:Delete]\"><em></em>[RESX:Delete]</li>");
                else
                    sbOutput.Replace("[ACTIONS:DELETE]", "<a href=\"javascript:void(0);\" class=\"af-actions af-delete\" onclick=\"amaf_postDel(" + topicId + "," + replyId + ");\" title=\"[RESX:Delete]\"><em></em>[RESX:Delete]</a>");
            }
            else
            {
                sbOutput.Replace("[ACTIONS:DELETE]", string.Empty);
            }

            // Edit Action
            if (_bModEdit || (_bEdit && authorId == UserId && (_editInterval == 0 || SimulateDateDiff.DateDiff(SimulateDateDiff.DateInterval.Minute, dateCreated, DateTime.Now) < _editInterval)))
            {
                var sAction = "re";
                if (replyId == 0)
                    sAction = "te";

                var editParams = new[] { ParamKeys.ViewType + "=post", "action=" + sAction, ParamKeys.ForumId + "=" + ForumId, ParamKeys.TopicId + "=" + topicId, "postid=" + postId };
                if (_useListActions)
                    sbOutput.Replace("[ACTIONS:EDIT]", "<li class=\"af-edit\" onclick=\"window.location.href='" + Utilities.NavigateUrl(TabId, "", editParams) + "';\" title=\"[RESX:Edit]\"><em></em>[RESX:Edit]</li>");
                else
                    sbOutput.Replace("[ACTIONS:EDIT]", "<a class=\"af-actions af-edit\" href=\"" + Utilities.NavigateUrl(TabId, "", editParams) + "\" title=\"[RESX:Edit]\"><em></em>[RESX:Edit]</a>");
            }
            else
            {
                sbOutput.Replace("[ACTIONS:EDIT]", string.Empty);
            }

            // Reply and Quote Actions
            if (!_bLocked && CanReply)
            {
                var quoteParams = new[] { ParamKeys.ViewType + "=post", ParamKeys.ForumId + "=" + ForumId, ParamKeys.TopicId + "=" + topicId, ParamKeys.QuoteId + "=" + postId };
                var replyParams = new[] { ParamKeys.ViewType + "=post", ParamKeys.ForumId + "=" + ForumId, ParamKeys.TopicId + "=" + topicId, ParamKeys.ReplyId + "=" + postId };
                if (_useListActions)
                {
                    sbOutput.Replace("[ACTIONS:QUOTE]", "<li class=\"af-quote\" onclick=\"window.location.href='" + Utilities.NavigateUrl(TabId, "", quoteParams) + "';\" title=\"[RESX:Quote]\"><em></em>[RESX:Quote]</li>");
                    sbOutput.Replace("[ACTIONS:REPLY]", "<li class=\"af-reply\" onclick=\"window.location.href='" + Utilities.NavigateUrl(TabId, "", replyParams) + "';\" title=\"[RESX:Reply]\"><em></em>[RESX:Reply]</li>");
                }
                else
                {
                    sbOutput.Replace("[ACTIONS:QUOTE]", "<a class=\"af-actions af-quote\" href=\"" + Utilities.NavigateUrl(TabId, "", quoteParams) + "\" title=\"[RESX:Quote]\"><em></em>[RESX:Quote]</a>");
                    sbOutput.Replace("[ACTIONS:REPLY]", "<a class=\"af-actions af-reply\" href=\"" + Utilities.NavigateUrl(TabId, "", replyParams) + "\" title=\"[RESX:Reply]\"><em></em>[RESX:Reply]</a>");
                }
            }
            else
            {
                sbOutput.Replace("[ACTIONS:QUOTE]", string.Empty);
                sbOutput.Replace("[ACTIONS:REPLY]", string.Empty);
            }

            // Status
            if (_statusId <= 0 || (_statusId == 3 && replyStatusId == 0))
            {
                sbOutput.Replace("[ACTIONS:ANSWER]", string.Empty);
            }
            else if (replyStatusId == 1)
            {
                // Answered
                if (_useListActions)
                    sbOutput.Replace("[ACTIONS:ANSWER]", "<li class=\"af-answered\" title=\"[RESX:Status:Answer]\"><em></em>[RESX:Status:Answer]</li>");
                else
                    sbOutput.Replace("[ACTIONS:ANSWER]", "<span class=\"af-actions af-answered\" title=\"[RESX:Status:Answer]\"><em></em>[RESX:Status:Answer]</span>");
            }
            else
            {
                // Not Answered
                if ((UserId == _topicAuthorId && !_bLocked) || _bModEdit)
                {
                    // Can mark answer
                    if (_useListActions)
                        sbOutput.Replace("[ACTIONS:ANSWER]", "<li class=\"af-markanswer\" onclick=\"amaf_markAnswer(" + topicId.ToString() + "," + replyId.ToString() + ");\" title=\"[RESX:Status:SelectAnswer]\"><em></em>[RESX:Status:SelectAnswer]</li>");
                    else
                        sbOutput.Replace("[ACTIONS:ANSWER]", "<a class=\"af-actions af-markanswer\" href=\"#\" onclick=\"amaf_markAnswer(" + topicId.ToString() + "," + replyId.ToString() + "); return false;\" title=\"[RESX:Status:SelectAnswer]\"><em></em>[RESX:Status:SelectAnswer]</a>");
                }
                else
                {
                    // Display Nothing
                    sbOutput.Replace("[ACTIONS:ANSWER]", string.Empty);
                }
            }

            // User Edit Date
            if (dateUpdated == dateCreated || dateUpdated == DateTime.MinValue || dateUpdated == Utilities.NullDate())
            {
                sbOutput.Replace("[EDITDATE]", string.Empty);
            }
            else
            {
                sbOutput.Replace("[EDITDATE]", Utilities.GetDate(dateUpdated, ModuleId, TimeZoneOffset));
            }

            // Mod Edit Date
            if (_bModEdit)
            {
                if (dateCreated == dateUpdated || dateUpdated == DateTime.MinValue || dateUpdated == Utilities.NullDate())
                    sbOutput.Replace("[MODEDITDATE]", string.Empty);
                else
                    sbOutput.Replace("[MODEDITDATE]", Utilities.GetDate(dateUpdated, ModuleId, TimeZoneOffset));
            }
            else
            {
                sbOutput.Replace("[MODEDITDATE]", string.Empty);
            }

            // Poll Results
            if (sOutput.Contains("[POLLRESULTS]") )
            {
                if (_topicType == 1)
                {
                    var polls = new Polls();
                    sbOutput.Replace("[POLLRESULTS]", polls.PollResults(topicId, ImagePath));
                }
                else
                {
                    sbOutput.Replace("[POLLRESULTS]", string.Empty);
                }
            }

            // Mod Alert
            var alertParams = new[] { ParamKeys.ViewType + "=modreport", ParamKeys.ForumId + "=" + ForumId, ParamKeys.TopicId + "=" + topicId, ParamKeys.ReplyId + "=" + postId };
            if (Request.IsAuthenticated)
            {
                if (_useListActions)
                    sbOutput.Replace("[ACTIONS:ALERT]", "<li class=\"af-alert\" onclick=\"window.location.href='" + Utilities.NavigateUrl(TabId, "", alertParams) + "';\" title=\"[RESX:Alert]\"><em></em>[RESX:Alert]</li>");
                else
                    sbOutput.Replace("[ACTIONS:ALERT]", "<a class=\"af-actions af-alert\" href=\"" + Utilities.NavigateUrl(TabId, "", alertParams) + "\" title=\"[RESX:Alert]\"><em></em>[RESX:Alert]</a>");
            }
            else
            {
                sbOutput.Replace("[ACTIONS:ALERT]", string.Empty);
            }

            // Process Body
            if (string.IsNullOrEmpty(body))
                body = " <br />";

            var sBody = Utilities.ManageImagePath(body);

            sBody = sBody.Replace("[", "&#91;");
            sBody = sBody.Replace("]", "&#93;");
            if (sBody.ToUpper().Contains("&#91;CODE&#93;"))
            {
                sBody = Regex.Replace(sBody, "(&#91;CODE&#93;)", "[CODE]", RegexOptions.IgnoreCase);
                sBody = Regex.Replace(sBody, "(&#91;\\/CODE&#93;)", "[/CODE]", RegexOptions.IgnoreCase);

            }
            //sBody = sBody.Replace("&lt;CODE&gt;", "<CODE>")
            if (Regex.IsMatch(sBody, "\\[CODE([^>]*)\\]", RegexOptions.IgnoreCase))
            {
                var objCode = new CodeParser();
                sBody = CodeParser.ParseCode(Utilities.HTMLDecode(sBody));
            }
            sBody = Utilities.StripExecCode(sBody);
            if (MainSettings.AutoLinkEnabled)
                sBody = Utilities.AutoLinks(sBody, Request.Url.Host);

            if (sBody.Contains("<%@"))
                sBody = sBody.Replace("<%@ ", "&lt;&#37;@ ");

            if (body.ToLowerInvariant().Contains("runat"))
                sBody = Regex.Replace(sBody, "runat", "&#114;&#117;nat", RegexOptions.IgnoreCase);

            sbOutput.Replace("[BODY]", sBody);

            // Subject
            sbOutput.Replace("[SUBJECT]", subject);

            // Attachments
            var sAttach =  (_dtAttach.Rows.Count > 0) ? GetAttachments(contentId, _bAttach, PortalId, ModuleId) : string.Empty;
            sbOutput.Replace("[ATTACHMENTS]", sAttach);

            // Switch back from the string builder to a normal string before we perform the image/thumbnail replacements.

            sOutput = sbOutput.ToString();

            // &#91;IMAGE:38&#93;
            if (sOutput.Contains("&#91;IMAGE:"))
            {
                var strHost = Common.Globals.AddHTTP(Common.Globals.GetDomainName(Request)) + "/";
                const string pattern = "(&#91;IMAGE:(.+?)&#93;)";
                sOutput = Regex.Replace(sOutput, pattern, match => "<img src=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + PortalId + "&moduleid=" + ModuleId + "&attachid=" + match.Groups[2].Value + "\" border=\"0\" class=\"afimg\" />");
            }

            // &#91;THUMBNAIL:38&#93;
            if (sOutput.Contains("&#91;THUMBNAIL:"))
            {
                var strHost = Common.Globals.AddHTTP(Common.Globals.GetDomainName(Request)) + "/";
                const string pattern = "(&#91;THUMBNAIL:(.+?)&#93;)";
                sOutput = Regex.Replace(sOutput, pattern, match =>
                {
                    var thumbId = match.Groups[2].Value.Split(':')[0];
                    var parentId = match.Groups[2].Value.Split(':')[1];
                    return "<a href=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + PortalId + "&moduleid=" + ModuleId + "&attachid=" + parentId + "\" target=\"_blank\"><img src=\"" + strHost + "DesktopModules/ActiveForums/viewer.aspx?portalid=" + PortalId + "&moduleid=" + ModuleId + "&attachid=" + thumbId + "\" border=\"0\" class=\"afimg\" /></a>";
                });
            }

            return sOutput;
        }
Example #35
0
        private void InternalValidateCodes(CodeCommand[] codes, List <LogInfo> logs)
        {
            string targetCodeSection      = null;
            string targetInterfaceSection = null;

            foreach (CodeCommand cmd in codes)
            {
                switch (cmd.Type)
                {
                    #region Check CodeSections
                case CodeType.If:
                {
                    CodeInfo_If info = cmd.Info.Cast <CodeInfo_If>();

                    if (info.Condition.Type == BranchConditionType.ExistSection)
                    {
                        // For recursive section call
                        // Ex) If,ExistSection,%ScriptFile%,DoWork,Run,%ScriptFile%,DoWork
                        if (info.Condition.Arg1.Equals("%ScriptFile%", StringComparison.OrdinalIgnoreCase) &&
                            info.Embed.Type == CodeType.Run || info.Embed.Type == CodeType.Exec)
                        {
                            CodeInfo_RunExec subInfo = info.Embed.Info.Cast <CodeInfo_RunExec>();
                            if (subInfo.ScriptFile.Equals("%ScriptFile%", StringComparison.OrdinalIgnoreCase))
                            {
                                if (info.Condition.Arg2.Equals(subInfo.SectionName, StringComparison.OrdinalIgnoreCase))
                                {
                                    continue;
                                }
                            }
                        }
                    }

                    InternalValidateCodes(info.Link.ToArray(), logs);
                }
                break;

                case CodeType.Else:
                {
                    CodeInfo_Else info = cmd.Info.Cast <CodeInfo_Else>();

                    InternalValidateCodes(info.Link.ToArray(), logs);
                }
                break;

                case CodeType.Run:
                case CodeType.Exec:
                case CodeType.RunEx:
                {
                    CodeInfo_RunExec info = cmd.Info.Cast <CodeInfo_RunExec>();

                    // CodeValidator does not have Variable information, so just check with predefined literal
                    if (info.ScriptFile.Equals("%ScriptFile%", StringComparison.OrdinalIgnoreCase) &&
                        !CodeParser.StringContainsVariable(info.SectionName))
                    {
                        targetCodeSection = info.SectionName;
                    }
                }
                break;

                case CodeType.Loop:
                case CodeType.LoopLetter:
                case CodeType.LoopEx:
                case CodeType.LoopLetterEx:
                {
                    CodeInfo_Loop info = cmd.Info.Cast <CodeInfo_Loop>();

                    if (info.Break)
                    {
                        continue;
                    }

                    // CodeValidator does not have Variable information, so just check with predefined literal
                    if (info.ScriptFile.Equals("%ScriptFile%", StringComparison.OrdinalIgnoreCase) &&
                        !CodeParser.StringContainsVariable(info.SectionName))
                    {
                        targetCodeSection = info.SectionName;
                    }
                }
                break;

                    #endregion
                    #region Check InterfaceSections
                case CodeType.AddInterface:
                {
                    CodeInfo_AddInterface info = cmd.Info.Cast <CodeInfo_AddInterface>();

                    // CodeValidator does not have Variable information, so just check with predefined literal
                    if (info.ScriptFile.Equals("%ScriptFile%", StringComparison.OrdinalIgnoreCase) &&
                        CodeParser.StringContainsVariable(info.Section))
                    {
                        targetInterfaceSection = info.Section;
                    }
                }
                break;

                case CodeType.ReadInterface:
                {
                    CodeInfo_ReadInterface info = cmd.Info.Cast <CodeInfo_ReadInterface>();

                    // CodeValidator does not have Variable information, so just check with predefined literal
                    if (info.ScriptFile.Equals("%ScriptFile%", StringComparison.OrdinalIgnoreCase) &&
                        CodeParser.StringContainsVariable(info.Section))
                    {
                        targetInterfaceSection = info.Section;
                    }
                }
                break;

                case CodeType.WriteInterface:
                {
                    CodeInfo_WriteInterface info = cmd.Info.Cast <CodeInfo_WriteInterface>();

                    // CodeValidator does not have Variable information, so just check with predefined literal
                    if (info.ScriptFile.Equals("%ScriptFile%", StringComparison.OrdinalIgnoreCase) &&
                        CodeParser.StringContainsVariable(info.Section))
                    {
                        targetInterfaceSection = info.Section;
                    }
                }
                break;
                    #endregion
                }

                if (targetCodeSection != null && !_visitedSections.Contains(targetCodeSection))
                {
                    _visitedSections.Add(targetCodeSection);

                    if (_sc.Sections.ContainsKey(targetCodeSection))
                    {
                        logs.AddRange(ValidateCodeSection(_sc.Sections[targetCodeSection], cmd.RawCode, cmd.LineIdx));
                    }
                    else
                    {
                        logs.Add(new LogInfo(LogState.Error, $"Section [{targetCodeSection}] does not exist", cmd));
                    }
                }

                if (targetInterfaceSection != null && !_visitedSections.Contains(targetInterfaceSection))
                {
                    _visitedSections.Add(targetInterfaceSection);

                    if (_sc.Sections.ContainsKey(targetInterfaceSection))
                    {
                        logs.AddRange(ValidateInterfaceSection(_sc.Sections[targetInterfaceSection], cmd.RawCode, cmd.LineIdx));
                    }
                    else
                    {
                        logs.Add(new LogInfo(LogState.Error, $"Section [{targetInterfaceSection}] does not exist", cmd));
                    }
                }
            }
        }
Example #36
0
 public ReturnToken(CodeParser Parser, String Content) : base(Parser, Content)
 {
 }
Example #37
0
 public LessOrEqualToken(CodeParser Parser, String Content) : base(Parser, Content)
 {
 }
Example #38
0
 public ToUpper__Token(CodeParser Parser, String Content)
     : base(Parser, Content)
 {
 }
Example #39
0
        public Macro(Project project, Variables variables, out List <LogInfo> logs)
        {
            logs = new List <LogInfo>();

            MacroEnabled = true;
            if (!project.MainScript.Sections.ContainsKey(ScriptSection.Names.Variables))
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Info, "Macro not defined"));
                return;
            }

            ScriptSection mainScriptVarSection = project.MainScript.Sections[ScriptSection.Names.Variables];

            Dictionary <string, string> varDict = IniReadWriter.ParseIniLinesVarStyle(mainScriptVarSection.Lines);

            if (!(varDict.ContainsKey(KnownVar.API) && varDict.ContainsKey(KnownVar.APIVAR)))
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Info, "Macro not defined"));
                return;
            }

            // Get macroScript
            string rawScriptPath   = varDict[KnownVar.API];
            string macroScriptPath = variables.Expand(varDict[KnownVar.API]); // Need expansion

            MacroScript = project.AllScripts.Find(x => x.RealPath.Equals(macroScriptPath, StringComparison.OrdinalIgnoreCase));
            if (MacroScript == null)
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Error, $"Macro defined but unable to find macro script [{rawScriptPath}"));
                return;
            }

            // Get macroScript
            if (!MacroScript.Sections.ContainsKey(varDict[KnownVar.APIVAR]))
            {
                MacroEnabled = false;
                logs.Add(new LogInfo(LogState.Error, $"Macro defined but unable to find macro section [{varDict[KnownVar.APIVAR]}"));
                return;
            }
            MacroSection = MacroScript.Sections[varDict[KnownVar.APIVAR]];
            variables.SetValue(VarsType.Global, KnownVar.API, macroScriptPath);
            if (MacroScript.Sections.ContainsKey(ScriptSection.Names.Variables))
            {
                logs.AddRange(variables.AddVariables(VarsType.Global, MacroScript.Sections[ScriptSection.Names.Variables]));
            }

            // Import Section [APIVAR]'s variables, such as '%Shc_Mode%=0'
            logs.AddRange(variables.AddVariables(VarsType.Global, MacroSection));

            // Parse Section [APIVAR] into MacroDict
            {
                ScriptSection section = MacroSection;
                Dictionary <string, string> rawDict = IniReadWriter.ParseIniLinesIniStyle(MacroSection.Lines);
                foreach (var kv in rawDict)
                {
                    try
                    {
                        if (Regex.Match(kv.Key, MacroNameRegex, RegexOptions.Compiled | RegexOptions.CultureInvariant).Success)
                        { // Macro Name Validation
                            CodeParser parser = new CodeParser(section, Global.Setting, section.Project.Compat);
                            GlobalDict[kv.Key] = parser.ParseStatement(kv.Value);
                        }
                        else
                        {
                            logs.Add(new LogInfo(LogState.Error, $"Invalid macro name [{kv.Key}]"));
                        }
                    }
                    catch (Exception e)
                    {
                        logs.Add(new LogInfo(LogState.Error, e));
                    }
                }
            }

            // Parse MainScript's section [Variables] into MacroDict
            // (Written by SetMacro, ... ,PERMANENT
            if (project.MainScript.Sections.ContainsKey(ScriptSection.Names.Variables))
            {
                ScriptSection permaSection          = project.MainScript.Sections[ScriptSection.Names.Variables];
                Dictionary <string, string> rawDict = IniReadWriter.ParseIniLinesIniStyle(permaSection.Lines);
                foreach (var kv in rawDict)
                {
                    try
                    {
                        if (Regex.Match(kv.Key, MacroNameRegex, RegexOptions.Compiled | RegexOptions.CultureInvariant).Success)
                        { // Macro Name Validation
                            CodeParser parser = new CodeParser(permaSection, Global.Setting, permaSection.Project.Compat);
                            GlobalDict[kv.Key] = parser.ParseStatement(kv.Value);
                        }
                        else
                        {
                            logs.Add(new LogInfo(LogState.Error, $"Invalid macro name [{kv.Key}]"));
                        }
                    }
                    catch (Exception e)
                    {
                        logs.Add(new LogInfo(LogState.Error, e));
                    }
                }
            }
        }