Example #1
0
        private void SaveDialog(CfrV8Value callback, string Filter)
        {
            var oThread = new Thread(() => {
                var basePath = AppDomain.CurrentDomain.BaseDirectory;
                var dialog   = new SaveFileDialog
                {
                    Filter = Filter
                };

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    originalName = dialog.FileName;
                    retStr       = dialog.FileName;
                }
            });

            oThread.SetApartmentState(ApartmentState.STA);
            oThread.Start();
            var isSafe       = oThread.Join(new TimeSpan(2, 0, 0));
            var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor());

            if (isSafe)
            {
                oThread.Abort();
            }

            callbackArgs.SetValue("filename", CfrV8Value.CreateString(originalName), CfxV8PropertyAttribute.ReadOnly);
            callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs });
        }
Example #2
0
 private CfrV8Value CreateV8Value(object value)
 {
     if (value is bool)
     {
         return(CfrV8Value.CreateBool((bool)value));
     }
     else if (value is DateTime)
     {
         return(CfrV8Value.CreateDate(CfrTime.FromUniversalTime((DateTime)value)));
     }
     else if (value is double)
     {
         return(CfrV8Value.CreateDouble((double)value));
     }
     else if (value is int)
     {
         return(CfrV8Value.CreateInt((int)value));
     }
     else if (value is uint)
     {
         return(CfrV8Value.CreateUint((uint)value));
     }
     else if (value is string)
     {
         return(CfrV8Value.CreateString((string)value));
     }
     else if (value == null)
     {
         return(CfrV8Value.CreateUndefined());
     }
     else
     {
         throw new ArgumentException($"Type \"{ value.GetType().Name }\" is not supported.");
     }
 }
Example #3
0
        public override CfrV8Value OnExtensionExecute(string nativeFunctionName, CfrV8Value[] arguments, CfrV8Value @this, ref string exception)
        {
            CfrV8Value retval = null;

            Console.WriteLine($"[FUNC]:{nativeFunctionName}");

            switch (nativeFunctionName)
            {
            case nameof(Version):
                var accessor = new CfrV8Accessor();

                var versionObject = CfrV8Value.CreateObject(accessor);

                versionObject.SetValue("nanui", CfrV8Value.CreateString(Version), CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly);
                versionObject.SetValue("cef", CfrV8Value.CreateString(CefVersion), CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly);
                versionObject.SetValue("chromium", CfrV8Value.CreateString(ChromiumVersion), CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly);



                retval = versionObject;

                break;
            }
            return(retval);
        }
Example #4
0
        public CfrV8Value GetHostWindowState()
        {
            var windowStateName = Container.WindowState.ToString().ToLower();
            var windowStateCode = (int)Container.WindowState;
            var clientRect      = new RECT();

            User32.GetClientRect(ContainerHandle, ref clientRect);

            var retval      = CfrV8Value.CreateObject(new CfrV8Accessor());
            var windowState = CfrV8Value.CreateObject(new CfrV8Accessor());



            windowState.SetValue("state", CfrV8Value.CreateString(windowStateName), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete);
            windowState.SetValue("code", CfrV8Value.CreateInt(windowStateCode), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete);

            retval.SetValue("windowState", windowState, CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete);

            retval.SetValue("clientWidth", CfrV8Value.CreateInt(clientRect.Width), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete);
            retval.SetValue("clientHeight", CfrV8Value.CreateInt(clientRect.Height), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete);

            retval.SetValue("width", CfrV8Value.CreateInt(Container.Width), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete);
            retval.SetValue("height", CfrV8Value.CreateInt(Container.Height), CfxV8PropertyAttribute.ReadOnly | CfxV8PropertyAttribute.DontDelete);

            return(retval);
        }
 private void ChromeFXUIV8Handler_Execute(object sender, Remote.Event.CfrV8HandlerExecuteEventArgs e)
 {
     if (e.Name == "GetVersion")
     {
         e.SetReturnValue(CfrV8Value.CreateString(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()));
     }
 }
Example #6
0
 protected override CfrV8Value Function(CfrV8HandlerExecuteEventArgs args, JsBinding binding, HtmlTextureWrapper wrapper)
 {
     if (Arguments.Length >= 1 && Arguments[0].IsString)
     {
         Selector = Arguments[0].StringValue;
     }
     return(CfrV8Value.CreateString(Selector));
 }
        public IEnumerable <IJavascriptObject> CreateBasics(IEnumerable <object> from)
        {
            _BasicBulkBuilder.Value.ExecuteFunction(null, new[] {
                CfrV8Value.CreateString(CreateStringValue(from)),
                _ObjectCreationCallbackFunction.Value
            });
            var results = _ObjectCallback.GetLastArguments();

            return(results.Select(result => result.ConvertBasic()));
        }
Example #8
0
        private static CfrV8Value ClrToV8Value(object clrValue)
        {
            var type = clrValue.GetType();

            var typeCode = Type.GetTypeCode(type);

            CfrV8Value value = null;


            switch (typeCode)
            {
            case TypeCode.Boolean:
                value = CfrV8Value.CreateBool((bool)clrValue);
                break;

            case TypeCode.Int16:
            case TypeCode.Int32:
            case TypeCode.Int64:
                value = CfrV8Value.CreateInt((int)clrValue);

                break;

            case TypeCode.SByte:
            case TypeCode.Byte:
            case TypeCode.UInt16:
            case TypeCode.UInt32:
            case TypeCode.UInt64:
                value = CfrV8Value.CreateUint((uint)clrValue);

                break;

            case TypeCode.Single:
            case TypeCode.Double:
                value = CfrV8Value.CreateDouble((double)clrValue);

                break;

            case TypeCode.Decimal:
                value = CfrV8Value.CreateDouble((double)Convert.ChangeType(clrValue, TypeCode.Double));
                break;

            case TypeCode.DateTime:
                value = CfrV8Value.CreateDate(CfrTime.FromUniversalTime((DateTime)clrValue));
                break;

            case TypeCode.Char:
            case TypeCode.String:
                value = CfrV8Value.CreateString((string)clrValue);
                break;
            }

            return(value);
        }
Example #9
0
        private void JsCodeEditorObject_ExecuteOpen(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e)
        {
            var result = parentForm.OpenFile();

            if (result != null)
            {
                e.SetReturnValue(CfrV8Value.CreateString(result));
            }
            else
            {
                e.SetReturnValue(CfrV8Value.CreateNull());
            }
        }
Example #10
0
        public IEnumerable <IJavascriptObject> CreateFromExcecutionCode(IEnumerable <string> @from)
        {
            var stringEval = $"[{string.Join(",", from)}]";

            if (stringEval.Length == 2)
            {
                return(Enumerable.Empty <IJavascriptObject>());
            }

            _BasicBulkBuilder.Value.ExecuteFunction(null, new[] {
                CfrV8Value.CreateString(stringEval),
                _ObjectCreationCallbackFunction.Value
            });
            return(_ObjectCallback.GetLastArguments().Select(ChromiumFxJavascriptObjectExtension.ConvertBasic));
        }
Example #11
0
 static ChromiumFxFactory()
 {
     Register <string>(CfrV8Value.CreateString);
     Register <Int64>((source) => CfrV8Value.CreateDouble((double)source));
     Register <UInt64>((source) => CfrV8Value.CreateDouble((double)source));
     Register <float>((source) => CfrV8Value.CreateDouble((double)source));
     Register <Int32>(CfrV8Value.CreateInt);
     Register <Int16>((source) => CfrV8Value.CreateInt((int)source));
     Register <UInt32>(CfrV8Value.CreateUint);
     Register <UInt16>((source) => CfrV8Value.CreateUint((UInt32)source));
     Register <char>((source) => CfrV8Value.CreateString(new StringBuilder().Append(source).ToString()));
     Register <double>(CfrV8Value.CreateDouble);
     Register <decimal>((source) => CfrV8Value.CreateDouble((double)source));
     Register <bool>(CfrV8Value.CreateBool);
     Register <DateTime>((source) => CfrV8Value.CreateDate(CfrTime.FromUniversalTime(source.ToUniversalTime())));
 }
Example #12
0
        /// <summary>
        /// 在ToolsManager中新建一个参数
        /// </summary>
        /// <param name="packName">包名</param>
        /// <param name="name">注册函数名字</param>
        public void registerFunc(string packName, string name)
        {
            //ToolsManager.
            ITools it  = dllList[packName];
            var    fun = it.js.AddFunction(name);

            fun.Execute += (func, args) =>
            {
                var stringArgument = args.Arguments.FirstOrDefault(p => p.IsString);
                if (stringArgument != null)
                {
                    MethodInfo m_func = it.type.GetMethod("func_" + name, new Type[] { typeof(string) });
                    string     result = (string)m_func.Invoke(it.obj, new object[] { stringArgument.StringValue });
                    args.SetReturnValue(CfrV8Value.CreateString(result));
                }
            };
        }
Example #13
0
        public static void addFunction(JSObject myObject)
        {
            //刷新
            var changeConstantCloudTypeFunc = myObject.AddFunction("changeConstantCloudType");

            changeConstantCloudTypeFunc.Execute += (func, args) =>
            {
                var jsArray  = CfrV8Value.CreateArray(1);
                var jsparams = args.Arguments.FirstOrDefault(p => p.IsArray);

                //切换类型
                Constant.CloudType = jsparams.GetValue(0).IntValue;

                Result result = new Result();
                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(result)));
                args.SetReturnValue(jsArray);
            };
        }
Example #14
0
        private void InvokeHandler(object sender, CfrV8HandlerExecuteEventArgs e)
        {
            MethodInfo method = HandlerMap.FirstOrDefault(element => element.Key == e.Name).Value;

            if (method == null)
            {
                e.Exception = $"There is no function named { e.Name }.";
            }

            ParameterInfo[] infos = method.GetParameters();

            if ((e.Arguments == null || e.Arguments.Length == 0) && infos.Length != 0)
            {
                //js传递参数数量为0,但是对应的Handler需要传参
                e.Exception = "ArgumentException";
                return;
            }

            object ret = null;

            if (infos.Length == 0)
            {
                ret = method.Invoke(this, null); //对应的Handler不需要传参
            }
            else if (infos[0].ParameterType == typeof(string))
            {
                ret = method.Invoke(this, new object[1] {
                    e.Arguments[0].StringValue
                });                                                                      //对应的Handler需要传参
            }
            else
            {
                throw new ArgumentException(); //对应的Handler参数类型错误
            }
            if (method.ReturnType != typeof(void))
            {
                //给js返回值
                using (CfrV8Value retvalue = CfrV8Value.CreateString((string)ret))
                    e.SetReturnValue(retvalue);
            }
        }
Example #15
0
        private void OpenDialog(CfrV8Value callback, string Filter)
        {
            var oThread = new Thread(() => {
                var basePath = AppDomain.CurrentDomain.BaseDirectory;
                var dialog   = new OpenFileDialog
                {
                    Filter = Filter
                };

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    var file    = new FileInfo(dialog.FileName);
                    var ext     = file.Extension;
                    var newName = Guid.NewGuid() + ext;
                    var newPath = Path.Combine(basePath, @"Assets\upload\", newName);

                    file.CopyTo(newPath);

                    originalName = file.Name;
                    retStr       = newName;
                }
            });

            oThread.SetApartmentState(ApartmentState.STA);
            oThread.Start();
            var isSafe       = oThread.Join(new TimeSpan(2, 0, 0));
            var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor());

            if (isSafe)
            {
                oThread.Abort();
            }

            callbackArgs.SetValue("hashname", CfrV8Value.CreateString(retStr), CfxV8PropertyAttribute.ReadOnly);
            callbackArgs.SetValue("filename", CfrV8Value.CreateString(originalName), CfxV8PropertyAttribute.ReadOnly);
            callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs });
        }
Example #16
0
        private void FormV8Handler_Execute(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e)
        {
            switch (e.Name)
            {
            case "Minimize":
            {
                HostForm.RequireUIThread(() =>
                    {
                        if (HostForm.WindowState == FormWindowState.Minimized)
                        {
                            HostForm.WindowState = FormWindowState.Normal;
                        }
                        else
                        {
                            HostForm.WindowState = FormWindowState.Minimized;
                        }
                    });
            }
            break;

            case "Maximize":
            {
                HostForm.RequireUIThread(() =>
                    {
                        if (HostForm.WindowState == FormWindowState.Maximized)
                        {
                            HostForm.WindowState = FormWindowState.Normal;
                        }
                        else
                        {
                            HostForm.WindowState = FormWindowState.Maximized;
                        }
                    });
            }
            break;

            case "Restore":
            {
                HostForm.RequireUIThread(() =>
                    {
                        HostForm.WindowState = FormWindowState.Normal;
                    });
            }
            break;

            case "Close":
            {
                if (HostForm != null && !HostForm.IsDisposed)
                {
                    HostForm.RequireUIThread(() =>
                        {
                            HostForm.Close();
                        });
                }
            }
            break;

            case "GetWinActivated":
            {
                if (HostForm != null && !HostForm.IsDisposed)
                {
                    e.SetReturnValue(CfrV8Value.CreateBool(Form.ActiveForm == HostForm));
                }
            }
            break;

            case "GetWinState":
            {
                if (HostForm != null && !HostForm.IsDisposed)
                {
                    var obj          = CfrV8Value.CreateObject(new CfrV8Accessor());
                    var stateString  = "normal";
                    var currentState = 0;

                    if (HostForm.WindowState == FormWindowState.Maximized)
                    {
                        currentState = 2;
                        stateString  = "maximized";
                    }
                    else if (HostForm.WindowState == FormWindowState.Minimized)
                    {
                        currentState = 1;
                        stateString  = "minimized";
                    }

                    obj.SetValue("state", CfrV8Value.CreateInt(currentState), Chromium.CfxV8PropertyAttribute.ReadOnly | Chromium.CfxV8PropertyAttribute.DontDelete);
                    obj.SetValue("stateName", CfrV8Value.CreateString(stateString), Chromium.CfxV8PropertyAttribute.ReadOnly | Chromium.CfxV8PropertyAttribute.DontDelete);
                    obj.SetValue("width", CfrV8Value.CreateInt(HostForm.ClientSize.Width), Chromium.CfxV8PropertyAttribute.ReadOnly | Chromium.CfxV8PropertyAttribute.DontDelete);
                    obj.SetValue("height", CfrV8Value.CreateInt(HostForm.ClientSize.Height), Chromium.CfxV8PropertyAttribute.ReadOnly | Chromium.CfxV8PropertyAttribute.DontDelete);

                    e.SetReturnValue(obj);
                }
            }
            break;
            }
        }
Example #17
0
 public IJavascriptObject CreateString(string value)
 {
     return(CfrV8Value.CreateString(value).Convert());
 }
Example #18
0
        public Mian()
            : base(AnimationType.Center, "wwwroot/Pages/Main2.html", false)
        {
            InitializeComponent();
            base.ContextMenuHandler.OnBeforeContextMenu += (sender, e_) => e_.Model.Clear();  //禁用右键
            this.MinimumSize     = new Size(1000, 700);
            this.MaximumSize     = new Size(1000, 700);
            this.FormBorderStyle = FormBorderStyle.FixedToolWindow;

            //注册显示注册界面事件到JS
            base.GlobalObject.AddFunction("showRegistered").Execute += (_, args) =>
            {
                this.RequireUIThread(() =>
                {
                });
            };

            //注册显示主界    面窗体到JS
            base.GlobalObject.AddFunction("viewMain").Execute += (_, args) =>
            {
                this.RequireUIThread(() =>
                {
                    //Application.Run(new Main());
                    //this.Close();
                    //this.Dispose();
                    //this.DialogResult = DialogResult.OK;
                    //new Main(this).Show();
                    //this.Close();
                });
            };
            var FuncExport = GlobalObject.AddFunction("Func_Export");

            FuncExport.Execute += (func, args) =>
            {
                var stringArgument = args.Arguments.FirstOrDefault(p => p.IsString);
                if (stringArgument != null)
                {
                    var str = stringArgument.StringValue;
                    str = str.Replace("ind", "序号");
                    str = str.Replace("one", "数字");
                    str = str.Replace("two", "排序");
                    str = str.Replace("three", "正负");
                    ExportList tables = Newtonsoft.Json.JsonConvert.DeserializeObject <ExportList>(str);

                    //导出五个表
                    var saveDir = System.Environment.CurrentDirectory;

                    string currDate = DateTime.Now.ToString("yyyy-MM-dd");
                    string currTime = DateTime.Now.ToString("HH-mm");
                    if (!Directory.Exists(saveDir + "\\数据表格"))
                    {
                        Directory.CreateDirectory(saveDir + "\\数据表格");
                    }
                    if (!Directory.Exists(saveDir + "\\数据表格\\" + currDate))
                    {
                        Directory.CreateDirectory(saveDir + "\\数据表格\\" + currDate);
                    }
                    try
                    {
                        var path = saveDir + "\\数据表格\\" + currDate;
                        //if (tables.table1 != null && tables.table1.Rows.Count > 0) FileHelper.ExportExcel(path + "\\千位" + currTime + "正比率" + GetPrecent(tables.table1) + ".xls", tables.table1, "");
                        //if (tables.table2 != null && tables.table2.Rows.Count > 0) FileHelper.ExportExcel(path + "\\百位" + currTime + "正比率" + GetPrecent(tables.table2) + ".xls", tables.table2, "");
                        //if (tables.table3 != null && tables.table3.Rows.Count > 0) FileHelper.ExportExcel(path + "\\十位" + currTime + "正比率" + GetPrecent(tables.table3) + ".xls", tables.table3, "");
                        //if (tables.table4 != null && tables.table4.Rows.Count > 0) FileHelper.ExportExcel(path + "\\个位" + currTime + "正比率" + GetPrecent(tables.table4) + ".xls", tables.table4, "");
                        //if (tables.table5 != null && tables.table5.Rows.Count > 0) FileHelper.ExportExcel(path + "\\球五" + currTime + "正比率" + GetPrecent(tables.table5) + ".xls", tables.table5, "");
                        var resultStr = CfrV8Value.CreateString(Newtonsoft.Json.JsonConvert.SerializeObject(true));
                        args.SetReturnValue(resultStr);
                    }
                    catch {
                        var resultStr = CfrV8Value.CreateString(Newtonsoft.Json.JsonConvert.SerializeObject(false));
                        args.SetReturnValue(resultStr);
                    }
                }
            };

            //注册最小化事件到JS
            base.GlobalObject.AddFunction("minForm").Execute += (_, args) => this.RequireUIThread(() => this.WindowState = FormWindowState.Minimized);

            //注册最大化事件到JS
            base.GlobalObject.AddFunction("maxForm").Execute += (_, args) => this.RequireUIThread(() => this.WindowState = FormWindowState.Maximized);

            //注册默认大小事件到JS
            base.GlobalObject.AddFunction("normalForm").Execute += (_, args) => this.RequireUIThread(() => this.WindowState = FormWindowState.Normal);

            //注册关闭窗体事件到JS
            base.GlobalObject.AddFunction("closeForm").Execute += (_, args) =>
            {
                this.RequireUIThread(() =>
                {
                    this.Close();
                    this.Dispose();
                    Application.Exit();
                });
            };
            this.Visible = true;

            //#if DEBUG
            //            base.LoadHandler.OnLoadStart += (sender, e) =>
            //            {
            //                base.Chromium.ShowDevTools();
            //            };
            //#endif
        }
Example #19
0
        public void addFunction(JSObject myObject)
        {
            //获取全部列表
            var getArrayFromCSFunc = myObject.AddFunction("getArrayFromCSharp");

            getArrayFromCSFunc.Execute += (func, args) =>
            {
                var jsparams = args.Arguments.FirstOrDefault(p => p.IsArray);

                int    pageNum  = jsparams.GetValue(0).IntValue;
                int    pageSize = jsparams.GetValue(1).IntValue;
                Result result   = new Result();
                var    jsArray  = CfrV8Value.CreateArray(1);

                BosConfig bosConfig = Constant.CloudType == 0 ? BaiduBOSAPI.BosConfig : TencentBOSAPI.BosConfig;

                if (bosConfig == null)
                {
                    result.State = 3;
                    result.Msg   = "配置未初始化";
                }
                else
                {
                    try
                    {
                        if (Constant.CloudType == 0)
                        {
                            BaiduCloudFileService.UpdateBaiduAll();
                        }
                        else
                        {
                            TencentCloudFileService.UpdateTencentAll();
                        }

                        result.Data = CommonCloudFileService.Page(pageNum, pageSize);
                    } catch (BceServiceException exception) {
                        if (exception.Message.IndexOf("is an overdue bill of your account") != -1)
                        {
                            result.State = 1;
                            result.Msg   = "您的百度云账号已欠费,请充值后使用";
                        }
                    } catch (Exception exception)
                    {
                        Console.WriteLine("Exception caught: {0}", exception);
                        result.State = 4;
                        result.Msg   = "配置信息错误";
                    }
                }

                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(result)));

                args.SetReturnValue(jsArray);
            };

            //刷新
            var refreshCloudFileFunc = myObject.AddFunction("refreshCloudFile");

            refreshCloudFileFunc.Execute += (func, args) =>
            {
                var jsArray = CfrV8Value.CreateArray(1);

                Result result = new Result();

                try
                {
                    if (Constant.CloudType == 0)
                    {
                        BaiduCloudFileService.UpdateBaiduAll();
                    }
                    else
                    {
                        TencentCloudFileService.UpdateTencentAll();
                    }

                    result.Data = CommonCloudFileService.Page(1, 15);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception caught: {0}", e);
                    result.State = 1;
                }
                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(result)));
                args.SetReturnValue(jsArray);
            };
        }
Example #20
0
        public void addFunction(JSObject myObject)
        {
            //修改配置
            var editBosConfigFunc = myObject.AddFunction("editBosConfig");

            editBosConfigFunc.Execute += (func, args) =>
            {
                var       jsparams  = args.Arguments.FirstOrDefault(p => p.IsArray);
                var       jsArray   = CfrV8Value.CreateArray(1);
                BosConfig bosConfig = new BosConfig();
                bosConfig.AccessKeyId = jsparams.GetValue(0).StringValue;
                bosConfig.AccessKey   = jsparams.GetValue(1).StringValue;
                bosConfig.BucketName  = jsparams.GetValue(2).StringValue;
                bosConfig.Endpoint    = jsparams.GetValue(3).StringValue;
                bosConfig.Id          = jsparams.GetValue(4).IntValue;
                bosConfig.AppId       = jsparams.GetValue(5).StringValue;
                Result result = new Result();

                BosConfig beforeBosConfig = Constant.CloudType == 0 ? BaiduBOSAPI.BosConfig : TencentBOSAPI.BosConfig;

                try
                {
                    BaiduBOSAPI.SetBosConfig(bosConfig);

                    if (Constant.CloudType == 0)
                    {
                        BaiduBOSAPI.BosConfig = bosConfig;
                        BaiduCloudFileService.UpdateBaiduAll();
                    }
                    else
                    {
                        TencentBOSAPI.BosConfig = bosConfig;
                        TencentCloudFileService.UpdateTencentAll();
                    }


                    BosConfigService.Update(bosConfig);
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Exception caught: {0}", exception);
                    result.State = 4;
                    result.Msg   = "配置信息错误,请检查后再次提交";
                    if (Constant.CloudType == 0)
                    {
                        BaiduBOSAPI.SetBosConfig(beforeBosConfig);
                    }
                    else
                    {
                        TencentBOSAPI.BosConfig = beforeBosConfig;
                    }
                }

                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(result)));
                args.SetReturnValue(jsArray);
            };

            //获取配置信息
            var getBosConfigFunc = myObject.AddFunction("getBosConfig");

            getBosConfigFunc.Execute += (func, args) =>
            {
                var       jsArray = CfrV8Value.CreateArray(1);
                Result    result  = new Result();
                BosConfig config  = BosConfigService.Get(" Type=" + Constant.CloudType);
                if (config == null)
                {
                    config = new BosConfig();
                }
                config.Type = Constant.CloudType;
                result.Data = config;
                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(result)));
                args.SetReturnValue(jsArray);
            };
        }
Example #21
0
        // 浏览器Javascript环境初始化完成
        protected override void OnRegisterGlobalObject(JSObject global)
        {
            // 可以在此处将C#对象注入到当前窗口的JS上下文中



            //add a function with callback function
            Console.Write(global);
            var callbackTestFunc = global.AddFunction("callbackTest");

            callbackTestFunc.Execute += (func, args) => {
                var callback = args.Arguments.FirstOrDefault(p => p.IsFunction);
                if (callback != null)
                {
                    WebBrowser.ExecuteJavascript("ChangeTitle()");


                    var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor());
                    callbackArgs.SetValue("success", CfrV8Value.CreateBool(true), CfxV8PropertyAttribute.ReadOnly);
                    callbackArgs.SetValue("text", CfrV8Value.CreateString("Message from Windows Client"), CfxV8PropertyAttribute.ReadOnly);

                    callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs });
                }
            };



            //register the "my" object
            var myObject = global.AddObject("my");

            //add property "name" to my, you should implemnt the getter/setter of name property by using PropertyGet/PropertySet events.
            var nameProp = myObject.AddDynamicProperty("name");

            nameProp.PropertyGet += (prop, args) =>
            {
                string computerName = Environment.MachineName;

                string value = $"My Computer Name is JoyNop :)\n{computerName}";

                // getter - if js code "my.name" executes, it'll get the string "NanUI".
                args.Retval = CfrV8Value.CreateString(value);
                args.SetReturnValue(true);
            };
            nameProp.PropertySet += (prop, args) =>
            {
                // setter's value from js context, here we do nothing, so it will store or igrone by your mind.
                var value = args.Value;
                args.SetReturnValue(true);
            };


            //add a function showCSharpMessageBox
            var showMessageBoxFunc = myObject.AddFunction("showCSharpMessageBox");

            showMessageBoxFunc.Execute += (func, args) =>
            {
                //it will be raised by js code "my.showCSharpMessageBox(`some text`)" executed.
                //get the first string argument in Arguments, it pass by js function.
                var stringArgument = args.Arguments.FirstOrDefault(p => p.IsString);

                if (stringArgument != null)
                {
                    string osVersionName = Environment.OSVersion.ToString();
                    MessageBox.Show(osVersionName, "Windows 内核版本", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            };


            var friends             = new string[] { "Mr.JSON", "Mr.Lee", "Mr.BONG" };
            var getObjectFormCSFunc = myObject.AddFunction("getObjectFromCSharp");

            getObjectFormCSFunc.Execute += (func, args) =>
            {
                //create the CfrV8Value object and the accssor of this Object.
                var jsObjectAccessor = new CfrV8Accessor();
                var jsObject         = CfrV8Value.CreateObject(jsObjectAccessor);

                //create a CfrV8Value array
                var jsArray = CfrV8Value.CreateArray(friends.Length);

                for (int i = 0; i < friends.Length; i++)
                {
                    jsArray.SetValue(i, CfrV8Value.CreateString(friends[i]));
                }

                jsObject.SetValue("libName", CfrV8Value.CreateString("NanUI"), CfxV8PropertyAttribute.ReadOnly);
                jsObject.SetValue("friends", jsArray, CfxV8PropertyAttribute.DontDelete);


                args.SetReturnValue(jsObject);

                //in js context, use code "my.getObjectFromCSharp()" will get an object like { friends:["Mr.JSON", "Mr.Lee", "Mr.BONG"], libName:"NanUI" }
            };
        }
Example #22
0
        public Login()
            : base(AnimationType.Center, "wwwroot/Pages/Login.html", false)
        {
            InitializeComponent();
            base.ContextMenuHandler.OnBeforeContextMenu += (sender, e_) => e_.Model.Clear();  //禁用右键
            this.MinimumSize = new Size(475, 335);
            this.MaximumSize = new Size(475, 335);
            //this.FormBorderStyle = FormBorderStyle.FixedToolWindow;

            //注册显示注册界面事件到JS
            base.GlobalObject.AddFunction("showRegistered").Execute += (_, args) =>
            {
                this.RequireUIThread(() =>
                {
                    if (registered == null || registered.IsDisposed)
                    {
                        registered = new Registered();
                        registered.Show();
                    }
                    else
                    {
                        //if (registered.WindowState == FormWindowState.Minimized)
                        //    registered.WindowState = FormWindowState.Normal;
                        registered.Activate();
                    }
                    //Mian main = new Mian();
                    //main.Show();
                });
            };

            //注册关闭事件到JS
            base.GlobalObject.AddFunction("closeForm").Execute += (_, args) =>
            {
                this.RequireUIThread(() =>
                {
                    this.Close();
                    this.Dispose();
                    Application.Exit();
                });
            };

            //注册最小化事件到JS
            base.GlobalObject.AddFunction("minForm").Execute += (_, args) =>
                                                                this.RequireUIThread(() =>
                                                                                     this.WindowState = FormWindowState.Minimized);

            //注册显示主界面窗体到JS
            base.GlobalObject.AddFunction("viewMain").Execute += (_, args) =>
            {
                this.RequireUIThread(() =>
                {
                    //Application.Run(new Main());
                    this.Close();
                    this.Dispose();
                    //this.DialogResult = DialogResult.OK;
                    Mian main = new Mian();
                    main.Show();

                    //this.Close();
                });
            };
            var myObject = GlobalObject.AddObject("my");
            var nameProp = myObject.AddDynamicProperty("name");

            nameProp.PropertyGet += (prop, args) =>
            {
                args.Retval = CfrV8Value.CreateString("MyLogin");
                args.SetReturnValue(true);
            };
            nameProp.PropertySet += (prop, args) =>
            {
                var value = args.Value;
                args.SetReturnValue(true);
            };


            /*登录*/
            var FuncLogin = myObject.AddFunction("Func_login");

            FuncLogin.Execute += (func, args) =>
            {
                var stringArgument = args.Arguments.FirstOrDefault(p => p.IsString);
                if (stringArgument != null)
                {
                    var     str   = stringArgument.StringValue;
                    JObject model = JObject.Parse(str);

                    ReturnMessageModel returnMessage = LoginFun(model);


                    var resultStr = CfrV8Value.CreateString(Newtonsoft.Json.JsonConvert.SerializeObject(returnMessage));
                    args.SetReturnValue(resultStr);
                }
            };



            //注册验证码到JS
            base.GlobalObject.AddFunction("ClickValidateCode").Execute += (_, args) =>
            {
                string base64 = BaseImgCode();
                ExecuteJavascript("ImgCode('data:image/jpg;base64," + base64 + "')");
            };

            //加载获取验证码
            LoadHandler.OnLoadEnd += LoadValidaeCode;


            //google调试器
            base.LoadHandler.OnLoadStart += (sender, e) =>
            {
                base.Chromium.ShowDevTools();
            };
        }
Example #23
0
        private static void RenderProcessHandler_OnContextCreated(object sender, Chromium.Remote.Event.CfrOnContextCreatedEventArgs e)
        {
            var obj = e.Context.Global;

            obj.SetValue("__nanui_version__", CfrV8Value.CreateString(System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()), CfxV8PropertyAttribute.ReadOnly);
        }
Example #24
0
        public void addFunction(JSObject myObject)
        {
            //添加下载记录
            var addDownloadRecordFunc = myObject.AddFunction("addDownloadRecord");

            addDownloadRecordFunc.Execute += (func, args) =>
            {
                var jsparams = args.Arguments.FirstOrDefault(p => p.IsArray);
                var jsArray  = CfrV8Value.CreateArray(1);

                DownloadRecord record = new DownloadRecord();
                record.CloudFileId = jsparams.GetValue(0).IntValue;

                Result result = new Result();

                int code = 0;

                try
                {
                    record.TargetFolder = selectFolder();
                    if (record.TargetFolder == null)
                    {
                        code = 1;
                    }
                    else
                    {
                        record.CloudFile = CommonCloudFileService.selectById(record.CloudFileId);
                        record.Type      = record.CloudFile.Type;
                        record.FileName  = record.CloudFile.Key;
                        DownloadRecordService.Insert(record);
                        record.Id = DownloadRecordService.getLastId();
                        //开始下载
                        if (record.Type == 0)
                        {
                            DownloadThreadPool.Me.StartDownload(record);
                        }
                        else
                        {
                            TencentDownloadThreadPool.Me.StartDownload(record);
                        }
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Exception caught: {0}", exception);
                    result.State = 1;
                    result.Msg   = "系统繁忙";
                }

                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(result)));
                jsArray.SetValue(1, CfrV8Value.CreateString(code.ToString()));
                args.SetReturnValue(jsArray);
            };

            //添加下载记录
            var addDownloadRecordsFunc = myObject.AddFunction("addDownloadRecords");

            addDownloadRecordsFunc.Execute += (func, args) =>
            {
                var jsparams = args.Arguments.FirstOrDefault(p => p.IsArray);
                int length   = jsparams.GetValue(0).IntValue;
                var jsArray  = CfrV8Value.CreateArray(1);

                Result result = new Result();

                int code = 0;

                try
                {
                    string folderPath = selectFolder();
                    if (folderPath == null)
                    {
                        code = 1;
                    }
                    else
                    {
                        //同时下载多个文件
                        List <DownloadRecord> records = new List <DownloadRecord>();

                        for (int i = 1, size = length; i < size; i++)
                        {
                            DownloadRecord record = new DownloadRecord();
                            record.CloudFileId = jsparams.GetValue(i).IntValue;

                            if (record.CloudFileId == 0)
                            {
                                continue;
                            }

                            record.CloudFile    = CommonCloudFileService.selectById(record.CloudFileId);
                            record.Type         = record.CloudFile.Type;
                            record.TargetFolder = folderPath;


                            if (i > 6)
                            {
                                record.DownloadState = 1;
                                records.Add(record);
                            }
                            else
                            {
                                records.Add(record);
                            }
                            record.FileName = record.CloudFile.Key;
                            DownloadRecordService.Insert(record);

                            record.Id = DownloadRecordService.getLastId();


                            if (record.Type == 0)
                            {
                                DownloadThreadPool.Me.StartDownload(record);
                            }
                            else
                            {
                                TencentDownloadThreadPool.Me.StartDownload(record);
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Exception caught: {0}", exception);
                    result.State = 1;
                    result.Msg   = "系统繁忙";
                }

                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(result)));
                jsArray.SetValue(1, CfrV8Value.CreateString(code.ToString()));
                args.SetReturnValue(jsArray);
            };


            //批量修改下载状态
            var toggerDownloadStatesFunc = myObject.AddFunction("toggerDownloadStates");

            toggerDownloadStatesFunc.Execute += (func, args) =>
            {
                var jsparams = args.Arguments.FirstOrDefault(p => p.IsArray);
                var jsArray  = CfrV8Value.CreateArray(1);

                int state = jsparams.GetValue(0).IntValue;

                List <int> ids = new List <int>();

                for (int i = 1; i < jsparams.ArrayLength; i++)
                {
                    if (state == 1)
                    {
                        DownloadThreadPool.Me.PauseDownload(jsparams.GetValue(i).IntValue + "");
                        TencentDownloadThreadPool.Me.PauseDownload(jsparams.GetValue(i).IntValue + "");
                    }
                    else if (state == 0)
                    {
                        DownloadRecord record = DownloadRecordService.selectById(jsparams.GetValue(i).IntValue);
                        record.CloudFile = CommonCloudFileService.selectById(record.CloudFileId);

                        if (record.Type == 0)
                        {
                            DownloadThreadPool.Me.StartDownload(record);
                        }
                        else
                        {
                            TencentDownloadThreadPool.Me.StartDownload(record);
                        }
                    }
                }
                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(new Result())));
                args.SetReturnValue(jsArray);
            };


            //修改下载状态
            var toggerDownloadStateFunc = myObject.AddFunction("toggerDownloadState");

            toggerDownloadStateFunc.Execute += (func, args) =>
            {
                var jsparams = args.Arguments.FirstOrDefault(p => p.IsArray);
                var jsArray  = CfrV8Value.CreateArray(1);
                int id       = jsparams.GetValue(0).IntValue;
                int state    = jsparams.GetValue(1).IntValue;

                if (state == 1)
                {
                    DownloadThreadPool.Me.PauseDownload(id + "");
                    TencentDownloadThreadPool.Me.PauseDownload(id + "");
                }
                else if (state == 0)
                {
                    DownloadRecord record = DownloadRecordService.selectById(id);
                    record.CloudFile = CommonCloudFileService.selectById(record.CloudFileId);
                    if (record.Type == 0)
                    {
                        DownloadThreadPool.Me.StartDownload(record);
                    }
                    else
                    {
                        TencentDownloadThreadPool.Me.StartDownload(record);
                    }
                }
                else if (state == 4)
                {
                    //停止下载
                }

                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(new Result())));
                args.SetReturnValue(jsArray);
            };

            //查询下载记录
            var listDownloadRecordFunc = myObject.AddFunction("listDownloadRecord");

            listDownloadRecordFunc.Execute += (func, args) =>
            {
                var jsparams   = args.Arguments.FirstOrDefault(p => p.IsArray);
                var jsArray    = CfrV8Value.CreateArray(1);
                int queryState = jsparams.GetValue(0).IntValue;
                int pageNum    = jsparams.GetValue(1).IntValue;
                int pageSize   = jsparams.GetValue(2).IntValue;

                Page <DownloadRecord> page = null;

                Result result = new Result();

                try
                {
                    if (queryState == 0)
                    {
                        page = DownloadRecordService.PageDownloadingRecord(pageNum, pageSize, Constant.CloudType);
                    }
                    else
                    {
                        page = DownloadRecordService.PageDownloadDoneRecord(pageNum, pageSize, Constant.CloudType);
                    }
                    result.Data = page;
                }
                catch (Exception exception)
                {
                    Console.WriteLine("Exception caught: {0}", exception);
                    result.State = 1;
                    result.Msg   = "系统繁忙";
                }

                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(result)));
                args.SetReturnValue(jsArray);
            };


            //查询下载记录
            var openDownloadFileFolderFunc = myObject.AddFunction("openDownloadFileFolder");

            openDownloadFileFolderFunc.Execute += (func, args) =>
            {
                var jsparams = args.Arguments.FirstOrDefault(p => p.IsArray);
                var jsArray  = CfrV8Value.CreateArray(1);
                int id       = jsparams.GetValue(0).IntValue;
                openFolder(DownloadRecordService.selectById(id));
                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(new Result())));
                args.SetReturnValue(jsArray);
            };

            //删除下载记录
            var deleteDownloadRecordFunc = myObject.AddFunction("deleteDownloadRecords");

            deleteDownloadRecordFunc.Execute += (func, args) =>
            {
                var        jsparams = args.Arguments.FirstOrDefault(p => p.IsArray);
                List <int> ids      = new List <int>();

                for (int i = 0; i < jsparams.ArrayLength; i++)
                {
                    ids.Add(jsparams.GetValue(i).IntValue);
                }

                DownloadRecordService.deletes(ids);

                var jsArray = CfrV8Value.CreateArray(1);

                jsArray.SetValue(0, CfrV8Value.CreateString(JsonConvert.SerializeObject(new Result())));
                args.SetReturnValue(jsArray);
            };
        }
Example #25
0
        public Form1()
            : base("http://res.app.local/www/index.html")
        {
            InitializeComponent();

            LoadHandler.OnLoadEnd += LoadHandler_OnLoadEnd;

            //register the "my" object
            var myObject = GlobalObject.AddObject("my");

            //add property "name" to my, you should implemnt the getter/setter of name property by using PropertyGet/PropertySet events.
            var nameProp = myObject.AddDynamicProperty("name");

            nameProp.PropertyGet += (prop, args) =>
            {
                // getter - if js code "my.name" executes, it'll get the string "NanUI".
                args.Retval = CfrV8Value.CreateString("NanUI");
                args.SetReturnValue(true);
            };
            nameProp.PropertySet += (prop, args) =>
            {
                // setter's value from js context, here we do nothing, so it will store or igrone by your mind.
                var value = args.Value;
                args.SetReturnValue(true);
            };


            //add a function showCSharpMessageBox
            var showMessageBoxFunc = myObject.AddFunction("showCSharpMessageBox");

            showMessageBoxFunc.Execute += (func, args) =>
            {
                //it will be raised by js code "my.showCSharpMessageBox(`some text`)" executed.
                //get the first string argument in Arguments, it pass by js function.
                var stringArgument = args.Arguments.FirstOrDefault(p => p.IsString);

                if (stringArgument != null)
                {
                    MessageBox.Show(this, stringArgument.StringValue, "C# Messagebox", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            };

            //add a function getArrayFromCSharp, this function has an argument, it will combind C# string array with js array and return to js context.
            var friends = new string[] { "Mr.JSON", "Mr.Lee", "Mr.BONG" };

            var getArrayFromCSFunc = myObject.AddFunction("getArrayFromCSharp");

            getArrayFromCSFunc.Execute += (func, args) =>
            {
                var jsArray = args.Arguments.FirstOrDefault(p => p.IsArray);



                if (jsArray == null)
                {
                    jsArray = CfrV8Value.CreateArray(friends.Length);
                    for (int i = 0; i < friends.Length; i++)
                    {
                        jsArray.SetValue(i, CfrV8Value.CreateString(friends[i]));
                    }
                }
                else
                {
                    var newArray = CfrV8Value.CreateArray(jsArray.ArrayLength + friends.Length);

                    for (int i = 0; i < jsArray.ArrayLength; i++)
                    {
                        newArray.SetValue(i, jsArray.GetValue(i));
                    }

                    var jsArrayLength = jsArray.ArrayLength;

                    for (int i = 0; i < friends.Length; i++)
                    {
                        newArray.SetValue(i + jsArrayLength, CfrV8Value.CreateString(friends[i]));
                    }


                    jsArray = newArray;
                }


                //return the array to js context

                args.SetReturnValue(jsArray);

                //in js context, use code "my.getArrayFromCSharp()" will get an array like ["Mr.JSON", "Mr.Lee", "Mr.BONG"]
            };

            //add a function getObjectFromCSharp, this function has no arguments, but it will return a Object to js context.
            var getObjectFormCSFunc = myObject.AddFunction("getObjectFromCSharp");

            getObjectFormCSFunc.Execute += (func, args) =>
            {
                //create the CfrV8Value object and the accssor of this Object.
                var jsObjectAccessor = new CfrV8Accessor();
                var jsObject         = CfrV8Value.CreateObject(jsObjectAccessor);

                //create a CfrV8Value array
                var jsArray = CfrV8Value.CreateArray(friends.Length);

                for (int i = 0; i < friends.Length; i++)
                {
                    jsArray.SetValue(i, CfrV8Value.CreateString(friends[i]));
                }

                jsObject.SetValue("libName", CfrV8Value.CreateString("NanUI"), CfxV8PropertyAttribute.ReadOnly);
                jsObject.SetValue("friends", jsArray, CfxV8PropertyAttribute.DontDelete);


                args.SetReturnValue(jsObject);

                //in js context, use code "my.getObjectFromCSharp()" will get an object like { friends:["Mr.JSON", "Mr.Lee", "Mr.BONG"], libName:"NanUI" }
            };


            //add a function with callback

            var callbackTestFunc = GlobalObject.AddFunction("callbackTest");

            callbackTestFunc.Execute += (func, args) => {
                var callback = args.Arguments.FirstOrDefault(p => p.IsFunction);
                if (callback != null)
                {
                    var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor());
                    callbackArgs.SetValue("success", CfrV8Value.CreateBool(true), CfxV8PropertyAttribute.ReadOnly);
                    callbackArgs.SetValue("text", CfrV8Value.CreateString("Message from C#"), CfxV8PropertyAttribute.ReadOnly);

                    callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs });
                }
            };


            //add a function with async callback
            var asyncCallbackTestFunc = GlobalObject.AddFunction("asyncCallbackTest");

            asyncCallbackTestFunc.Execute += async(func, args) => {
                //save current context
                var v8Context = CfrV8Context.GetCurrentContext();
                var callback  = args.Arguments.FirstOrDefault(p => p.IsFunction);

                //simulate async methods.
                await Task.Delay(5000);

                if (callback != null)
                {
                    //get render process context
                    var rc = callback.CreateRemoteCallContext();

                    //enter render process
                    rc.Enter();

                    //create render task
                    var task = new CfrTask();
                    task.Execute += (_, taskArgs) =>
                    {
                        //enter saved context
                        v8Context.Enter();

                        //create callback argument
                        var callbackArgs = CfrV8Value.CreateObject(new CfrV8Accessor());
                        callbackArgs.SetValue("success", CfrV8Value.CreateBool(true), CfxV8PropertyAttribute.ReadOnly);
                        callbackArgs.SetValue("text", CfrV8Value.CreateString("Message from C#"), CfxV8PropertyAttribute.ReadOnly);

                        //execute callback
                        callback.ExecuteFunction(null, new CfrV8Value[] { callbackArgs });


                        v8Context.Exit();

                        //lock task from gc
                        lock (task)
                        {
                            Monitor.PulseAll(task);
                        }
                    };

                    lock (task)
                    {
                        //post task to render process
                        v8Context.TaskRunner.PostTask(task);
                    }

                    rc.Exit();

                    GC.KeepAlive(task);
                }
            };
        }
        public static CfrV8Value V8Serialize(this object o, HashSet <object> refin = null)
        {
            if (Accessor == null)
            {
                Accessor = new CfrV8Accessor();
            }
            var propattr = CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly;

            switch (o)
            {
            case null:
                return(CfrV8Value.CreateNull());

            case bool onb:
                return(CfrV8Value.CreateBool(onb));

            case string os:
                return(CfrV8Value.CreateString(os));

            case Enum oenum:
                return(CfrV8Value.CreateString(oenum.ToString()));

            case int oni:
                return(CfrV8Value.CreateInt(oni));

            case sbyte oni:
                return(CfrV8Value.CreateInt(oni));

            case short oni:
                return(CfrV8Value.CreateInt(oni));

            case long oni:
                return(CfrV8Value.CreateInt((int)oni));

            case uint onui:
                return(CfrV8Value.CreateUint(onui));

            case byte onui:
                return(CfrV8Value.CreateUint(onui));

            case ushort onui:
                return(CfrV8Value.CreateUint(onui));

            case double ond:
                return(CfrV8Value.CreateDouble(ond));

            case float onf:
                return(CfrV8Value.CreateDouble(onf));

            case ObjectBuilder oob:
                return(oob.Serialize(refin));

            case RGBAColor ocv:
                var vcolres = CfrV8Value.CreateObject(Accessor);
                vcolres.SetValue("r", CfrV8Value.CreateInt(ocv.Color.R), propattr);
                vcolres.SetValue("g", CfrV8Value.CreateInt(ocv.Color.G), propattr);
                vcolres.SetValue("b", CfrV8Value.CreateInt(ocv.Color.B), propattr);
                vcolres.SetValue("a", CfrV8Value.CreateDouble(ocv.A), propattr);
                vcolres.SetValue("name", CfrV8Value.CreateString("#" + ocv.Color.Name.Remove(0, 2)), propattr);
                return(vcolres);

            case Color4 ocdx:
                var dxcolres = CfrV8Value.CreateObject(Accessor);
                dxcolres.SetValue("r", CfrV8Value.CreateDouble(ocdx.Red * 255), propattr);
                dxcolres.SetValue("g", CfrV8Value.CreateDouble(ocdx.Green * 255), propattr);
                dxcolres.SetValue("b", CfrV8Value.CreateDouble(ocdx.Blue * 255), propattr);
                dxcolres.SetValue("a", CfrV8Value.CreateDouble(ocdx.Alpha), propattr);
                dxcolres.SetValue("name", CfrV8Value.CreateString(ocdx.ToString()), propattr);
                return(dxcolres);

            case TimeSpan ots:
                return(CfrV8Value.CreateDate(new CfrTime()
                {
                    Year = 0,
                    Month = 0,
                    DayOfMonth = ots.Days,
                    DayOfWeek = ots.Days,
                    Hour = ots.Hours,
                    Minute = ots.Minutes,
                    Second = ots.Seconds,
                    Millisecond = ots.Milliseconds
                }));

            case DateTime odt:
                return(CfrV8Value.CreateDate(new CfrTime()
                {
                    Year = odt.Year,
                    Month = odt.Month,
                    DayOfMonth = odt.Day,
                    DayOfWeek = (int)odt.DayOfWeek,
                    Hour = odt.Hour,
                    Minute = odt.Minute,
                    Second = odt.Second,
                    Millisecond = odt.Millisecond
                }));

            case IEnumerable oenum:
                lock (oenum)
                {
                    var reslist = (from object obj in oenum select obj.V8Serialize()).ToList();
                    var res     = CfrV8Value.CreateArray(reslist.Count);
                    for (int i = 0; i < reslist.Count; i++)
                    {
                        res.SetValue(i, reslist[i]);
                    }
                    return(res);
                }

            default:
                var referenced = refin;
                if (referenced != null && referenced.Contains(o))
                {
                    return(CfrV8Value.CreateNull());
                }
                else if (referenced == null)
                {
                    referenced = new HashSet <object> {
                        o
                    };
                }
                else
                {
                    referenced.Add(o);
                }

                var oT = o.GetType();
                if (oT.IsClass || (oT.IsValueType && !oT.IsPrimitive))
                {
                    var reso = CfrV8Value.CreateObject(Accessor);
                    foreach (var prop in oT.GetProperties().Where(p =>
                                                                  p.CanRead &&
                                                                  p.GetMethod.IsPublic &&
                                                                  !p.GetMethod.IsStatic &&
                                                                  !p.PropertyType.IsPointer)
                             )
                    {
                        var cobj = prop.GetValue(o).V8Serialize(referenced);
                        reso.SetValue(prop.Name, cobj, propattr);
                    }
                    foreach (var field in oT.GetFields().Where(f =>
                                                               f.IsPublic &&
                                                               !f.IsStatic &&
                                                               !f.FieldType.IsPointer)
                             )
                    {
                        var cobj = field.GetValue(o).V8Serialize(referenced);
                        reso.SetValue(field.Name, cobj, propattr);
                    }
                    return(reso);
                }
                else
                {
                    return(CfrV8Value.CreateNull());
                }
            }
        }
Example #27
0
        public static CfrV8Value GetCfrObject(this JSObject _, object item)
        {
            var nameDict = new Dictionary <string, string>();

            var accessor = new CfrV8Accessor();

            var o = CfrV8Value.CreateObject(accessor);

            var t = item.GetType();

            foreach (var p in t.GetProperties())
            {
                var name = p.Name.Substring(0, 1).ToLower() + p.Name.Substring(1);

                nameDict[name] = p.Name;


                o.SetValue(name, CfxV8AccessControl.Default, CfxV8PropertyAttribute.DontDelete);
            }

            accessor.Get += (s, e) =>
            {
                var name = nameDict[e.Name];

                var p = t.GetProperty(name);

                var value     = p.GetValue(item, null);
                var valueType = value?.GetType();



                if (value == null)
                {
                    e.Retval = CfrV8Value.CreateNull();
                }
                else if (valueType == typeof(string) || valueType == typeof(Guid))
                {
                    e.Retval = CfrV8Value.CreateString((string)value);
                }
                else if (valueType == typeof(int) || valueType == typeof(short) || valueType == typeof(long))
                {
                    e.Retval = CfrV8Value.CreateInt((int)value);
                }
                else if (valueType == typeof(decimal))
                {
                    e.Retval = CfrV8Value.CreateDouble(Convert.ToDouble(value));
                }
                else if (valueType == typeof(float) || valueType == typeof(double))
                {
                    e.Retval = CfrV8Value.CreateDouble(Convert.ToDouble(value));
                }
                else if (valueType == typeof(bool))
                {
                    e.Retval = CfrV8Value.CreateBool(Convert.ToBoolean(value));
                }
                else if (valueType == typeof(DateTime))
                {
                    e.Retval = CfrV8Value.CreateDate(CfrTime.FromUniversalTime((DateTime)value));
                }
                else
                {
                    e.Retval = CfrV8Value.CreateNull();
                }



                e.SetReturnValue(true);
            };


            return(o);
        }