问:
Rails undefined method "to_time_preserves_timezone"
Something was broken and now no one generator is not works but i'm nothing change after i'm using rails generator last time. That's i got in a console

```<code>/home/sanua/ct/config/initializers/new_framework_defaults.rb:15:in `<top (required)>': undefined method `to_time_preserves_timezone=' for ActiveSupport:Module (NoMethodError)
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `block in load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:652:in `block in load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/active_support/notifications.rb:166:in `instrument'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:651:in `load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `block in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `instance_exec'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `run'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:55:in `block in run_initializers'
 from /usr/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:421:in `block in each_strongly_connected_component_from'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `tsort_each_child'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:54:in `run_initializers'
 from /usr/lib/ruby/vendor_ruby/rails/application.rb:352:in `initialize!'
 from /home/sanua/ct/config/environment.rb:5:in `<top (required)>'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `block in require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:92:in `preload'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:143:in `serve'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:131:in `block in run'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `loop'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `run'
 from /usr/lib/ruby/vendor_ruby/spring/application/boot.rb:18:in `<top (required)>'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from -e:1:in `<main>'/home/sanua/ct/config/initializers/new_framework_defaults.rb:15:in `<top (required)>': undefined method `to_time_preserves_timezone=' for ActiveSupport:Module (NoMethodError)
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `block in load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:652:in `block in load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/active_support/notifications.rb:166:in `instrument'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:651:in `load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `block in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `instance_exec'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `run'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:55:in `block in run_initializers'
 from /usr/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:421:in `block in each_strongly_connected_component_from'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `tsort_each_child'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:54:in `run_initializers'
 from /usr/lib/ruby/vendor_ruby/rails/application.rb:352:in `initialize!'
 from /home/sanua/ct/config/environment.rb:5:in `<top (required)>'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `block in require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:92:in `preload'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:143:in `serve'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:131:in `block in run'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `loop'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `run'
 from /usr/lib/ruby/vendor_ruby/spring/application/boot.rb:18:in `<top (required)>'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from -e:1:in `<main>'
</code>```

I constantly see this message whatever i write(rails generate controller, model...)

答: @TRIGUN117 I would suggest you to create a new rails app since its a problem with initializer. I believe something is corrupted in your app.</p>

Body:
Something was broken and now no one generator is not works but i'm nothing change after i'm using rails generator last time. That's i got in a console

/home/sanua/ct/config/initializers/new_framework_defaults.rb:15:in `<top (required)>': undefined method `to_time_preserves_timezone=' for ActiveSupport:Module (NoMethodError)
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `block in load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:652:in `block in load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/active_support/notifications.rb:166:in `instrument'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:651:in `load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `block in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `instance_exec'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `run'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:55:in `block in run_initializers'
 from /usr/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:421:in `block in each_strongly_connected_component_from'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `tsort_each_child'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:54:in `run_initializers'
 from /usr/lib/ruby/vendor_ruby/rails/application.rb:352:in `initialize!'
 from /home/sanua/ct/config/environment.rb:5:in `<top (required)>'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `block in require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:92:in `preload'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:143:in `serve'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:131:in `block in run'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `loop'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `run'
 from /usr/lib/ruby/vendor_ruby/spring/application/boot.rb:18:in `<top (required)>'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from -e:1:in `<main>'/home/sanua/ct/config/initializers/new_framework_defaults.rb:15:in `<top (required)>': undefined method `to_time_preserves_timezone=' for ActiveSupport:Module (NoMethodError)
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `block in load'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:268:in `load'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:652:in `block in load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/active_support/notifications.rb:166:in `instrument'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:651:in `load_config_initializer'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/engine.rb:615:in `block in <class:Engine>'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `instance_exec'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:30:in `run'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:55:in `block in run_initializers'
 from /usr/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:421:in `block in each_strongly_connected_component_from'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:44:in `tsort_each_child'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:415:in `each_strongly_connected_component_from'
 from /usr/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `call'
 from /usr/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component'
 from /usr/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each'
 from /usr/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each'
 from /usr/lib/ruby/vendor_ruby/rails/initializable.rb:54:in `run_initializers'
 from /usr/lib/ruby/vendor_ruby/rails/application.rb:352:in `initialize!'
 from /home/sanua/ct/config/environment.rb:5:in `<top (required)>'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `block in require'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:240:in `load_dependency'
 from /usr/lib/ruby/vendor_ruby/active_support/dependencies.rb:274:in `require'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:92:in `preload'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:143:in `serve'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:131:in `block in run'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `loop'
 from /usr/lib/ruby/vendor_ruby/spring/application.rb:125:in `run'
 from /usr/lib/ruby/vendor_ruby/spring/application/boot.rb:18:in `<top (required)>'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /usr/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from -e:1:in `'

I constantly see this message whatever i write(rails generate controller, model...)


来源: stackexchange

问:
Can't find method app.UseStaticFiles()
I'm following this guide and in step 4, I'm asked to add three lines to the project.json file (which I did and then ran dotnet restore getting a lot of updated packages).

When I enter the three lines in the Configure method, I get red lines on all of them. The methods aren't recognized, no intellisense provided etc.

I also noticed that in the example in the guide, the method signature only takes one parameter of IApplicationBuilder, whereas the one I got generated (using the yo aspnet command) looks like this.

```<code>Configure(IApplicationBuilder, IHostingEnvironment, ILoggerFactory);
</code>```

I'm not sure how to resolve it. My guess is that there's a new version of something in the process (Yo, Generators, Core etc.) but I'm not entirely sure.

I've also found this blog where the method signature resembles the one I'm getting. However, the author of it suggest the same syntax that doesn't work for me. I'm guessing it's a matter of referencing the wrong libraries. How do I approach the issue?

答: That guide is outdated. The updated .Net core does not use project.json anymore which is unfortunate. Instead it is now part of csproj file. And to add the Static file library you have to add it to the project using nuget packet manager. And when you rebuild you will see an entry in csproj file for that library. I think the project.json was a great idea which was inline with core opt-in methodology, since it would allow intellisense to kick in to help you select from available libraries. And since csproj file cant be directly edited in solution you lose that feature. </p>

ContentLicense: CC BY-SA 3.0

Title: Can't find method app.UseStaticFiles()

Body:
I'm following this guide and in step 4, I'm asked to add three lines to the project.json file (which I did and then ran dotnet restore getting a lot of updated packages).

When I enter the three lines in the Configure method, I get red lines on all of them. The methods aren't recognized, no intellisense provided etc.

I also noticed that in the example in the guide, the method signature only takes one parameter of IApplicationBuilder, whereas the one I got generated (using the yo aspnet command) looks like this.

Configure(IApplicationBuilder, IHostingEnvironment, ILoggerFactory);

I'm not sure how to resolve it. My guess is that there's a new version of something in the process (Yo, Generators, Core etc.) but I'm not entirely sure.

I've also found this blog where the method signature resembles the one I'm getting. However, the author of it suggest the same syntax that doesn't work for me. I'm guessing it's a matter of referencing the wrong libraries. How do I approach the issue?


问:
Button's OnClick event doesn't fire
The following code is my ASP.NET page :

```<code><MdsMenu:MenuItem Text="Button" Href="#">
   <asp:Button ID="Button1" runat="server" Text="Button 01" OnClick="Button_Click" />
   <asp:Button ID="Button2" runat="server" Text="Button 02" OnClick="Button_Click" />
</MdsMenu:MenuItem>
</code>```

I don't know why Button_Click event doesn't fire !!!

```<code>protected void Button_Click(object sender, EventArgs e)
{
   Button senderButton = sender as Button;
   Label1.Text = senderButton.ID.ToString();
}
</code>```

MdsMenu:MenuItem is my custom WebControl.
If I insert a Button control out of MdsMenu:MenuItem tag it works well but if I inserted it within MdsMenu:MenuItem tag it doesn't fire the concerned method.
What's wrong with my code ?

Thanks.

Edit:

Menu.cs

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using System.Collections;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Web.UI.HtmlControls;
using System.IO;

namespace MenuServerControl
{
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [DefaultProperty("MenuItems")]
    [ParseChildren(true, "MenuItems")]
    [ToolboxData("<{0}:Menu runat=\"server\"> </{0}:Menu>")]
    public class Menu : WebControl
    {
        #region Fields

        private List<MenuItem> _MenuItems;
        string _Direction
        {
            get
            {
                string direction = "";
                switch (this.Direction)
                {
                    case Directions.LeftToRight:
                        direction = "direction:ltr;";
                        break;
                    case Directions.RightToLeft:
                        direction = "direction:rtl;";
                        break;
                    default:
                        direction = "direction:rtl;";
                        break;
                }
                return direction;
            }
        }
        string _AnimationDelay
        {
            get
            {
                if (AnimationDelay == null)
                    AnimationDelay = 1000;
                return AnimationDelay.ToString().ToLower();
            }
        }
        string _AnimationType
        {
            get
            {
                switch (this.AnimationType)
                {
                    case AnimationType.Opacity_Height:
                        return "animation:{opacity:'show',height:'show'}";
                    case AnimationType.Opacity_Width:
                        return "animation:{opacity:'show',width:'show'}";
                    case AnimationType.Opacity:
                        return "animation:{opacity:'show'}";
                    case AnimationType.Height:
                        return "animation:{height:'show'}";
                    case AnimationType.Width:
                        return "animation:{width:'show'}";
                    case AnimationType.Height_Toggle:
                        return "animation: {height: 'toggle'}";
                    case AnimationType.Width_Toggle:
                        return "animation: {width: 'toggle'}";
                    default:
                        return "animation:{opacity:'show',height:'show'}";
                }
            }
        }
        string _AnimationSpeed
        {
            get
            {
                switch (this.AnimationSpeed)
                {
                    case AnimationSpeed.Fast:
                        return "speed:'fast'";
                    case AnimationSpeed.Normal:
                        return "speed:'normal'";
                    case AnimationSpeed.Slow:
                        return "speed:'slow'";
                    default:
                        return "speed:'fast'";
                }
            }
        }
        string FloatStyle
        {
            get
            {
                if (Direction == Directions.RightToLeft)
                    return "float:right;";
                else return "";
            }
        }
        string _Main_ul_CssClass = "";

        #endregion

        #region Properties

        public string Main_ul_CssClass
        {
            get
            {
                if (string.IsNullOrEmpty(_Main_ul_CssClass)) return "";
                _Main_ul_CssClass = "class=" + _Main_ul_CssClass;
                return _Main_ul_CssClass;
            }

            set
            {
                _Main_ul_CssClass = value.Trim();
            }
        }

        public Directions Direction { get; set; }

        public int? AnimationDelay { get; set; }

        public AnimationType AnimationType { get; set; }

        public AnimationSpeed AnimationSpeed { get; set; }

        public bool DropShadow { get; set; }

        public bool AutoArrows { get; set; }

        [Category("Behavior")]
        [Description("The menu collection")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        public List<MenuItem> MenuItems
        {
            get
            {
                if (_MenuItems == null)
                    _MenuItems = new List<MenuItem>();
                return _MenuItems;
            }
        }

        public VerOrHor VerticalOrHorizontal { get; set; }

        #endregion

        #region Methods

        public Menu()
        {
            DropShadow = true;
            AutoArrows = true;
        }

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            writer.Write("<div id=\"" + this.ID + "\" style=\"" + _Direction + " " + FloatStyle + "\">");
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
            writer.Write("</div>");
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            #region Adding Script & link Tags

            HtmlGenericControl jquery = new HtmlGenericControl("script");
            jquery.Attributes.Add("type", "text/javascript");
            jquery.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(MenuServerControl.Menu), "MenuServerControl.JavaScriptFiles.jquery_1_4_3.js"));
            jquery.EnableViewState = false;
            Page.Header.Controls.Add(jquery);

            HtmlGenericControl hoverIntent = new HtmlGenericControl("script");
            hoverIntent.Attributes.Add("type", "text/javascript");
            hoverIntent.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.hoverIntent.js"));
            hoverIntent.EnableViewState = false;
            Page.Header.Controls.Add(hoverIntent);

            HtmlGenericControl jquery_bgiframe_min = new HtmlGenericControl("script");
            jquery_bgiframe_min.Attributes.Add("type", "text/javascript");
            jquery_bgiframe_min.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.jquery_bgiframe_min.js"));
            jquery_bgiframe_min.EnableViewState = false;
            Page.Header.Controls.Add(jquery_bgiframe_min);

            HtmlGenericControl superfish = new HtmlGenericControl("script");
            superfish.Attributes.Add("type", "text/javascript");
            superfish.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.superfish.js"));
            superfish.EnableViewState = false;
            Page.Header.Controls.Add(superfish);

            HtmlGenericControl supersubs = new HtmlGenericControl("script");
            supersubs.Attributes.Add("type", "text/javascript");
            supersubs.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.supersubs.js"));
            supersubs.EnableViewState = false;
            Page.Header.Controls.Add(supersubs);

            if (Direction == Directions.LeftToRight)
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.superfish.css"));
                csslink.ID = "NavigationMenu";
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                csslink.EnableViewState = false;
                Page.Header.Controls.Add(csslink);
            }
            else
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.RightToLeft superfish.css"));
                csslink.ID = "NavigationMenu";
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                csslink.EnableViewState = false;
                Page.Header.Controls.Add(csslink);
            }

            if (this.VerticalOrHorizontal == VerOrHor.Vertical && this.Direction == Directions.RightToLeft)
            {
                HtmlGenericControl csslink01 = new HtmlGenericControl("link");
                csslink01.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.RightToLeft superfish-vertical.css"));
                csslink01.Attributes.Add("type", "text/css");
                csslink01.Attributes.Add("rel", "stylesheet");
                csslink01.EnableViewState = false;
                Page.Header.Controls.Add(csslink01);
            }
            else if (this.VerticalOrHorizontal == VerOrHor.Vertical)
            {
                HtmlGenericControl csslink01 = new HtmlGenericControl("link");
                csslink01.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.superfish-vertical.css"));
                csslink01.Attributes.Add("type", "text/css");
                csslink01.Attributes.Add("rel", "stylesheet");
                csslink01.EnableViewState = false;
                Page.Header.Controls.Add(csslink01);
            }

            #endregion
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write(CreateMenuHtmlTags());
        }

        StringBuilder CreateMenuHtmlTags()
        {
            if (this._MenuItems == null)
                throw new Exception("تگ های مربوط به منو را کامل کنید");

            StringBuilder Html = new StringBuilder("");

            #region Add <Script>

            if (String.IsNullOrEmpty(Main_ul_CssClass))
                Html.Append("<script>$(document).ready(function() { $(\"ul.sf-menu\").superfish({pathLevels:    1,");
            else
                Html.Append("<script>$(document).ready(function() { $(\"ul." + Main_ul_CssClass + "\").superfish({ pathLevels:    1,");

            Html.Append("delay:" + _AnimationDelay + ",");
            Html.Append(_AnimationType + ",");
            Html.Append(_AnimationSpeed + ",");
            Html.Append("dropShadows:  " + DropShadow.ToString().ToLower() + ",");
            Html.Append(@"autoArrows:  " + AutoArrows.ToString().ToLower() + "});});</script>");

            #endregion

            if (string.IsNullOrEmpty(Main_ul_CssClass) && VerticalOrHorizontal == VerOrHor.Vertical)
                Html.Append("<ul class=\"sf-menu sf-vertical sf-js-enabled sf-shadow\" id='sample-menu-1'>");
            else if (String.IsNullOrEmpty(Main_ul_CssClass))
                Html.Append("<ul class=\"sf-menu sf-js-enabled sf-shadow\" id='sample-menu-1'>");
            else
                Html.Append("<ul class=\"" + Main_ul_CssClass + "\" id='sample-menu-1'>");

            foreach (MenuItem item in _MenuItems)
            {
                if (item == null) continue;
                if (item.SubMenuItems != null && item.SubMenuItems.Count > 0)
                {
                    Html.Append("<li" + item.li_CssClass + ">");
                    Html.Append("<a href=\"" + item.Href + "\">" + item.Text.Trim() + "</a>");
                    ParseSubMenuItems(ref Html, item);
                    Html.Append("</li>");
                }
                else if (item.SubMenuItems != null)
                    Html.Append("<li" + item.li_CssClass + "><a href=\"" + item.Href + "\">" + item.Text.Trim() + "</a></li>");
            }
            Html.Append("</ul>");

            return Html;
        }

        void ParseSubMenuItems(ref StringBuilder Html, MenuItem menuItems)
        {
            if (menuItems == null) return;

            Html.Append("<ul " + menuItems.ul_CssClass + " style=\"display: none; visibility: hidden;\">");

            foreach (var item in menuItems.SubMenuItems)
            {
                if (item == null) continue;

                MenuItem Sub_MenuItem = item as MenuItem;
                WebControl webControl = item as WebControl;

                if (Sub_MenuItem != null)
                {
                    if (Sub_MenuItem.SubMenuItems != null && Sub_MenuItem.SubMenuItems.Count > 0)
                    {
                        Html.Append("<li" + Sub_MenuItem.li_CssClass + ">");
                        Html.Append("<a href=\"" + Sub_MenuItem.Href + "\">" + Sub_MenuItem.Text.Trim() + "</a>");
                        ParseSubMenuItems(ref Html, Sub_MenuItem);
                        Html.Append("</li>");
                    }
                    else if (Sub_MenuItem.SubMenuItems != null)
                        Html.Append("<li" + Sub_MenuItem.li_CssClass + "><a href=\"" + Sub_MenuItem.Href + "\">" + Sub_MenuItem.Text.Trim() + "</a></li>");
                }
                else if (webControl != null)
                {
                    Html.Append("<li>");
                    webControl.EnableViewState = true;
                    this.Controls.Add(webControl);
                    webControl.EnableViewState = true;

                    StringBuilder sb = new StringBuilder();
                    sb.Append("<div>");
                    using (StringWriter sw = new StringWriter(sb))
                    {
                        using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))
                        {
                            webControl.RenderControl(textWriter);
                        }
                    }

                    sb.Append("</div>");

                    Html.Append(sb.ToString());
                    Html.Append("</li>");
                }
            }
            Html.Append("</ul>");
        }

        #endregion
    }
}
</code>```

MenuItem.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

namespace MenuServerControl
{
    [DefaultProperty("SubMenuItems")]
    [ParseChildren(true, "SubMenuItems")]
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public class MenuItem : INamingContainer
    {
        #region Fields

        ArrayList _SubMenuItems;
        string text = "";
        string href = "#";
        string _ul_CssClass = "";
        string _li_CssClass = "";

        #endregion

        #region Properties

        [Description("متن منو آیتم")]
        [DefaultValue("")]
        [NotifyParentProperty(true)]
        public string Text
        {
            get
            {
                return text;
            }

            set
            {
                text = value;
            }
        }

        [DefaultValue("#")]
        [Description("<a /> href attribute")]
        [NotifyParentProperty(true)]
        public string Href
        {
            get
            {
                return href;
            }

            set
            {
                href = value;
            }
        }

        [DefaultValue("")]
        [Description("<ul /> css class")]
        [NotifyParentProperty(true)]
        public string ul_CssClass
        {
            get
            {
                if (string.IsNullOrEmpty(_ul_CssClass)) return "";
                _ul_CssClass = " class=\"" + _ul_CssClass + "\"";
                return _ul_CssClass;
            }
            set { this._ul_CssClass = value.Trim(); }
        }

        [DefaultValue("")]
        [Description("<li /> css class")]
        [NotifyParentProperty(true)]
        public string li_CssClass
        {
            get
            {
                if (string.IsNullOrEmpty(_li_CssClass)) return "";
                _li_CssClass = " class=\"" + _li_CssClass + "\"";
                return _li_CssClass;
            }
            set { this._li_CssClass = value.Trim(); }
        }

        [Category("Behavior")]
        [Description("The MenuItems collection")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        public ArrayList SubMenuItems
        {
            get
            {
                if (_SubMenuItems == null)
                    _SubMenuItems = new ArrayList();
                return _SubMenuItems;
            }
        }

        #endregion
    }
}
</code>```

You can download the project from here.

答:
Step #1: have hidden button with the desired OnClick outside of the control, in the .aspx page itself e.g.

```<code><asp:Button ID="Button1" runat="server" OnClick="Button_Click" style="display: none;"  />
</code>```

Step #2: have OnClientClick in the button inside the control, like this:

```<code><asp:Button ID="SomeIdHere" runat="server" Text="Button 01" OnClientClick="return MakeRealClick('Button1');" />
</code>```

Make sure to put the ID of the "real" button as the argument for "MakeRealClick" function.

Step #3: have this JavaScript code in the page:

```<code><script type="text/javascript">
    function MakeRealClick(sButtonID) {
        var arrInputs = document.getElementsByTagName("input");
        for (var i = 0; i < arrInputs.length; i++) {
            var oCurInput = arrInputs[i];
            if (oCurInput.type == "submit" && (oCurInput.id == sButtonID || EndsWith(oCurInput.id, "_" + sButtonID)))
                oCurInput.click();
        }
        return false;
    }

    function EndsWith(s1, s2) {
        return (s1.length >= s2.length) && (s1.substr(s1.length - s2.length, s2.length) == s2);
    }
</script>
</code>```

This will cause that when clicked, the button inside the menu will search for other button that is outside the menu thus still has "real" OnClick, and auto click it so the final result is the same as if you clicked the hidden button.

Pretty sure there's better way, but like I said: quick fix with minimal change in code.

ContentLicense: CC BY-SA 2.5

Title: Button's OnClick event doesn't fire

Body:
The following code is my ASP.NET page :

<MdsMenu:MenuItem Text="Button" Href="#">
   <asp:Button ID="Button1" runat="server" Text="Button 01" OnClick="Button_Click" />
   <asp:Button ID="Button2" runat="server" Text="Button 02" OnClick="Button_Click" />
</MdsMenu:MenuItem>

I don't know why Button_Click event doesn't fire !!!

protected void Button_Click(object sender, EventArgs e)
{
   Button senderButton = sender as Button;
   Label1.Text = senderButton.ID.ToString();
}

MdsMenu:MenuItem is my custom WebControl.
If I insert a Button control out of MdsMenu:MenuItem tag it works well but if I inserted it within MdsMenu:MenuItem tag it doesn't fire the concerned method.
What's wrong with my code ?

Thanks.

Edit:

Menu.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Permissions;
using System.Collections;
using System.ComponentModel.Design;
using System.Drawing.Design;
using System.Web.UI.HtmlControls;
using System.IO;

namespace MenuServerControl
{
    [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal)]
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
    [DefaultProperty("MenuItems")]
    [ParseChildren(true, "MenuItems")]
    [ToolboxData("<{0}:Menu runat=\"server\"> </{0}:Menu>")]
    public class Menu : WebControl
    {
        #region Fields

        private List<MenuItem> _MenuItems;
        string _Direction
        {
            get
            {
                string direction = "";
                switch (this.Direction)
                {
                    case Directions.LeftToRight:
                        direction = "direction:ltr;";
                        break;
                    case Directions.RightToLeft:
                        direction = "direction:rtl;";
                        break;
                    default:
                        direction = "direction:rtl;";
                        break;
                }
                return direction;
            }
        }
        string _AnimationDelay
        {
            get
            {
                if (AnimationDelay == null)
                    AnimationDelay = 1000;
                return AnimationDelay.ToString().ToLower();
            }
        }
        string _AnimationType
        {
            get
            {
                switch (this.AnimationType)
                {
                    case AnimationType.Opacity_Height:
                        return "animation:{opacity:'show',height:'show'}";
                    case AnimationType.Opacity_Width:
                        return "animation:{opacity:'show',width:'show'}";
                    case AnimationType.Opacity:
                        return "animation:{opacity:'show'}";
                    case AnimationType.Height:
                        return "animation:{height:'show'}";
                    case AnimationType.Width:
                        return "animation:{width:'show'}";
                    case AnimationType.Height_Toggle:
                        return "animation: {height: 'toggle'}";
                    case AnimationType.Width_Toggle:
                        return "animation: {width: 'toggle'}";
                    default:
                        return "animation:{opacity:'show',height:'show'}";
                }
            }
        }
        string _AnimationSpeed
        {
            get
            {
                switch (this.AnimationSpeed)
                {
                    case AnimationSpeed.Fast:
                        return "speed:'fast'";
                    case AnimationSpeed.Normal:
                        return "speed:'normal'";
                    case AnimationSpeed.Slow:
                        return "speed:'slow'";
                    default:
                        return "speed:'fast'";
                }
            }
        }
        string FloatStyle
        {
            get
            {
                if (Direction == Directions.RightToLeft)
                    return "float:right;";
                else return "";
            }
        }
        string _Main_ul_CssClass = "";

        #endregion

        #region Properties

        public string Main_ul_CssClass
        {
            get
            {
                if (string.IsNullOrEmpty(_Main_ul_CssClass)) return "";
                _Main_ul_CssClass = "class=" + _Main_ul_CssClass;
                return _Main_ul_CssClass;
            }

            set
            {
                _Main_ul_CssClass = value.Trim();
            }
        }

        public Directions Direction { get; set; }

        public int? AnimationDelay { get; set; }

        public AnimationType AnimationType { get; set; }

        public AnimationSpeed AnimationSpeed { get; set; }

        public bool DropShadow { get; set; }

        public bool AutoArrows { get; set; }

        [Category("Behavior")]
        [Description("The menu collection")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        public List<MenuItem> MenuItems
        {
            get
            {
                if (_MenuItems == null)
                    _MenuItems = new List<MenuItem>();
                return _MenuItems;
            }
        }

        public VerOrHor VerticalOrHorizontal { get; set; }

        #endregion

        #region Methods

        public Menu()
        {
            DropShadow = true;
            AutoArrows = true;
        }

        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            writer.Write("
");
        }

        public override void RenderEndTag(HtmlTextWriter writer)
        {
            writer.Write("
");
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            #region Adding Script & link Tags

            HtmlGenericControl jquery = new HtmlGenericControl("script");
            jquery.Attributes.Add("type", "text/javascript");
            jquery.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(MenuServerControl.Menu), "MenuServerControl.JavaScriptFiles.jquery_1_4_3.js"));
            jquery.EnableViewState = false;
            Page.Header.Controls.Add(jquery);

            HtmlGenericControl hoverIntent = new HtmlGenericControl("script");
            hoverIntent.Attributes.Add("type", "text/javascript");
            hoverIntent.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.hoverIntent.js"));
            hoverIntent.EnableViewState = false;
            Page.Header.Controls.Add(hoverIntent);

            HtmlGenericControl jquery_bgiframe_min = new HtmlGenericControl("script");
            jquery_bgiframe_min.Attributes.Add("type", "text/javascript");
            jquery_bgiframe_min.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.jquery_bgiframe_min.js"));
            jquery_bgiframe_min.EnableViewState = false;
            Page.Header.Controls.Add(jquery_bgiframe_min);

            HtmlGenericControl superfish = new HtmlGenericControl("script");
            superfish.Attributes.Add("type", "text/javascript");
            superfish.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.superfish.js"));
            superfish.EnableViewState = false;
            Page.Header.Controls.Add(superfish);

            HtmlGenericControl supersubs = new HtmlGenericControl("script");
            supersubs.Attributes.Add("type", "text/javascript");
            supersubs.Attributes.Add("src", Page.ClientScript.GetWebResourceUrl(typeof(Menu), "MenuServerControl.JavaScriptFiles.supersubs.js"));
            supersubs.EnableViewState = false;
            Page.Header.Controls.Add(supersubs);

            if (Direction == Directions.LeftToRight)
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.superfish.css"));
                csslink.ID = "NavigationMenu";
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                csslink.EnableViewState = false;
                Page.Header.Controls.Add(csslink);
            }
            else
            {
                HtmlGenericControl csslink = new HtmlGenericControl("link");
                csslink.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.RightToLeft superfish.css"));
                csslink.ID = "NavigationMenu";
                csslink.Attributes.Add("type", "text/css");
                csslink.Attributes.Add("rel", "stylesheet");
                csslink.EnableViewState = false;
                Page.Header.Controls.Add(csslink);
            }

            if (this.VerticalOrHorizontal == VerOrHor.Vertical && this.Direction == Directions.RightToLeft)
            {
                HtmlGenericControl csslink01 = new HtmlGenericControl("link");
                csslink01.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.RightToLeft superfish-vertical.css"));
                csslink01.Attributes.Add("type", "text/css");
                csslink01.Attributes.Add("rel", "stylesheet");
                csslink01.EnableViewState = false;
                Page.Header.Controls.Add(csslink01);
            }
            else if (this.VerticalOrHorizontal == VerOrHor.Vertical)
            {
                HtmlGenericControl csslink01 = new HtmlGenericControl("link");
                csslink01.Attributes.Add("href", Page.ClientScript.GetWebResourceUrl
                    (typeof(Menu), "MenuServerControl.CSS.superfish-vertical.css"));
                csslink01.Attributes.Add("type", "text/css");
                csslink01.Attributes.Add("rel", "stylesheet");
                csslink01.EnableViewState = false;
                Page.Header.Controls.Add(csslink01);
            }

            #endregion
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write(CreateMenuHtmlTags());
        }

        StringBuilder CreateMenuHtmlTags()
        {
            if (this._MenuItems == null)
                throw new Exception("تگ های مربوط به منو را کامل کنید");

            StringBuilder Html = new StringBuilder("");

            #region Add ");

            #endregion

            if (string.IsNullOrEmpty(Main_ul_CssClass) && VerticalOrHorizontal == VerOrHor.Vertical)
                Html.Append("
");
            else if (String.IsNullOrEmpty(Main_ul_CssClass))
                Html.Append("
");
            else
                Html.Append("
");

            foreach (MenuItem item in _MenuItems)
            {
                if (item == null) continue;
                if (item.SubMenuItems != null && item.SubMenuItems.Count > 0)
                {
                    Html.Append("
");
                    Html.Append("" + item.Text.Trim() + "");
                    ParseSubMenuItems(ref Html, item);
                    Html.Append("
");
                }
                else if (item.SubMenuItems != null)
                    Html.Append("
" + item.Text.Trim() + "
");
            }
            Html.Append("
");

            return Html;
        }

        void ParseSubMenuItems(ref StringBuilder Html, MenuItem menuItems)
        {
            if (menuItems == null) return;

            Html.Append("
");

            foreach (var item in menuItems.SubMenuItems)
            {
                if (item == null) continue;

                MenuItem Sub_MenuItem = item as MenuItem;
                WebControl webControl = item as WebControl;

                if (Sub_MenuItem != null)
                {
                    if (Sub_MenuItem.SubMenuItems != null && Sub_MenuItem.SubMenuItems.Count > 0)
                    {
                        Html.Append("
");
                        Html.Append("" + Sub_MenuItem.Text.Trim() + "");
                        ParseSubMenuItems(ref Html, Sub_MenuItem);
                        Html.Append("
");
                    }
                    else if (Sub_MenuItem.SubMenuItems != null)
                        Html.Append("
" + Sub_MenuItem.Text.Trim() + "
");
                }
                else if (webControl != null)
                {
                    Html.Append("
");
                    webControl.EnableViewState = true;
                    this.Controls.Add(webControl);
                    webControl.EnableViewState = true;

                    StringBuilder sb = new StringBuilder();
                    sb.Append("
");
                    using (StringWriter sw = new StringWriter(sb))
                    {
                        using (HtmlTextWriter textWriter = new HtmlTextWriter(sw))
                        {
                            webControl.RenderControl(textWriter);
                        }
                    }

                    sb.Append("
");

                    Html.Append(sb.ToString());
                    Html.Append("
");
                }
            }
            Html.Append("
");
        }

        #endregion
    }
}

MenuItem.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;

namespace MenuServerControl
{
    [DefaultProperty("SubMenuItems")]
    [ParseChildren(true, "SubMenuItems")]
    [TypeConverter(typeof(ExpandableObjectConverter))]
    public class MenuItem : INamingContainer
    {
        #region Fields

        ArrayList _SubMenuItems;
        string text = "";
        string href = "#";
        string _ul_CssClass = "";
        string _li_CssClass = "";

        #endregion

        #region Properties

        [Description("متن منو آیتم")]
        [DefaultValue("")]
        [NotifyParentProperty(true)]
        public string Text
        {
            get
            {
                return text;
            }

            set
            {
                text = value;
            }
        }

        [DefaultValue("#")]
        [Description(" href attribute")]
        [NotifyParentProperty(true)]
        public string Href
        {
            get
            {
                return href;
            }

            set
            {
                href = value;
            }
        }

        [DefaultValue("")]
        [Description("
 css class")]
        [NotifyParentProperty(true)]
        public string ul_CssClass
        {
            get
            {
                if (string.IsNullOrEmpty(_ul_CssClass)) return "";
                _ul_CssClass = " class=\"" + _ul_CssClass + "\"";
                return _ul_CssClass;
            }
            set { this._ul_CssClass = value.Trim(); }
        }

        [DefaultValue("")]
        [Description("
 css class")]
        [NotifyParentProperty(true)]
        public string li_CssClass
        {
            get
            {
                if (string.IsNullOrEmpty(_li_CssClass)) return "";
                _li_CssClass = " class=\"" + _li_CssClass + "\"";
                return _li_CssClass;
            }
            set { this._li_CssClass = value.Trim(); }
        }

        [Category("Behavior")]
        [Description("The MenuItems collection")]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        public ArrayList SubMenuItems
        {
            get
            {
                if (_SubMenuItems == null)
                    _SubMenuItems = new ArrayList();
                return _SubMenuItems;
            }
        }

        #endregion
    }
}

You can download the project from here.

Body:
Step #1: have hidden button with the desired OnClick outside of the control, in the .aspx page itself e.g.

<asp:Button ID="Button1" runat="server" OnClick="Button_Click" style="display: none;"  />

Step #2: have OnClientClick in the button inside the control, like this:

<asp:Button ID="SomeIdHere" runat="server" Text="Button 01" OnClientClick="return MakeRealClick('Button1');" />

Make sure to put the ID of the "real" button as the argument for "MakeRealClick" function.

Step #3: have this JavaScript code in the page:

<script type="text/javascript">
    function MakeRealClick(sButtonID) {
        var arrInputs = document.getElementsByTagName("input");
        for (var i = 0; i < arrInputs.length; i++) {
            var oCurInput = arrInputs[i];
            if (oCurInput.type == "submit" && (oCurInput.id == sButtonID || EndsWith(oCurInput.id, "_" + sButtonID)))
                oCurInput.click();
        }
        return false;
    }

    function EndsWith(s1, s2) {
        return (s1.length >= s2.length) && (s1.substr(s1.length - s2.length, s2.length) == s2);
    }
</script>

This will cause that when clicked, the button inside the menu will search for other button that is outside the menu thus still has "real" OnClick, and auto click it so the final result is the same as if you clicked the hidden button.

Pretty sure there's better way, but like I said: quick fix with minimal change in code.


问:
Counting preceding/succeeding cell values in a range in Excel
I am trying to figure out how to write a formula to count preceding and succeeding cell values of a specific value in a range. Here is an example:

For this column, how many times does "black" come before "red", how many times does "green" come before "yellow", etc?

Color List

答:
If you mean how many times does "black" appear in the cell immediately before "red" and "green" in the cell immediately before "yellow" then this will work:</p>

```<code>=COUNTIFS(A2:A14,"red",A1:A13,"black")+COUNTIFS(A2:A14,"yellow",A1:A13,"green")
</code>```

Body:
If you mean how many times does "black" appear in the cell immediately before "red" and "green" in the cell immediately before "yellow" then this will work:

=COUNTIFS(A2:A14,"red",A1:A13,"black")+COUNTIFS(A2:A14,"yellow",A1:A13,"green")


问:
Given a List of Lists, return a Listh with Lists' length ( in another list)
When I try to run the following function, I get an error:

```<code>len' [] = 0
len' (_:xs) = 1 + len' xs

listlon [] = 0
listlon [[]] = 1
listlon (x:xs) = ((len' x):(listlon xs))
</code>```

functions.hs:41:1: error:
     • Non type-variable argument in the constraint: Num [a]
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        listlon :: forall a t. (Num [a], Num a) => [[t]] -> [a]

Can some one explain me, How to fix this? What is this error conveying exactly?

答:
The line

```<code>listlon [] = 0
</code>```

produces the output 0 in place of something of type [a]. You most probably meant listlon [] = []. However I suggest listlon = map length or listlon = map len'. Or maybe I just do not understand what it is that you really want. As a first step, it always helps to provide the intended signature. Is it true that you are after a function listlon :: [[a]] -> [Int]?

If my understanding is correct, the most direct fix would be:

```<code>listlon [] = []
listlon [x] = [len' x]
listlon (x:xs) = len' x : listlon xs
</code>```

This fixes the types. But you can notice that the second equation is redundant and this is sufficient

```<code>listlon [] = []
listlon (x:xs) = len' x : listlon xs
</code>```

and now you can notice that this in fact is mapping len' over the list, hence map len' as the pointfree definition of listlon.

The error says that the compiler got confused about the return type. You are trying to return a Num by literals 0 and 1 as well as in form of a list (constructed by the last line). The constraint Num [a] is only possible using the extension FlexibleContexts. But in fact it only indicates the problem I described above. These kinds of error messages are sometimes confusing because the compiler cannot read your mind, and so it assumes you know what you are doing and only reports a problem when it cannot continue inferring types anymore due to some conflict.

Body:
When I try to run the following function, I get an error:

len' [] = 0
len' (_:xs) = 1 + len' xs

listlon [] = 0
listlon [[]] = 1
listlon (x:xs) = ((len' x):(listlon xs))

functions.hs:41:1: error:
     • Non type-variable argument in the constraint: Num [a]
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        listlon :: forall a t. (Num [a], Num a) => [[t]] -> [a]

Can some one explain me, How to fix this? What is this error conveying exactly?

Body:
The line

listlon [] = 0

produces the output 0 in place of something of type [a]. You most probably meant listlon [] = []. However I suggest listlon = map length or listlon = map len'. Or maybe I just do not understand what it is that you really want. As a first step, it always helps to provide the intended signature. Is it true that you are after a function listlon :: [[a]] -> [Int]?

If my understanding is correct, the most direct fix would be:

listlon [] = []
listlon [x] = [len' x]
listlon (x:xs) = len' x : listlon xs

This fixes the types. But you can notice that the second equation is redundant and this is sufficient

listlon [] = []
listlon (x:xs) = len' x : listlon xs

and now you can notice that this in fact is mapping len' over the list, hence map len' as the pointfree definition of listlon.

The error says that the compiler got confused about the return type. You are trying to return a Num by literals 0 and 1 as well as in form of a list (constructed by the last line). The constraint Num [a] is only possible using the extension FlexibleContexts. But in fact it only indicates the problem I described above. These kinds of error messages are sometimes confusing because the compiler cannot read your mind, and so it assumes you know what you are doing and only reports a problem when it cannot continue inferring types anymore due to some conflict.


问:
What tool should I use to split git commit into multiple ones?
I've coded a feature spanning thousand of modified lines in a project, and now it all ended up in one big commit (I've squashed the work-in-progress commits). Now I'd like to split the changes into multiple commits for easier review/possibly multiple PRs.

Some files contain multiple changes that should end up in different commits, so I am looking for a WYSIWIG editor using three-pane view, that would allow me to move some lines to the intermediate commit while seeing the previous and future version (+ some manual changes). I use IntelliJ IDEA for the development, so I imagine something similar to conflict resolution dialog.

I could switch to different branch/tag the single-commit version and do Git->Compare with Branch (and grab the changes from there), but I am looking for something of more convenience.

While this could be marked as off-topic/opinionated, I believe that a neutral suggestion for a different workflow might be valuable.

答:
Not sure about a tool that lets you do this, but, as according to the git documentation you can split a commit using the builtin rebase function. Something like:

```<code>git rebase -i
...
pick abc1234 the commit I wanna keep
edit 5904fjl THE COMMIT I WANT TO SPLIT
pick alkj022 my latest commit to keep
</code>```

After that run git reset HEAD^ and you can manually break out your changes into commits. You can use the git add --patch to more easily split your intra-file changes into commits. Or if your Intellij IDE has a good git GUI you can use that. The splitting, at least in my experience, has to be done from the command line.

Body:
Not sure about a tool that lets you do this, but, as according to the git documentation you can split a commit using the builtin rebase function. Something like:

git rebase -i
...
pick abc1234 the commit I wanna keep
edit 5904fjl THE COMMIT I WANT TO SPLIT
pick alkj022 my latest commit to keep

After that run git reset HEAD^ and you can manually break out your changes into commits. You can use the git add --patch to more easily split your intra-file changes into commits. Or if your Intellij IDE has a good git GUI you can use that. The splitting, at least in my experience, has to be done from the command line.


问:
MySql Fulltext Search not correct with short words
After many tries and many searches i came to the following query:

```<code>SELECT id,
       title,
       description,
       MATCH(title,description,tags) AGAINST ('$search' IN NATURAL LANGUAGE MODE) AS score
FROM pages
</code>```

I use this query to search inside a large amounts of pages which contain music lessons. It works quite wel. Pages get a score based on how good they match to the query.

Except when the users search for something like "C Chord" or "Am Chord" the first part is ignored. If i search for "A chord" or "E chord" the page called "C chord" is always on top.

So.. Part 1 of my question is: how can i fix that?

Then part 2. Is it possible to give the column "Title" a bigger importance for the score then "Description"?

答:
MySQL has two important parameters for full text search, stop words and minimum word length.  The first is the minimum word size (documented here):

Innodb:  innodb_ft_min_token_size (default 3)

MyIsam:  ft_min_word_len (default 4)

Words shorter than the minimum are not indexed, so you cannot search on them.  Remember to rebuild the index after changing the parameter.  Conveniently (hah!) they have different default values.

In addition, there are stop word lists to remove common stop words.  Whether or not this is an issue depends on what words you are searching for.  You can customize the stop words.

Body:
After many tries and many searches i came to the following query:

SELECT id,
       title,
       description,
       MATCH(title,description,tags) AGAINST ('$search' IN NATURAL LANGUAGE MODE) AS score
FROM pages

I use this query to search inside a large amounts of pages which contain music lessons. It works quite wel. Pages get a score based on how good they match to the query.

Except when the users search for something like "C Chord" or "Am Chord" the first part is ignored. If i search for "A chord" or "E chord" the page called "C chord" is always on top.

So.. Part 1 of my question is: how can i fix that?

Then part 2. Is it possible to give the column "Title" a bigger importance for the score then "Description"?


问:
Silex with Doctrine and PHP classes
So, I'm trying to get around in Silex. Just learn the way it works and I'm trying to use Doctrine in it. I can use it on the index.php, but I'd also like to use it in my classes. These lines are used in the normal root file (index.php):

```<code>$images = $app['db']->prepare("SELECT * FROM images");
$images->execute();

$images = $images->fetchAll(\PDO::FETCH_CLASS, \AI\Models\Image::class);
</code>```

So that would give me the ability to do something with the images. But I don't want to work this way. I'd like classes to do it all for me, so that I just script some methods which do all the hard work for me. That would let me just run one line for each Route in index.php

The problem is that I don't know how to connect with Doctrine from inside my classes. Because there is no '$app' in there. I think it would be weird to start the app inside of a class.

So let's say I wanted to create a user class. This SQL would give me all the users: "SELECT * FROM users". But how would I use Doctrine inside the User class?

```<code><?php

namespace Models;

class User {

    public function find($user){
        if($user) {
            $field = (is_numeric($user)) ? 'id' : 'username';

            $sql = "SELECT * FROM users";

            $data = // RUN QUERY $SQL
            if($data->count()) {
                $this->_data = $data->all();
                return true;
            }
        }
        return false;
    }

}
</code>```

答:
In your index.php follow these steps.

Create instance of the silex application:

```<code>$app = new Silex\Application();
$app->register(new Silex\Provider\ServiceControllerServiceProvider());
</code>```

Set the database configuration:

```<code>$config = new \Doctrine\DBAL\Configuration();
$connParams = array(
    'driver'   => 'driver',
    'dbname'   => 'dbname',
    'host'     => 'host',
    'user'     => 'user',
    'password' => 'pass',
    'charset'  => 'charset',
    'port'     => 'port'
);
</code>```

Connect to database:

```<code>$conn = \Doctrine\DBAL\DriverManager::getConnection($connParams, $config);
</code>```

Now you have different ways to make this db instance accessible throughout your app. You can whether make a global variable adding the instance in it:

```<code>global $dbcon;
$dbcon = $conn;
</code>```

Or simply add it to the $app itself:

```<code>$app['dbcon'] = $conn;
</code>```

Furthermore you might want to add a constructor to your models like this:

```<code>public function __construct($db)
{
    $this->db = $db;
}
</code>```

Title: Silex with Doctrine and PHP classes

Body:
So, I'm trying to get around in Silex. Just learn the way it works and I'm trying to use Doctrine in it. I can use it on the index.php, but I'd also like to use it in my classes. These lines are used in the normal root file (index.php):

$images = $app['db']->prepare("SELECT * FROM images");
$images->execute();

$images = $images->fetchAll(\PDO::FETCH_CLASS, \AI\Models\Image::class);

So that would give me the ability to do something with the images. But I don't want to work this way. I'd like classes to do it all for me, so that I just script some methods which do all the hard work for me. That would let me just run one line for each Route in index.php

The problem is that I don't know how to connect with Doctrine from inside my classes. Because there is no '$app' in there. I think it would be weird to start the app inside of a class.

So let's say I wanted to create a user class. This SQL would give me all the users: "SELECT * FROM users". But how would I use Doctrine inside the User class?

<?php

namespace Models;

class User {

    public function find($user){
        if($user) {
            $field = (is_numeric($user)) ? 'id' : 'username';

            $sql = "SELECT * FROM users";

            $data = // RUN QUERY $SQL
            if($data->count()) {
                $this->_data = $data->all();
                return true;
            }
        }
        return false;
    }

}

Body:
In your index.php follow these steps.

Create instance of the silex application:

$app = new Silex\Application();
$app->register(new Silex\Provider\ServiceControllerServiceProvider());

Set the database configuration:

$config = new \Doctrine\DBAL\Configuration();
$connParams = array(
    'driver'   => 'driver',
    'dbname'   => 'dbname',
    'host'     => 'host',
    'user'     => 'user',
    'password' => 'pass',
    'charset'  => 'charset',
    'port'     => 'port'
);

Connect to database:

$conn = \Doctrine\DBAL\DriverManager::getConnection($connParams, $config);

Now you have different ways to make this db instance accessible throughout your app. You can whether make a global variable adding the instance in it:

global $dbcon;
$dbcon = $conn;

Or simply add it to the $app itself:

$app['dbcon'] = $conn;

Furthermore you might want to add a constructor to your models like this:

public function __construct($db)
{
    $this->db = $db;
}


问:
table header view height is wrong when using auto layout, IB, and font sizes
I am trying to create a header view for my uiTableView (not a section header, I already have those.) I have set up an XIB in interface builder. All the connections are hooked up and it runs beautifully... except the table doesn't give it enough room! My problem is that the top of the table overlaps the table's header by a little.

My XIB is setup with autlayout for all the buttons, and IB is happy that the constraints don't conflict / ambiguous. The view is set to Freeform size, which in my case ended up being 320 x 471. Then in constraints for the view, I set an intrinsic size for the view of the same.

Now this works perfectly with my table. Everything looks great. But if I manually change any of the fonts in the header view with code, the layout makes the view bigger, and it ends up underneath my table.

Any ideas how to get the tableviewcontroller to leave enough room for the header view after setting fonts and sizes? I hope I've made sense explaining this.

答:
Combining answers by @SwiftArchitect, @vokilam, and @mayqiyue, and using a programmatically created tableHeaderView instead of a nib (although, I don't see any reason why it shouldn't work with a nib), and under iOS 10.x/Xcode 8.2.1, here is what I have working:

Create the view in your view controller's -viewDidLoad or -init methods, or wherever you're using the table view:

```<code>MyCustomTableHeaderView *myCustomTableHeaderView = [[MyCustomTableHeaderView alloc] init]; // Don't set its frame
myCustomTableHeaderView.translatesAutoresizingMaskIntoConstraints = NO;
self.myTableView.tableHeaderView = myCustomTableHeaderView;
self.myCustomTableHeaderView = myCustomTableHeaderView;  // We set and update our constraints in separate methods so we store the table header view in a UIView property to access it later
</code>```

Wherever you set up your custom header view's constraints (could be in `updateConstraints but this method could be called multiple times):

```<code>// We use Pure Layout in our project, but the workflow is the same:
// Set width and height constraints on your custom view then pin it to the top and left of the table view
// Could also use VFL or NSLayoutConstraint methods
[self.myCustomTableHeaderView autoSetDimension:ALDimensionWidth toSize:CGRectGetWidth(self.superview.frame)]; // Width set to tableview's width
[self.myCustomTableHeaderView autoSetDimension:ALDimensionHeight toSize:height]; // Whatever you want your height to be
[self.myCustomTableHeaderView autoPinEdgeToSuperviewEdge:ALEdgeTop];
[self.myCustomTableHeaderView autoPinEdgeToSuperviewEdge:ALEdgeLeft];

// This is important
[self.myCustomTableHeaderView layoutIfNeeded]; // We didn't need to call -setNeedsLayout or reassign our custom header view to the table view's tableHeaderView property again, as was noted in other answers
</code>```

Body:
Combining answers by @SwiftArchitect, @vokilam, and @mayqiyue, and using a programmatically created tableHeaderView instead of a nib (although, I don't see any reason why it shouldn't work with a nib), and under iOS 10.x/Xcode 8.2.1, here is what I have working:

Create the view in your view controller's -viewDidLoad or -init methods, or wherever you're using the table view:

MyCustomTableHeaderView *myCustomTableHeaderView = [[MyCustomTableHeaderView alloc] init]; // Don't set its frame
myCustomTableHeaderView.translatesAutoresizingMaskIntoConstraints = NO;
self.myTableView.tableHeaderView = myCustomTableHeaderView;
self.myCustomTableHeaderView = myCustomTableHeaderView;  // We set and update our constraints in separate methods so we store the table header view in a UIView property to access it later

Wherever you set up your custom header view's constraints (could be in `updateConstraints but this method could be called multiple times):

// We use Pure Layout in our project, but the workflow is the same:
// Set width and height constraints on your custom view then pin it to the top and left of the table view
// Could also use VFL or NSLayoutConstraint methods
[self.myCustomTableHeaderView autoSetDimension:ALDimensionWidth toSize:CGRectGetWidth(self.superview.frame)]; // Width set to tableview's width
[self.myCustomTableHeaderView autoSetDimension:ALDimensionHeight toSize:height]; // Whatever you want your height to be
[self.myCustomTableHeaderView autoPinEdgeToSuperviewEdge:ALEdgeTop];
[self.myCustomTableHeaderView autoPinEdgeToSuperviewEdge:ALEdgeLeft];

// This is important
[self.myCustomTableHeaderView layoutIfNeeded]; // We didn't need to call -setNeedsLayout or reassign our custom header view to the table view's tableHeaderView property again, as was noted in other answers


问:
query from different oracle connections in sqldeveloper
I have 2 connections with different tables in sqldeveloper.

let's say:

ConnectionA with tables: A,B,C
ConnectionB with tables: D,E,F

Now I want to have a query that looks like this:

select aa.name,dd.id
from A aa,D dd;

How can i do this?

答:
Apparently TOAD Data Point supports Cross-Connection Queries , see:

http://dev.toadfordataanalyst.com/webhelp/Content/Query_Builder/Create_CrossConnection_Queries.htm

Also Oracle SQL Developer seems to support something similar. (see this blog post: Cross Connection Queries)


问:
Disable cascade delete with EF?
I have 2 entities linked by a one-to-many relationship as follows (I used code first):

```<code>public class Computer
{
    [Key]
    public int ComputerId { get; set; }

    [Required]
    public int ComputerIdInventory { get; set; }

    [DataType(DataType.Date)]
    public DateTime? AcquisitionDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? LastUpdate { get; set; }

    public string Comment { get; set; }

    //Foreign keys
    public int? ComputerModelId { get; set; }

    public int? EmployeeId { get; set; }

    //Navigation properties
    public virtual ICollection<Screen> Screens { get; set; }
}

public class Screen
{
    [Key]
    public int ScreenId { get; set; }

    [Required]
    public int ScreenIdInventory { get; set; }

    public string Comment { get; set; }

    //Foreign keys
    public int? ComputerId { get; set; }

    //Navigation properties
    public virtual Computer Computer { get; set; }
}
</code>```

When I delete a computer that is linked to one or many screens, I have the following error:

[SqlException (0x80131904): The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Screen_dbo.Computer_ComputerId". The conflict occurred in database "CPInventory", table "dbo.Screen", column 'ComputerId'.

I have read many posts, and I tried 2 things that seemed to have worked for others. I changed the "OnModelCreating" method and added :

```<code>modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
</code>```

And I tried this too:

```<code>modelBuilder.Entity<Computer>()
            .HasMany<Screen>(c => c.Screens)
            .WithOptional(s => s.Computer)
            .WillCascadeOnDelete(false);
</code>```

But none of the solutions worked... Am I doing something wrong ? I also update the database but nothing has changed. Do I have to completely drop my database and recreate it in order for those changes to be taken into account?

Thank a lot !

Edit:
Here is the delete code

```<code>public ActionResult DeleteConfirmed(int id)
    {
        Computer computer = db.Computers.Find(id);
        db.Computers.Remove(computer);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
</code>```

答:
You can't delete a computer where a screen has a ComputerId that matches the computer's ComputerId.

So update the screen:

```<code>screen.ComputerId = null;
</code>```

then delete your computer

```<code>db.Set<Computer>().Remove(computer);
</code>```

then save changes

```<code>db.SaveChanges();
</code>```

Title: Disable cascade delete with EF?

Body:
I have 2 entities linked by a one-to-many relationship as follows (I used code first):

public class Computer
{
    [Key]
    public int ComputerId { get; set; }

    [Required]
    public int ComputerIdInventory { get; set; }

    [DataType(DataType.Date)]
    public DateTime? AcquisitionDate { get; set; }

    [DataType(DataType.Date)]
    public DateTime? LastUpdate { get; set; }

    public string Comment { get; set; }

    //Foreign keys
    public int? ComputerModelId { get; set; }

    public int? EmployeeId { get; set; }

    //Navigation properties
    public virtual ICollection<Screen> Screens { get; set; }
}

public class Screen
{
    [Key]
    public int ScreenId { get; set; }

    [Required]
    public int ScreenIdInventory { get; set; }

    public string Comment { get; set; }

    //Foreign keys
    public int? ComputerId { get; set; }

    //Navigation properties
    public virtual Computer Computer { get; set; }
}

When I delete a computer that is linked to one or many screens, I have the following error:

[SqlException (0x80131904): The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Screen_dbo.Computer_ComputerId". The conflict occurred in database "CPInventory", table "dbo.Screen", column 'ComputerId'.

I have read many posts, and I tried 2 things that seemed to have worked for others. I changed the "OnModelCreating" method and added :

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

And I tried this too:

modelBuilder.Entity<Computer>()
            .HasMany<Screen>(c => c.Screens)
            .WithOptional(s => s.Computer)
            .WillCascadeOnDelete(false);

But none of the solutions worked... Am I doing something wrong ? I also update the database but nothing has changed. Do I have to completely drop my database and recreate it in order for those changes to be taken into account?

Thank a lot !

Edit:
Here is the delete code

public ActionResult DeleteConfirmed(int id)
    {
        Computer computer = db.Computers.Find(id);
        db.Computers.Remove(computer);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

Body:
You can't delete a computer where a screen has a ComputerId that matches the computer's ComputerId.

So update the screen:

screen.ComputerId = null;

then delete your computer

db.Set<Computer>().Remove(computer);

then save changes

db.SaveChanges();


问:
Eclipse is freezing itself before getting started
I've been trying to open Eclipse to start my work today, and it freezes everytime during load.

My Eclipse is Helios. Someone told me I should remove a file called .lock from .metadata folder, but still didn't work.

Does anyone have any idea of how do I "melt" this thing up?

ps: I opened it yesterday with no problems.

答: Have you already tried to start Eclipse with a -clean parameter? Sometimes this can resolve some issues..</p>


问:
Python Selenium, get elementtext xPath
I am stacked at the code where I need to print full text of
 element

```<code><h2>Product details</h2>
  <div class="content">

<ul>

    <li> <b>Paperback:</b> 288 pages</li>
    <li> <b>Publisher:</b> Pocket Books (October 1, 1998)</li>
    <li> <b>Language:</b> English</li>
    <li> <b>ISBN-10:</b> 0671027034</li>
    <li> <b>ISBN-13:</b> 978-0671027032</li>
    <li>  <b>Product Dimensions: </b>5.3 x 0.8 x 8.2 inches</li>

</ul>
</code>```

It's actually amazon product details.I am using xpath to find class that contains text "ISBN-10":

```<code>print driver.find_element_by_xpath("//*[contains(text(), 'ISBN-10')]").text
</code>```

It finds element great, but my output will be:

```<code>ISBN-10
</code>```

What should I use to get text that comes with ISBN-10 so my output should be:

```<code>ISBN-10: 0671027034
</code>```

I don't want to search for all
 elements and print [3] from list.

答:
Try Following xpath and let me know if you face any issue</p>

```<code>print driver.find_element_by_xpath("//div[@class='content']/ul/li[contains(.,'ISBN-10')]").text
</code>```

Title: Python Selenium, get elementtext xPath

Body:
I am stacked at the code where I need to print full text of
 element

Product details

 Paperback: 288 pages

 Publisher: Pocket Books (October 1, 1998)

 Language: English

 ISBN-10: 0671027034

 ISBN-13: 978-0671027032

  Product Dimensions: 5.3 x 0.8 x 8.2 inches

It's actually amazon product details.I am using xpath to find class that contains text "ISBN-10":

print driver.find_element_by_xpath("//*[contains(text(), 'ISBN-10')]").text

It finds element great, but my output will be:

ISBN-10

What should I use to get text that comes with ISBN-10 so my output should be:

ISBN-10: 0671027034

I don't want to search for all
 elements and print [3] from list.

Body:
Try Following xpath and let me know if you face any issue

print driver.find_element_by_xpath("//div[@class='content']/ul/li[contains(.,'ISBN-10')]").text


问:
Mocking an abstract method, but not the class constructor
I have a scenario where I have an abstract class similar to the below. I want to mock out the RandomNumberGenerator instance that is supplied via the constructor and I want to write a unit test to test the logic in the doSomethingRandomLotsOfTimes method.

Is there a way I can do this with mockito/another framework?

```<code>public abstract class MyClass {

    private final RandomNumberGenerator randomNumberGenerator;

    public MyClass(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public abstract void doSomething(int x);

    public void doSomethingRandomLotsOfTimes() {
        for(int i=0; i<10; i++) {
            int r = randomNumberGenerator.next();
            doSomething(r);
        }
    }
}
</code>```

My Test

```<code>@Test
public void testItDoesSomething10Times() {
    // Given
    when(randomNumberGenerator.next()).thenReturn(0);
    MyClass myClass = ...

    // When
    myClass.doSomethingRandomLotsOfTimes();

    // Then
    // Assert Something
}
</code>```

答:
There is no way to directly instantiate an abstract class.
You must instantiate a non-abstract class that extends the abstract class.

Declare a non-abstract class that extends the abstract class in the unit test class (for example public static class blam extends MyClass) and provide empty implementations of all abstract methods.

Once you have a class that you can instantiate,
create a spy of the RandomNumberGenerator class.
A spy allows you to test that methods in the spy are called.

Create an instance of blam and pass the spy RandomNumberGenerator as the constructor parameter.

Body:
I have a scenario where I have an abstract class similar to the below. I want to mock out the RandomNumberGenerator instance that is supplied via the constructor and I want to write a unit test to test the logic in the doSomethingRandomLotsOfTimes method.

Is there a way I can do this with mockito/another framework?

public abstract class MyClass {

    private final RandomNumberGenerator randomNumberGenerator;

    public MyClass(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public abstract void doSomething(int x);

    public void doSomethingRandomLotsOfTimes() {
        for(int i=0; i<10; i++) {
            int r = randomNumberGenerator.next();
            doSomething(r);
        }
    }
}

My Test

@Test
public void testItDoesSomething10Times() {
    // Given
    when(randomNumberGenerator.next()).thenReturn(0);
    MyClass myClass = ...

    // When
    myClass.doSomethingRandomLotsOfTimes();

    // Then
    // Assert Something
}


问:
Difference between 'var foo = function ...' and 'function foo() ...'

Possible Duplicates:

  “Usual” functions vs function variables in JavaScript

  What do you call this JavaScript syntax, so I can research it?

Is there a fundamental difference between

```<code>function foo()
{
    things();
}
</code>```

and

```<code>var foo = function()
{
    things();
}
</code>```

Or is function ... just syntactical sugar?

Thanks in advance.

答:
They are different (but produce similar results). Basically, the first is an actual named function. The second is a regular variable declaration with an anonymous function attached to it. There are some subtle differences...they are summed up nicely here:

JavaScript Function Declaration Ambiguity (Be sure to read the comments too...more good info there)

Body:
Possible Duplicates:

  “Usual” functions vs function variables in JavaScript

  What do you call this JavaScript syntax, so I can research it?

Is there a fundamental difference between

function foo()
{
    things();
}

and

var foo = function()
{
    things();
}

Or is function ... just syntactical sugar?

Thanks in advance.


问:
How does a broadcast receiver work among activities?
I have multiple activities suppose A , B , C , D and all are register to same BroadCastReceiver. While sending the broadcast message in which order activities will receive the broadcast intents. Is it in order like A , B , C , D or random.

Please let me know, give me some suggestions.

答:
You have no control of that, because System dispatches those actions to registered broadcast listeners. You have no any guarantee on the ordering broadcast listeners will be fired at.

Unless it is ordered broadcast. From docs:

The sendOrderedBroadcast(Intent, String) method sends broadcasts to one receiver at a time. As each receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the broadcast so that it won't be passed to other receivers. The order receivers run in can be controlled with the android:priority attribute of the matching intent-filter; receivers with the same priority will be run in an arbitrary order.


问:
cfthread - how long can it run?
Using Railo, I am processing large video files using cfthread. After the file is uploaded, I call <cfthread type="task"> to process the file using ffmpeg (type="task" is Railo specific). For large files, this can take a while, and it looks like my threads are being terminated before they complete.

1) How can I verify that the threads are being terminated?

2) Is there a way to change how long a thread can run?

3) What's the best way to monitor thread activity in Railo?

答: Check the thread.log and requesttimeout.log in {web-root-directory}/WEB-INF/railo/logs/. Use the default task type (daemon) and set a request timeout within the thread to override the global request timeout. Doesn't seem to work with type="task" though (using Lucee rather than Railo)</p>

Title: cfthread - how long can it run?


问:
Code Igniter email config to config.php
I've put my email configurations in the config.php but I don't know how I can access them in my controller.

In my config.php:

```<code>/*EMAIL CONFIG*/
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_user'] = 'username';
$config['smtp_pass'] = 'pass';
$config['smtp_port'] = '465';
$config['mailtype'] = 'html';
</code>```

Should I make an instance of the super global object?

Thanks in advance.

答:
You can access it with:

```<code>$this->config->item('protocol');
</code>```

Also, see the relevant chapter in CodeIgniter User Guide

Title: Code Igniter email config to config.php

Body:
I've put my email configurations in the config.php but I don't know how I can access them in my controller.

In my config.php:

/*EMAIL CONFIG*/
$config['protocol'] = 'smtp';
$config['smtp_host'] = 'ssl://smtp.googlemail.com';
$config['smtp_user'] = 'username';
$config['smtp_pass'] = 'pass';
$config['smtp_port'] = '465';
$config['mailtype'] = 'html';

Should I make an instance of the super global object?

Thanks in advance.

Body:
You can access it with:

$this->config->item('protocol');

Also, see the relevant chapter in CodeIgniter User Guide


问:
Telling regex search to only start searching at a certain index
Normally, a regex search will start searching for matches from the beginning of the string I provide. In this particular case, I'm working with a very large string (up to several megabytes), and I'd like to run successive regex searches on that string, but beginning at specific indices.

Now, I'm aware that I could use the substr function to simply throw away the part at the beginning I want to exclude from the search, but I'm afraid this is not very efficient, since I'll be doing it several thousand times.

The specific purpose I want to use this for is to jump from word to word in a very large text, skipping whitespace (regardless of whether it's simple space, tabs, newlines, etc). I know that I could just use the split function to split the text into words by passing \s+ as the delimiter, but that would make things for more complicated for me later on, as there a various other possible word delimiters such as quotes (ok, I'm using the term 'word' a bit generously here), so it would be easier for me if I could just hop from word to word using successive regex searches on the same string, always specifying the next index at which to start looking as I go. Is this doable in Perl?

答:
In the absence of more information, I can only suggest the pos function

When doing a global regex search, the engine saves the position where the previous match ended so that it knows where to start searching for the next iteration. The pos function gives access to that value and allows it to be set explicitly, so that a subsequent m//g will start looking at the specified position instead of at the start of the string

This program gives an example. The string is searched for the first non-space character after each of a list of offsets, and displays the character found, if any

Note that the global match must be done in scalar context, which is applied by if here, so that only the next match will  be reported. Otherwise the global search will just run on to the end of the file and leave information about only the very last match

```<code>use strict;
use warnings 'all';
use feature 'say';

my $str = 'a  b  c  d  e  f  g  h  i  j  k  l  m  n';
#          0123456789012345678901234567890123456789
#                    1         2         3

for ( 4, 31, 16, 22 ) {

    pos($str) = $_;

    say $1 if $str =~ /(\S)/g;
}
</code>```

output

```<code>c
l
g
i
</code>```

Body:
In the absence of more information, I can only suggest the pos function

When doing a global regex search, the engine saves the position where the previous match ended so that it knows where to start searching for the next iteration. The pos function gives access to that value and allows it to be set explicitly, so that a subsequent m//g will start looking at the specified position instead of at the start of the string

This program gives an example. The string is searched for the first non-space character after each of a list of offsets, and displays the character found, if any

Note that the global match must be done in scalar context, which is applied by if here, so that only the next match will  be reported. Otherwise the global search will just run on to the end of the file and leave information about only the very last match

use strict;
use warnings 'all';
use feature 'say';

my $str = 'a  b  c  d  e  f  g  h  i  j  k  l  m  n';
#          0123456789012345678901234567890123456789
#                    1         2         3

for ( 4, 31, 16, 22 ) {

    pos($str) = $_;

    say $1 if $str =~ /(\S)/g;
}

output

c
l
g
i


问:
Creating blank CSV file with headers only
I'm trying to create a CSV file for logging server reboot information.  Reboot status, last reboot timestamp and current reboot timestamp.

I've found code to create a CSV as follows but when I open the CSV in notepad, there's a blank line.  How can I create a CSV file with headers and no blank line?  I've tried looking for alternate methods for creating a blank CSV file with headers but none of them work as this does.

The blank line in notepad "","","",""

```<code>#Create CSV
$headers = "Server", "Status", "LastRebootTime", "CurrentRebootTime"
$psObject = New-Object psobject
foreach($header in $headers)
 {
  Add-Member -InputObject $psobject -MemberType noteproperty -Name $header -Value ""
 }
$psObject | Export-Csv d:\scripts\WorkFlowTest.csv -NoTypeInformation
</code>```

答:
By default, PowerShell uses Unicode, which apparently causes Excel to load the data into a single column. Try the following, which creates an ASCII output file:</p>

```<code># Begin "here string"

$csv = @"
index,name
1,Ed
2,Teresa
"@ # End of "here string"

$csv | Out-File temp.csv -Encoding ASCII

start temp.csv
</code>```

Body:
I'm trying to create a CSV file for logging server reboot information.  Reboot status, last reboot timestamp and current reboot timestamp.

I've found code to create a CSV as follows but when I open the CSV in notepad, there's a blank line.  How can I create a CSV file with headers and no blank line?  I've tried looking for alternate methods for creating a blank CSV file with headers but none of them work as this does.

The blank line in notepad "","","",""

#Create CSV
$headers = "Server", "Status", "LastRebootTime", "CurrentRebootTime"
$psObject = New-Object psobject
foreach($header in $headers)
 {
  Add-Member -InputObject $psobject -MemberType noteproperty -Name $header -Value ""
 }
$psObject | Export-Csv d:\scripts\WorkFlowTest.csv -NoTypeInformation

Body:
By default, PowerShell uses Unicode, which apparently causes Excel to load the data into a single column. Try the following, which creates an ASCII output file:

# Begin "here string"

$csv = @"
index,name
1,Ed
2,Teresa
"@ # End of "here string"

$csv | Out-File temp.csv -Encoding ASCII

start temp.csv


问:
How to get two <div> floating below each other
I want to ask how can I move floated  below another so both of them are floating on the same side but they're below each other. Thanks.</p>

答: add clear: right; to its CSS...

ContentLicense: CC BY-SA 4.0

Body: add clear: right; to its CSS...


问:
Issues in displaying a flash message in my HTML page
I just started to learn python some months ago...
I would like to display an message when there is no result for a query in my Query page (html). I am using python and flask. The code that I tried did not display any message.
My id.html code is (I included the code outside the search form):

```<code><div class="flashes">
  {% for message in get_flashed_messages() %}
    {{ message }}
  {% endfor %}
</div>
</code>```

And my python code is:

```<code>@app.route('/id')
def id():
    params={}
    params['entryname']='Search ID'
    idn=request.args.get('idn')
    sql=text('select * from DATA where info LIKE :id')
    words=engine.execute(sql,id=idn).fetchall()
    params['objs']=words
    if params['objs']==0:
        flash('No Results')
    return render_template('id.html', **params)
</code>```

I also tried this just for testing and did not work

```<code>if params['objs']>0:
        flash('Results')
</code>```

I am not sure what is wrong in my code, the query search is working, but no message...

答:
"I also tried this just for testing and did not work"

```<code>if params['objs']>0:
        flash('Results')
</code>```

I don't use Python but it sounds like you're trying to check the size to make sure it contains something? If yes, then possibly this logic might help you :

Either use is_empty or the len properties :

```<code>if is_empty(params)==True:
        flash('No Results')

if len(params)==0:
        flash('No Results')
</code>```

Also if you wanted bigger-than then write as :  if len(params) > 0: flash('Results')

Body:
I just started to learn python some months ago...
I would like to display an message when there is no result for a query in my Query page (html). I am using python and flask. The code that I tried did not display any message.
My id.html code is (I included the code outside the search form):

  {% for message in get_flashed_messages() %}
    {{ message }}
  {% endfor %}

And my python code is:

@app.route('/id')
def id():
    params={}
    params['entryname']='Search ID'
    idn=request.args.get('idn')
    sql=text('select * from DATA where info LIKE :id')
    words=engine.execute(sql,id=idn).fetchall()
    params['objs']=words
    if params['objs']==0:
        flash('No Results')
    return render_template('id.html', **params)

I also tried this just for testing and did not work

if params['objs']>0:
        flash('Results')

I am not sure what is wrong in my code, the query search is working, but no message...

Body:
"I also tried this just for testing and did not work"

if params['objs']>0:
        flash('Results')

I don't use Python but it sounds like you're trying to check the size to make sure it contains something? If yes, then possibly this logic might help you :

Either use is_empty or the len properties :

if is_empty(params)==True:
        flash('No Results')

if len(params)==0:
        flash('No Results')

Also if you wanted bigger-than then write as :  if len(params) > 0: flash('Results')


问:
How should I go along to design a web forum?
im pretty new to web development and I thought about doing a project where I designed a basic web forum. Is there anyway someone could point me in the right direction or how I should go along with it? My current stack is vue2, express, mongodb with passport for authentication. Is it possible/manageable with this stack? or are there some new technologies I should pick up?</p>

答:
It is possible with any stack. This is such a general question that it's really hard to answer anything meaningful. This is a nice goal to learn your tech stack so go for it. You can use any language, any framework and any database to make a forum so I can only say that yes, it's possible.

To answer the second part of your question on how you should go along with that then well, try to learn your stack as much as you can, read a lot of documentation and if you get stuck then first try to search for question asked here by other people and if you have a problem that was not discussed before then post a new question with a short example of code that can reproduce the problem, information what you have tried and what errors did you have.

The most important is: start coding first, ask questions second.


问:
How can I find words in matrix of letters
This is another question I was asked in the telephonic interview:

Given a dictionary and a crossword(2d matrix of characters) find all the dictionary words which can be found in the crossword.

All I could think of was hash the dictionary, find every possible word in the crossword and search the hash. I could not optimize it all.

Must admit Microsoft interview questions are tough :(

Please give me the lines to think on.

答:
This question is exactly how one would play Boggle.

This past question in SO more than sufficiently ANSWERS THIS QUESTION.

Have fun...