//-----------------------------------------------------------------------
//  This file is part of the Microsoft Code Samples.
// 
//  Copyright (C) Microsoft Corporation.  All rights reserved.
// 
//This source code is intended only as a supplement to Microsoft
//Development Tools and/or on-line documentation.  See these other
//materials for detailed information regarding Microsoft code samples.
// 
//THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//PARTICULAR PURPOSE.
//-----------------------------------------------------------------------

#region Using directives

using System;
using Microsoft.Samples.SqlServer;
using System.Xml;

#endregion

public class LineItem
{
	protected int m_itemNumber;
	public int ItemNumber
	{
		get { return m_itemNumber; }
		set { m_itemNumber = value; }
	}

	protected int m_quantity;
	public int Quantity
	{
		get { return m_quantity; }
		set { m_quantity = value; }
	}

	protected string m_name;
	public string Name
	{
		get { return m_name; }
		set { m_name = value; }
	}

	protected double m_unitPrice;
	public double UnitPrice
	{
		get { return m_unitPrice; }
		set { m_unitPrice = value; }
	}

	public double Price
	{
		get { return m_unitPrice * m_quantity; }
	}

	public LineItem(int itemNumber)
	{
		m_itemNumber = itemNumber;
	}

	public static LineItem Deserialize(Message message)
	{
		XmlDocument doc = new XmlDocument();
		doc.Load(new XmlTextReader(message.Body));
		if (doc.DocumentElement.Name != "LineItem")
			throw new InvalidMessageException("Document element name is not LineItem");

		LineItem li = new LineItem();
		foreach (XmlElement prop in doc.DocumentElement.ChildNodes) {
			switch (prop.Name) {
				case "ItemNumber":
					li.ItemNumber = Int32.Parse(prop.InnerText);
					break;
				case "Quantity":
					li.Quantity = Int32.Parse(prop.InnerText);
					break;
				case "UnitPrice":
					li.UnitPrice = Double.Parse(prop.InnerText);
					break;
				case "Name":
					li.Name = prop.InnerText;
					break;
				default:
					throw new InvalidMessageException("LineItem contains invalid sub-element '" + prop.Name + "'");
			}
		}
		return li;
	}

	public LineItem()
	{
		m_itemNumber = -1;
	}
}