|
I can serialize my class with xmlserializer.
but when i add a DataTable typed property to my class, xmlserializer submit an error to me.
please guide to me.
|
|
|
|
|
We need the error mesage you're getting. We also need to know how your adding this DataTable to your class. Some code snippets would help alot.
Without these items, it's impossible to tell you what your doing wrong.
RageInTheMachine9532
"...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome
|
|
|
|
|
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Collections;
using System.Data ;
/* The XmlRootAttribute allows you to set an alternate name
(PurchaseOrder) of the XML element, the element namespace; by
default, the XmlSerializer uses the class name. The attribute
also allows you to set the XML namespace for the element. Lastly,
the attribute sets the IsNullable property, which specifies whether
the xsi:null attribute appears if the class instance is set to
a null reference. */
[XmlRootAttribute("PurchaseOrder", Namespace="http://www.cpandl.com",
IsNullable = false)]
public class PurchaseOrder
{
public Address ShipTo;
public string OrderDate;
/* The XmlArrayAttribute changes the XML element name
from the default of "OrderedItems" to "Items". */
[XmlArrayAttribute("Items")]
public OrderedItem[] OrderedItems;
public decimal SubTotal;
public decimal ShipCost;
public decimal TotalCost;
}
public class Address
{
/* The XmlAttribute instructs the XmlSerializer to serialize the Name
field as an XML attribute instead of an XML element (the default
behavior). */
[XmlAttribute]
public string Name;
public string Line1;
/* Setting the IsNullable property to false instructs the
XmlSerializer that the XML attribute will not appear if
the City field is set to a null reference. */
[XmlElementAttribute(IsNullable = false)]
public string City;
public string State;
public string Zip;
}
public class OrderedItem
{
public string ItemName;
public string Description;
public decimal UnitPrice;
public int Quantity;
public decimal LineTotal;
/* Calculate is a custom method that calculates the price per item,
and stores the value in a field. */
public void Calculate()
{
LineTotal = UnitPrice * Quantity;
}
}
public class Test
{
public static void Main()
{
// Read and write purchase orders.
Test t = new Test();
t.CreatePO("po.xml");
t.ReadPO("po.xml");
t.CreatCol() ;
}
private void CreatCol()
{
XmlSerializer serializer =
new XmlSerializer(typeof(MyCoulumnClollectionClass));
TextWriter writer = new StreamWriter("Hadi.xml");
MyCoulumnClollectionClass d=new MyCoulumnClollectionClass() ;
SCol s1=new SCol() ;
s1.FieldName ="stud_no" ;
s1.DisplayName="stud_displayname";
d.Add(s1);
s1=new SCol() ;
s1.FieldName="FN2" ;
s1.DisplayName="DN2" ;
s1.AAAA="====" ;
d.Add(s1) ;
serializer.Serialize(writer, d);
writer.Close();
}
private void CreatePO(string filename)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to serialize.
XmlSerializer serializer =
new XmlSerializer(typeof(PurchaseOrder));
TextWriter writer = new StreamWriter(filename);
PurchaseOrder po=new PurchaseOrder();
// Create an address to ship and bill to.
Address billAddress = new Address();
billAddress.Name = "Teresa Atkinson";
billAddress.Line1 = "1 Main St.";
billAddress.City = "AnyTown";
billAddress.State = "WA";
billAddress.Zip = "00000";
// Set ShipTo and BillTo to the same addressee.
po.ShipTo = billAddress;
po.OrderDate = System.DateTime.Now.ToLongDateString();
// Create an OrderedItem object.
OrderedItem i1 = new OrderedItem();
i1.ItemName = "Widget S";
i1.Description = "Small widget";
i1.UnitPrice = (decimal) 5.23;
i1.Quantity = 3;
i1.Calculate();
// Insert the item into the array.
OrderedItem [] items = {i1};
po.OrderedItems = items;
// Calculate the total cost.
decimal subTotal = new decimal();
foreach(OrderedItem oi in items)
{
subTotal += oi.LineTotal;
}
po.SubTotal = subTotal;
po.ShipCost = (decimal) 12.51;
po.TotalCost = po.SubTotal + po.ShipCost;
// Serialize the purchase order, and close the TextWriter.
serializer.Serialize(writer, po);
writer.Close();
}
protected void ReadPO(string filename)
{
// Create an instance of the XmlSerializer class;
// specify the type of object to be deserialized.
XmlSerializer serializer = new XmlSerializer(typeof(PurchaseOrder));
/* If the XML document has been altered with unknown
nodes or attributes, handle them with the
UnknownNode and UnknownAttribute events.*/
serializer.UnknownNode+= new
XmlNodeEventHandler(serializer_UnknownNode);
serializer.UnknownAttribute+= new
XmlAttributeEventHandler(serializer_UnknownAttribute);
// A FileStream is needed to read the XML document.
FileStream fs = new FileStream(filename, FileMode.Open);
// Declare an object variable of the type to be deserialized.
PurchaseOrder po;
/* Use the Deserialize method to restore the object's state with
data from the XML document. */
po = (PurchaseOrder) serializer.Deserialize(fs);
// Read the order date.
Console.WriteLine ("OrderDate: " + po.OrderDate);
// Read the shipping address.
Address shipTo = po.ShipTo;
ReadAddress(shipTo, "Ship To:");
// Read the list of ordered items.
OrderedItem [] items = po.OrderedItems;
Console.WriteLine("Items to be shipped:");
foreach(OrderedItem oi in items)
{
Console.WriteLine("\t"+
oi.ItemName + "\t" +
oi.Description + "\t" +
oi.UnitPrice + "\t" +
oi.Quantity + "\t" +
oi.LineTotal);
}
// Read the subtotal, shipping cost, and total cost.
Console.WriteLine("\t\t\t\t\t Subtotal\t" + po.SubTotal);
Console.WriteLine("\t\t\t\t\t Shipping\t" + po.ShipCost);
Console.WriteLine("\t\t\t\t\t Total\t\t" + po.TotalCost);
}
protected void ReadAddress(Address a, string label)
{
// Read the fields of the Address object.
Console.WriteLine(label);
Console.WriteLine("\t"+ a.Name );
Console.WriteLine("\t" + a.Line1);
Console.WriteLine("\t" + a.City);
Console.WriteLine("\t" + a.State);
Console.WriteLine("\t" + a.Zip );
Console.WriteLine();
}
protected void serializer_UnknownNode
(object sender, XmlNodeEventArgs e)
{
Console.WriteLine("Unknown Node:" + e.Name + "\t" + e.Text);
}
protected void serializer_UnknownAttribute
(object sender, XmlAttributeEventArgs e)
{
System.Xml.XmlAttribute attr = e.Attr;
Console.WriteLine("Unknown attribute " +
attr.Name + "='" + attr.Value + "'");
}
}
public class SCol
{
// public string FiledName
// {
// get
// {
// return m_fieldName ;
// }
// }
// public void SetFiledName(string f)
// {
// m_fieldName=f ;
// }
[XmlElement(ElementName = "TaxRate")]
public string FieldName
{
get
{
return m_ ;
}
set
{
m_=value ;
}
}
public string DisplayName ;
// ***** in this property , xmlSerializer submit error ***
public DataTable m_columnTable ;
private string m_ ;
[XmlElement]
public string AAAA ;
}
public class MyCoulumnClollectionClass : CollectionBase
{
//[XmlElement(ElementName = "Collection")]
//[XmlArrayAttribute("Items")]
public SCol this[ int index ]
{
get
{
return( (SCol) List[index] );
}
set
{
List[index] = value;
}
}
public int Add( SCol value )
{
return( List.Add( value ) );
}
public int IndexOf( SCol value )
{
return( List.IndexOf( value ) );
}
public void Insert( int index, SCol value )
{
List.Insert( index, value );
}
public void Remove( SCol value )
{
List.Remove( value );
}
public bool Contains( SCol value )
{
// If value is not of type Int16, this will return false.
return( List.Contains( value ) );
}
}
|
|
|
|
|
I creat a component that have a collection object.
when i use this component on my form, and fill collection and save form, the collection`s contetnt not save into form`s resource.
please guide to me.
|
|
|
|
|
If by "form's resource" you mean the ResX file, then you have to use a CodeDomSerializer derivative that uses the System.Resources namespace classes.
If you want to simple serialize the collection to code in your .cs source file, then just use the DesignerSerializationVisibilityAttribute :
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public MyCollection MyObjects
{
} That's it.
If you want custom serialization, again extend CodeDomSerializer . If all you want is to serialize a collection like a ComboBox would for items, for example, then just use the attribute and enumeration value I mentioned above.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Hello.
Thank you very much for your guiding. it is very interest.
I use "[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]" in a collection that contain "int" data type and it is ok. But when i use this attribute for a collection that contain a class or struct , it is not work , mean that the contect of content class of collection not save in form code.
please guide to me again, very very thank you.
Hadi: hd_ali@yahoo.com
|
|
|
|
|
Hi!
I’ve read about a topic like this earlier. I would like a program to generate a picture of my programming project from my .sc (C#) or my .h (C++) files.
Anyone got a tip of a good free alternative? I’m using VS.NET and would be very happy if I have a solution there…
I’ve heard about MS Visio but is there a possibility to load existing files in the way I want?
...and justice for all
APe
|
|
|
|
|
Microsoft Visio Professional adds a plugin for VS.NET that will generate a UML diagram for your project.
Rational XDE (got $2,500 bucks to spare?) allows you to do this from within VS.NET and synchronize your class diagram with your project.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Actualy i have Microsoft Visio Professional.
Where do i find and use the plugin in VS.NET?
Thanks
...and justice for all
APe
|
|
|
|
|
It was an install option when you installed Visio. It's only available for VS.NET 2003, IIRC. It should've installed by default. Just click on Project menu and you should see a Visio UML menu item.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Please HELP.
I have class hierarchy model (a.k.a. an Object Domain), where I store my data. This objects are finaly stored in ArrayList that I use as DataSource for my DataGrid.
This idea corectly works with fixed columns count, because objects in ArrayList have property for each column and DataGrid maps this properties.
How can I customize my model for variable columns count?
I try to change my structured objects to collections and properties to array property. However, in this case, DataGrid can't map this property and columns can't be append.
Any help is much appreciated.
Sincerely,
Morfo
|
|
|
|
|
What is the use of following method?
Graphics.AddMetafileComment(metaComment);
where do and what for we use MetaFile Comments?
Please guide
reagrds
|
|
|
|
|
|
Yes
I have seen it, it says what it is and how to do it, nothing is said about why and where it is required.
thanks
|
|
|
|
|
It adds a comment to a metafile (.wmf, .emf, and other supported properties). Not that the name implies that or anything.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Since when are comments required in anything?
They're no different from // in C, C++, C#, or REM or ' in Visual Basic.
RageInTheMachine9532
"...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome
|
|
|
|
|
How do we again read those comments using C#?
regards
|
|
|
|
|
You would have to use the Graphics.EnumerateMetafileMethod to playback the metafile records and pick out the Comment type records you want. When you call this method, you have to supply a EnumerateMetafileProc delegate to the function so it can call your record handler with each record in the file. Your record handler wouldhave to pick out the Comments as they were sent to you...
RageInTheMachine9532
"...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome
|
|
|
|
|
1. I have a class, called 'UserManager'. The UserDataSource propertie is presented below:
///
///
///
public DataSet UserDataSourse
{
get
{
DataSet dataset;
dataset=mLibraryItem.Copy();
return dataset;
}
}
Note: mLibraryItem is a dataset which stores current data of the User.
2. I have a Windows form, form1. I add a combobox to form1 and perform the bind data using the formload event:
usermanager=new UserManager();
comboBox1.DataSource=usermanager.UserDataSourse.Tables["User"];
comboBox1.DisplayMember="UserName";
Result: The number of items in the combox is correct but the Username isn't displayed in the combobox as expected. The System.Data.DataRowView is shown instead
Please advise how to solve this problem.
Thanks,
Uyen Chi
|
|
|
|
|
Hi,
I think you have to set first the datatextfield
comboBox1.datatextfield = "UserName";
comboBox1.DataSource=usermanager.UserDataSourse.Tables["User"];
comboBox1.DisplayMember="UserName";
I'm not sure maybe I can help, try it.
Regards
/Dabuskol
|
|
|
|
|
Thank dabuskol for your reply.
I have already fixed this bug. The problem is the name of field must be capital
Regards,
Uyen Chi
|
|
|
|
|
This is because Reflection is used to bind to properties. A property called "name", for example, is different than a property called "Name". While possible, it is a violation of the CLI (Common Language Infrastructure).
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Hi.
Can anyone tell me or point me to a HOWTO on making messager-like messageboxes?
A have a win app in which i would like to show some notifications to the user when something occurs, but without disturbing the user.
I want to do this the same way that messenger does it when you fx have a new mail or when some friend logged in.
How do i do this?
\Regards finger
|
|
|
|
|
|
Hi,
I'm just wondering if a class with the [Serializable] attribute could be serialized to an XML file. Whats the easiest way? Where to start reading?
Thanks in advance,
Matthias
If eell I ,nust draw to your atenttion to het fakt that I can splel perfrectly well - i;ts my typeying that sukcs.
(Lounge/David Wulff)
www.emvoid.de
|
|
|
|