コード例 #1
0
        private void QueryExecute(object sender, CfrV8HandlerExecuteEventArgs e)
        {
            try
            {
                var qryString   = e.Arguments[0].StringValue;
                var paramObject = ParseParameter(e.Arguments[1]);
                var counter     = 0;

                using (var connect = GetConnection())
                {
                    var reader = connect.Query(qryString, paramObject);
                    var arrObj = CfrV8Value.CreateArray(reader.Count());

                    foreach (var obj in reader)
                    {
                        var exp_obj = ToExpandoObject(obj);
                        arrObj.SetValue(counter, ConvertValue(exp_obj));

                        counter++;
                    }

                    e.SetReturnValue(arrObj);
                }
            }
            catch (Exception ex)
            {
                e.Exception = ex.Message;
                e.SetReturnValue(CfrV8Value.CreateUndefined());
            }
        }
コード例 #2
0
        public IJavascriptObject CreateArray(IEnumerable <IJavascriptObject> iCollection)
        {
            var col = iCollection.ToList();
            var res = CfrV8Value.CreateArray(col.Count);

            col.ForEach((el, i) => res.SetValue(i, el.Convert()));
            return(UpdateConvert(res));
        }
コード例 #3
0
        public CfrV8Value Serialize(HashSet <object> refin = null)
        {
            var propattr = CfxV8PropertyAttribute.DontDelete | CfxV8PropertyAttribute.ReadOnly;

            var referenced = refin;

            if (referenced != null && referenced.Contains(this))
            {
                return(CfrV8Value.CreateNull());
            }
            else if (referenced == null)
            {
                referenced = new HashSet <object>();
                referenced.Add(this);
            }
            else
            {
                referenced.Add(this);
            }

            switch (Type)
            {
            case TokenType.Array:
                lock (Array)
                {
                    var reslist = (from object obj in Array select obj.V8Serialize(referenced)).ToList();
                    var resa    = CfrV8Value.CreateArray(reslist.Count);
                    for (int i = 0; i < reslist.Count; i++)
                    {
                        resa.SetValue(i, reslist[i]);
                    }
                    return(resa);
                }

            case TokenType.Object:
                var reso = CfrV8Value.CreateObject(ClrV8ValueSerializer.Accessor);

                lock (Properties)
                {
                    foreach (var prop in Properties.ToArray())
                    {
                        var cobj = prop.Value.V8Serialize(referenced);
                        reso.SetValue(prop.Key, cobj, propattr);
                    }
                }
                return(reso);

            default:
                return(reso = CfrV8Value.CreateUndefined());
            }
        }
コード例 #4
0
ファイル: ConstantControl.cs プロジェクト: ganmkTrue/INetDisk
        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);
            };
        }
コード例 #5
0
        private void GetNoteContentHistoryFormCSFunc_Execute(object sender, CfrV8HandlerExecuteEventArgs e)
        {
            var noteID = e.Arguments.FirstOrDefault(p => p.IsString).ToString();

            noteContentHistoryList = noteUtils.GetHistoryNoteContent(Convert.ToInt32(noteID));
            if (noteContentHistoryList != null && noteContentHistoryList.Count > 0)
            {
                var jsObjectAccessor = new CfrV8Accessor();
                var jsObject         = CfrV8Value.CreateObject(jsObjectAccessor);
                var noteListArray    = CfrV8Value.CreateArray(noteContentHistoryList.Count);
                int i = 0;
                foreach (var note in noteContentHistoryList)
                {
                    noteListArray.SetValue(i, note.create_time);
                    i++;
                }
                jsObject.SetValue("historyArray", noteListArray, CfxV8PropertyAttribute.DontDelete);
                e.SetReturnValue(jsObject);
            }
        }
コード例 #6
0
        private void GetTitleFormCSFunc_Execute(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e)
        {
            var noteList         = noteUtils.GetNotesTitle();
            var jsObjectAccessor = new CfrV8Accessor();
            var jsObject         = CfrV8Value.CreateObject(jsObjectAccessor);
            var noteListArray    = CfrV8Value.CreateArray(noteList.Count);
            int i = 0;

            foreach (var note in noteList)
            {
                //jsObject.SetValue(note.id.ToString(), CfrV8Value.CreateString(note.n_title), CfxV8PropertyAttribute.ReadOnly);
                var jsArray = CfrV8Value.CreateArray(5);
                jsArray.SetValue("id", note.id, CfxV8PropertyAttribute.DontDelete);
                jsArray.SetValue("n_title", note.n_title, CfxV8PropertyAttribute.DontDelete);
                jsArray.SetValue("n_length", note.n_length, CfxV8PropertyAttribute.DontDelete);
                jsArray.SetValue("create_time", note.create_time, CfxV8PropertyAttribute.DontDelete);
                jsArray.SetValue("update_time", note.update_time, CfxV8PropertyAttribute.DontDelete);
                noteListArray.SetValue(i, jsArray);
                i++;
            }
            jsObject.SetValue("noteArray", noteListArray, CfxV8PropertyAttribute.DontDelete);
            e.SetReturnValue(jsObject);
        }
コード例 #7
0
        private static CfrV8Value ClrValueToV8Value(object clrValue)
        {
            CfrV8Value value = null;


            if (clrValue == null)
            {
                return(CfrV8Value.CreateNull());
            }

            var valueType = clrValue.GetType();


            var typeCode = Type.GetTypeCode(valueType);


            if (typeCode == TypeCode.Object)
            {
                if (valueType.IsArray)
                {
                    var clrArray = (Array)clrValue;
                    var v8Array  = new List <CfrV8Value>();
                    foreach (var item in clrArray)
                    {
                        var itemValue = ClrValueToV8Value(item);

                        if (itemValue != null)
                        {
                            v8Array.Add(itemValue);
                        }
                    }

                    if (v8Array.Count > 0)
                    {
                        value = CfrV8Value.CreateArray(v8Array.Count);

                        for (int i = 0; i < v8Array.Count; i++)
                        {
                            value.SetValue(i, v8Array[i]);
                        }
                    }
                }
                else if (valueType.IsGenericType && valueType.GetInterfaces().Count(p => p.IsGenericType && p.GetGenericTypeDefinition() == typeof(IEnumerable <>)) > 0)
                {
                    var clrArray = (IEnumerable <object>)clrValue;
                    var v8Array  = new List <CfrV8Value>();

                    foreach (var item in clrArray)
                    {
                        var itemValue = ClrValueToV8Value(item);

                        if (itemValue != null)
                        {
                            v8Array.Add(itemValue);
                        }
                    }

                    if (v8Array.Count > 0)
                    {
                        value = CfrV8Value.CreateArray(v8Array.Count);

                        for (int i = 0; i < v8Array.Count; i++)
                        {
                            value.SetValue(i, v8Array[i]);
                        }
                    }
                }
                else
                {
                    var jsObject = new JSObject(JSInvokeMode.DontInvoke);

                    RegisterJSObjectProperties(jsObject, clrValue);

                    value = jsObject.GetV8Value(jsObject.v8Context);
                }
            }


            if (value == null)
            {
                value = ClrToV8Value(clrValue);

                if (value == null)
                {
                    value = CfrV8Value.CreateUndefined();
                }
            }



            return(value);
        }
コード例 #8
0
        public IJavascriptObject CreateArray(int size)
        {
            var res = CfrV8Value.CreateArray(size);

            return(UpdateConvert(res));
        }
コード例 #9
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);
            };
        }
コード例 #10
0
        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());
                }
            }
        }
コード例 #11
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);
            };
        }
コード例 #12
0
ファイル: BaseObject.cs プロジェクト: AfzaalLucky/HotelUI
        public CfrV8Value ConvertValue(object data)
        {
            if (data == null)
            {
                return(CfrV8Value.CreateNull());
            }

            var typObject = data.GetType();
            var retValue  = CfrV8Value.CreateUndefined();

            switch (typObject.Name)
            {
            case "Boolean":
                retValue = Convert.ToBoolean(data);
                break;

            case "ExpandoObject":
                IDictionary <string, object> keyValues = data as IDictionary <string, object>;
                var resultx = CfrV8Value.CreateObject(new CfrV8Accessor(), new CfrV8Interceptor());

                foreach (var keypair in keyValues)
                {
                    resultx.SetValue(keypair.Key, ConvertValue(keypair.Value), CfxV8PropertyAttribute.ReadOnly);
                }

                retValue = resultx;
                break;

            case "DBNull":
                retValue = CfrV8Value.CreateNull();
                break;

            case "DateTime":
                var newValt    = Convert.ToDateTime(data);
                var univerTime = newValt.ToUniversalTime();
                retValue = CfrV8Value.CreateDate(CfrTime.FromUniversalTime(univerTime));
                break;

            case "Decimal":
            case "Double":
            case "Single":
                retValue = Convert.ToDouble(data);
                break;

            case "Byte":
            case "UInt16":
            case "UInt32":
            case "UInt64":
                retValue = Convert.ToUInt64(data);
                break;

            case "SByte":
            case "Int16":
            case "Int32":
            case "Int64":
                retValue = Convert.ToInt64(data);
                break;

            case "String":
                retValue = (string)data;
                break;

            default:
                if (typObject.IsEnum)
                {
                    retValue = Enum.GetName(typObject, data);
                }
                else if (typObject.IsArray)
                {
                    var pos = 0;

                    if (typObject.Name == "Byte[]")
                    {
                        var arr_byte = (byte[])data;
                        var result   = CfrV8Value.CreateArray(arr_byte.Length);

                        foreach (var item in arr_byte)
                        {
                            result.SetValue(pos++, ConvertValue(item));
                        }

                        retValue = result;
                    }
                    else
                    {
                        var arr    = (object[])data;
                        var result = CfrV8Value.CreateArray(arr.Length);

                        foreach (var item in arr)
                        {
                            result.SetValue(pos++, ConvertValue(item));
                        }

                        retValue = result;
                    }
                }
                else if (typObject.Name.StartsWith("Dictionary"))
                {
                    var dictionary = (IDictionary <string, object>)data;
                    var result     = CfrV8Value.CreateObject(new CfrV8Accessor(), new CfrV8Interceptor());

                    foreach (var keypair in dictionary)
                    {
                        result.SetValue(keypair.Key, ConvertValue(keypair.Value), CfxV8PropertyAttribute.ReadOnly);
                    }

                    retValue = result;
                }
                else if (typObject.IsClass)
                {
                    var propertyInfoes = typObject.GetProperties();
                    var result         = CfrV8Value.CreateObject(new CfrV8Accessor(), new CfrV8Interceptor());

                    foreach (var item in propertyInfoes)
                    {
                        result.SetValue(item.Name, ConvertValue(item.GetValue(data)), CfxV8PropertyAttribute.ReadOnly);
                    }

                    retValue = result;
                }
                break;
            }

            return(retValue);
        }
コード例 #13
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);
                }
            };
        }
コード例 #14
0
ファイル: MainWindows.cs プロジェクト: JoyNop/BrowserClient
        // 浏览器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" }
            };
        }
コード例 #15
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);
            };
        }