Example #1
0
        public void TestAnalyseTemplateList_一般情况()
        {
            string html = string.Empty;

            using (StreamReader reader = new StreamReader(TestContext.TestDeploymentDir + "\\TemplateFiles\\10.综合测试.一般情况.htm"))
            {
                html = reader.ReadToEnd();

                reader.Close();
            }

            List <TemplateObject> infoList = TemplateAnalyser.AnalyseTemplateList(html);

            Assert.IsNotNull(infoList);
            Assert.AreEqual(2, infoList.Count);

            TemplateObject info1 = infoList[0];

            Assert.AreEqual("list", info1.Category);
            Assert.AreEqual("TestDisp1", info1.DisplayName);
            Assert.AreEqual("Image", info1.DataType);
            Assert.AreEqual(1, info1.Children.Count);
            Assert.AreEqual("Sub1", info1.Children[0].DisplayName);

            TemplateObject info2 = infoList[1];

            Assert.AreEqual("item", info2.Category);
            Assert.AreEqual("TestDisp2", info2.DisplayName);
            Assert.AreEqual("String", info2.DataType);
            Assert.AreEqual(0, info2.Children.Count);
        }
        /// <summary>Executes the command.</summary>
        /// <param name="queue">The command queue involved.</param>
        /// <param name="entry">Entry to be executed.</param>
        public static void Execute(CommandQueue queue, CommandEntry entry)
        {
            string            configName = entry.GetArgument(queue, 0).ToLowerFast();
            AutoConfiguration config     = queue.Engine.Context.GetConfig(configName);

            if (config is null)
            {
                queue.HandleError(entry, $"Invalid config name '{TextStyle.SeparateVal(configName)}' - are you sure you typed it correctly?");
                return;
            }
            string configKey = entry.GetArgument(queue, 1);

            AutoConfiguration.Internal.SingleFieldData field = config.TryGetFieldInternalData(configKey, out AutoConfiguration section, true);
            if (field is null)
            {
                queue.HandleError(entry, $"Invalid config setting key '{TextStyle.SeparateVal(configKey)}' - are you sure you typed it correctly?");
                return;
            }
            TemplateObject newValue = entry.GetArgumentObject(queue, 2);
            object         rawValue = ConvertForType(field.Field.FieldType, newValue, queue);

            field.SetValue(section, rawValue);
            field.OnChanged?.Invoke();
            if (queue.ShouldShowGood())
            {
                queue.GoodOutput($"For config '{TextStyle.SeparateVal(configName)}', set '{TextStyle.SeparateVal(configKey)}' to '{TextStyle.SeparateVal(rawValue)}'");
            }
        }
        /// <summary>
        /// Initializes this instance.
        /// </summary>
        public bool TryRunFrontMatter(IFrontMatter frontMatter, TemplateObject obj, ScriptObject newGlobal = null)
        {
            if (frontMatter == null)
            {
                throw new ArgumentNullException(nameof(frontMatter));
            }
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }

            var context = CreatePageContext();

            context.PushGlobal(obj);
            if (newGlobal != null)
            {
                context.PushGlobal(newGlobal);
            }
            try
            {
                context.EnableOutput   = false;
                context.TemplateLoader = new TemplateLoaderFromIncludes(Site);

                Site.SetValue(PageVariables.Site, this, true);
                frontMatter.Evaluate(context);
            }
            catch (ScriptRuntimeException exception)
            {
                LogException(exception);
                return(false);
            }
            return(true);
        }
Example #4
0
 /// <summary>Checks an object holder's validity (non-null and contains non-null data), for CIL usage.</summary>
 /// <param name="queue">The command queue involved.</param>
 /// <param name="entry">Entry to be executed.</param>
 /// <param name="obj">Object in question.</param>
 /// <param name="varn">Variable the object holder was gotten from.</param>
 public static void CheckForValidity(CommandQueue queue, CommandEntry entry, TemplateObject obj, string varn)
 {
     if (obj == null)
     {
         queue.HandleError(entry, "A variable was required but not found: " + varn + "!");
     }
 }
        private string GetItemHtmlByFlow(TemplateSetItem flow, TemplateObject obj)
        {
            string html = flow.Template.InnerHTML;

            if (obj.Category.Equals("List", StringComparison.OrdinalIgnoreCase))
            {
                TemplateObject item = obj.Children[0];
                if (item.Children != null && item.Children.Count > 0 && item.Children.Count == flow.ChildrenCount)
                {
                    for (int i = 0; i < item.Children.Count; i++)
                    {
                        TemplateObject sub     = item.Children[i];
                        string         oldText = sub.OuterHTML;
                        if (sub.NoUse)
                        {
                            html = html.Replace(oldText, "");
                        }
                        else
                        {
                            int index;
                            if (int.TryParse(sub.DataSource, out index))
                            {
                                string newText = flow.Value.Split(',')[index];
                                html = html.Replace(oldText, newText);
                            }
                            else
                            {
                            }
                        }
                    }
                }
            }
            return(html);
        }
Example #6
0
        internal static TemplateObjectList GetTemplateObjectListFromTmFile(Form form)
        {
            try
            {
                TemplateObjectList templateObjectList = new TemplateObjectList();

                String fileContent = FileUtil.ReadToEndWithStandardEncoding(Path.Combine(ConstantUtil.ApplicationExecutionPath(), ConstantUtil.tmFile));

                String[] separator           = { Environment.NewLine };
                String[] splittedFileContent = fileContent.Split(separator, StringSplitOptions.RemoveEmptyEntries);

                foreach (String extensionString in splittedFileContent)
                {
                    separator[0] = "@|-";
                    String[] splittedExtensionContent = extensionString.Split(separator, StringSplitOptions.None);

                    TemplateObject templateObject = new TemplateObject(splittedExtensionContent[0], splittedExtensionContent[1]);
                    templateObjectList.Add(templateObject);
                }

                return(templateObjectList);
            }
            catch (Exception)
            {
                WindowManager.ShowAlertBox(form, LanguageUtil.GetCurrentLanguageString("ErrorReading", className));
                FileListManager.SaveFileList(ConstantUtil.tmFile, String.Empty);

                return(GetTemplateObjectListFromTmFile(form));
            }
        }
Example #7
0
        internal static int AddTemplate(Templates form, TemplateObjectList templateObjectList, int newTemplateIdentity)
        {
            TreeView templateTreeView   = form.templateTreeView;
            TextBox  descriptionTextBox = form.descriptionTextBox;
            TextBox  textTextBox        = form.textTextBox;
            Button   removeButton       = form.removeButton;

            String newTemplate = LanguageUtil.GetCurrentLanguageString("New", className);

            newTemplateIdentity++;
            String description = String.Format("{0} ({1})", newTemplate, newTemplateIdentity);

            while (CheckIdentityExists(form, templateObjectList, description))
            {
                newTemplateIdentity++;
                description = String.Format("{0} ({1})", newTemplate, newTemplateIdentity);
            }

            TemplateObject extensionObject = new TemplateObject(description, String.Empty);

            templateObjectList.Add(extensionObject);

            templateTreeView.Focus();
            templateTreeView.Nodes.Add(description);
            templateTreeView.SelectedNode = templateTreeView.Nodes[templateTreeView.Nodes.Count - 1];

            descriptionTextBox.Enabled = true;
            textTextBox.Enabled        = true;
            removeButton.Enabled       = true;

            return(newTemplateIdentity);
        }
Example #8
0
        public override void Execute(FreneticScript.CommandSystem.CommandQueue queue, CommandEntry entry)
        {
            TemplateObject tcolor = entry.GetArgumentObject(queue, 0);
            ColorTag       color  = ColorTag.For(tcolor);

            if (color == null)
            {
                queue.HandleError(entry, "Invalid color: " + TagParser.Escape(tcolor.ToString()));
                return;
            }
            string    message  = entry.GetArgument(queue, 1);
            EChatMode chatMode = EChatMode.SAY;

            if (entry.Arguments.Count > 2)
            {
                string mode = entry.GetArgument(queue, 2);
                try
                {
                    chatMode = (EChatMode)Enum.Parse(typeof(EChatMode), mode.ToUpper());
                } catch (ArgumentException)
                {
                    queue.HandleError(entry, "Invalid chat mode: " + mode);
                    return;
                }
            }
            ChatManager.manager.channel.send("tellChat", ESteamCall.OTHERS, ESteamPacket.UPDATE_UNRELIABLE_BUFFER, new object[]
            {
                CSteamID.Nil,
                (byte)chatMode,
                color.Internal,
                message
            });
        }
Example #9
0
        public override void Execute(CommandQueue queue, CommandEntry entry)
        {
            TemplateObject cb = entry.GetArgumentObject(queue, 0);

            if (cb.ToString() == "\0CALLBACK")
            {
                return;
            }
            if (entry.InnerCommandBlock == null)
            {
                queue.HandleError(entry, "Invalid or missing command block!");
                return;
            }
            ListTag          mode  = ListTag.For(cb);
            List <ItemStack> items = new List <ItemStack>();

            for (int i = 1; i < entry.Arguments.Count; i++)
            {
                ItemTag required = ItemTag.For(TheServer, entry.GetArgumentObject(queue, i));
                if (required == null)
                {
                    queue.HandleError(entry, "Invalid required item!");
                    return;
                }
                items.Add(required.Internal);
            }
            TheServer.Recipes.AddRecipe(RecipeRegistry.ModeFor(mode), entry.InnerCommandBlock, entry.BlockStart, items.ToArray());
            queue.CurrentEntry.Index = entry.BlockEnd + 2;
            if (entry.ShouldShowGood(queue))
            {
                entry.Good(queue, "Added recipe!");
            }
        }
 public static LocationTag For(TemplateObject input)
 {
     if (input == null)
     {
         return(null);
     }
     return((input is LocationTag) ? (LocationTag)input : For(input.ToString()));
 }
Example #11
0
 /// <summary>Creates a SystemTag for the given input data.</summary>
 /// <param name="dat">The tag data.</param>
 /// <param name="input">The text input.</param>
 /// <returns>A valid time tag.</returns>
 public static TimeTag CreateFor(TemplateObject input, TagData dat)
 {
     return(input switch
     {
         TimeTag ttag => ttag,
         DynamicTag dtag => CreateFor(dtag.Internal, dat),
         _ => For(input.ToString()),
     });
Example #12
0
 /// <summary>Creates a BinaryTag for the given input data.</summary>
 /// <param name="dat">The tag data.</param>
 /// <param name="input">The text input.</param>
 /// <returns>A valid binary tag.</returns>
 public static BinaryTag CreateFor(TemplateObject input, TagData dat)
 {
     return(input switch
     {
         BinaryTag itag => itag,
         DynamicTag dtag => CreateFor(dtag.Internal, dat),
         _ => For(dat, input.ToString()),
     });
 public static LocationTag For(TemplateObject input)
 {
     if (input == null)
     {
         return null;
     }
     return (input is LocationTag) ? (LocationTag)input : For(input.ToString());
 }
Example #14
0
 /// <summary>
 /// Converts a generic object to a map tag.
 /// Never null. Will ignore invalid entries.
 /// </summary>
 /// <param name="input">The input object.</param>
 /// <returns>The map represented by the input object.</returns>
 public static MapTag For(TemplateObject input)
 {
     return(input switch
     {
         MapTag itag => itag,
         DynamicTag dtag => For(dtag.Internal),
         _ => For(input.ToString()),
     });
Example #15
0
        internal static TemplateObjectList LoadTemplatesList(Templates form)
        {
            TreeView templateTreeView   = form.templateTreeView;
            TextBox  descriptionTextBox = form.descriptionTextBox;
            TextBox  textTextBox        = form.textTextBox;
            Button   removeButton       = form.removeButton;

            TemplateObjectList templateObjectList = new TemplateObjectList();

            String fileContent = FileUtil.ReadToEndWithStandardEncoding(Path.Combine(ConstantUtil.ApplicationExecutionPath(), ConstantUtil.tmFile));

            String[] separator           = { Environment.NewLine };
            String[] splittedFileContent = fileContent.Split(separator, StringSplitOptions.RemoveEmptyEntries);

            if (splittedFileContent.Length > 0)
            {
                templateTreeView.BeginUpdate();
            }

            foreach (String templateString in splittedFileContent) //HTML@|-<html></html>
            {
                separator[0] = "@|-";
                String[] splittedExtensionContent = templateString.Split(separator, StringSplitOptions.None);

                if (splittedExtensionContent.Length != 2)
                {
                    WindowManager.ShowAlertBox(form, LanguageUtil.GetCurrentLanguageString("ErrorReading", className));
                    FileListManager.SaveFileList(ConstantUtil.tmFile, String.Empty);
                    return(LoadTemplatesList(form));
                }

                templateTreeView.Nodes.Add(splittedExtensionContent[0]); //HTML

                TemplateObject templateObject = new TemplateObject(splittedExtensionContent[0], splittedExtensionContent[1]);
                templateObjectList.Add(templateObject);
            }

            if (splittedFileContent.Length > 0)
            {
                templateTreeView.EndUpdate();
            }

            templateTreeView.Focus();

            if (templateTreeView.Nodes.Count > 0)
            {
                templateTreeView.SelectedNode = templateTreeView.Nodes[0];
            }
            else
            {
                descriptionTextBox.Enabled = false;
                textTextBox.Enabled        = false;
                removeButton.Enabled       = false;
            }

            return(templateObjectList);
        }
Example #16
0
 /// <summary>
 /// Get an integer tag relevant to the specified input, erroring on the command system if invalid input is given (Returns 0 in that case).
 /// Never null!
 /// </summary>
 /// <param name="err">Error call if something goes wrong.</param>
 /// <param name="input">The input text to create a integer from.</param>
 /// <returns>The integer tag.</returns>
 public static IntegerTag For(TemplateObject input, Action <string> err)
 {
     return(input switch
     {
         IntegerTag itag => itag,
         IIntegerTagForm itf => new IntegerTag(itf.IntegerForm),
         DynamicTag dtag => For(dtag.Internal, err),
         _ => For(err, input.ToString()),
     });
Example #17
0
 /// <summary>Helps debug output for the var command.</summary>
 /// <param name="res">The object saved as a var.</param>
 /// <param name="varName">The variable name stored into.</param>
 /// <param name="typeName">The variable type name.</param>
 /// <param name="queue">The queue.</param>
 /// <param name="entry">The entry.</param>
 public static void DebugHelper(TemplateObject res, string varName, string typeName, CommandQueue queue, CommandEntry entry)
 {
     if (entry.ShouldShowGood(queue))
     {
         entry.GoodOutput(queue, "Stored variable '" + TextStyle.Separate + varName
                          + TextStyle.Base + "' with value: '" + TextStyle.Separate + res.GetDebugString()
                          + TextStyle.Base + "' as type: '" + TextStyle.Separate + typeName + TextStyle.Base + "'.");
     }
 }
 /// <summary>Converts a script object type to a specific raw type (if possible) for the ConfigSet command.</summary>
 public static object ConvertForType(Type fieldType, TemplateObject input, CommandQueue queue)
 {
     if (fieldType == typeof(string))
     {
         return(input.ToString());
     }
     else if (fieldType == typeof(bool))
     {
         return(BooleanTag.TryFor(input)?.Internal);
     }
     else if (fieldType == typeof(long))
     {
         return(IntegerTag.TryFor(input)?.Internal);
     }
     else if (fieldType == typeof(int))
     {
         IntegerTag integer = IntegerTag.TryFor(input);
         if (integer is not null)
         {
             return((int)integer.Internal);
         }
     }
     else if (fieldType == typeof(short))
     {
         IntegerTag integer = IntegerTag.TryFor(input);
         if (integer is not null)
         {
             return((short)integer.Internal);
         }
     }
     else if (fieldType == typeof(byte))
     {
         IntegerTag integer = IntegerTag.TryFor(input);
         if (integer is not null)
         {
             return((byte)integer.Internal);
         }
     }
     else if (fieldType == typeof(double))
     {
         return(NumberTag.TryFor(input)?.Internal);
     }
     else if (fieldType == typeof(float))
     {
         NumberTag number = NumberTag.TryFor(input);
         if (number is not null)
         {
             return((float)number.Internal);
         }
     }
     else
     {
         queue.HandleError($"Cannot convert script objects to config type {TextStyle.SeparateVal(fieldType.Name)}");
     }
     return(null);
 }
 public static bool EntityDamaged(TemplateObject entity, ref byte amount)
 {
     // TODO: causes?
     EntityDamagedEventArgs evt = new EntityDamagedEventArgs();
     evt.Entity = entity;
     evt.Amount = new NumberTag(amount);
     UnturnedFreneticEvents.OnEntityDamaged.Fire(evt);
     amount = (byte)evt.Amount.Internal;
     return evt.Cancelled;
 }
        TemplateObject verify(TemplateObject input)
        {
            string low = input.ToString().ToLowerFast();

            if (low == "primary" || low == "secondary")
            {
                return(new TextTag(low));
            }
            return(null);
        }
Example #21
0
        internal static TemplateObjectList MoveTemplate(Templates form, ObjectListUtil.Movement move, TemplateObjectList templateObjectList)
        {
            TreeView templateTreeView = form.templateTreeView;

            TreeNode       selectedNode      = templateTreeView.SelectedNode;
            int            selectedNodeIndex = templateTreeView.SelectedNode.Index;
            TemplateObject templateObject    = (TemplateObject)templateObjectList[selectedNodeIndex];

            return((TemplateObjectList)ObjectListUtil.MoveObject(move, templateObjectList, templateObject, templateTreeView, selectedNode, selectedNodeIndex));
        }
Example #22
0
        TemplateObject verify(TemplateObject input)
        {
            string low = input.ToString().ToLowerFast();

            if (low == "award" || low == "take")
            {
                return(new TextTag(low));
            }
            return(null);
        }
Example #23
0
        public static bool EntityDestroyed(TemplateObject entity, ref ushort amount)
        {
            // TODO: causes?
            EntityDestroyedEventArgs evt = new EntityDestroyedEventArgs();

            evt.Entity = entity;
            evt.Amount = new NumberTag(amount);
            UnturnedFreneticEvents.OnEntityDestroyed.Fire(evt);
            amount = (ushort)evt.Amount.Internal;
            return(evt.Cancelled);
        }
Example #24
0
        public static bool EntityDeath(TemplateObject entity, ref byte amount)
        {
            // TODO: causes?
            EntityDeathEventArgs evt = new EntityDeathEventArgs();

            evt.Entity = entity;
            evt.Amount = new NumberTag(amount);
            UnturnedFreneticEvents.OnEntityDeath.Fire(evt);
            amount = (byte)evt.Amount.Internal;
            return(evt.Cancelled);
        }
 /// <summary>
 /// Saves the result of this command, if <see cref="AbstractCommand.SaveMode"/> is set.
 /// <para>Check <see cref="CanSave"/> to determine if a save is expected.</para>
 /// </summary>
 /// <param name="queue">The relevant queue.</param>
 /// <param name="resultObj">The result object.</param>
 public void SaveResult(CommandQueue queue, TemplateObject resultObj)
 {
     if (!CanSave)
     {
         return;
     }
     if (SaveAction == null)
     {
         SaveAction = CCSE.GetSetter(SaveLoc);
     }
     SaveAction(queue.CurrentRunnable, resultObj);
 }
Example #26
0
        public override TemplateObject Handle(TagData data)
        {
            TemplateObject pname = data.GetModifierObject(0);
            ItemTag        ptag  = ItemTag.For(TheServer, pname);

            if (ptag == null)
            {
                data.Error("Invalid player '" + TagParser.Escape(pname.ToString()) + "'!");
                return(new NullTag());
            }
            return(ptag.Handle(data.Shrink()));
        }
Example #27
0
        public override TemplateObject Handle(TagData data)
        {
            TemplateObject rdata = data.GetModifierObject(0);
            RecipeTag      rtag  = RecipeTag.For(TheServer, data, rdata);

            if (rtag == null)
            {
                data.Error("Invalid recipe '" + TagParser.Escape(rdata.ToString()) + "'!");
                return(new NullTag());
            }
            return(rtag.Handle(data.Shrink()));
        }
        public TemplateObject GetSingle(GetTemplateObject PostDataArrived)
        {
            try
            {
                Sqlconn.Open();
                try
                {
                    TemplateObject tmpObj   = null;
                    SqlDataReader  dtReader = null;

                    string sqlquery = string.Format("Select * from Template where [tmplKey]='{0}'",
                                                    new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(
                                                        PostDataArrived.Template.Dataflow.id
                                                        + "+" + PostDataArrived.Template.Dataflow.agency
                                                        + "+" + PostDataArrived.Template.Dataflow.version
                                                        + "+" + PostDataArrived.Template.Configuration.EndPoint).Replace("'", "''"));
                    using (SqlCommand comm = new SqlCommand(sqlquery, Sqlconn))
                    {
                        dtReader = comm.ExecuteReader();
                        if (dtReader.Read())
                        {
                            tmpObj                = new TemplateObject();
                            tmpObj.TemplateId     = dtReader["TemplateId"].ToString();
                            tmpObj.Title          = (string)dtReader["Title"];
                            tmpObj.Configuration  = new JavaScriptSerializer().Deserialize <EndpointSettings>((string)dtReader["Configuration"]);
                            tmpObj.Dataflow       = new JavaScriptSerializer().Deserialize <MaintenableObj>((string)dtReader["Dataflow"]);
                            tmpObj.Criteria       = new JavaScriptSerializer().Deserialize <Dictionary <string, List <string> > >((string)dtReader["Criteria"]);
                            tmpObj.Layout         = new JavaScriptSerializer().Deserialize <LayoutObj>((string)dtReader["Layout"]);
                            tmpObj.HideDimension  = new JavaScriptSerializer().Deserialize <List <string> >((string)dtReader["HideDimension"]);
                            tmpObj.BlockXAxe      = (bool)dtReader["BlockXAxe"];
                            tmpObj.BlockYAxe      = (bool)dtReader["BlockYAxe"];
                            tmpObj.BlockZAxe      = (bool)dtReader["BlockZAxe"];
                            tmpObj.EnableCriteria = (bool)dtReader["EnableCriteria"];
                            tmpObj.EnableVaration = (bool)dtReader["EnableVaration"];
                            tmpObj.EnableDecimal  = (bool)dtReader["EnableDecimal"];
                        }
                    }
                    dtReader.Close();
                    return(tmpObj);
                }
                catch (Exception) { throw; }
                finally
                {
                    Sqlconn.Close();
                }
            }

            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
                throw new Exception(string.Format(ErrorOccuredMess, ex.Message));
            }
        }
        /// <summary>Executes the command.</summary>
        /// <param name="queue">The command queue involved.</param>
        /// <param name="entry">Entry to be executed.</param>
        public static void Execute(CommandQueue queue, CommandEntry entry)
        {
            TemplateObject arg1 = entry.GetArgumentObject(queue, 0);
            BooleanTag     bt   = BooleanTag.TryFor(arg1);

            if (bt == null || !bt.Internal)
            {
                queue.HandleError(entry, "Assertion failed: " + entry.GetArgument(queue, 1));
                return;
            }
            entry.GoodOutput(queue, "Assert command passed, assertion valid!");
        }
Example #30
0
 public static ListTag CreateFor(TemplateObject input)
 {
     return(input switch
     {
         ListTag ltag => ltag,
         IListTagForm lform => lform.ListForm,
         DynamicTag dtag => CreateFor(dtag.Internal),
         TextTag _ => For(input.ToString()),
         _ => new ListTag(new List <TemplateObject>()
         {
             input
         }),
     });
Example #31
0
 public static EntityTag For(TemplateObject input)
 {
     if (input is EntityTag)
     {
         return (EntityTag)input;
     }
     else if (input is ZombieTag)
     {
         return new EntityTag(((ZombieTag)input).Internal.gameObject);
     }
     // TODO: Other common entity types!
     return For(input.ToString());
 }
 public static EntityTag For(TemplateObject input)
 {
     if (input is EntityTag)
     {
         return((EntityTag)input);
     }
     else if (input is ZombieTag)
     {
         return(new EntityTag(((ZombieTag)input).Internal.gameObject));
     }
     // TODO: Other common entity types!
     return(For(input.ToString()));
 }
Example #33
0
        private static int GetTemplatePositionInList(IList templateObjectList, String templateDescription)
        {
            for (int i = 0; i < templateObjectList.Count; i++)
            {
                TemplateObject templateObject = (TemplateObject)templateObjectList[i];

                if (templateObject.Description == templateDescription)
                {
                    return(i);
                }
            }

            return(-1);
        }
Example #34
0
 public static RecipeTag For(Server tserver, TagData data, TemplateObject input)
 {
     if (input is RecipeTag)
     {
         return (RecipeTag)input;
     }
     int ind = (int)IntegerTag.For(data, input).Internal;
     if (ind < 0 || ind >= tserver.Recipes.Recipes.Count)
     {
         data.Error("Invalid recipe input!");
         return null;
     }
     return new RecipeTag(tserver.Recipes.Recipes[ind]);
 }
Example #35
0
 public static RecipeResultTag For(Server tserver, TagData data, TemplateObject input)
 {
     if (input is RecipeResultTag)
     {
         return (RecipeResultTag)input;
     }
     ListTag list = ListTag.For(input);
     RecipeTag recipe = RecipeTag.For(tserver, data, list.ListEntries[0]);
     List<ItemStack> used = new List<ItemStack>();
     for (int i = 1; i < list.ListEntries.Count; i++)
     {
         used.Add(ItemTag.For(tserver, list.ListEntries[i]).Internal);
     }
     return new RecipeResultTag(new RecipeResult() { Recipe = recipe.Internal, UsedInput = used });
 }
 TemplateObject verify(TemplateObject input)
 {
     string low = input.ToString().ToLowerFast();
     if (low == "primary" || low == "secondary")
     {
         return new TextTag(low);
     }
     return null;
 }
 TemplateObject verify(TemplateObject input)
 {
     string low = input.ToString().ToLowerFast();
     if (low == "award" || low == "take")
     {
         return new TextTag(low);
     }
     return null;
 }
Example #38
0
 public static ColorTag For(TemplateObject obj)
 {
     return obj is ColorTag ? (ColorTag)obj : For(obj.ToString());
 }
        public SessionImplObject GetCodemap(SessionQuery query, ConnectionStringSettings connectionStringSetting)
        {
            try
            {
                ISdmxObjects structure = query.Structure;// GetDsd();
                IDataflowObject df = structure.Dataflows.First();
                IDataStructureObject kf = structure.DataStructures.First();

                if (kf == null)
                    throw new InvalidOperationException("DataStructure is not set");
                if (df == null)
                    throw new InvalidOperationException("Dataflow is not set");

                Dictionary<string, ICodelistObject> ConceptCodelists = GetCodelistMap(query, false);

                if (this.SessionObj.SdmxObject!=null )
                { this.SessionObj.SdmxObject.Codelists.Clear();

                foreach (ICodelistObject codelist in ConceptCodelists.Values)
                    this.SessionObj.SdmxObject.AddCodelist(codelist);
                }

                /*check if exist connection and one template*/
                TemplateWidget templateWidget = new TemplateWidget();
                var template = new TemplateObject();

                ///if (connectionStringSetting.ConnectionString!=null && connectionStringSetting.ConnectionString.ToLower() != "file")
                if (connectionStringSetting.ConnectionString != null)
                {
                    templateWidget = new TemplateWidget(connectionStringSetting.ConnectionString);
                    template = templateWidget.GetSingle(new GetTemplateObject()
                    {
                        Template = new TemplateObject()
                        {
                            Dataflow = CodemapObj.Dataflow,
                            Configuration = CodemapObj.Configuration,
                        }
                    });
                }
                else
                { template = null; }

                CodemapSpecificResponseObject codemapret = new CodemapSpecificResponseObject()
                {
                    codemap = ParseCodelist(ConceptCodelists),
                    costraint = (template != null) ? template.Criteria : null,
                    hideDimension = (template != null) ? template.HideDimension : null,
                    //enabledVar = (template != null) ? template.EnableVaration : true,
                    enabledVar = (template != null) ? template.EnableVaration : false,
                    enabledCri = (template != null) ? template.EnableCriteria : true,
                    enabledDec = (template != null) ? template.EnableDecimal : true,
                    key_time_dimension = kf.TimeDimension.Id,
                    freq_dimension = kf.FrequencyDimension.Id,
                    dataflow = new MaintenableObj()
                    {
                        id = df.Id,
                        agency = df.AgencyId,
                        version = df.Version,
                        name = TextTypeHelper.GetText(df.Names, this.CodemapObj.Configuration.Locale),
                        description = TextTypeHelper.GetText(df.Descriptions, this.CodemapObj.Configuration.Locale)
                    }
                };

                this.SessionObj.SavedCodemap = new JavaScriptSerializer().Serialize(codemapret);
                return this.SessionObj;
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
                throw ex;
            }
        }
        public SessionImplObject GetSpecificCodemap(bool firstDimension, ConnectionStringSettings connectionStringSetting, SessionQuery query)
        {
            try
            {
                ISdmxObjects structure;
                //ISdmxObjects structure = query._structure;
                if (query.Structure == null)
                { structure = GetDsd(); }
                else
                { structure =
                    query.Structure; }

                IDataflowObject df = structure.Dataflows.First();
                IDataStructureObject kf = structure.DataStructures.First();

                query.Structure = structure;
                query.Dataflow = df;

                if (kf == null)
                    throw new InvalidOperationException("DataStructure is not set");

                TemplateWidget templateWidget = new TemplateWidget();
                var template = new TemplateObject();
                //if (connectionStringSetting.ConnectionString !=null && connectionStringSetting.ConnectionString.ToLower() != "file")
                if (connectionStringSetting.ConnectionString != null)
                {
                    templateWidget = new TemplateWidget(connectionStringSetting.ConnectionString);
                    template = templateWidget.GetSingle(new GetTemplateObject()
                    {
                        Template = new TemplateObject()
                        {
                            Dataflow = CodemapObj.Dataflow,
                            Configuration = CodemapObj.Configuration,
                        }
                    });
                }
                else
                { template = null; }

                string dimension = null;
                Dictionary<string, ICodelistObject> ConceptCodelists = null;

                // Se ha una template forzo il retrive di tutte le codelist per evitare problemi in stampa tabella
                if (template!=null)
                {
                    ConceptCodelists = this.GetCodelistMap(query, false);
                    query.Criteria = template.Criteria;

                    if (template.Criteria.ContainsKey(kf.TimeDimension.Id))
                    {
                        List<string> typeCheck = template.Criteria[kf.TimeDimension.Id] as List<string>;
                        if (typeCheck != null)
                            typeCheck.Sort();
                        query.SetCriteriaTime(typeCheck);
                    }
                }
                else
                 {
                    dimension = (firstDimension) ? kf.DimensionList.Dimensions.FirstOrDefault().Id : CodemapObj.Codelist;
                    IComponent component = kf.GetComponent(dimension);
                    ICodelistObject ConceptCodelistsComponent = GetCodeList(query, component);
                    //se chiedo tutte le codelist insieme
                    //ConceptCodelists = GetCodelistMap(query, false);
                    //se chiedo una codelist alla volta
                    //ConceptCodelists = GetCodelistMap(component.Id, df, kf;
                    ConceptCodelists = GetCodelistMap(component.Id, df, kf,query);

                  }

                CodemapSpecificResponseObject codemapret = new CodemapSpecificResponseObject()
                {
                    codemap = ParseCodelist(ConceptCodelists,kf,query),
                    costraint = (template != null) ? template.Criteria : null,
                    hideDimension = (template != null) ? template.HideDimension : null,
                    //enabledVar = (template != null) ? template.EnableVaration : true,
                    enabledVar = (template != null) ? template.EnableVaration : false,
                    enabledCri = (template != null) ? template.EnableCriteria : true,
                    enabledDec = (template != null) ? template.EnableDecimal : true,
                    codelist_target = dimension,
                    key_time_dimension = kf.TimeDimension.Id,
                    freq_dimension = kf.FrequencyDimension.Id,
                    dataflow = new MaintenableObj()
                    {
                        id = df.Id,
                        agency = df.AgencyId,
                        version = df.Version,
                        name = TextTypeHelper.GetText(df.Names, this.CodemapObj.Configuration.Locale),
                        description = TextTypeHelper.GetText(df.Descriptions, this.CodemapObj.Configuration.Locale)
                    }
                };

                this.SessionObj.SavedCodemap = new JavaScriptSerializer().Serialize(codemapret);
                return this.SessionObj;
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
                throw ex;
            }
        }
Example #41
0
 public static PlayerTag For(Server tserver, TemplateObject obj)
 {
     return (obj is PlayerTag) ? (PlayerTag)obj : For(tserver, obj.ToString());
 }
Example #42
0
 public static ItemTag For(Server tserver, TemplateObject input)
 {
     return input is ItemTag ? (ItemTag)input : For(tserver, input.ToString());
 }
 private void SortChildren(TemplateObject value)
 {
     value.Children.Sort(new TemplateComparer());
 }
        public static TemplateObject AnalyseTemplate(string html)
        {
            if (string.IsNullOrEmpty(html))
            {
                throw new ArgumentException("分析模板 - 参数不能为空。", "html");
            }
            TemplateObject info = new TemplateObject();

            #region 外部文本

            info.OuterHTML = html;

            #endregion

            #region 内部文本

            Regex regex_InnerText = new Regex(Pattern_InnerText, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            Match match_InnerText = regex_InnerText.Match(html, 0);
            if (match_InnerText.Success)
            {
                info.InnerHTML = match_InnerText.Value;
            }
            else
            {
                info.InnerHTML = string.Empty;
            }

            #endregion

            #region 模板分类

            Regex regex_Category = new Regex(Pattern_Category, RegexOptions.IgnoreCase);
            Match match_Category = regex_Category.Match(html, 0);
            if (match_Category.Success)
            {
                info.Category = match_Category.Value;
            }
            else
            {
                info.Category = string.Empty;
            }

            #endregion

            #region 属性

            Regex regex_Properties = new Regex(Pattern_Properties, RegexOptions.IgnoreCase);
            Match match_Properties = regex_Properties.Match(html, 0);
            if (match_Properties.Success)
            {
                Regex regex_Property = new Regex(Pattern_Property, RegexOptions.IgnoreCase);
                Match match_Property = regex_Property.Match(match_Properties.Value, 0);
                while (match_Property.Success)
                {
                    string text = match_Property.Value;
                    int index = text.IndexOf("=");
                    string title = text.Substring(0, index);
                    string value = text.Substring(index + 1).Trim('"');
                    switch (title.ToLower())
                    {
                        case "id":
                            info.Id = value;
                            break;
                        case "displayname":
                            info.DisplayName = value;
                            break;
                        case "cssname":
                            info.CssName = value;
                            break;
                        case "datatype":
                            info.DataType = value;
                            break;
                        case "datasource":
                            info.DataSource = value;
                            break;
                        case "defaultvalue":
                            info.DefaultValue = value;
                            break;
                        case "showtitle":
                            info.ShowTitle = bool.Parse(value);
                            break;
                        case "demoinput":
                            info.DemoInput = value;
                            break;
                        case "information":
                            info.Information = value;
                            break;
                        case "showthis":
                            info.ShowThis = bool.Parse(value);
                            break;
                        case "index":
                            info.Index = int.Parse(value);
                            break;
                        case "titlewidth":
                            info.TitleWidth = int.Parse(value);
                            break;
                        case "inputwidth":
                            info.InputWidth = int.Parse(value);
                            break;
                        case "inputheight":
                            info.InputHeight = int.Parse(value);
                            break;
                        case "nouse":
                            info.NoUse = bool.Parse(value);
                            break;
                    }

                    match_Property = match_Property.NextMatch();
                }
            }

            #endregion

            return info;
        }
        public TemplateObject GetSingle(GetTemplateObject PostDataArrived)
        {
            try
            {
                Sqlconn.Open();
                try
                {
                    TemplateObject tmpObj = null;
                    SqlDataReader dtReader = null;

                    string sqlquery = string.Format("Select * from Template where [tmplKey]='{0}'",
                        new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(
                        PostDataArrived.Template.Dataflow.id
                        + "+" + PostDataArrived.Template.Dataflow.agency
                        + "+" + PostDataArrived.Template.Dataflow.version
                        + "+" + PostDataArrived.Template.Configuration.EndPoint).Replace("'", "''"));
                    using (SqlCommand comm = new SqlCommand(sqlquery, Sqlconn))
                    {
                        dtReader = comm.ExecuteReader();
                        if(dtReader.Read())
                        {
                            tmpObj = new TemplateObject();
                            tmpObj.TemplateId = dtReader["TemplateId"].ToString();
                            tmpObj.Title = (string)dtReader["Title"];
                            tmpObj.Configuration = new JavaScriptSerializer().Deserialize<EndpointSettings>((string)dtReader["Configuration"]);
                            tmpObj.Dataflow = new JavaScriptSerializer().Deserialize<MaintenableObj>((string)dtReader["Dataflow"]);
                            tmpObj.Criteria = new JavaScriptSerializer().Deserialize<Dictionary<string, List<string>>>((string)dtReader["Criteria"]);
                            tmpObj.Layout = new JavaScriptSerializer().Deserialize<LayoutObj>((string)dtReader["Layout"]);
                            tmpObj.HideDimension = new JavaScriptSerializer().Deserialize<List<string>>((string)dtReader["HideDimension"]);
                            tmpObj.BlockXAxe = (bool)dtReader["BlockXAxe"];
                            tmpObj.BlockYAxe = (bool)dtReader["BlockYAxe"];
                            tmpObj.BlockZAxe = (bool)dtReader["BlockZAxe"];
                            tmpObj.EnableCriteria = (bool)dtReader["EnableCriteria"];
                            tmpObj.EnableVaration = (bool)dtReader["EnableVaration"];
                            tmpObj.EnableDecimal = (bool)dtReader["EnableDecimal"];
                        }
                    }
                    dtReader.Close();
                    return tmpObj;
                }
                catch (Exception) { throw; }
                finally
                {
                    Sqlconn.Close();
                }
            }

            catch (Exception ex)
            {
                Logger.Warn(ex.Message, ex);
                throw new Exception(string.Format(ErrorOccuredMess, ex.Message));
            }
        }
        public List<TemplateObject> Get(GetTemplateObject PostDataArrived)
        {
            try
            {

                //if (PostDataArrived == null

                //    || PostDataArrived.Template == null)

                //    throw new Exception("Input Error");

                Sqlconn.Open();

                try
                {

                    List<TemplateObject> tmpListTemplateObjects = new List<TemplateObject>();

                    string sqlquery;

                    SqlDataReader dtReader;

                    sqlquery = "Select * from Template";

                    using (SqlCommand comm = new SqlCommand(sqlquery, Sqlconn))
                    {

                        dtReader = comm.ExecuteReader();

                        while (dtReader.Read())
                        {

                            TemplateObject tmpObj = new TemplateObject();

                            tmpObj.TemplateId = dtReader["TemplateId"].ToString();

                            tmpObj.Title = (string)dtReader["Title"];

                            tmpObj.Configuration = new JavaScriptSerializer().Deserialize<EndpointSettings>((string)dtReader["Configuration"]);

                            tmpObj.Dataflow = new JavaScriptSerializer().Deserialize<MaintenableObj>((string)dtReader["Dataflow"]);

                            tmpObj.Criteria = new JavaScriptSerializer().Deserialize<Dictionary<string, List<string>>>((string)dtReader["Criteria"]);

                            tmpObj.Layout = new JavaScriptSerializer().Deserialize<LayoutObj>((string)dtReader["Layout"]);

                            tmpObj.HideDimension = new JavaScriptSerializer().Deserialize<List<string>>((string)dtReader["HideDimension"]);

                            tmpObj.BlockXAxe = (bool)dtReader["BlockXAxe"];

                            tmpObj.BlockYAxe = (bool)dtReader["BlockYAxe"];

                            tmpObj.BlockZAxe = (bool)dtReader["BlockZAxe"];

                            tmpObj.EnableCriteria = (bool)dtReader["EnableCriteria"];
                            tmpObj.EnableVaration = (bool)dtReader["EnableVaration"];
                            tmpObj.EnableDecimal = (bool)dtReader["EnableDecimal"];

                            tmpListTemplateObjects.Add(tmpObj);

                        }

                    }

                    dtReader.Close();

                    return tmpListTemplateObjects;

                }

                catch (Exception) { throw; }

                finally
                {

                    Sqlconn.Close();

                }

            }

            catch (Exception ex)
            {

                Logger.Warn(ex.Message, ex);

                throw new Exception(string.Format(ErrorOccuredMess, ex.Message));

            }
        }
 private string GetItemHtmlByFlow(TemplateSetItem flow, TemplateObject obj)
 {
     string html = flow.Template.InnerHTML;
     if (obj.Category.Equals("List", StringComparison.OrdinalIgnoreCase))
     {
         TemplateObject item = obj.Children[0];
         if (item.Children != null && item.Children.Count > 0 && item.Children.Count == flow.ChildrenCount)
         {
             for (int i = 0; i < item.Children.Count; i++)
             {
                 TemplateObject sub = item.Children[i];
                 string oldText = sub.OuterHTML;
                 if (sub.NoUse)
                 {
                     html = html.Replace(oldText, "");
                 }
                 else
                 {
                     int index;
                     if (int.TryParse(sub.DataSource, out index))
                     {
                         string newText = flow.Value.Split(',')[index];
                         html = html.Replace(oldText, newText);
                     }
                     else
                     {
                     }
                 }
             }
         }
     }
     return html;
 }