using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Xml;
using System.Windows.Browser;
using System.ServiceModel;
using System.ServiceModel.Channels;
using SLReadXML.LBControl;
namespace SLReadXML
{
    public partial class App : Application
    {

        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();
        }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            #region
            Uri uri = new Uri(GetURL() + "/Config.xml", UriKind.Absolute);
            WebClient Appclient = new WebClient();
            Appclient.OpenReadAsync(uri);
            Appclient.OpenReadCompleted += new OpenReadCompletedEventHandler(Appclient_OpenReadCompleted);
            #endregion
        }
        void Appclient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            Stream stream = e.Result;
            using (XmlReader xReader = XmlReader.Create(stream))
            {
                xReader.ReadToFollowing("TestData");
                string TestData = xReader.ReadElementContentAsString();
                MessageBox.Show(TestData);
                xReader.ReadToNextSibling("SecData");
                string SecData = xReader.ReadElementContentAsString();
                InitializeServices(TestData);
            }
        }
        public void InitializeServices(string serviceAddress)
        {
            BasicHttpBinding basicBinding = new BasicHttpBinding();
            basicBinding.MaxBufferSize = 2147483647;
            basicBinding.MaxReceivedMessageSize = 2147483647;
            CustomBinding binding = new CustomBinding(basicBinding);

            BindingElement binaryElement = new BinaryMessageEncodingBindingElement();

            EndpointAddress endPoint = new EndpointAddress(serviceAddress);

            WebServiceSoapClient _LBControl = new WebServiceSoapClient();
            _LBControl = (WebServiceSoapClient)Activator.CreateInstance(typeof(WebServiceSoapClient), binding, endPoint);
            _LBControl.HelloWorldAsync();
            _LBControl.HelloWorldCompleted += new EventHandler<HelloWorldCompletedEventArgs>(_LBControl_HelloWorldCompleted);
        }

        void _LBControl_HelloWorldCompleted(object sender, HelloWorldCompletedEventArgs e)
        {
            MessageBox.Show(e.Result);
        }
        private void Application_Exit(object sender, EventArgs e)
        {

        }

        private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            // 如果应用程序是在调试器外运行的，则使用浏览器的
            // 异常机制报告该异常。在 IE 上，将在状态栏中用一个 
            // 黄色警报图标来显示该异常，而 Firefox 则会显示一个脚本错误。
            if (!System.Diagnostics.Debugger.IsAttached)
            {

                // 注意: 这使应用程序可以在已引发异常但尚未处理该异常的情况下
                // 继续运行。 
                // 对于生产应用程序，此错误处理应替换为向网站报告错误
                // 并停止应用程序。
                e.Handled = true;
                Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
            }
        }

        private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
        {
            try
            {
                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
                errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

                System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 获取当前SILVERLIGHT程序存放网络URL的前缀
        /// </summary>
        /// <returns>URL前缀</returns>
        public static string GetURL()
        {
            ScriptObject location = (HtmlPage.Window.GetProperty("location") as ScriptObject);
            object r = location.GetProperty("href");
            string URL = r.ToString().Substring(0, r.ToString().LastIndexOf('/')); //截取到当前SILVERLIGHT程序存放网络URL的前缀
            return URL;
        }
    }
}
