-2

我在单独的程序集中创建了一个接口,并在 2 个不同的项目中添加了对它的引用。

在一个项目中,我尝试创建一个实现接口的类型的实例,但我得到了一个无法转换类型异常的对象。

这是代码,这里显示了 3 个代码片段。例外当然是 Form1_load

namespace InvoiceBuilder
{
    public interface IInvoiceBuilder
    {
        string Execute(ListView.CheckedListViewItemCollection items);
    }
}

   private void Form1_Load(object sender, EventArgs e)
    {
        Assembly assembly = Assembly.LoadFrom(@"c:\users\malcolm\documents\mdsdevstudio\InvoiceBuilder.dll");

        Type type = assembly.GetType("InvoiceBuilder.WordDocumentBuilder");

        IInvoiceBuilder instanceOfMyType = (IInvoiceBuilder)Activator.CreateInstance(type);

        string msg = instanceOfMyType.Execute(new ListView.CheckedListViewItemCollection(null));
        MessageBox.Show(msg);
    }


namespace InvoiceBuilder 
{
public class WordDocumentBuilder : IInvoiceBuilder
{
    string _clientName;
    //    Object _templateFile = @"C:\Data\Invoices\Invoicetemplate.doc";
    //    const string _invoicesPath = @"C:\Data\Invoices";
    Object _templateFile = @"C:\Users\Malcolm\Documents\Invoicing\Invoicetemplate.doc";
    const string _invoicesPath = @"C:\Users\Malcolm\Documents\Invoicing";
    List<Task> _tasks;
    TimesheetsDBDataContext _ctx = new TimesheetsDBDataContext();
    bool _newInvoicePerProject;
    decimal _gstRate = 0;
    double _hours=0;
    decimal _subtotal=0;
    decimal _total = 0;
    decimal _gst = 0;
    string _invoiceNo;
    string _msg = "";

    public WordDocumentBuilder()
    {
    }

    public string Execute(ListView.CheckedListViewItemCollection items)
    {
        return BuildDocument(items);
    }

    public string BuildDocument(ListView.CheckedListViewItemCollection items)
    {
        try
        {
            MainForm frm = new MainForm();
            frm.ShowDialog();
            _newInvoicePerProject = frm.CreateNewInvoicePerProject;
            _gstRate = frm.GstRate / 100;
            GetTasks();
            ProcessData(items);
        }
        catch (Exception ex)
        {
            _msg += ex.ToString();
        }

        return _msg;
    }

    private void ProcessData(ListView.CheckedListViewItemCollection items)
    {
        IQueryable list=null;
        List<TimesheetSelection> selections = GetSelectionList(items);
        if (_newInvoicePerProject)
        {
            list = from tsh in _ctx.TimeSheets
                   join sl in selections on tsh.tshID equals sl.tshID
                   group tsh by tsh.tshProID into g
                   select g;
        }
        else
        {
            list = from tsh in _ctx.TimeSheets
                   join sl in selections on tsh.tshID equals sl.tshID
                   group tsh by tsh into g
                   select g;
        }

        foreach (IGrouping<int, TimeSheet> timesheets in list)
        {
            BuildDocument(timesheets.ToList());
            UpdateRowsAsInvoiced(timesheets.ToList());
            AddInvoiceRow();
        }
    }

    private void BuildDocument(List<TimeSheet> timesheets)
    {
        Word._Application word=null;
        Word._Document doc;
        Word.Table table;
        Object missing = System.Reflection.Missing.Value;
        Object bookmarkname;
        object range=0;

        try
        {
            word = new Word.Application();

            //doc = word.Documents.Add();//
            doc = word.Documents.Open(ref _templateFile, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing);

            GetInvoiceNo();
            string filename = GetDocumentFilename();
            _msg += filename + "created." + Environment.NewLine;

            bookmarkname = "InvoiceNo";
            doc.Bookmarks.get_Item(ref bookmarkname).Range.Text = _invoiceNo;
            bookmarkname = "InvoiceDate";
            doc.Bookmarks.get_Item(ref bookmarkname).Range.Text = DateTime.Today.ToString("dd/MM/yyyy");
            bookmarkname = "ClientName";
            _clientName = _ctx.Clients.Where(cli => cli.cliID == _ctx.Projects.Where(prj => prj.proID == timesheets[0].tshProID).Single().proCliID).Single().cliClientName;
            doc.Bookmarks.get_Item(ref bookmarkname).Range.Text = _clientName;
            bookmarkname = "Project";
            doc.Bookmarks.get_Item(ref bookmarkname).Range.Text = _ctx.Projects.Where(prj => prj.proID == timesheets[0].tshProID).Single().proProjectName;

            //doc.Range(ref range, ref range).Tables[1].Range.Font.Size = 0;

            table = doc.Range(ref missing, ref missing).Tables[1];
            table.Range.Font.Size = 9;

            int row = 2;
            foreach (TimeSheet timesheet in timesheets)
            {
                table.Rows.Add(ref missing);
                table.Cell(row, 1).Range.InsertAfter(timesheet.tshDate.Value.ToString("dd/MM/yyyy"));
                table.Cell(row, 1).Range.Bold = 0;

                table.Cell(row, 2).Range.InsertAfter(_tasks.Where(tsk => tsk.tskID == timesheet.tshTskID).Select(tsk => tsk.tskTaskDescription).Single());
                table.Cell(row, 2).Range.Bold = 0;

                table.Cell(row, 3).Range.InsertAfter(timesheet.tshDescription.ToString());
                table.Cell(row, 3).Range.Bold = 0;

                table.Cell(row, 4).Range.InsertAfter(timesheet.tshRate.Value.ToString("0.00"));
                table.Cell(row, 4).Range.Bold = 0;

                table.Cell(row, 5).Range.InsertAfter(timesheet.tshHours.ToString());
                table.Cell(row, 5).Range.Bold = 0;

                row += 1;
                _hours += Convert.ToDouble(timesheet.tshHours);
                _subtotal += Convert.ToDecimal(timesheet.tshHours) * timesheet.tshRate.Value;
            }

            string totaldesc;

            totaldesc = string.Format("Subtotal ({0} Hours):", _hours.ToString());

            table = doc.Range(ref missing, ref missing).Tables[2];

            table.Cell(1, 1).Range.InsertAfter(totaldesc);
            table.Cell(1, 1).Range.Bold = 1;

            _subtotal = Math.Round(_subtotal, 2);
            table.Cell(1, 2).Range.InsertAfter(string.Format("{0:c}", _subtotal));
            table.Cell(1, 2).Range.Bold = 1;

            _gst = Math.Round(_subtotal * _gstRate, 2);
            _total = Math.Round(_subtotal + _gst, 2);

            //Add Gst row
            table.Rows.Add(ref missing);
            table.Cell(2, 1).Range.InsertAfter("GST");
            table.Cell(2, 1).Range.Bold = 1;
            table.Cell(2, 2).Range.InsertAfter(string.Format("{0:c}", _gst));
            table.Cell(2, 2).Range.Bold = 1;

            //Add Total row
            table.Rows.Add(ref missing);
            table.Cell(3, 1).Range.InsertAfter("Invoice Total");
            table.Cell(3, 1).Range.Bold = 1;
            table.Cell(3, 2).Range.InsertAfter(string.Format("{0:c}", _total));
            table.Cell(3, 2).Range.Bold = 1;

            object fname = (object)filename;
            doc.SaveAs(ref fname, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,
                ref missing, ref missing, ref missing);

            Object oFalse = false;
            doc.Close(ref oFalse, ref missing, ref missing);

        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            word.Quit(ref missing, ref missing, ref missing);
            word = null;
        }

    }

    private void UpdateRowsAsInvoiced(List<TimeSheet> timesheets)
    {
        foreach(TimeSheet timesheet in timesheets)
        {
            timesheet.tshInvoiced = true;
        }
        _ctx.SubmitChanges();
    }

    private void AddInvoiceRow()
    {
        Invoice invoice = new Invoice();

        invoice.invDate = DateTime.Today;
        invoice.invInvoiceNo = _invoiceNo;
        invoice.invClient = _clientName;
        invoice.invTotalHours = _hours;
        invoice.invSubtotal = _subtotal;
        invoice.invGST = _gst;
        invoice.invInvoiceTotal = _total;

        _ctx.Invoices.InsertOnSubmit(invoice);
    }

    private string GetDocumentFilename()
    {
        string filename = _invoicesPath + @"\Invoice_" + _invoiceNo + ".doc";

        return filename;
    }

    private void GetInvoiceNo()
    {
        string invno = DateTime.Today.ToString("yyyyMMdd");
        int suffix = 65;

        while (true)
        {
            suffix += 1;
            invno = DateTime.Today.ToString("yyyyMMdd") + ((char)suffix).ToString();
            bool exists = _ctx.Invoices.Where(inv => inv.invInvoiceNo == invno).Count() > 0;
            if (exists)
                break;
        }

        _invoiceNo = invno;
    }

    private List<TimesheetSelection> GetSelectionList(ListView.CheckedListViewItemCollection items)
    {
        List<TimesheetSelection> list = new List<TimesheetSelection>();

        foreach (ListViewItem lvi in items)
        {
            list.Add(new TimesheetSelection { tshID = Convert.ToInt32(lvi.Text) });
        }
        return list;
    }

    private void GetTasks()
    {
        _tasks = (from tsk in _ctx.Tasks select tsk).ToList(); 
    }
}

public class TimesheetSelection
{
    public int tshID { get; set; }
}
}
4

1 回答 1

0

很可能您有不止一个地方定义 IInvoiceBuilder 接口(即,您在单独的库和主程序中有接口)。

完整的错误信息将比代码页更有用......

于 2012-04-17T02:46:25.470 回答