using System;
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.Runtime.InteropServices;

// Steps ...
// 1. Add a Web Reference to http://localhost/currencyws/Service.asmx
// 2. Name the Web Service "ConvertWS"
// 3. Project - Properties - Build - Generate Serialization Assembly "ON"
// 4. Permission level to External
// 5. Add a 

[SqlUserDefinedAggregate(Format.UserDefined,
  MaxByteSize = 64,
  IsInvariantToDuplicates = false,
  IsInvariantToNulls = true,
  IsInvariantToOrder = true,
  IsNullIfEmpty = true), Serializable(),
  StructLayout(LayoutKind.Sequential)]
public class MaxCurrency : IBinarySerialize
{
  public decimal amount, max;
  public string currencyCode;

  public void Init()
  {
    max = 0m;
    amount = 0m;
    currencyCode = "";
  }

  public void Accumulate(Currency value)
  {

    CoolDBObjects.ConvertWS.Service ws = new CoolDBObjects.ConvertWS.Service();
    decimal stdAmount = ws.Convert(value.Amount, value.CurrencyCode, "USD");

    // Get all values in USD

    if (stdAmount > max)
    {
      max = stdAmount;
      amount = value.Amount;
      currencyCode = value.CurrencyCode;
    }
  }

  public void Merge(MaxCurrency maxCur)
  {
    if (maxCur.max > max)
    {
      max = maxCur.max;
      amount = maxCur.amount;
      currencyCode = maxCur.currencyCode;
    }
  }

  public string Terminate()
  {
    Currency currency = new Currency();
    currency.Amount = amount;
    currency.CurrencyCode = currencyCode;
    return currency.ToString();
  }

  public void Write(System.IO.BinaryWriter w)
  {
    w.Write(max);
    w.Write(amount);
    w.Write(currencyCode);
  }

  public void Read(System.IO.BinaryReader r)
  {
    max = r.ReadDecimal();
    amount = r.ReadDecimal();
    currencyCode = r.ReadString();
  }
}