﻿/////////////////////////////////////////////////////////////////////////
// Client.cs - Console Client of Service uploads binary file to host   //
//                                                                     //
// Jim Fawcett, CSE686 - Internet Programming, Summer 2010             //
/////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.IO;

namespace ConsoleApplication1
{
  class Client
  {
    static void Main(string[] args)
    {
      Console.Write("\n  Demonstrating FileService hosted by Web Server");
      Console.Write("\n ================================================\n");

      ServiceReference1.FileService service
        = new ServiceReference1.FileServiceClient();

      Console.Write("\n  Using FileService to upload text file as single string");
      Console.Write("\n --------------------------------------------------------");

      if(service.PutFile("Hello","Hello CSE686"))
        Console.Write("\n  upload succeeded\n");
      else
        Console.Write("\n  upload failed\n");

      Console.Write("\n  Using FileService to upload binary file in blocks");
      Console.Write("\n ---------------------------------------------------");

      if(service.OpenFileForWrite("testfile2.txt"))
      {
        Console.Write("\n  opening source file for reading and destination for writing");
        FileStream fs = null;
        try
        {
          fs = File.Open("../../Client.cs",FileMode.Open);
          int bytesRead;
          int count = 0;
          while(true)
          {
            long BlockSize = 512;
            long remainder = (int)(fs.Length - fs.Position);
            if(remainder == 0)
              break;
            long size = Math.Min(BlockSize, remainder);
            byte[] block = new byte[size];
            bytesRead = fs.Read(block, 0, block.Length);
            //Console.Write("\n  {0}", ASCIIEncoding.ASCII.GetString(block));
            Console.Write("\n  writting block #{0} of {1} bytes", ++count, size);
            service.WriteBlock(block);
          }
          Console.Write("\n  closing source and destination files\n\n");
          fs.Close();
          service.CloseFile();
        }
        catch
        {
          Console.Write("\n  File handling error\n\n");
          if (fs != null)
            fs.Close();
          return;
        }
      }
    }
  }
}
