Errors when using delegates in my class

Getting cannot be serialized because it does not have a parameterless

Page 1 of 1

2 Replies - 1681 Views - Last Post: 30 December 2010 - 01:37 PM Rate Topic: -----

#1 gcoleman0828   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 30-December 10

Errors when using delegates in my class

Posted 30 December 2010 - 01:02 PM

Hello,

I am trying to use delegates to set up sorting for my List<T> objects in an abstract manner and then binding it as a DataScource to a GridView. Unfortunately I keep getting the following error when attempting to use delegates.. Any ideas? In bold is where I think the issue is. if I remove the delegates, everything works fine (outside of sorting of course)

2010-12-30 14:43:48.032 ExtList.FromXML: Got exception 'System.InvalidOperationException: There was an error reflecting type 'CAPS.CAPSLibrary.ExtList'. ---> System.InvalidOperationException: There was an error reflecting property 'ExtItemList'. ---> System.InvalidOperationException: There was an error reflecting type 'CAPS.CAPSLibrary.ExtItem'. ---> System.InvalidOperationException: Cannot serialize member 'CAPS.CAPSLibrary.ExtItem.NameComparison' of type 'System.Comparison`1[[CAPS.CAPSLibrary.ExtItem, CAPS.CAPSLibrary, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]', see inner exception for more details. ---> System.InvalidOperationException: System.Comparison`1[CAPS.CAPSLibrary.ExtItem] cannot be serialized because it does not have a parameterless constructor.

Here is my class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Serialization;
using System.IO;

namespace CAPS.CAPSLibrary
{
    // This is a single Extension item from the Extensions XML file
    public class ExtItem : IComparable<ExtItem>
    {
        #region Private fields

        private string _aesExt;      // Extension we will monitor for calls coming in
        private string _aesClearPassword;  // Clear text password we use for user entry
        private string _aesHashPassword;   // Encrypted password we display and read/write
        private AniList _fromAni;       // List of ANI identifications.
        private string _name;           // Name of user associated with that extension
        private string _jpgImageName;   // File name for 90x90 jpeg image for this user
        private string _bigImageName;   // File name for 180x180 jpeg image for this user
        private string _wbmpImageName;  // file name for 90x90 wbmp image for this user

        #endregion

        #region Public properties

        public string AesExt
        {
            get { return _aesExt; }
            set { _aesExt = value; }
        }

        [XmlIgnore]
        public string AesClearPassword
        {
            get { return _aesClearPassword; }
            set { _aesClearPassword = value; }
        }

        public string AesHashPassword
        {
            get { return _aesHashPassword; }
            set { _aesHashPassword = value; }
        }

        public AniList FromAni
        {
            get { return _fromAni; }
            set { _fromAni = value; }
        }

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public string JpgImageName
        {
            get { return _jpgImageName; }
            set { _jpgImageName = value; }
        }

        public string BigImageName
        {
            get { return _bigImageName; }
            set { _bigImageName = value; }
        }

        public string WbmpImageName
        {
            get { return _wbmpImageName; }
            set { _wbmpImageName = value; }
        }

        #endregion

        #region DELEGATES

       //public Comparison<ExtItem> NameComparison = (delegate(ExtItem Item1, ExtItem Item2)
       //  {
       //      return Item2.Name.CompareTo(Item1.Name);
       //  });

       //public Comparison<ExtItem> ExtensionComparison = (delegate(ExtItem Item1, ExtItem Item2)
       //{
       //    return Item2.AesExt.CompareTo(Item1.AesExt);
       //});

        #endregion

        #region Constructors

        /// <summary>
		/// Set default values for all fields.
		/// </summary>
		public ExtItem()
		{
			Reset();
        }

        /// <summary>
        /// Set all fields according to arguments
        /// </summary>
        /// <param name="aToExt"></param>
        /// <param name="aClearPass"></param>
        /// <param name="aHashPass"></param>
        /// <param name="aFromAni"></param>
        /// <param name="aName"></param>
        /// <param name="aJpeg"></param>
        /// <param name="aBig"></param>
        /// <param name="aWbmp"></param>
        public ExtItem(string aToExt, string aClearPass, string aHashPass, AniList aFromAni, string aName, string aJpeg, 
            string aBig, string aWbmp)
        {
            Set(aToExt, aClearPass, aHashPass, aFromAni, aName, aJpeg, aBig, aWbmp);
        }

        public ExtItem(ExtItem aItem)
        {
            Set(aItem);
        }

        #endregion

        #region Reset, Set

        /// <summary>
        /// Set fields to default values
        /// </summary>
        public void Reset()
        {
            _aesExt = "";
            _aesClearPassword = "";
            _aesHashPassword = "";
            _fromAni = new AniList();
            _name = "";
            _jpgImageName = "";
            _bigImageName = "";
            _wbmpImageName = "";
        }

        /// <summary>
        /// Set the values of every field according to arguments
        /// </summary>
        /// <param name="aToExt"></param>
        /// <param name="aClearPass"></param>
        /// <param name="aHashPass"></param>
        /// <param name="aFromAni"></param>
        /// <param name="aName"></param>
        /// <param name="aJpeg"></param>
        /// <param name="aBig"></param>
        /// <param name="aWbmp"></param>
        public void Set(string aToExt, string aClearPass, string aHashPass, AniList aFromAni, string aName, string aJpeg,
            string aBig, string aWbmp)
        {
            _aesExt = aToExt;
            _aesClearPassword = aClearPass;
            _aesHashPassword = aHashPass;
            _fromAni = aFromAni;
            _name = aName;
            _jpgImageName = aJpeg;
            _bigImageName = aBig;
            _wbmpImageName = aWbmp;
        }

        /// <summary>
        /// Copy our values from given ExtItem
        /// </summary>
        /// <param name="from"></param>
        public void Set(ExtItem from)
        {
            _aesExt = from._aesExt;
            _aesClearPassword = from._aesClearPassword;
            _aesHashPassword = from._aesHashPassword;
            _fromAni = new AniList(from._fromAni);  // Force a copy
            _name = from._name;
            _jpgImageName = from._jpgImageName;
            _bigImageName = from._bigImageName;
            _wbmpImageName = from._wbmpImageName;
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// modify as needed
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return "ToExt=["+_aesExt + "], ClearPass=[" + _aesClearPassword + "], HashPass=[" + _aesHashPassword
                + "], Name=[" + _name + "], Jpg=[" + _jpgImageName + "], big=[" + _bigImageName + "], Wbmp=[" + _wbmpImageName + "]\r\n" +
                "        fromAni:"+ _fromAni.ToString();
        }

        /// <summary>
        /// Log the contents of this class
        /// </summary>
        /// <param name="hdr">Header info: ExtItem: or [0]: or whatever</param>
        /// <param name="lvl">DEBUG_LEVEL to log at</param>
        public void Logit(string hdr, Log.DEBUG_LEVEL lvl)
        {
            Log.WriteLine(hdr + " AesExt=[" + _aesExt + "], ClearPass=[" + _aesClearPassword + "], HashPass=[" + _aesHashPassword
                + "], Name=[" + _name + "], Jpg=[" + _jpgImageName + "], big=[" + _bigImageName + "], Wbmp=[" + _wbmpImageName + "]", lvl);
            _fromAni.Logit("    ", lvl);
        }

        #endregion

        #region I/O routines

        /// <summary>
        /// Convert our class to an XML string via Serialize. Can throw exceptions
        /// </summary>
        /// <returns></returns>
        public string ToXML()
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ExtItem));
                StringWriter stringWriter = new StringWriter();
                serializer.Serialize(stringWriter, this);
                return stringWriter.ToString();
            }
            catch (Exception ex)
            {
                Log.WriteLine("ExtItem.ToXML: Exception '" + ex + "'", Log.DEBUG_LEVEL.TERSE);
                throw new Exception("ExtItem_ToXML", ex);
            }
        }

        /// <summary>
        /// Convert given xml string to our class. Throw exception on fail.
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public ExtItem FromXML(string xml)
        {
            ExtItem ei = null;

            if ((xml != null) && (xml.Length > 0))
            {
                try
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(ExtItem));
                    ei = (ExtItem)serializer.Deserialize(new StringReader(xml));
                }
                catch (Exception ex)
                {
                    Log.WriteLine("ExtItem.FromXML: Got exception '" + ex + "'", Log.DEBUG_LEVEL.TERSE);
                    throw new Exception("ExtItem_FromXML", ex);
                }
            }
                
            return ei;
        }

        /// <summary>
        /// Write out our class to given file. Return true on success, false on fail.
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool WriteFile(string fileName)
        {
            try
            {
                StreamWriter writer = new StreamWriter(fileName);
                writer.Write(this.ToXML());
                writer.Close();
            }
            catch (Exception ex)
            {
                Log.WriteLine("ExtItem.WriteFile: Got exception '" + ex + "'", Log.DEBUG_LEVEL.TERSE);
                return false;
            }

            // Success
            return true;
        }

        /// <summary>
        /// Read our class from given file. Return true on success, false on fail.
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public bool ReadFile(string fileName, bool translateClear)
        {
            try
            {
                StreamReader reader = new StreamReader(fileName);
                string contents = reader.ReadToEnd();
                reader.Close();
                
                // Set all our values from what we got back
                this.Set(FromXML(contents));
            }
            catch (Exception ex)
            {
                Log.WriteLine("ExtItem.ReadFile: Got exception '" + ex + "'", Log.DEBUG_LEVEL.TERSE);
                return false;
            }

            // Load the clear from the encrypted

            try
            {
                if (_aesHashPassword == null || _aesHashPassword.Length < 1 || _aesHashPassword == "none" ||
                    translateClear == false)
                {
                    EnDecrypt encryptor = new EnDecrypt("SetMyKey", "SaltGenerator");
                    _aesClearPassword = encryptor.decrypt(_aesHashPassword);
                }
            }
            catch (Exception ex)
            {
                Log.WriteLine("ExtItem.Readfile: EnDecrypt exception '" + ex + "'", Log.DEBUG_LEVEL.TERSE);
                return false;
            }

            // Success
            return true;
        }

        #endregion

        public int CompareTo(ExtItem other)
        {
            return Name.CompareTo(other.Name);
        }
    }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Errors when using delegates in my class

#2 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Errors when using delegates in my class

Posted 30 December 2010 - 01:27 PM

The error is not related to the delegates.
This might help for events

Quick and easy custom events
Bulding an application - Part 1

But you have the error:
System.Comparison`1[CAPS.CAPSLibrary.ExtItem] cannot be serialized because it does not have a parameterless constructor.

So what is your actual question? Your class does not have a parameterless constructor and a class MUST have a parameterless constructor in order to be created through reflection, being (de)serialized or any place you are trying to make a new instance of that class without providing a parameter. myClass myInstance = new myClass();// note no parameter

This post has been edited by tlhIn'toq: 30 December 2010 - 01:31 PM

Was This Post Helpful? 1
  • +
  • -

#3 gcoleman0828   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 30-December 10

Re: Errors when using delegates in my class

Posted 30 December 2010 - 01:37 PM

View PosttlhIn, on 30 December 2010 - 12:27 PM, said:

The error is not related to the delegates.
This might help for events

Quick and easy custom events
Bulding an application - Part 1

But you have the error:
System.Comparison`1[CAPS.CAPSLibrary.ExtItem] cannot be serialized because it does not have a parameterless constructor.

So what is your actual question? Your class does not have a parameterless constructor and a class MUST have a parameterless constructor in order to be created through reflection - or any place you are trying to make a new instance of that class without providing a parameter.


My actual question is what I can do to fix this and why when i add a delegate Serialization all of the sudden doesn't work, but your saying it's not related. Why would commenting out the delegate would Serializing work and the Grid I create from the Read() method work??

Also maybe I am missunderstanding the parameterless constructor?? is that the same as this?? which is in the class

  public ExtItem()  

         {  

             Reset();  

         }  

    



I Instantiate the Class in a Class where the GridView lives... This class stripped down is as follows

  public partial class ClickToDial : System.Web.UI.Page
    {
        #region PUBLIC FIELDS

        public ExtList  _extList = new ExtList();
        public ExtItem  _extItem = new ExtItem();
        
        #endregion

        #region PRIVATE FIELDS

        private const string  XMLLocation = @"C:\inetpub\wwwroot\CAPS\Data\extensions.xml";
        private int FromExtn;
        private string ClientIP = "";
        private const string ASCENDING = "ASC";
        private const string DESCENDING = "DESC";

        #endregion

        #region PRIVATE PROPERTIES  

        private SortDirection GridViewSortDirection
        {
            get
            {
                if (ViewState["sortDirection"] == null)
                {
                    ViewState["sortDirection"] = SortDirection.Ascending;
                }

                return (SortDirection)ViewState["sortDirection"];
            }

            set
            {
                ViewState["sortDirection"] = value;
            }
        }


        #endregion

        //TODO: Gregg: Add A-Z filtering and column sorting on GridView

        protected void Page_Load(object sender, EventArgs e)
        {
            // Set Current Directory for logging
            SetDirectory();

            // Hide Form until user selects a caller
            HideForm();

            // Get Client IP Address to check extension exists
            ClientIP = GetIPAddress();
            TestTextBox.Text = ClientIP;

            // Read Database (extensions.xml) and bind to Grid
            if (_extList.ReadFile(XMLLocation, false))
            {
                ExtensionGridView.DataSource = _extList.ExtItemList;
                ExtensionGridView.DataBind();
            }

        }




        #region SET DIRECTORY

        /// <summary>
        /// Set Directory to current Applications folder for logging and write to log to start it
        /// </summary>
        public void SetDirectory()
        {
            // Must be done before logging or Settings()  
            if (Globals.SetBaseDir() == false)
            {
                HttpContext.Current.Response.Write("Unable to set BaseDir<br>");
                return;

            }
            Directory.SetCurrentDirectory(Globals.BaseDir + @"\ClickToDial");

            Log.WriteLine("SetDirectory:1 Current Directory = " + Directory.GetCurrentDirectory(), Log.DEBUG_LEVEL.TERSE);
        }

        #endregion

        #region EXTENSIONGRIDVIEW METHODS
       
        protected void ExtensionGridView_SelectedIndexChanged(object sender, EventArgs e)
        {

            // Read Database to search for Client IP and return success or failure
            if (ReadFromExtnDb(ClientIP) == true)
            {
                FromExtnTextBox.Text = FromExtn.ToString();
            }

            // If IP Address does not exist we have nothing to give the user
            else
            {
                FromExtnTextBox.Text = "";
                Notifier("Please Enter the extension you wish to call 'from'", Color.Red);
            }


            ShowForm();

            GridViewRow row = ExtensionGridView.SelectedRow;
           
            ToExtnTextBox.Text = row.Cells[2].Text;

            Log.WriteLine("ExtensionGridView_SelectedIndexChanged:1 From Text : " + FromExtnTextBox.Text, Log.DEBUG_LEVEL.TERSE);

        }

        #endregion


        #region DATABASE METHODS
        

        public bool ReadFromExtnDb(string ipAddress)
        {
            bool IsSuccess = false;
            
            Log.WriteLine("ReadFromExtnDb:0 User IPADDRESS: " + ipAddress, Log.DEBUG_LEVEL.TERSE);

            Log.WriteLine("ReadFromExtnDb:1 Started getting application info: ", Log.DEBUG_LEVEL.TERSE);

            #region Build SQL Connection with SPROC to Check for valid Extension

            Log.WriteLine("ReadFromExtnDb: SQL Server: " + SQLLookup.DatabaseString, Log.DEBUG_LEVEL.TERSE);

            // Create a Connection to SQL Server
            SqlConnection MyConnection = new SqlConnection(@"Data Source= " + SQLLookup.DatabaseString + @"; Initial Catalog=PhoneDb;Integrated Security=True");

            SqlCommand myCommand = new SqlCommand("GetFromExtension", MyConnection);
            myCommand.CommandType = CommandType.StoredProcedure;

            #endregion

            #region Test SP Command

            Log.WriteLine("ReadFromExtnDb:2 Before Try: " , Log.DEBUG_LEVEL.MODERATE);

            try
            {
                myCommand.Parameters.Add(new SqlParameter("@IPAddress", ipAddress));

                MyConnection.Open();
                myCommand.ExecuteNonQuery();
                SqlDataReader Reader = myCommand.ExecuteReader();

                // While loop decides if bool is false ..
                // If we never have anything, bool stays false
                while (Reader.Read())
                {
                    Log.WriteLine("ReadFromExtnDb:4 Extension = " + Reader.GetInt32(0), Log.DEBUG_LEVEL.TERSE);

                    FromExtn = Reader.GetInt32(0);

                    IsSuccess = true;
                    
                }

                MyConnection.Close();

                Log.WriteLine("ReadFromExtnDb:3 After try completed ", Log.DEBUG_LEVEL.MODERATE);
            }
            catch (Exception ex)
            {
                Log.WriteLine("ReadFromExtnDb: Unable to retrieve Extension from Database. Check database exists " + ex.Message, Log.DEBUG_LEVEL.TERSE);
                IsSuccess = false;
            }

            MyConnection.Close();

            return IsSuccess;

            #endregion
        }

        /// <summary>
        /// Updates Database with users From Extension for ClicktoDial
        /// </summary>
        /// <param name="extension">From Extension that is provided by user / database</param>
        /// <param name="ipAddress">MAC Address from machine user is logged on for verification</param>
        /// <returns></returns>
        public bool UpdateFromExtnDb(string extension, string ipAddress)
        {
            bool IsCompleted = false;

            Log.WriteLine("UpdateFromExtnDb: Started ", Log.DEBUG_LEVEL.TERSE);
            Log.WriteLine("UpdateFromExtnDb: extension " + extension , Log.DEBUG_LEVEL.TERSE);
            Log.WriteLine("UpdateFromExtnDb: ipAddress " + ipAddress, Log.DEBUG_LEVEL.TERSE);

            #region Build SQL Connection with SPROC to Check for valid Extension

            Log.WriteLine("UpdateFromExtnDb: SQL Server: " + SQLLookup.DatabaseString, Log.DEBUG_LEVEL.TERSE);

            // Create a Connection to SQL Server
            SqlConnection MyConnection = new SqlConnection(@"Data Source= " + SQLLookup.DatabaseString + @"; Initial Catalog=PhoneDb;Integrated Security=True");

            SqlCommand myCommand = new SqlCommand("InsertFromExtension", MyConnection);
            myCommand.CommandType = CommandType.StoredProcedure;

            #endregion

            #region Test SP Command

            try
            {
                //Parameters for Stored procedure
                myCommand.Parameters.Add(new SqlParameter("@FromExtension", extension));
                myCommand.Parameters.Add(new SqlParameter("@IPAddress", ipAddress));

                MyConnection.Open();
                myCommand.ExecuteNonQuery();
                MyConnection.Close();

                IsCompleted = true;

            }
            catch (Exception ex)
            {
                Log.WriteLine("UpdateFromExtnDb: Unable to Write to Database. Check database exists " + ex.Message, Log.DEBUG_LEVEL.TERSE);
            }

            MyConnection.Close();

            return IsCompleted;

            #endregion

        }

        #endregion


        #region PUBLIC METHODS
        
        /// <summary>
        ///  Returns string IP address of CLIENT nic card
        /// </summary>
        /// <returns> ipAddress string ( address currently active )</returns>
        public string GetIPAddress()
        {
            string ipAddress = "";

          
           // Check that an address is valid
            if( Request.UserHostAddress !="" )
            {

             ipAddress = Request.UserHostAddress;

            }
            
            return ipAddress;

        }

        public void Notifier(string message, Color notificationColor)
        {
             NotificationLabel.Font.Size = 12;
             NotificationLabel.ForeColor = notificationColor;

            if (notificationColor == Color.Red)
                NotificationLabel.Font.Bold = true;
            else
                NotificationLabel.Font.Bold = false;

            NotificationLabel.Text = message;

        }

        public void HideForm()
        {
            NotificationLabel.Visible       = false;
            FromExtnLabel.Visible           = false;
            FromExtnTextBox.Visible         = false;
            ToExtnLabel.Visible             = false;
            ToExtnTextBox.Visible           = false;
            TestLabel.Visible               = false;
            TestTextBox.Visible             = false;
            DialButton.Visible              = false;

        }

        public void ShowForm()
        {
            NotificationLabel.Visible       = true;
            FromExtnLabel.Visible           = true;
            FromExtnTextBox.Visible         = true;
            ToExtnLabel.Visible             = true;
            ToExtnTextBox.Visible           = true;
            TestLabel.Visible               = true;
            TestTextBox.Visible             = true;
            DialButton.Visible              = true;

        }

        #endregion

              protected void ExtensionGridView_Sorting(object sender, GridViewSortEventArgs e)
        {
            string sortExpression = e.SortExpression;
            ViewState["SortExpression"] = sortExpression;

            if (GridViewSortDirection == SortDirection.Ascending)
            {
                GridViewSortDirection = SortDirection.Descending;
                SortGridView(sortExpression, DESCENDING);
            }
            else
            {
                GridViewSortDirection = SortDirection.Ascending;
                SortGridView(sortExpression, ASCENDING);
            }
            
        }

      
        private void SortGridView(string sortExpression, string direction)
        {

           

         
            _extList.ExtItemList.Sort(_extItem.NameComparison);

         
         ExtensionGridView.DataSource = _extList.ExtItemList;
            ExtensionGridView.DataBind();



Was This Post Helpful? 0
  • +
  • -

Page 1 of 1