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

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

Serializing an Enum

Posted By:      Posted Date: October 14, 2010    Points: 0   Category :.NET Framework
Hi all,

i need to backup a list filled with objects of this class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace XML2
  public enum userLevel { Manager, Librarian, Reader };
  public class Users
    public string _username { get; set; }
    public string _password { get; set; }
    public userLevel _level { get; set; }
    public Users()

    public Users(string name, string password, userLevel level)
      _username = name;
      _password = password;
      _level = level;
This is my list class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace XML2

  public class userDB
    List<Users> users = new List<Users>();
    public userDB()
      users.Add(new Users("Administrator", "12345678", userLevel.Manager));
      users.Add(new Users("Librarian", "12345678", userLevel.Librarian));
      users.Add(new Use

View Complete Post

More Related Resource Links

Problems with serializing/deserializing C# enum as XML attribute


I have this enum definition (everything here is sanitized, so it may appear to be overly simplistic)...

public enum Option :

How to cast integer values as an array of enum values?


Hello all!

I'm working with VS2010 Beta2, ASP.NET and Dynamic Data. I'm using VB but will certainly be happy to receive a C# example if necessary. Laughing

I used a few of Steve's examples (Writing Attributes and Extension Methods for Dynamic Data and Dynamic Data - Hiding Columns in selected PageTemplates) to create a custom property attribute to be applied to a dynamic data column and want it to accept an array of enum values (each value will represent a dynamic data page template where this column should not be displayed).  My new attribute works fine when I hardcode it like this, meaning the HideColumnIn attribute is properly populated with the array of enum values:

<HideColumnIn(PageTemplate.List, PageTemplate.Edit)> _
Public Property My_DD_Column As Object


However, I want to store the values to be used for the HideColumnIn in the DB as integer values that correspond to the

Serializing XML and storing as XML in Database


Hi All,

I know this may sound a daft question but I'm wanting to save Serialized XML into a databse but for the life of me I cant do it.

So far I have my class

public static void SerializeToXML(Candidate candidate)
            XmlSerializer serializer = new XmlSerializer(typeof(Candidate));
            TextWriter textWriter = new StreamWriter(@"C:\movie.xml");            
            serializer.Serialize(textWriter, candidate);

This basically save the serialized properties in the Candidate class into the movie.xml file which is great but I want it to return XML (so it can be re-used) so I can store the XML in the XML database field

Any help would be greatly appreciated



Toolbox: Serializing objects, Scott Allen's blog, Site Performance, and more


Serialize and Deserialize Fixed Length and Delimited Files, Scott Allen's blog, inspecting Web Pages, and more.

Scott Mitchell

MSDN Magazine August 2008

enum and switch need help

void Main()
	string t = "Vendor";
	switch (t)
		case PType.Client :
		case PartyType.Vendor :

public enum PType

When I try to run these code got error:  cannot implicitly convert type PType to string

If I change PType.Client to PType.Client.ToString() got error: A constant value is expected


how to use enum in class


hi there
in my class i have this code

  public enum userTypeID
            Superuser = 1,
            User = 2
        public userTypeID Tipo;

and i am trying to use with

int use= int.Parse(CLS_UserType.userTypeID.Superuser)

it return error because it is not possible cast int to enumeration
how can i do to get a value?

Comparing Enum values in a collection - BC42025: Access of shared member, constant member, enum mem


I am upgrading from asp1.1 to 2.0

I use collection classes to sort data (e.g in datagrids etc)


Enum newsFields
End Enum

Public Overloads Sub Sort(ByVal sortField As newsFields, ByVal isAscending As Boolean)
Select Case sortField
Case newsFields.title

Serializing and Deserializing Problem


Hi, I used serialization and de-serialization in my project. 

Below is my class and form code for your reference.

Public Class Serialization
    Public Function XmlSerialization(ByRef objEmployee As Object) As String
        'XML Serialization
        Dim encoding As New UTF8Encoding()
        Dim Serializer As New XmlSerializer(objEmployee.GetType())

Serializing objects which implement IEnumerable<>

Hi, I'm trying for long time to serialize an object which contains an object which implements IEnumerable<>. The last object also contains an object which implements IEnumerable<>. The objects strucutre is as followed: [Serializable] public class A { public B _b {get; set; } } [Serializable] public class B : IEnumerable<C> { public List<C> c_items {get; set;} public void Add (C obj){} } [Serializable] public class C : IEnumerable<D> { public List<D> d_items {get; set;} public void Add (D obj){} } [Serializable] public class D { public int Key {get; set;} public int Value {get; set;} } In the code line: A obj = new A(); XmlSerializer serializer = new XmlSerializer(obj.GetType()); I'm getting the exception: unable to generate temporary class (result=1), error CS0030: Cannot convert type 'C' to type 'D'... When I remove the IEnumerable implementation from one of B or C, the serialization works. What as I getting wrong? Any help would be appreciated!

Serializing Linq to Entities for use in a REST Service

What would be the best approach to send data retrieved from Linq to Entities over a rest service? For example, if you have a Linq to Entities class, say Products from the Northwind database. I want to return a subset of the Products (based on a query on the model) back through a service. First a retrieve a List<Product> from the context, and then i need to serialize the data and send it over the wire. If I use the exact Linq to Entities class, then there is so much "garbage" that it either fails outright (from a circular reference) or you are wasting bandwith. What is a design to overcome this? Create POCO objects for each linq to entities class you want to send and create custom code to tranform each object in the list to the POCO object? This is the only way I can see doing it, although it would be very tedius to create and maintain (unless some custom code generation was created). Is there a better approach? clients

serializing generic classes?

  heys all i'm rreally confused with where the serialization is in my web service. i've included a fully working short example (if you try to run it you will see the error message   Types 'WebService1.My.Abstract.Result`1[WebService1.My.CheckEmailResult.EnumError]' and 'WebService1.My.Abstract.Result`1[WebService1.My.CheckUserNameResult.EnumError]' both use the XML type name, 'ResultOfEnumError', from namespace 'http://tempuri.org/'. Use XML attributes to specify a unique XML name and/or namespace for the type.       Imports System.Web.Services Imports System.Web.Services.Protocols Imports System.ComponentModel ' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. ' <System.Web.Script.Services.ScriptService()> _ <System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _ <System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _ <ToolboxItem(False)> _ Public Class Service1 Inherits System.Web.Services.WebService <WebMethod()> _ Public Function HelloWorld() As String Return "Hello World" End Function <WebMethod()> _ Public Function CheckUserName() As My.CheckUserNameResult Return New My.CheckUserNameResult End Function <WebMethod()> _ Public Function CheckEmail() As My.CheckEmail

Bug: Specifying values in the definition of an enum in Web Parts in subsites

Pardon the cumbersome title, but I wanted to make it as descriptive as possible! Anyway, I stumbled upon this bug and spent a good while trying to figure out what was wrong. I'm developing a WebPart for use in MOSS 2007. The WebPart in question is mostly unremarkable, but I was getting the following error when editing the WebPart properties: "Some of the properties for this Web Part cannot be displayed properly. For more information, see your site administrator." I've searched Google, Bing and Yahoo for this error and have found nothing, so hopefully this post will be of use to anyone else who searches for it. Turns out the problem was in the enumerator definition. It looked like this:   public enum KPIPalette { Grey = 1, Green, Blue, Orange }   The colour palettes of the components we're using started at 1, so I set the enumerator to do that also. SharePoint, however, had other ideas. The solution is to leave enumerator definitions out. When the number was required later in code, a 1 was added. Error begone, problem solved!

How to cast integer values to an array of enum values?

Hello all! I'm new to VB.NET (and OOP in general) and am struggling a bit...  I'm working with VS2010 Beta2, ASP.NET and Dynamic Data, however I'm thinking this question may be more related to VB so hopefully I've chosen the correct forum. I have a list of integer values stored in the DB and would like to cast them to an array of enum values so that they may be passed to my constructor.  The values in the DB directly correspond to the enum values.  Here is stripped down version of the code that hopefully highlights what I'm attempting to do:Private _pageTemplate() As PageTemplate Public Sub New(ByVal ParamArray pageTemplateArray As PageTemplate()) _pageTemplate = pageTemplateArray End Sub Public Enum PageTemplate Details = 1 Edit = 2 Insert = 3 List = 4 ListDetails = 5 End Enum What I'm having difficulty with is reading integer values from the DB and casting them to an array of PageTemplate() to be passed to the constructor above.  The integer values in the DB will be 1 through 5 to correspond to the enum values listed above.  Here is how I'm trying to build the ParamArray to be passed to the attribute constructor:Dim hideFieldsIn(-1) As PageTemplate Dim rowCount As Integer = -1 If reader.HasRows Then While reader.Read() rowCount += 1 ReDim hideFieldsIn(rowCount)

How to expose an enum type to a client via WCF if it isn't used as a param type in any service oper

Hi,   I want to 'expose' an enum type from my server via WCF so that my client can access it. This happens automagically if I use the enum as a parameter type within a service operation, however, what if the particular enum isn't part of any service operation?   In other words, I've defined serveral enums within my Server that are quite useful to my client (even though they don't appear in any of my paramter declarations for the service operations).   The only way I can get this to work is simply create dummy service operations that contains these enum's as arguments. The MEX page then exposes these types for my client to use, but this seems a bit naff.   Thanks   Paul.

CommunicationException when serializing my business POCO object

Hi! I'm currently blocked by a strange problem, here is the situation: I've a client and a server, running with .Net 4.0 framework. I'm using Entity Framework server side, and WCF to communicate between client and Server. I use POCO object on my Entity Framework model. One month ago, I had a problem: In some case entity framework has already loaded an object and then want to return it when the WCF service is queried. Example: An User has a collection of Orders, and Orders knows which User handle it---> cyclic references I searched online how to resolve this and I found this: http://chabster.blogspot.com/2008/02/wcf-cyclic-references-support.html It worked like a charmed for me until now. I can get data from the server without server, ... Now I'm trying to call my Save(User) method from the client to the server, and I get this error:   System.ServiceModel.CommunicationException was caught Message=There was an error while trying to serialize parameter http://tempuri.org/:User. The InnerException message was 'Type 'System.DelegateSerializationHolder+DelegateEntry' with data contract name 'DelegateSerializationHolder.DelegateEntry:http://schemas.datacontract.org/2004/07/System' is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribu

Enum in WCF is throwing exception

wcf service method is returning a datacontract that contains an enum .The following error is thrown in the clientSystem.ServiceModel.CommunicationException was caught  Message="An error occurred while receiving the HTTP response to http://localhost:8731/Design_Time_Addresses/WCFTest3/Service1/. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details."  Source="mscorlib"  StackTrace:    Server stack trace:        at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)       at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)       at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)       at System.ServiceModel.Channels.ClientReliableChannelBinder`1.RequestClientReliableChannelBinder`1.OnRequest(TRequestChannel channel, Message message, TimeSpan timeout, MaskingMode maskingMode)       at System.ServiceModel.Channels.ClientReliableChannelBinder`1.Request(Message message, TimeSpan timeout, MaskingMode maskingMode)       at System.ServiceModel.Channels.ClientReliableChannelBind
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