/// <summary>
            /// Implementors should return any tag/js content
            /// to be rendered after the form tag is closed.
            /// </summary>
            /// <param name="formId">The form id.</param>
            /// <returns></returns>
            public override string CreateBeforeFormClosed(string formId)
            {
                var sb = new StringBuilder();

                sb.Append("if (!window.prototypeValidators) prototypeValidators = new Object();\n");
                sb.AppendFormat("var validator = new Validation('{0}', {1});\n", formId, AjaxHelper.JavascriptOptions(jsOptions));
                sb.AppendFormat("prototypeValidators['{0}'] = validator;\n", formId);

                if (rules.Count != 0)
                {
                    sb.Append("Validation.addAllThese([\n");

                    var addedFirstRule = false;
                    var Comma          = "";

                    foreach (var rule in rules.Values)
                    {
                        sb.AppendFormat("{0} ['{1}', '{2}', {{ {3} }}]\n",
                                        Comma, rule.className,
                                        rule.violationMessage != null ? rule.violationMessage.Replace("'", "\'") : null,
                                        rule.rule);

                        if (!addedFirstRule)
                        {
                            addedFirstRule = true;
                            Comma          = ",";
                        }
                    }

                    sb.Append("]);\n");
                }

                return(AbstractHelper.ScriptBlock(sb.ToString()));
            }
        public void ScriptBlockGeneratesValidatableXHTML()
        {
            const string script      = "var i = 1;";
            var          scriptBlock = AbstractHelper.ScriptBlock(script);

            Assert.AreEqual("\r\n<script type=\"text/javascript\">/*<![CDATA[*/\r\n" + script + "/*]]>*/</script>\r\n", scriptBlock);
        }
Exemplo n.º 3
0
 private string WrapProxyIfNeeded(string result)
 {
     if (WrapProxyInScriptBlock)
     {
         return(AbstractHelper.ScriptBlock(result));
     }
     return(result);
 }
Exemplo n.º 4
0
        /// <summary>
        /// Overwrites a previous message to the output.
        /// </summary>
        /// <param name="messages">An array of string.</param>
        /// <param name="newLine">Whether to add a newline or not.</param>
        /// <param name="size">The size of line will overwrites.</param>
        /// <param name="stderr">Whether is stderr output.</param>
        /// <param name="verbosity">Verbosity level from the verbosity * constants.</param>
        private void DoOverwrite(string[] messages, bool newLine = false, int size = -1,
                                 bool stderr = false, Verbosities verbosity        = Verbosities.Normal)
        {
            var message = string.Join(newLine ? Environment.NewLine : string.Empty, messages);

            if (size < 0)
            {
                // since overwrite is supposed to overwrite last message.
                size = AbstractHelper.StrlenWithoutDecoration(
                    Output.Formatter,
                    (stderr && Output is IOutputConsole) ? lastMessageError : lastMessage);
            }

            // let's fill its length with backspaces
            DoWrite(Str.Repeat("\x08", size), false, stderr, verbosity);

            DoWrite(message, false, stderr, verbosity);

            // In cmd.exe on Win8.1 (possibly 10?), the line can not
            // be cleared, so we need to track the length of previous
            // output and fill it with spaces to make sure the line
            // is cleared.
            var fill = size - AbstractHelper.StrlenWithoutDecoration(Output.Formatter, message);

            if (fill > 0)
            {
                DoWrite(Str.Repeat(fill), false, stderr, verbosity);
                DoWrite(Str.Repeat("\x08", fill), false, stderr, verbosity);
            }

            if (newLine)
            {
                DoWrite(string.Empty, true, stderr, verbosity);
            }

            var output = Output;

            if (stderr && Output is IOutputConsole consoleOutput)
            {
                output = consoleOutput.GetErrorOutput();
            }

            if (!SatisfyVerbosity(output, verbosity))
            {
                return;
            }

            if (stderr)
            {
                lastMessageError = message;
            }
            else
            {
                lastMessage = message;
            }
        }
        public void JavascriptAsGenericSortedListTestOptionsTest()
        {
            IDictionary <string, string> options = new SortedList <string, string>
            {
                { "key1", "option1" },
                { "key2", "option2" }
            };

            Assert.AreEqual("{key1:option1, key2:option2}", AbstractHelper.JavascriptOptions(options));
        }
Exemplo n.º 6
0
        /// <summary>
        /// Selects the relevant elements.
        /// </summary>
        /// <param name="ids">The ids.</param>
        private void SelectRelevantElements(params string[] ids)
        {
            if (ids.Length == 0)
            {
                throw new InvalidOperationException("Must pass at least one id");
            }

            CodeGenerator.Write("jQuery(");
            CodeGenerator.Write(AbstractHelper.Quote(string.Join(",", ids)));
            CodeGenerator.Write(")");
        }
Exemplo n.º 7
0
 public virtual void Report(ProgressChanged value)
 {
     if (value.IsUnknowSize)
     {
         io?.OverwriteError($"{prompt}Downloading ({AbstractHelper.FormatMemory(value.ReceivedSize)})", false);
     }
     else
     {
         io?.OverwriteError($"{prompt}Downloading (<comment>{value}%</comment>)", false);
     }
 }
Exemplo n.º 8
0
 public EditStudentDialog(List<Class> classList, AbstractHelper helper, Action action)
 {
     InitializeComponent();
     this._helper = helper;
     this.Text = action + " student";
     bEditStud.Text = action.ToString();
     foreach (Class c in classList)
     {
         cmbClassList.Items.Add(c);
         cmbEditStudClass.Items.Add(c);
     }
     cmbClassList.SelectedIndex = -1;
 }
        /// <summary>
        /// Render the validation init script
        /// </summary>
        /// <param name="formId"></param>
        /// <returns></returns>
        public override string CreateAfterFormOpened(string formId)
        {
            var display = CommonUtils.ObtainEntryAndRemove(jsOptions, "display");

            var script = new StringBuilder();

            script.Append("$('" + formId + "').setAttribute('z:options','" + AjaxHelper.JavascriptOptions(jsOptions) + "')");
            script.AppendLine(";");

            script.Append("$('" + formId + "').setAttribute('z:display','" + display + "')");
            script.AppendLine(";");

            return(AbstractHelper.ScriptBlock(script.ToString()));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Writes a message to the output.
        /// </summary>
        /// <param name="messages">An array of string.</param>
        /// <param name="newLine">Whether to add a newline or not.</param>
        /// <param name="stderr">Whether is stderr output.</param>
        /// <param name="verbosity">Verbosity level from the verbosity * constants.</param>
        private void DoWrite(string[] messages, bool newLine = false, bool stderr = false,
                             Verbosities verbosity           = Verbosities.Normal)
        {
            if (!VerbosityMapping.TryGetValue(verbosity, out OutputOptions options))
            {
                return;
            }

            if (stopwatch != null && stopwatch.IsRunning)
            {
                var memoryUsage = AbstractHelper.FormatMemory(Environment.WorkingSet);
                var timeSpent   = stopwatch.Elapsed;
                messages = Arr.Map(messages, (message) =>
                {
                    if (!string.IsNullOrEmpty(message))
                    {
                        return($"[{memoryUsage}/{timeSpent.TotalSeconds.ToString("0.00")}s] {message}");
                    }

                    return(message);
                });
            }

            if (stderr && Output is IOutputConsole consoleOutput)
            {
                var errorOutput = consoleOutput.GetErrorOutput();
                Array.ForEach(messages, (message) =>
                {
                    errorOutput.Write(message, newLine, options);
                });

                if (SatisfyVerbosity(errorOutput, options))
                {
                    lastMessageError = string.Join(newLine ? Environment.NewLine : string.Empty, messages);
                }

                return;
            }

            Array.ForEach(messages, (message) =>
            {
                Output.Write(message, newLine, options);
            });

            if (SatisfyVerbosity(Output, options))
            {
                lastMessage = string.Join(newLine ? Environment.NewLine : string.Empty, messages);
            }
        }
Exemplo n.º 11
0
        public void RedirectTo(object url)
        {
            string target;

            if (url is IDictionary)
            {
                target = jsCodeGenerator.UrlBuilder.BuildUrl(
                    jsCodeGenerator.EngineContext.UrlInfo, url as IDictionary);
            }
            else
            {
                target = url.ToString();
            }

            Assign("window.location.href", AbstractHelper.Quote(target));
        }
Exemplo n.º 12
0
        /// <summary>
        /// Pendent
        /// </summary>
        /// <param name="position"></param>
        /// <param name="id"></param>
        /// <param name="renderOptions"></param>
        public override void InsertHtml(string position, string id, object renderOptions)
        {
            var pos = (Position)Enum.Parse(typeof(Position), position, true);

            position = pos.ToString();
            var selector = id;
            var render   = Render(renderOptions);

            if (pos == Position.appendTo || pos == Position.prependTo)
            {
                selector = render.ToString().Replace("\"", "");
                render   = AbstractHelper.Quote(id);
            }
            SelectRelevantElements(selector);

            CodeGenerator.Write("." + position);
            CodeGenerator.Write("(" + render + ");");
            WriteNewLine();
        }
Exemplo n.º 13
0
        /// <summary>
        /// Outputs the content using the renderOptions approach.
        /// <para>
        /// If the renderOptions is a string, the content is escaped and quoted.
        /// </para>
        ///     <para>
        /// If the renderOptions is a dictionary, we extract the key <c>partial</c>
        /// and evaluate the template it points to. The content is escaped and quoted.
        /// </para>
        /// </summary>
        /// <param name="renderOptions">The render options.</param>
        /// <returns></returns>
        /// <example>
        /// The following example uses nvelocity syntax:
        /// <code>
        /// $page.Call('myJsFunction', $page.render("%{partial='shared/newmessage.vm'}") )
        /// </code>
        ///     <para>
        /// Which outputs:
        /// </para>
        ///     <code>
        /// myJsFunction('the content from the newmessage partial view template')
        /// </code>
        /// </example>
        public object Render(object renderOptions)
        {
            if (renderOptions == null)
            {
                throw new ArgumentNullException("renderOptions",
                                                "renderOptions cannot be null. Must be a string or a dictionary");
            }
            if (renderOptions is IDictionary)
            {
                var options = (IDictionary)renderOptions;

                var partialName = (String)options["partial"];

                if (partialName == null)
                {
                    throw new ArgumentNullException("renderOptions",
                                                    "renderOptions, as a dictionary, must have a 'partial' " +
                                                    "entry with the template name to render");
                }

                try
                {
                    var writer = new StringWriter();

                    viewEngineManager.ProcessPartial(partialName, writer, engineContext, controller, context);

                    // Ideally we would call (less overhead and safer)
                    // viewEngineManager.ProcessPartial(partialName, writer, engineContext, parameters);

                    renderOptions = writer.ToString();
                }
                catch (Exception ex)
                {
                    throw new MonoRailException("Could not process partial " + partialName, ex);
                }
            }

            return(AbstractHelper.Quote(JsEscape(renderOptions.ToString())));
        }
Exemplo n.º 14
0
            private static void AddParameterToOptions(IDictionary parameters, IDictionary options, string parameterName,
                                                      bool quote, string prefixToRemove)
            {
                var parameterValue        = CommonUtils.ObtainEntryAndRemove(parameters, parameterName, null);
                var parameterNameToInsert = parameterName;

                if (!string.IsNullOrEmpty(prefixToRemove))
                {
                    parameterNameToInsert = parameterName.Replace(prefixToRemove, string.Empty);
                }

                if (parameterValue != null)
                {
                    if (quote && !parameterValue.StartsWith("'") && !parameterValue.StartsWith("\""))
                    {
                        options.Add(parameterNameToInsert, AbstractHelper.SQuote(parameterValue));
                    }
                    else
                    {
                        options.Add(parameterNameToInsert, parameterValue);
                    }
                }
            }
Exemplo n.º 15
0
 /// <summary>
 /// Quotes the specified content.
 /// </summary>
 /// <param name="content">The content.</param>
 /// <returns></returns>
 protected string Quote(string content)
 {
     return(AbstractHelper.Quote(content));
 }
Exemplo n.º 16
0
 /// <summary>
 /// Replaces the entire target element -- and not only its innerHTML --
 /// by the content evaluated.
 /// </summary>
 /// <param name="id">The target element id</param>
 /// <param name="renderOptions">Defines what to render</param>
 /// <example>
 /// The following example uses nvelocity syntax:
 /// <code>
 /// $page.Replace('messagediv', "%{partial='shared/newmessage.vm'}")
 /// </code>
 /// </example>
 public override void Replace(String id, object renderOptions)
 {
     CodeGenerator.Call("Element.replace", AbstractHelper.Quote(id), Render(renderOptions));
 }
Exemplo n.º 17
0
 /// <summary>
 /// Called by the framework so the component can
 /// render its content
 /// </summary>
 public override void Render()
 {
     Context.Writer.WriteLine(AbstractHelper.ScriptBlock(GenerateJS()));
 }
Exemplo n.º 18
0
 private void SetXmlAsSource()
 {
     if (xmlUri == null)
     {
         SelectXml();
     }
     else
     {
         lblXmlSelected.Text = LBLSELECTEDXML_SELECTED + xmlUri;
     }
     helper = new LinqToXmlHelper(xmlUri);
     databaseToolStripMenuItem.Checked = false;
     xMLToolStripMenuItem.Checked = true;
 }
Exemplo n.º 19
0
 private void SetNetworkAsSource()
 {
     helper = new NetworkHelper(new Client());
     lblXmlSelected.Text = LBLSELECTEDNETWORK;
     networkToolStripMenuItem.Checked = true;
 }
Exemplo n.º 20
0
 private void SetDatabaseAsSource()
 {
     helper = new SqlHelper(StudentsDatabase.GetInstance());
     lblXmlSelected.Text = LBLSELECTEDXML_DEFAULT;
     databaseToolStripMenuItem.Checked = true;
     xMLToolStripMenuItem.Checked = false;
 }
Exemplo n.º 21
0
            /// <summary>
            /// Implementors should return any tag/js content
            /// to be rendered after the form tag is closed.
            /// </summary>
            /// <param name="formId">The form id.</param>
            /// <returns></returns>
            public override string CreateBeforeFormClosed(string formId)
            {
                var stringBuilder = new StringBuilder();

                if (_rules.Count > 0)
                {
                    _options[JQueryOptions.Rules] = AbstractHelper.JavascriptOptions(_rules);
                }

                if (_messages.Count > 0)
                {
                    _options[JQueryOptions.Messages] = AbstractHelper.JavascriptOptions(_messages);
                }

                bool isAjax;

                bool.TryParse(CommonUtils.ObtainEntryAndRemove(
                                  _options,
                                  JQueryOptions.IsAjax,
                                  bool.FalseString), out isAjax);

                if (isAjax)
                {
                    var submitHandler = CommonUtils.ObtainEntryAndRemove(_options, JQueryOptions.SubmitHandler);

                    if (submitHandler == null)
                    {
                        if (_ajaxOptions.Count > 0)
                        {
                            _options.Add(
                                JQueryOptions.SubmitHandler,
                                string.Concat(
                                    "function( form ) { jQuery( form ).ajaxSubmit( ",
                                    AbstractHelper.JavascriptOptions(_ajaxOptions),
                                    "); }"));
                        }
                        else
                        {
                            _options.Add(
                                JQueryOptions.SubmitHandler,
                                "function( form ) { jQuery( form ).ajaxSubmit(); }");
                        }
                    }
                }

                MergeGroupDefinitionsWithOptions();
                GenerateGroupNotEmptyValidatorCustomRule();
                GenerateGroupNotEmptyValidatorCustomClass();

                stringBuilder.Append("jQuery( document ).ready( function() { ");
                stringBuilder.AppendFormat("jQuery(\"#{0}\").validate( {1} );", formId, AbstractHelper.JavascriptOptions(_options));

                if (_customRules.Count > 0)
                {
                    foreach (var rule in _customRules.Values)
                    {
                        stringBuilder.Append(Environment.NewLine);
                        stringBuilder.Append("jQuery.validator.addMethod('");
                        stringBuilder.Append(rule.Name);
                        stringBuilder.Append("', ");
                        stringBuilder.Append(rule.Rule);
                        stringBuilder.Append(", '");
                        stringBuilder.Append(rule.ViolationMessage);
                        stringBuilder.Append("' );");
                    }
                }

                if (_customClasses.Count > 0)
                {
                    foreach (var pair in _customClasses)
                    {
                        stringBuilder.Append(Environment.NewLine);
                        stringBuilder.Append("jQuery.validator.addClassRules({");
                        stringBuilder.Append(string.Format("required{0}", pair.Key));
                        stringBuilder.Append(": ");
                        stringBuilder.Append(AbstractHelper.JavascriptOptions(pair.Value));
                        stringBuilder.Append("});");
                    }
                }

                stringBuilder.Append(" });");

                return(AbstractHelper.ScriptBlock(stringBuilder.ToString()));
            }
Exemplo n.º 22
0
        /// <summary>
        /// Inserts a content snippet relative to the element specified by the <paramref name="id"/>
        ///     <para>
        /// The supported positions are
        /// Top, After, Before, Bottom
        /// </para>
        /// </summary>
        /// <param name="position">The position to insert the content relative to the element id</param>
        /// <param name="id">The target element id</param>
        /// <param name="renderOptions">Defines what to render</param>
        /// <example>
        /// The following example uses nvelocity syntax:
        /// <code>
        /// $page.InsertHtml('Bottom', 'messagestable', "%{partial='shared/newmessage.vm'}")
        /// </code>
        /// </example>
        public override void InsertHtml(string position, string id, object renderOptions)
        {
            position = Enum.Parse(typeof(Position), position, true).ToString();

            CodeGenerator.Call("new Insertion." + position, AbstractHelper.Quote(id), Render(renderOptions));
        }
Exemplo n.º 23
0
        /// <inheritdoc />
        public bool GC(int ttl, int maxSize)
        {
            if (!Enable)
            {
                return(false);
            }

            cacheCollected = true;

            var candidates  = new SortSet <IMetaData, DateTime>();
            var directories = new Queue <string>();

            void AddCandidate(string file)
            {
                var meta = fileSystem.GetMetaData(file);

                candidates.Add(meta, meta.LastAccessTime);
            }

            if (!fileSystem.Exists(CacheDirectory, FileSystemOptions.Directory))
            {
                return(true);
            }

            var contents = fileSystem.GetContents(CacheDirectory);

            Array.ForEach(contents.GetDirectories(), directories.Enqueue);
            Array.ForEach(contents.GetFiles(), AddCandidate);

            while (directories.Count > 0)
            {
#pragma warning disable S4158 // bug: Empty collections should not be accessed or iterated
                contents = fileSystem.GetContents(directories.Dequeue());
#pragma warning restore S4158

                Array.ForEach(contents.GetDirectories(), directories.Enqueue);
                Array.ForEach(contents.GetFiles(), AddCandidate);
            }

            var freeSpace    = 0L;
            var deletedFiles = 0;

            // gc with ttl.
            var expire = DateTime.Now.AddSeconds(-ttl);
            foreach (var candidate in candidates)
            {
                if (candidate.LastAccessTime >= expire)
                {
                    // The sorset will have sorted the modification time.
                    break;
                }

                fileSystem.Delete(candidate.Path);
                candidates.Remove(candidate);
                freeSpace += candidate.Size;
                deletedFiles++;
            }

            void PromptFree()
            {
                io.WriteError($"Cache garbage collection completed, delete {deletedFiles} files, free {AbstractHelper.FormatMemory(freeSpace)} space.");
            }

            // gc with maxSize
            var totalSize = fileSystem.GetMetaData(CacheDirectory).Size;
            if (totalSize < maxSize)
            {
                PromptFree();
                return(true);
            }

            foreach (var candidate in candidates)
            {
                if (totalSize < maxSize)
                {
                    break;
                }

                fileSystem.Delete(candidate.Path);
                totalSize -= candidate.Size;
                freeSpace += candidate.Size;
                deletedFiles++;
            }

            PromptFree();
            return(true);
        }
Exemplo n.º 24
0
 public static string BuildQueryString(this AbstractHelper helper, System.Object parameters)
 {
     return(helper.BuildQueryString(new ModelDictionary(parameters)));
 }
Exemplo n.º 25
0
        /// <inheritdoc />
        protected override int DoRun(IInput input, IOutput output)
        {
            disablePluginsByDefault = input.HasRawOption("--no-plugins");
            var ioConsole = new IOConsole(input, output);

            io = ioConsole;

            var commandName = GetCommandName(input);

            TryGetCommand(commandName, out BaseCommand command);

            LoadPluginCommands(command);

            var isProxyCommand = false;

            if (!string.IsNullOrEmpty(commandName) || command != null)
            {
                // Maybe the command is provided by the plugin. If we can't find
                // us again, we will stop intercepting the exception.
                if (command == null)
                {
                    command = Find(commandName);
                }

                isProxyCommand = command is Command.BaseCommand baseCommand && baseCommand.IsProxyCommand;
            }

            if (!isProxyCommand)
            {
                io.WriteError(
                    $"Running {Bucket.GetVersionPretty()} ({Bucket.GetVersion()},{Bucket.GetReleaseDataPretty()}) on {Platform.GetOSInfo()}",
                    verbosity: Verbosities.Debug);

                if (!(command is CommandSelfUpdate) && Bucket.IsDev && (DateTime.Now - Bucket.GetReleaseData()) > new TimeSpan(60, 0, 0, 0, 0))
                {
                    io.WriteError(
                        "<warning>Warning: This development build of bucket is over 60 days old. It is recommended to update it by running \"self-update\" to get the latest version.</warning>");
                }
            }

            Stopwatch stopWatch = null;

            try
            {
                if (input.HasRawOption("--profile"))
                {
                    stopWatch = new Stopwatch();
                    ioConsole.SetDebugging(stopWatch);
                }

                stopWatch?.Start();
                var exitCode = base.DoRun(input, output);
                stopWatch?.Stop();

                if (stopWatch != null)
                {
                    var memoryUsage = AbstractHelper.FormatMemory(Environment.WorkingSet);
                    var timeSpent   = stopWatch.Elapsed;
                    io.WriteError(string.Empty);
                    io.WriteError($"<info>Memory usage: {memoryUsage}, total time: {timeSpent.TotalSeconds.ToString("0.00")}s</info>");
                    io.WriteError(string.Empty);
                }

                return(exitCode);
            }
            catch (ScriptExecutionException ex)
            {
                return(ex.ExitCode);
            }
        }
Exemplo n.º 26
0
        public void SaveOrUpdate(PageDto item)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item", "The post must be contains a valid instance");
            }

            Page page = this.Session.Load <Page>(item.Id)
                        ?? new Page
            {
                CreatedAt = DateTimeOffset.Now
            };

            if (string.IsNullOrEmpty(item.Author))
            {
                item.Author = Thread.CurrentPrincipal.Identity.Name;
            }

            item.MapPropertiesToInstance(page);

            if (string.IsNullOrEmpty(page.Excerpt))
            {
                page.Excerpt = AbstractHelper.GenerateAbstract(page.Content);
            }

            if (string.IsNullOrEmpty(page.Slug))
            {
                page.Slug = SlugHelper.GenerateSlug(page.Title, page.Id, this.GetPostBySlugInternal);
            }

            if (page.IsTransient)
            {
                ItemComments comments = new ItemComments
                {
                    Item = new ItemReference
                    {
                        Id              = page.Id,
                        Status          = page.Status,
                        ItemPublishedAt = page.PublishAt
                    }
                };

                this.Session.Store(comments);
                page.CommentsId = comments.Id;

                ItemTrackbacks trackbacks = new ItemTrackbacks
                {
                    Item = new ItemReference
                    {
                        Id              = page.Id,
                        Status          = page.Status,
                        ItemPublishedAt = page.PublishAt
                    }
                };

                this.Session.Store(trackbacks);
                page.TrackbacksId = trackbacks.Id;
            }

            this.Session.Store(page);

            UpdateDenormalizedItemIndex.UpdateIndexes(this.store, this.Session, page);

            item.Id = RavenIdHelper.Resolve(page.Id);
        }
Exemplo n.º 27
0
 /// <summary>
 /// Quotes the specified content array.
 /// </summary>
 /// <param name="content">The content array.</param>
 /// <returns></returns>
 protected string[] Quote(object[] content)
 {
     return(AbstractHelper.Quote(content));
 }
Exemplo n.º 28
0
 /// <summary>
 /// Shows the specified elements.
 /// </summary>
 /// <param name="ids">The elements ids.</param>
 /// <remarks>
 /// The elements must exist.
 /// </remarks>
 /// <example>
 /// The following example uses nvelocity syntax:
 /// <code>
 /// $page.Show('div1', 'div2')
 /// </code>
 /// </example>
 public override void Show(params string[] ids)
 {
     CodeGenerator.Call("Element.show", AbstractHelper.Quote(ids));
 }
Exemplo n.º 29
0
		/// <summary>
		/// Creates the standard helpers.
		/// </summary>
		public virtual void CreateStandardHelpers()
		{
			AbstractHelper[] builtInHelpers =
				new AbstractHelper[]
					{
						new AjaxHelper(engineContext), new BehaviourHelper(engineContext),
						new UrlHelper(engineContext), new TextHelper(engineContext),
						new EffectsFatHelper(engineContext), new ScriptaculousHelper(engineContext),
						new DateFormatHelper(engineContext), new HtmlHelper(engineContext),
						new ValidationHelper(engineContext), new DictHelper(engineContext),
						new PaginationHelper(engineContext), new FormHelper(engineContext),
						new JSONHelper(engineContext), new ZebdaHelper(engineContext)
					};

			foreach(AbstractHelper helper in builtInHelpers)
			{
				context.Helpers.Add(helper);

				if (helper is IServiceEnabledComponent)
				{
					serviceInitializer.Initialize(helper, engineContext);
				}
			}
		}
Exemplo n.º 30
0
 public void Alert(object message)
 {
     Call("alert", AbstractHelper.Quote(message));
 }
Exemplo n.º 31
0
        /// <summary>
        /// Selects a method from the given set of methods, based on the argument type.
        /// </summary>
        /// <returns>
        /// A <see cref="T:System.Reflection.MethodBase" /> object containing the matching method, if found; otherwise, null.
        /// </returns>
        /// <param name="bindingAttr">A bitwise combination of <see cref="T:System.Reflection.BindingFlags" /> values. </param>
        /// <param name="match">The set of methods that are candidates for matching. For example, when a <see cref="T:System.Reflection.Binder" /> object is used by <see cref="Overload:System.Type.InvokeMember" />, this is the set of methods Reflection has determined to be possible matches, typically because they have the correct member name. The default implementation provided by <see cref="P:System.Type.DefaultBinder" /> changes the order of this array.</param>
        /// <param name="types">The parameter types used to locate a matching method. </param>
        /// <param name="modifiers">An array of parameter modifiers that enable binding to work with parameter signatures in which the types have been modified. </param>
        /// <exception cref="T:System.Reflection.AmbiguousMatchException">For the default binder, <paramref name="match" /> contains multiple methods that are equally good matches for the parameter types described by <paramref name="types" />. For example, the array in <paramref name="types" /> contains a <see cref="T:System.Type" /> object for MyClass and the array in <paramref name="match" /> contains a method that takes a base class of MyClass and a method that takes an interface that MyClass implements. </exception>
        /// <exception cref="T:System.ArgumentException">For the default binder, <paramref name="match" /> is null or an empty array.-or-An element of <paramref name="types" /> derives from <see cref="T:System.Type" />, but is not of type RuntimeType.</exception>
        public override MethodBase SelectMethod(BindingFlags bindingAttr, MethodBase[] match, Type[] types, ParameterModifier[] modifiers)
        {
            bool matchFound;
            int  currentMatch, bestMatch = -1;

            for (int i = 0; i < match.Length; i++)
            {
                ParameterInfo[] pars = match[i].GetParameters();
                if (pars.Length == types.Length)
                {
                    matchFound   = true;
                    currentMatch = 0;
                    int j = 0;
                    while (j < pars.Length && matchFound)
                    {
                        Type t = types[j];
                        matchFound = (!pars[j].ParameterType.IsValueType && types[j] == NullType.Default) ||
                                     ((bindingAttr & BindingFlags.ExactBinding) == 0 ? (AbstractHelper.IsAssignableFrom(pars[j].ParameterType, t) && (!t.IsValueType || pars[j].ParameterType.IsValueType)) : pars[j].ParameterType == types[j]);
                        if (matchFound && pars[j].ParameterType.FullName.Equals(types[j].FullName))
                        {
                            currentMatch++;
                        }
                        j++;
                    }

                    if (matchFound && currentMatch > bestMatch)
                    {
                        bestMatch = currentMatch;
                        MethodBase temp = match[0];
                        match[0] = match[i];
                        match[i] = temp;
                    }
                }
            }
            return(bestMatch != -1 ? match[0] : null);
        }
Exemplo n.º 32
0
 /// <summary>
 /// Toggles the display status of the specified elements.
 /// </summary>
 /// <param name="ids">The elements ids.</param>
 /// <remarks>
 /// The elements must exist.
 /// </remarks>
 /// <example>
 /// The following example uses nvelocity syntax:
 /// <code>
 /// $page.Toggle('div1', 'div2')
 /// </code>
 /// </example>
 public override void Toggle(params string[] ids)
 {
     CodeGenerator.Call("Element.toggle", AbstractHelper.Quote(ids));
 }