Browse Source

添加JS交互类

章政 7 years ago
parent
commit
a58df04c43

+ 1 - 0
UAS_Web/Browser.cs

@@ -28,6 +28,7 @@ namespace UAS_Web
             {
             {
                 Dock = DockStyle.Fill
                 Dock = DockStyle.Fill
             };
             };
+            webBrowser.RegisterJsObject("", new BoundObject(), true);
             webBrowser.MenuHandler = new MenuHandler();
             webBrowser.MenuHandler = new MenuHandler();
             webBrowser.RequestHandler = new RequestHandler();
             webBrowser.RequestHandler = new RequestHandler();
             Controls.Add(webBrowser);
             Controls.Add(webBrowser);

+ 4 - 0
UAS_Web/UAS_Web.csproj

@@ -100,10 +100,14 @@
     </Compile>
     </Compile>
     <Compile Include="Program.cs" />
     <Compile Include="Program.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
+    <Compile Include="tool\BoundObject.cs" />
+    <Compile Include="tool\ExceptionTestBoundObject.cs" />
     <Compile Include="tool\FilterManager.cs" />
     <Compile Include="tool\FilterManager.cs" />
+    <Compile Include="tool\FormatterConverter.cs" />
     <Compile Include="tool\MenuHandler.cs" />
     <Compile Include="tool\MenuHandler.cs" />
     <Compile Include="tool\MessageFilter.cs" />
     <Compile Include="tool\MessageFilter.cs" />
     <Compile Include="tool\RequestHandler.cs" />
     <Compile Include="tool\RequestHandler.cs" />
+    <Compile Include="tool\SubBoundObject.cs" />
     <EmbeddedResource Include="Browser.resx">
     <EmbeddedResource Include="Browser.resx">
       <DependentUpon>Browser.cs</DependentUpon>
       <DependentUpon>Browser.cs</DependentUpon>
     </EmbeddedResource>
     </EmbeddedResource>

+ 337 - 0
UAS_Web/tool/BoundObject.cs

@@ -0,0 +1,337 @@
+using CefSharp;
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace UAS_Web.tool
+{
+    class BoundObject
+    {
+        public int MyProperty { get; set; }
+
+        public string MyReadOnlyProperty { get; internal set; }
+        public Type MyUnconvertibleProperty { get; set; }
+        public SubBoundObject SubObject { get; set; }
+        public ExceptionTestBoundObject ExceptionTestObject { get; set; }
+
+        public int this[int i]
+        {
+            get { return i; }
+            set { }
+        }
+
+        public uint[] MyUintArray
+        {
+            get { return new uint[] { 7, 8 }; }
+        }
+
+        public int[] MyIntArray
+        {
+            get { return new[] { 1, 2, 3, 4, 5, 6, 7, 8 }; }
+        }
+
+        public Array MyArray
+        {
+            get { return new short[] { 1, 2, 3 }; }
+        }
+
+        public byte[] MyBytes
+        {
+            get { return new byte[] { 3, 4, 5 }; }
+        }
+
+        public BoundObject()
+        {
+            MyProperty = 42;
+            MyReadOnlyProperty = "I'm immutable!";
+            IgnoredProperty = "I am an Ignored Property";
+            MyUnconvertibleProperty = GetType();
+            SubObject = new SubBoundObject();
+            ExceptionTestObject = new ExceptionTestBoundObject();
+        }
+
+        public void TestCallback(IJavascriptCallback javascriptCallback)
+        {
+            const int taskDelay = 1500;
+
+            //TaskFactory.Run(async () =>
+            //{
+            //    await TaskEx.Delay(taskDelay);
+
+            //    using (javascriptCallback)
+            //    {
+            //        //NOTE: Classes are not supported, simple structs are
+            //        var response = new CallbackResponseStruct("This callback from C# was delayed " + taskDelay + "ms");
+            //        await javascriptCallback.ExecuteAsync(response);
+            //    }
+            //});
+        }
+
+        //public string TestCallbackFromObject(SimpleClass simpleClass)
+        //{
+        //    if (simpleClass == null)
+        //    {
+        //        return "TestCallbackFromObject dictionary param is null";
+        //    }
+
+        //    IJavascriptCallback javascriptCallback = simpleClass.Callback;
+
+        //    if (javascriptCallback == null)
+        //    {
+        //        return "callback property not found or property is not a function";
+        //    }
+
+        //    const int taskDelay = 1500;
+
+        //    TaskEx.Run(async () =>
+        //    {
+        //        await TaskEx.Delay(taskDelay);
+
+        //        if (javascriptCallback != null)
+        //        {
+        //            using (javascriptCallback)
+        //            {
+        //                await javascriptCallback.ExecuteAsync("message from C# " + simpleClass.TestString + " - " + simpleClass.SubClasses[0].PropertyOne);
+        //            }
+        //        }
+        //    });
+
+        //    return "waiting for callback execution...";
+        //}
+
+        public int EchoMyProperty()
+        {
+            return MyProperty;
+        }
+
+        public string Repeat(string str, int n)
+        {
+            string result = String.Empty;
+            for (int i = 0; i < n; i++)
+            {
+                result += str;
+            }
+            return result;
+        }
+
+        public string EchoParamOrDefault(string param = "This is the default value")
+        {
+            return param;
+        }
+
+        public void EchoVoid()
+        {
+        }
+
+        public Boolean EchoBoolean(Boolean arg0)
+        {
+            return arg0;
+        }
+
+        public Boolean? EchoNullableBoolean(Boolean? arg0)
+        {
+            return arg0;
+        }
+
+        public SByte EchoSByte(SByte arg0)
+        {
+            return arg0;
+        }
+
+        public SByte? EchoNullableSByte(SByte? arg0)
+        {
+            return arg0;
+        }
+
+        public Int16 EchoInt16(Int16 arg0)
+        {
+            return arg0;
+        }
+
+        public Int16? EchoNullableInt16(Int16? arg0)
+        {
+            return arg0;
+        }
+
+        public Int32 EchoInt32(Int32 arg0)
+        {
+            return arg0;
+        }
+
+        public Int32? EchoNullableInt32(Int32? arg0)
+        {
+            return arg0;
+        }
+
+        public Int64 EchoInt64(Int64 arg0)
+        {
+            return arg0;
+        }
+
+        public Int64? EchoNullableInt64(Int64? arg0)
+        {
+            return arg0;
+        }
+
+        public Byte EchoByte(Byte arg0)
+        {
+            return arg0;
+        }
+
+        public Byte? EchoNullableByte(Byte? arg0)
+        {
+            return arg0;
+        }
+
+        public UInt16 EchoUInt16(UInt16 arg0)
+        {
+            return arg0;
+        }
+
+        public UInt16? EchoNullableUInt16(UInt16? arg0)
+        {
+            return arg0;
+        }
+
+        public UInt32 EchoUInt32(UInt32 arg0)
+        {
+            return arg0;
+        }
+
+        public UInt32? EchoNullableUInt32(UInt32? arg0)
+        {
+            return arg0;
+        }
+
+        public UInt64 EchoUInt64(UInt64 arg0)
+        {
+            return arg0;
+        }
+
+        public UInt64? EchoNullableUInt64(UInt64? arg0)
+        {
+            return arg0;
+        }
+
+        public Single EchoSingle(Single arg0)
+        {
+            return arg0;
+        }
+
+        public Single? EchoNullableSingle(Single? arg0)
+        {
+            return arg0;
+        }
+
+        public Double EchoDouble(Double arg0)
+        {
+            return arg0;
+        }
+
+        public Double? EchoNullableDouble(Double? arg0)
+        {
+            return arg0;
+        }
+
+        public Char EchoChar(Char arg0)
+        {
+            return arg0;
+        }
+
+        public Char? EchoNullableChar(Char? arg0)
+        {
+            return arg0;
+        }
+
+        public DateTime EchoDateTime(DateTime arg0)
+        {
+            return arg0;
+        }
+
+        public DateTime? EchoNullableDateTime(DateTime? arg0)
+        {
+            return arg0;
+        }
+
+        public Decimal EchoDecimal(Decimal arg0)
+        {
+            return arg0;
+        }
+
+        public Decimal? EchoNullableDecimal(Decimal? arg0)
+        {
+            return arg0;
+        }
+
+        public String EchoString(String arg0)
+        {
+            return arg0;
+        }
+
+        // TODO: This will currently not work, as it causes a collision w/ the EchoString() method. We need to find a way around that I guess.
+        //public String echoString(String arg)
+        //{
+        //    return "Lowercase echo: " + arg;
+        //}
+
+        public String lowercaseMethod()
+        {
+            return "lowercase";
+        }
+
+        public string ReturnJsonEmployeeList()
+        {
+            return "{\"employees\":[{\"firstName\":\"John\", \"lastName\":\"Doe\"},{\"firstName\":\"Anna\", \"lastName\":\"Smith\"},{\"firstName\":\"Peter\", \"lastName\":\"Jones\"}]}";
+        }
+
+        [JavascriptIgnore]
+        public string IgnoredProperty { get; set; }
+
+        [JavascriptIgnore]
+        public string IgnoredMethod()
+        {
+            return "I am an Ignored Method";
+        }
+
+        public string ComplexParamObject(object param)
+        {
+            if (param == null)
+            {
+                return "param is null";
+            }
+            return "The param type is:" + param.GetType();
+        }
+
+        public SubBoundObject GetSubObject()
+        {
+            return SubObject;
+        }
+
+        /// <summary>
+        /// Demonstrates the use of params as an argument in a bound object
+        /// </summary>
+        /// <param name="name">Dummy Argument</param>
+        /// <param name="args">Params Argument</param>
+        public string MethodWithParams(string name, params object[] args)
+        {
+            return "Name:" + name + ";Args:" + string.Join(", ", args.ToArray());
+        }
+
+        public string MethodWithoutParams(string name, string arg2)
+        {
+            return string.Format("{0}, {1}", name, arg2);
+        }
+
+        public string MethodWithoutAnything()
+        {
+            return "Method without anything called and returned successfully.";
+        }
+
+        public string MethodWithThreeParamsOneOptionalOneArray(string name, string optionalParam = null, params object[] args)
+        {
+            return "MethodWithThreeParamsOneOptionalOneArray:" + (name ?? "No Name Specified") + " - " + (optionalParam ?? "No Optional Param Specified") + ";Args:" + string.Join(", ", args.ToArray());
+        }
+    }
+}

+ 70 - 0
UAS_Web/tool/ExceptionTestBoundObject.cs

@@ -0,0 +1,70 @@
+using CefSharp;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace UAS_Web.tool
+{
+    class ExceptionTestBoundObject
+    {
+        [DebuggerStepThrough]
+        private double DivisionByZero(int zero)
+        {
+            return 10 / zero;
+        }
+
+        [DebuggerStepThrough]
+        public double TriggerNestedExceptions()
+        {
+            try
+            {
+                try
+                {
+                    return DivisionByZero(0);
+                }
+                catch (Exception innerException)
+                {
+                    throw new InvalidOperationException("Nested Exception Invalid", innerException);
+                }
+            }
+            catch (Exception e)
+            {
+                throw new OperationCanceledException("Nested Exception Canceled", e);
+            }
+        }
+
+        [DebuggerStepThrough]
+        public int TriggerParameterException(int parameter)
+        {
+            return parameter;
+        }
+
+        public void TestCallbackException(IJavascriptCallback errorCallback, IJavascriptCallback errorCallbackResult)
+        {
+            const int taskDelay = 500;
+
+            //Task.Run(async () =>
+            //{
+            //    await TaskEx.Delay(taskDelay);
+
+            //    using (errorCallback)
+            //    {
+            //        JavascriptResponse result = await errorCallback.ExecuteAsync("This callback from C# was delayed " + taskDelay + "ms");
+            //        string resultMessage;
+            //        if (result.Success)
+            //        {
+            //            resultMessage = "Fatal: No Exception thrown in error callback";
+            //        }
+            //        else
+            //        {
+            //            resultMessage = "Exception Thrown: " + result.Message;
+            //        }
+            //        await errorCallbackResult.ExecuteAsync(resultMessage);
+            //    }
+            //});
+        }
+    }
+}

+ 93 - 0
UAS_Web/tool/FormatterConverter.cs

@@ -0,0 +1,93 @@
+using System;
+using System.Runtime.Serialization;
+
+namespace UAS_Web.tool
+{
+    class FormatterConverter : IFormatterConverter
+    {
+        public object Convert(object value, TypeCode typeCode)
+        {
+            return value;
+        }
+
+        public object Convert(object value, Type type)
+        {
+            throw new NotImplementedException();
+        }
+
+        public bool ToBoolean(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public byte ToByte(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public char ToChar(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public DateTime ToDateTime(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public decimal ToDecimal(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public double ToDouble(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public short ToInt16(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public int ToInt32(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public long ToInt64(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public sbyte ToSByte(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public float ToSingle(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public string ToString(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public ushort ToUInt16(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public uint ToUInt32(object value)
+        {
+            throw new NotImplementedException();
+        }
+
+        public ulong ToUInt64(object value)
+        {
+            throw new NotImplementedException();
+        }
+    }
+}

+ 37 - 15
UAS_Web/tool/RequestHandler.cs

@@ -1,6 +1,7 @@
 using CefSharp;
 using CefSharp;
 using System;
 using System;
 using System.IO;
 using System.IO;
+using System.Runtime.Serialization;
 
 
 namespace UAS_Web.tool
 namespace UAS_Web.tool
 {
 {
@@ -9,7 +10,7 @@ namespace UAS_Web.tool
         public event Action<byte[]> NotifyMsg;
         public event Action<byte[]> NotifyMsg;
         IResponseFilter IRequestHandler.GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
         IResponseFilter IRequestHandler.GetResourceResponseFilter(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
         {
         {
-            Console.WriteLine("GetResourceResponseFilter1");
+            //Console.WriteLine("GetResourceResponseFilter1");
             var url = new Uri(request.Url);
             var url = new Uri(request.Url);
             if (url.AbsoluteUri.Contains("http://192.168.253.6/uas_dev/jsps/vendbarcode/login.jsp"))
             if (url.AbsoluteUri.Contains("http://192.168.253.6/uas_dev/jsps/vendbarcode/login.jsp"))
             {
             {
@@ -30,7 +31,7 @@ namespace UAS_Web.tool
 
 
         void IRequestHandler.OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
         void IRequestHandler.OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
         {
         {
-            Console.WriteLine("OnResourceLoadComplete1");
+            //Console.WriteLine("OnResourceLoadComplete1");
             if (request.Url.Contains("http://192.168.253.6/uas_dev/jsps/vendbarcode/login.jsp"))
             if (request.Url.Contains("http://192.168.253.6/uas_dev/jsps/vendbarcode/login.jsp"))
             {
             {
                 var filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
                 var filter = FilterManager.GetFileter(request.Identifier.ToString()) as MessageFilter;
@@ -42,7 +43,7 @@ namespace UAS_Web.tool
 
 
         public bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
         public bool GetAuthCredentials(IWebBrowser browserControl, IBrowser browser, IFrame frame, bool isProxy, string host, int port, string realm, string scheme, IAuthCallback callback)
         {
         {
-            Console.WriteLine("GetAuthCredentials");
+            //Console.WriteLine("GetAuthCredentials");
             return false;
             return false;
         }
         }
 
 
@@ -54,68 +55,84 @@ namespace UAS_Web.tool
 
 
         public bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool isRedirect)
         public bool OnBeforeBrowse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, bool isRedirect)
         {
         {
-            Console.WriteLine("OnBeforeBrowse");
+            //Console.WriteLine("OnBeforeBrowse");
             return false;
             return false;
         }
         }
 
 
         public CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
         public CefReturnValue OnBeforeResourceLoad(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IRequestCallback callback)
         {
         {
-            Console.WriteLine("OnBeforeResourceLoad");
+            //Console.WriteLine("OnBeforeResourceLoad");
             return CefReturnValue.Continue;
             return CefReturnValue.Continue;
         }
         }
 
 
         public bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
         public bool OnCertificateError(IWebBrowser browserControl, IBrowser browser, CefErrorCode errorCode, string requestUrl, ISslInfo sslInfo, IRequestCallback callback)
         {
         {
-            Console.WriteLine("OnCertificateError");
+            //Console.WriteLine("OnCertificateError");
             return false;
             return false;
         }
         }
 
 
         public bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
         public bool OnOpenUrlFromTab(IWebBrowser browserControl, IBrowser browser, IFrame frame, string targetUrl, WindowOpenDisposition targetDisposition, bool userGesture)
         {
         {
-            Console.WriteLine("OnOpenUrlFromTab");
+            //Console.WriteLine("OnOpenUrlFromTab");
             return false;
             return false;
         }
         }
 
 
         public void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath)
         public void OnPluginCrashed(IWebBrowser browserControl, IBrowser browser, string pluginPath)
         {
         {
-            Console.WriteLine("OnPluginCrashed");
+            //Console.WriteLine("OnPluginCrashed");
         }
         }
 
 
         public bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url)
         public bool OnProtocolExecution(IWebBrowser browserControl, IBrowser browser, string url)
         {
         {
-            Console.WriteLine("OnProtocolExecution");
+            //Console.WriteLine("OnProtocolExecution");
             return false;
             return false;
         }
         }
 
 
         public bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
         public bool OnQuotaRequest(IWebBrowser browserControl, IBrowser browser, string originUrl, long newSize, IRequestCallback callback)
         {
         {
-            Console.WriteLine("OnQuotaRequest");
+            //Console.WriteLine("OnQuotaRequest");
             return false;
             return false;
         }
         }
 
 
         public void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status)
         public void OnRenderProcessTerminated(IWebBrowser browserControl, IBrowser browser, CefTerminationStatus status)
         {
         {
-            Console.WriteLine("OnRenderProcessTerminated");
+            //Console.WriteLine("OnRenderProcessTerminated");
         }
         }
 
 
         public void OnRenderViewReady(IWebBrowser browserControl, IBrowser browser)
         public void OnRenderViewReady(IWebBrowser browserControl, IBrowser browser)
         {
         {
-            Console.WriteLine("OnRenderViewReady");
+            //Console.WriteLine("OnRenderViewReady");
         }
         }
 
 
         public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
         public void OnResourceLoadComplete(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response, UrlRequestStatus status, long receivedContentLength)
         {
         {
-            Console.WriteLine("OnResourceLoadComplete");
+            //Console.WriteLine("OnResourceLoadComplete");
         }
         }
 
 
         public void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, ref string newUrl)
         public void OnResourceRedirect(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, ref string newUrl)
         {
         {
-            Console.WriteLine("OnResourceRedirect");
+            //Console.WriteLine("OnResourceRedirect");
         }
         }
 
 
         bool IRequestHandler.OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
         bool IRequestHandler.OnResourceResponse(IWebBrowser browserControl, IBrowser browser, IFrame frame, IRequest request, IResponse response)
         {
         {
-            Console.WriteLine("OnResourceResponse");
+            if (request.Url.ToUpper().Contains(".ACTION"))
+            {
+                Console.WriteLine(request.Url);
+             
+                if (request.PostData != null)
+                {
+                    //for (int i = 0; i < request.PostData.Elements.Count; i++)
+                    //{
+                    //    Console.WriteLine(System.Text.Encoding.UTF8.GetString(request.PostData.Elements[i].Bytes));
+                    //}
+                    SerializationInfo info = new SerializationInfo(typeof(string), new FormatterConverter());
+                    StreamingContext con = new StreamingContext();
+                    response.ResponseHeaders.GetObjectData(info, con);
+                    Console.WriteLine(response.MimeType);
+                }
+            }
+            //Console.WriteLine("OnResourceResponse");
             //try
             //try
             //{
             //{
             //    var content_length = int.Parse(response.ResponseHeaders["Content-Length"]);
             //    var content_length = int.Parse(response.ResponseHeaders["Content-Length"]);
@@ -127,5 +144,10 @@ namespace UAS_Web.tool
             //catch { }
             //catch { }
             return false;
             return false;
         }
         }
+
+        public void GetData()
+        {
+
+        }
     }
     }
 }
 }

+ 27 - 0
UAS_Web/tool/SubBoundObject.cs

@@ -0,0 +1,27 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+
+namespace UAS_Web.tool
+{
+    class SubBoundObject
+    {
+        public string SimpleProperty { get; set; }
+
+        public SubBoundObject()
+        {
+            SimpleProperty = "This is a very simple property.";
+        }
+
+        public string GetMyType()
+        {
+            return "My Type is " + GetType();
+        }
+
+        public string EchoSimpleProperty()
+        {
+            return SimpleProperty;
+        }
+    }
+}