ASP.NET composite control FromToTextBoxes

This is a simple composite control , that has 2 edit text boxes with corresponding labels.
It will be useful to have labels as public properties (not done yet)
The possible and popular extension will be to have From/To date controls.

 The source code posted using CopySourceAsHtml

 

using System;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

 

 

 //based on http://localhost/quickstart/util/srcview.aspx?path=/quickstart/aspplus/samples/webforms/ctrlauth/composition/Composition1.src&file=CSComposition1.cs&font=3

    /// <summary>

    /// Summary description for FromToTextBoxes.

    /// </summary>

    public class FromToTextBoxes: Control, INamingContainer

    {

        public FromToTextBoxes()

        {

            //

            // TODO: Add constructor logic here

            //

        }

        #region   “Private properties”

            private TextBox m_txtFrom;

            private TextBox m_txtTo;

        #endregion  // “Private properties”

 

        #region  “Public properties”

        public string FromValue

        {

            get

            {

                this.EnsureChildControls();

                return m_txtFrom.Text;

            }

            set

            {

                this.EnsureChildControls();

                m_txtFrom.Text = value.ToString();

            }

        }

        public string ToValue

        {

            get

            {

                this.EnsureChildControls();

                return m_txtTo.Text;

            }

            set

            {

                this.EnsureChildControls();

                m_txtTo.Text = value.ToString();

            }

        }

        #endregion  //”Public properties”

 

        protected override void CreateChildControls()

        {

 

            this.Controls.Add(new LiteralControl( ” From: “));

            m_txtFrom = new TextBox();

            m_txtFrom.ID=“txtFrom”;

            //box.Text = “0”;

            this.Controls.Add(m_txtFrom);

            this.Controls.Add(new LiteralControl(” To: “));

            m_txtTo = new TextBox();

            m_txtTo.ID=“txtTo”;

            this.Controls.Add(m_txtTo);

        }

    }

 

ASP.NET custom control CheckBoxWithImage

A few years ago I posted ASP.NET custom control HyperLinkWithImage. I also created similar CheckBoxWithImage , but didn’t publish it at that time.
The class allows to have image next to CheckBox, and by clicking image check-box will be ticked/unticked.

using System;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.ComponentModel;

using System.Web.UI.Design; //!!!System.Design (in System.Design.dll)

using System.Drawing.Design;

using System.Collections.Specialized;//NameValueCollection Class 

using System.Diagnostics;

using FSHelperLib;

 

    /// <summary>

    /// Summary description for CheckBoxWithImage.

    /// </summary>

    [DefaultProperty(“Text”),

        ToolboxData(“<{0}:CheckBoxWithImage runat=server></{0}:CheckBoxWithImage>”)]

    public class CheckBoxWithImage : System.Web.UI.WebControls.CheckBox

    { //,IPostBackDataHandler

        private string m_ImageUrl;

        private ImageAlign m_ImageAlign;

        public CheckBoxWithImage() : base()

        {

//#if DEBUG

//            base.CheckedChanged += new System.EventHandler(this.OnCBCheckedChanged);

//#endif

        }

//#if DEBUG

//        void OnCBCheckedChanged(object sender, EventArgs e)

//        {

//            if (Checked == true)

//                Debug.WriteLine(  “OnCBCheckedChanged true”);

//            else

//                Debug.WriteLine(  “OnCBCheckedChanged false”);

//        }

//#endif

 

        [Bindable(true),

            Category(“Appearance”),

            DefaultValue(“”),

        EditorAttribute(typeof(System.Web.UI.Design.ImageUrlEditor), typeof(UITypeEditor))]

        public string ImageUrl

        {

            get

            {

                return m_ImageUrl;

            }

 

            set

            { 

                m_ImageUrl = value;

            }

        }

        //WebCategory(“Layout”)-internal in System.Web

        //WebSysDescription(“Image_ImageAlign”)-internal in System.Web

        [ Bindable(true), Category(“Layout”), DefaultValue(0)]

        public virtual ImageAlign ImageAlign

        {

            get

            {

                object obj1 = m_ImageAlign ;//this.ViewState[“ImageAlign”];

                if (obj1 != null)

                {

                    return ((ImageAlign) obj1);

                }

                return ImageAlign.NotSet;

            }

            set

            {

                if ((value < ImageAlign.NotSet) || (value > ImageAlign.TextTop))

                {

                    throw new ArgumentOutOfRangeException(“value”);

                }

                m_ImageAlign= value;// this.ViewState[“ImageAlign”] = value;

            }

        }

 

        /// <summary>

        /// Overrides the OnPreRender method.

        /// </summary>

        protected override void OnPreRender(System.EventArgs e)

        {

            base.OnPreRender(e);

            EWSoftware.Web.ResSrvHandler.RegisterStartupScript(this.Page,“ToggleCheckBox.js”);

            ClientScriptsHelper.RegisterScript_FindObjById(this.Page);        //EWSoftware.Web.ResSrvHandler.RegisterStartupScript(,”FSHelperLib”,”FindObjById”);

        }

 

        /// <summary>

        /// Render this control to the output parameter specified.

        /// </summary>

        /// <param name=”output”> The HTML writer to write out to </param>

        protected override void Render(HtmlTextWriter output)

        {

            string sUrl, sImg=null;

            if (!DataHelper.IsNullOrEmpty(m_ImageUrl))

            {   

                sUrl=this.ResolveUrl(m_ImageUrl);//to resolve ‘~’ can’t be called in construction time

                sImg=“<IMG alt=”” src=”” + sUrl + “” onclick=”ToggleCheckBox(‘” + this.ClientID + “‘)” >”;

            }

            bool bImageRight=(ImageAlign.Right== m_ImageAlign);

            if ((null!=sImg) && (!bImageRight))

            {   

                output.Write(sImg);

            }

            base.Render(output);

            if ((null!=sImg) && (bImageRight))

            {   

                output.Write(sImg);

            }

        }

//        #region Implementation of IPostBackDataHandler -not required

//        void IPostBackDataHandler.RaisePostDataChangedEvent()

//        {

//            base.OnCheckedChanged( System.EventArgs.Empty);

//        }

//        bool IPostBackDataHandler.LoadPostData(string postDataKey, NameValueCollection postCollection)

//        { //Exact copy of base implementation

//            string text1 = postCollection[postDataKey];

//            bool flag1 = (text1 == null ? false : text1.Length > 0);

//            bool flag2 = flag1 != this.Checked;

//            this.Checked = flag1;

//            return flag2;

//        }

//

////        bool IPostBackDataHandler.LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)

////        {   CheckBox bs=this;

////            IPostBackDataHandler ip=(IPostBackDataHandler)bs;

////            return ip.LoadPostData(postDataKey,postCollection);

////        }

//        #endregion

 

    }


Function to Navigate To Named Anchor

Below is  a helper function to insert javascript  to Navigate To Named Anchor

Page should have anchor with the passed name

<a name=”anchorName”></a>

   

    // from http://www.webdeveloper.com/forum/showthread.php?threadid=112603

    ///<summary>///

    ///</summary>

    ///<param name=”page”></param>

    ///<param name=”anchorName”></param>

    ///<remarks>Page should have anchor with the passed name <a name=”anchorName”></a>

    /// If there are more than one call on the page, first one will take preference

    ///</remarks>

    public static void NavigateToNamedAnchor(Page page, string anchorName)

    {

        String script = String.Format(“window.location.hash = ‘{0}’;”, anchorName);

        //NOTE: if there are more than one call on the page, first one will take preference

        //If we want that last will take preference, change key from MethodBase.GetCurrentMethod().Name to anchorName

        page.ClientScript.RegisterStartupScript(TypeForClientScript(), MethodBase.GetCurrentMethod().Name, script, true);

        //return script;

    }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Passing parameters in .Net Remoting

It is well known, that in .Net value type parameters are passed by value, and reference type parameters are passed by reference(more detailed and strict description can be found here).
I thought(even after a year working with application that extensively uses Remoting)  that .Net Remoting calls do the same. But I was wrong!
Recently I found that a method with custom class parameter  doesn’t have one of the properties updated after return, even if it is certainly updated inside the method.
I’ve read a few reference articles.
quickstart Remoting Overview is a little bit confusing:
Object passing. All objects created remotely are returned by reference and have to derive from MarshalByRefObject. Objects passed as parameters to a remote method call can be forwarded by value or by reference. The default behavior is pass by value provided the object in question is marked by the custom attribute [Serializable]. Additionally, the object could implement the ISerializable interface, which provides flexibility in how the object should be serialized and deserialized. Objects that are not marshal by reference or marshal by value are not remotable.
 

How to marshal an object to a remote server by value by using Visual C# is more clear:

Because parameter ForwardMe does not inherit from MarshalByRefObject, it is passed by value to the server.

And finally, article  Copying, Cloning, and Marshalling in .NET clarified it:

By default, all objects in .NET (both value- and reference-types) are marshalled by value when sent across the “wire” to a remote AppDomain.To override this default MBV behavior, one can simply derive one’s class from System.MarshalByRefObject .

So the Rules for passing parameters in .Net Remoting are the following:

1. Parameter should have attribute [Serializable] or derive from MarshalByRefObject.
(It would be unusual for a class to be both marked with the serializable attribute and extend MarshalByRefObject.)

2. If parameter is serializable, it is passed by value. Changes inside remote methods do not return to the client.

3. If parameter  derive from MarshalByRefObject , it is passed by reference.

4. I am not sure, what happens If you specify modifier ref  for serializable parameter. I hope that it is also passed by reference, but not sure.

The following links discuss how parameters are treated in WCF:

How to pass a reference in WCF 

Preserving Object Reference in WCF  

use Activator.CreateInstance to dynamically load the concrete class and avoid Circular references

I have a Factory class that creates number of classes to handle different XML responses, returned by Web Service. All of them are derived from some base class GwsResponse and created depending on the top name element name.
Previously factory and all created object classes were located in the same DLL.
Now we need to increase number of handled responses, but we want new classes to create in separate extension DLL. 

We are going to use Activator.CreateInstance to dynamically load the concrete class and avoid Circular references

The names of classes and assembly will be defined in config file.

The approach is well described in the thread:    

Circular references not possible?

Similar idea suggested in Creating an object dynamically using Reflection and running in a seperate thread

 

Links about Dependency Injection (pointed by TheCPUWizard)

Design Patterns Dependency Injection(MSDN Magazine, September 2005)

Unity competitors discussin on forum and post Microsoft releases Unity, an IoC library

 
 

Controls with the same name in GridView Templates

I’ve created the GridView with templates like the following:
       <asp:TemplateField SortExpression=”Date1″>

            <AlternatingItemTemplate>

                <asp:CheckBox ID=”chkSelected” runat=”server” />

            </AlternatingItemTemplate>

        </asp:TemplateField>

        <asp:TemplateField SortExpression=”Date2″>

            <AlternatingItemTemplate>

                <asp:CheckBox ID=”chkSelected” runat=”server” />

            </AlternatingItemTemplate>

        </asp:TemplateField>

On runtime it cause the error:
Message : Multiple controls with the same ID ‘chkSelected’ were found. FindControl requires that controls have unique IDs.
Type : System.Web.HttpException, System.Web, Version=
2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
Message : Multiple controls with the same ID ‘chkSelected’ were found. FindControl requires that controls have unique IDs.
Source : System.Web
ErrorCode : -2147467259
Stack Trace : at System.Web.UI.Control.FillNamedControlsTable(Control namingContainer, ControlCollection controls)
at System.Web.UI.Control.FillNamedControlsTable(Control namingContainer, ControlCollection controls)
at System.Web.UI.Control.EnsureNamedControlsTable()
at System.Web.UI.Control.FindControl(String id, Int32 pathOffset)
at System.Web.UI.Control.FindControl(String id, Int32 pathOffset)
at System.Web.UI.Control.FindControl(String id, Int32 pathOffset)
at System.Web.UI.Control.FindControl(String id, Int32 pathOffset)
at System.Web.UI.Control.FindControl(String id, Int32 pathOffset)
at System.Web.UI.Control.FindControl(String id, Int32 pathOffset)
at System.Web.UI.Control.FindControl(String id, Int32 pathOffset)
at System.Web.UI.Page.FindControl(String id)
at System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

The problem explained on forum “GridViewRow is the naming container in GridView, not individual TableCell.
 
I had to use Dynamic Template columns based on  page http://www.webswapp.com/codesamples/viewsource.aspx?file=~/codesamples/aspnet20/itemplate/checkboxtemplate.cs
Note that in that example the CheckBoxTemplate class declared as implemented INamingContainer.
It causes expectation, that generated cell is naming container, which is not correct.
Because template is not derived from Control, specifying INamingContainer interface has no effect and should be removed.
 
Similar templates are described in

Error: control with id … could not be located or a different control is assigned to the same ID after postback

Our application has the intermittent (not too often,but can be 10-20 per day) errors like the following:

An error has occurred because a control with id ‘grdComplaints$ctl04$ctl00’ could not be located or a different control is assigned to the same ID after postback. If the ID is not assigned, explicitly set the ID property of controls that raise postback events to avoid this error.
 System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +877
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
I’ve tried advice from http://p2p.wrox.com/TopicIndex/45979.htm  –
  “EnableViewState Property was set to ‘False’ when i change it to ‘True’ it becomes functional.”
but it didn’t eliminate errors.
Not sure, how to make the problem reproducible. I have some suspicion that it is relatted to An error “An entry with the same key already exists” when assigning ImageButton.ImageUrl