.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
Easy Web
Imran Ghani
Post New Web Links

How can Serialize ArrayList ?

Posted By:      Posted Date: September 13, 2010    Points: 0   Category :.NET Framework
 
Hi code sample?????????public class Employee :ISerializable { private int version =1; //ADD emoployee name in this list private ArrayList employeeList; private void  AddEmployee(){ // Adding employee to Employee List}protected TestData(SerializationInfo info,StreamingContext context) { this.version = info.GetInt32("version"); this.name = info.GetString("list"); } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("version", this.version); info.AddValue("list", this.employeeList); } }   Thanks in Advance nayakam


View Complete Post


More Related Resource Links

How to bind TemplateField DropDownList with ArrayList?

  

Hi Expert!

  I'm trying gridview templateField DropDownList bind with arraylist. When i set bindsource i got this error. "//Error Object reference not set to an instance of an object."

My Sample .aspx

<asp:TemplateField HeaderText="Type">
                    <FooterTemplate>
                        <asp:DropDownList ID="_grvcboType" runat="server" Width="117px" DataTextField="Display" DataValueField="Value">
                        </asp:DropDownList>
                    </FooterTemplate>
                    <ItemTemplate>
                        <asp:Label ID="Label7" runat="ser

how to serialize objects ??

  

Is there any way or process to serialize the the objects?? i am trying to store the instance of few control in viewstate but it shows error msg that it is not a serialized object. should i perform some steps to serialize the objects ???



Query an arraylist of array list using linq

  

I have an array list called Customer. I t holds a list of array list which has the account details.

proj.customer -> collection of arraylist of type customer

proj.customer.account -> collection of arraylist of type account


Account array list holds type account and it has a poperty account balance. How can I query all accounts which has account balance  >100


I tried the following one

var Accountlist= from Account accountdetails in proj.customer.account

where accountid.balance >100

select accountdetails.id

But it is always throwing an error saying cannot cast type customer to type account

Please help


ArrayList.ToArray fails!

  

In my app, I have code similar to the following:

          try

          {

               ArrayList alStartFrames = new ArrayList();
                byte[] abytTest = { 1, 2 };

                alStartFrames.Add(abytTest);

                byte[] abytCombinedFrame = (byte[])alStartFrames.ToArray(typeof(byte));
            }

            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }

The call to ToArray always fails and the exception is caught even though I'm pretty sure alStartFrames is an array list of byte arrays. Anyone have any insight on why this is happening?! TIA

ArrayList indexes not set properly

  

I have some basic code to fill items in an ArrayList as follows:

Dim intSteps As ArrayList = New ArrayList()
			
Select Case Session("type")
Case 1
	intSteps.Add(0)
	intSteps.Add(1)
	intSteps.Add(2)
	intSteps.Add(6)
	intSteps.Add(11)
	intSteps.Add(12)
Case 2
	intSteps.Add(0)
	intSteps.Add(1)
	intSteps.Add(2)
	intSteps.Add(5)
	intSteps.Add(6)
	intSteps.Add(11)
	intSteps.Add(12)
Case Else
	intSteps.Add(0)
	intSteps.Add(1)
	intSteps.Add(2)
	intSteps.Add(3)
	intSteps.Add(4)
	intSteps.Add(5)
	intSteps.Add(6)
	intSteps.Add(7)
	intSteps.Add(8)
	intSteps.Add(9)
	intSteps.Add(10)
	intSteps.Add(11)
	intSteps.Add(12)
End Select

Dim j As Integer
	For j = 0 To intSteps.Count - 1
        Response.Write(intSteps.IndexOf(j) & " : " & intSteps.Item(j) & "<br />")
Next

The issue is that for Case 1 the output is:

0 : 0
1 : 1
2 : 2
-1 : 6
-1 : 11
-1 : 12

For Case 2, it's:

0 : 0
1 : 1
2 : 2
-1 : 5
-1 : 6
3 : 11
4 : 12

And for Else, it's:

0 : 0
1 : 1
2 : 2
3 : 3
4 : 4
5 : 5
6 : 6
7 : 7
8 : 8
9 : 9
10 : 10
11 : 11
12 : 12

Why is the index being set as -1 for a few items?


How to: Serialize Hashtable contained inside another object that is serialized as an array of object

  
Update:  I've added the entire program in a single block of C# text near the end of these posts that can be placed into a C# Program.cs file of a console project.   I have a class called MyHashtable that inherits from Hashtable and implements IXmlSerializable.  MyHashtable is contained inside another object called MyObject and I need to xml serialize an array of MyObject[].  Whenever I xml deserialize, the hashtable is deserialized, but only 1 of MyObjects from the MyObject[] array is deserialized.  The ReadXml uses "while (reader.NodeType != XmlNodeType.EndElement)" so I don't think the reader is consuming all of the xml internally.   Does anyone know why this is happening?  Thanks.    

WSE 3.0 Can't Serialize String Types as Escaped CDATA

  
I know I should be using WCF.  HOWEVER, I'm utilizing services provided by Omniture that simply only work well with WSE 3.0 as Omniture's WSDL definitions and service endpoints have compatibility issues that are beyond my control.   While I was able to solve a lot of my compatibility problems with Omniture but there is one issue that is still causing me a lot of heartburn.  When passing strings values through WSE3.0 the Microsoft.Web.Services3.WebServicesClientProtocol class encodes the values as denoted below for the "script" argument.         <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">       <tns:ProductSubmitProductScript>       <productCode xsi:type="xsd:string">123456789</productCode>       <script xsi:type="xsd:string">&lt;genesis&gt;&lt;/genesis&gt;</script>       </tns:ProductSubmitProductScript>    Unfortunately, this encoding isn't going is promptly rejected by Omniture because the xml values are not subsequently decoded on their side.  When passing string values to Omniture they MUST be enclosed in the escape sequenice <![CDATA[ ]]>.  Thus, the prior request should be

binary serialize weird error

  
i got this class, when i wanna serialize it, i keep getting error System.Runtime.Serialization.SerializationException was unhandled by user code   Message=Type 'System.Linq.Enumerable+WhereSelectListIterator`2[[Data.Models],[System.Int32, mscorlib, Version=4.0.0.0, ...' in Assembly 'System.Core, Version=4.0.0.0, ... is not marked as serializable. [Serializable] public class XXX : ... { public IEnumerable<int> CardFilters { get; set; } //public void RequeryCardFilters() //{ //} public void RequeryCardFilters() { this.CardFilters = null; ... //IEnumerable<Data.Models> var rslt = RFDataViewModelFactory.GetReportCardFilters(this.Identifiers, this.PostcodeFrom, this.PostcodeTo, this.LastContactBefore, this.RecontactBy, this.SelectedCardType); ... IEnumerable<int> rsltIds = from i in rslt select i.Id; } } you can see inside the RequeryCardFilters(), i only play with 3 data/var, 1 of them is local public prop, the other 2 are local var. If you remark this out, and just use an empty method, it worked fine. what can cause the serialization to fail? IFormatter formatter = new BinaryFormatter(); MemoryStream memStrem = new MemoryStream(); formatter.Serialize(memStrem, myObj);

How to serialize a File using Filestream

  
Is there a way to serialize a file using File stream. If no how it can be done Any one please help

Serialize / DeSerialize XElement objecs using BinaryFormatter.

  
Hi, I'm having some business objects which contains XElement properties. I have some offline framework which serialize / deserialize using binary formatter. I'm getting the error "Type 'System.Xml.Linq.XElement' in Assembly 'System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable." when i try to serialize the xelement object I'm getting the XElement serializer error. We are bit too far with design and need to find some work around to solve this issue. The following program should give you the same error behavior. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml.Linq; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace XElementBinaryformatter {     public partial class Form1 : Form     {         private BinaryFormatter formatter = new BinaryFormatter();         public Form1()         {             InitializeComponent();         }         private void btnSerialize_Clic

Can you Serialize a Derived class, cast as it's base?

  
Can you Serialize a Derived class, cast as it's base? (Using the stock XmlSerializer.Serialize?)   (The overall goal I'm trying to achieve, is I have 1 object, and I need to serialize it in 2 different ways, 1 with full info, one with half info, and I *thought* a base class would be the way to do it)   e.g. I have a base and derived class   [XmlRoot("MyBaseXml" )] public class MyBaseClass { public string baseField = "base" ; } [XmlRoot("MyDerivedXml" )] public class MyDerviedClass : MyBaseClass { public string derivedField = "derived" ; }   I make a new instance of my derived class MyDerviedClass obj = new MyDerivedClass();   And then I have the following serialization method(s)   /// <summary> /// Saves an object to a file /// </summary> /// <param name="obj"> Object to save</param> /// <param name="fileName"> Path to output to</param> public void Serialize(object obj, string fileName) { Type type = obj.GetType(); XmlSerializer xmlSerializer = new XmlSerializer(type); Serialize(obj, fileName, type); } /// <summary> /// Saves an object to a file casting it as a specific type /// </summary> /// <param name="obj"> Object to save</param> /// <param name="fileName"

Serialize / DeSerialize XElement objecs using BinaryFormatter.

  
Hi, I'm having some business objects which contains XElement properties. I have some offline framework which serialize / deserialize using binary formatter. I'm getting the error "Type 'System.Xml.Linq.XElement' in Assembly 'System.Xml.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable." when i try to serialize the xelement object I'm getting the XElement serializer error. We are bit too far with design and need to find some work around to solve this issue. The following program should give you the same error behavior. using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml.Linq; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace XElementBinaryformatter {     public partial class Form1 : Form     {         private BinaryFormatter formatter = new BinaryFormatter();         public Form1()         {             InitializeComponent();         }         private void btnSerialize_Clic

Can serialize but not deserialize class containing an xs:list attribute using XmlSerializer

  
I have a simple serializable class along the lines of: [Serializable] [XmlType] public class MyClass { [XmlAttribute("values")] public int[] Values { get; set; } } If I create an instance of this class with Values set to an empty collection the XmlSerializer class produces this output as expected: <?xml version="1.0" encoding="utf-16" ?> <MyClass xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" values="" /> However, deserializing this exact output throws a System.FormatException: Input string was not in a correct format. Shouldn't the XmlSerializer be able to deserialize this, since it produced the xml string in the first place?

Have some error using arraylist in session to store multiple value

  
i have two buttons in user control, button1 is (like) and second is (dLike). if i click any button the count will increased in my database table by 1. our table have id,title,url,imagegalary,articleid. in everypage i take the article id as in sessioni alredy disable the links when you click once , after i went to next page and come back to the same page the button will visible how to solve this problem. how to store the multiple session values in the arraylist and display it . please anybody replay me protected void ImageButton1_Click(object sender, ImageClickEventArgs e){string ArticleID1 = GenerateArticleID();COLTools.DB.DataBaseType = COLTools.DataBaseType.SqlServer;COLTools.DB.ConnectionString = ConfigurationSettings.AppSettings["COLCMS"].ToString();string updateQuery = "update Article set Alike = Alike + 1 where Articleid =" + ArticleID1;COLTools.DB.RunSql(updateQuery);disablebutton();addtovotelist(ArticleID1);likedislike();}protected void ImageButton2_Click(object sender, ImageClickEventArgs e){string ArticleID1 = GenerateArticleID();COLTools.DB.DataBaseType = COLTools.DataBaseType.SqlServer;COLTools.DB.ConnectionString = ConfigurationSettings.AppSettings["COLCMS"].ToString();string updateQuery = "update Article set Dlike = Dlike + 1 where Articleid =" + ArticleID1;COLTools.DB.RunSql(updateQuery);disablebutton();addtovotelist(A

How do I parse/serialize when parent list element is missing?

  
First thank you ahead of time for you help. I really need some help with this. Background, this is to be a REST service in .net 4.0 and I understand I have to use xmlserializer instead of datacontract serializer. The xsd and the generated class assumes there can be one or more geo locations in a Locations element. However, based on an unchangable requirement, I have to assume the parent Locations element may not be there and the xml can contain only one child location element. So instead of <?xml version="1.0" encoding="UTF-8"?> <findService   xmlns="urn:ietf:params:xml:ns:lost1"   xmlns:p2="http://www.opengis.net/gml"   serviceBoundary="value"   recursive="true"> <Locations>   <location id="12334456" profile="geodetic-2d">     <p2:Point id="point1" srsName="urn:ogc:def:crs:EPSG::4326">       <p2:pos>40.85614955747385 -73.77044677734375</p2:pos>     </p2:Point>   </location> </Locations>   <service>urn:service:sos</service> </findService> they can send the following instead <?xml version="1.0" encoding="UTF-8"?> <findService   xmlns="urn:ietf:params:xml:ns:lost1&

Extension Method ForEach for ArrayList class

  
Hi,I need to create an extension method(ForEach) for arraylist classI have created an extension method for Array class but cannot do that for arraylist.Please help me namespace MyExtension { public static class IEnumerableExtension { public static void ForEach<T>(this IEnumerable<T> list, Action<T> action) { if (action == null) throw new ArgumentNullException("action"); foreach (T item in list) { action(item); } } } } Any Help Shall be appreciatedThanks

How do I count occurences of an item in an ArrayList?

  
Hi All- Please help, I'm stuck!  After executing a query with LINQ to SQL, the result I have is an arraylist (.ToList)  of items with ID numbers.  The number of items and their occurences will vary with each query.  I would simply like to count the occurences of each specific ID in the list.  How do I do that??  The only count function I know of (.count() ) is for a count on the entire list.   I've also I've been reading on how to loop through the list items but I don't understand how I can do that if I don't know how many specific ID's there will be from each query result.    
Categories: 
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend