Example #1
0
        private XtraPropertyInfoCollection GetFilterProps(ColumnView view)
        {
            var store = new XtraPropertyInfoCollection();
            var propList = new ArrayList();
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(view);
            propList.Add(properties.Find("Columns", false));
            propList.Add(properties.Find("OptionsView", false));
            propList.Add(properties.Find("ActiveFilterEnabled", false));
            propList.Add(properties.Find("ActiveFilterString", false));
            propList.Add(properties.Find("MRUFilters", false));
            propList.Add(properties.Find("ActiveFilter", false));

            MethodInfo mi = typeof (SerializeHelper).GetMethod("SerializeProperty",
                                                               BindingFlags.NonPublic | BindingFlags.Instance);
            MethodInfo miGetXtraSerializableProperty = typeof (SerializeHelper).GetMethod(
                "GetXtraSerializableProperty", BindingFlags.NonPublic |
                                               BindingFlags.Instance);
            var helper = new SerializeHelper(view);
            (view as IXtraSerializable).OnStartSerializing();
            foreach (PropertyDescriptor prop in propList)
            {
                var newXtraSerializableProperty =
                    miGetXtraSerializableProperty.Invoke(helper, new object[] {view, prop})
                    as XtraSerializableProperty;
                var p = new SerializablePropertyDescriptorPair(prop, newXtraSerializableProperty);
                mi.Invoke(helper, new object[] {store, view, p, XtraSerializationFlags.None, null});
            }
            (view as IXtraSerializable).OnEndSerializing();
            return store;
        }
Example #2
0
        protected IXtraPropertyCollection GetFilterProps(ColumnView view, string[] propertyNames)
        {
            var store = new XtraPropertyInfoCollection();
            if (propertyNames.Length > 0)
            {
                var propList = new ArrayList();
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(view);
                foreach (string propertyName in propertyNames)
                    propList.Add(properties.Find(propertyName, false));

                var helper = new SerializeHelper();
                MethodInfo mi = typeof (SerializeHelper).GetMethod("SerializeProperty",
                                                                   BindingFlags.NonPublic | BindingFlags.Instance);
                (view as IXtraSerializable).OnStartSerializing();
                foreach (PropertyDescriptor prop in propList)
                {
                    mi.Invoke(helper, new object[] {store, view, prop, XtraSerializationFlags.None, null});
                }
                (view as IXtraSerializable).OnEndSerializing();
            }
            return store;
        }
 public Task SaveQueuedMessagesAsync(IList <MqttManagedMessage> messages)
 {
     File.WriteAllText(Filename, SerializeHelper.Serialize(messages));
     return(Task.FromResult(0));
 }
Example #4
0
        /// <summary>
        /// MVC处理
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="routeTable"></param>
        /// <param name="controller"></param>
        /// <param name="actionName"></param>
        /// <param name="nameValues"></param>
        /// <param name="isPost"></param>
        /// <returns></returns>
        private static ActionResult MvcInvoke(HttpContext httpContext, RouteTable routeTable, Type controller, string actionName, NameValueCollection nameValues, bool isPost)
        {
            var routing = routeTable.GetOrAdd(controller, actionName, isPost);

            if (routing == null)
            {
                return(new ContentResult($"o_o,找不到:{controller.Name}/{actionName} 当前请求为:{(isPost ? ConstHelper.HTTPPOST : ConstHelper.HTTPGET)}", System.Net.HttpStatusCode.NotFound));
            }

            routing.Instance.HttpContext = httpContext;

            var nargs = new object[] { httpContext };


            //类过滤器
            if (routing.FilterAtrrs != null && routing.FilterAtrrs.Any())
            {
                foreach (var arr in routing.FilterAtrrs)
                {
                    var method = arr.GetType().GetMethod(ConstHelper.ONACTIONEXECUTING);

                    if (method != null)
                    {
                        var goOn = (bool)method.Invoke(arr, nargs.ToArray());

                        if (!goOn)
                        {
                            return(new ContentResult("o_o,当前逻辑已被拦截!", System.Net.HttpStatusCode.NotAcceptable));
                        }
                    }
                }
            }

            //方法过滤器
            if (routing.ActionFilterAtrrs != null && routing.ActionFilterAtrrs.Any())
            {
                foreach (var arr in routing.ActionFilterAtrrs)
                {
                    if (arr.ToString() == ConstHelper.OUTPUTCACHEATTRIBUTE)
                    {
                        var method = arr.GetType().GetMethod(ConstHelper.ONACTIONEXECUTING);

                        if (method != null)
                        {
                            httpContext.Session.CacheCalcResult = (string)arr.GetType().GetMethod(ConstHelper.ONACTIONEXECUTING).Invoke(arr, nargs.ToArray());
                        }
                    }
                    else
                    {
                        var method = arr.GetType().GetMethod(ConstHelper.ONACTIONEXECUTING);

                        if (method != null)
                        {
                            var goOn = (bool)arr.GetType().GetMethod(ConstHelper.ONACTIONEXECUTING).Invoke(arr, nargs.ToArray());

                            if (!goOn)
                            {
                                return(new ContentResult("o_o,当前逻辑已被拦截!", System.Net.HttpStatusCode.NotAcceptable));
                            }
                        }
                    }
                }
            }

            #region actionResult

            ActionResult result;

            if (httpContext.Request.ContentType == ConstHelper.FORMENCTYPE3 && !string.IsNullOrEmpty(httpContext.Request.Json))
            {
                var nnv = SerializeHelper.Deserialize <Dictionary <string, string> >(httpContext.Request.Json).ToNameValueCollection();

                result = MethodInvoke(routing.Action, routing.Instance, nnv);
            }
            else
            {
                result = MethodInvoke(routing.Action, routing.Instance, nameValues);
            }

            #endregion

            nargs = new object[] { httpContext, result };

            if (routing.FilterAtrrs != null && routing.FilterAtrrs.Any())
            {
                foreach (var arr in routing.FilterAtrrs)
                {
                    var method = arr.GetType().GetMethod(ConstHelper.ONACTIONEXECUTED);
                    if (method != null)
                    {
                        method.Invoke(arr, nargs);
                    }
                }
            }

            if (routing.ActionFilterAtrrs != null && routing.ActionFilterAtrrs.Any())
            {
                foreach (var arr in routing.ActionFilterAtrrs)
                {
                    if (arr.ToString() == ConstHelper.OUTPUTCACHEATTRIBUTE)
                    {
                        continue;
                    }
                    else
                    {
                        var method = arr.GetType().GetMethod(ConstHelper.ONACTIONEXECUTED);
                        if (method != null)
                        {
                            method.Invoke(arr, nargs);
                        }
                    }
                }
            }

            return(result);
        }
Example #5
0
        private void _server_OnReceive(object currentObj, byte[] data)
        {
            var mUserToken = (MessageUserToken)currentObj;

            mUserToken.Unpacker.Unpack(data, (s) =>
            {
                if (s.Content != null)
                {
                    try
                    {
                        var cm = SerializeHelper.PBDeserialize <ChatMessage>(s.Content);

                        switch (cm.Type)
                        {
                        case ChatMessageType.Login:
                            ReplyLogin(mUserToken, cm);
                            break;

                        case ChatMessageType.Subscribe:
                            ReplySubscribe(mUserToken, cm);
                            break;

                        case ChatMessageType.UnSubscribe:
                            ReplyUnsubscribe(mUserToken, cm);
                            break;

                        case ChatMessageType.ChannelMessage:
                            ReplyChannelMessage(mUserToken, cm);
                            break;

                        case ChatMessageType.PrivateMessage:
                            ReplyPrivateMessage(mUserToken, cm);
                            break;

                        case ChatMessageType.CreateGroup:
                            ReplyCreateGroup(mUserToken, cm);
                            break;

                        case ChatMessageType.AddMember:
                            ReplyAddMember(mUserToken, cm);
                            break;

                        case ChatMessageType.RemoveMember:
                            ReplyRemoveMember(mUserToken, cm);
                            break;

                        case ChatMessageType.RemoveGroup:
                            ReplyRemoveGroup(mUserToken, cm);
                            break;

                        case ChatMessageType.GroupMessage:
                            ReplyGroupMessage(mUserToken, cm);
                            break;

                        default:
                            throw new Exception("未知的协议");
                        }
                    }
                    catch (Exception ex)
                    {
                        _server.Disconnecte(mUserToken.ID);
                        LogHelper.Error("MessageServer._server_OnReceive", ex);
                    }
                }
            }, null, null);
        }
Example #6
0
 public new string ToString()
 {
     return(SerializeHelper.Serialize(this));
 }
Example #7
0
 /// <summary>
 /// 广播房间人物信息给房间其他用户
 /// </summary>
 /// <param name="memberID">除该ID以外都广播</param>
 public void BoardcastActorInfo(int uniqueID)
 {
     //需要修改
     byte[] message = SerializeHelper.Serialize <List <RoomActor> >(new List <RoomActor>(ActorList.Values));
     BoardcastMessage(MessageConvention.getRoommateInfo, message, uniqueID);
 }
Example #8
0
 protected T Deserialize <T>(string json)
 {
     return(SerializeHelper.Deserialize <T>(json));
 }
Example #9
0
 /// <summary>
 /// 设置对象
 /// </summary>
 public static void SetObject <T>(this ISession session, string key, T value) where T : class, new()
 {
     session.SetString(key, SerializeHelper <T> .ToJson(value));
 }
Example #10
0
    public void UpdateState(RoomActorUpdate roomActorUpdate)
    {
        int            index   = roomActorUpdate.userIndex;
        RoomActorState upState = (RoomActorState)int.Parse(roomActorUpdate.update);

        if (ActorList[index] == null)
        {
            return;
        }
        //if (ActorList[index].CurState != RoomActorState.ReConnect)
        {
            Log4Debug("站位 " + index + " 更新当前状态:" + ActorList[index].CurState + " -> " + (RoomActorState)int.Parse(roomActorUpdate.update));
            ActorList[index].CurState = upState;
            byte[] message = SerializeHelper.ConvertToByte(roomActorUpdate.GetSendInfo());
            BoardcastMessage(MessageConvention.updateActorState, message);

            if (CheckIsAllFixedState(RoomActorState.Ready))
            {
                ChangeRoomState(RoomActorState.Ready);
            }
            if (CurState == RoomActorState.Gaming)
            {
                switch (ActorList[index].CurState)
                {
                case RoomActorState.ReConnect:
                    break;

                case RoomActorState.WaitForStart:
                    Log4Debug("模型未准备好的玩家准备好进入游戏了。");
                    string       starttime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    byte[]       start     = SerializeHelper.ConvertToByte(starttime);
                    MessageXieYi xieyi     = new MessageXieYi((byte)MessageConvention.startGaming, 0, start);
                    AsyncIOCPServer.instance.SendSave(UserTokenInfo[index], xieyi.ToBytes());

                    roomActorUpdate = new RoomActorUpdate()
                    {
                        userIndex = index,
                        update    = (int)RoomActorState.Gaming + ""
                    };
                    UpdateState(roomActorUpdate);    //广播,修改玩家状态用来准备本机数据

                    break;

                case RoomActorState.Dead:
                    ActorList[index].timerDead = new Timer(new TimerCallback(SetAfterDead), index, RoomActor.DeadLastTime, 0);
                    break;
                }
            }
        }
        //else//reConnect时修改状态
        //{
        //    if (upState == RoomActorState.WaitForStart && RoomInfo.CurState == RoomActorState.Gaming)
        //    {
        //        ActorList[index].CurState = RoomActorState.Gaming;
        //        roomActorUpdate.update = (int)ActorList[index].CurState + "";
        //        byte[] message = SerializeHelper.ConvertToByte(roomActorUpdate.GetSendInfo());
        //        BoardcastMessage(MessageConvention.updateActorState, message);
        //    }
        //    else
        //    {
        //        Log4Debug("想要在重连时更新状态:" + upState);
        //    }
        //}
    }
Example #11
0
        public async Task OnSessionDataReceived(AsyncTcpServerSession session, byte[] data, int offset, int count)
        {
            if (data == null || data.Length <= 0)
            {
                return;
            }
            byte code = data[0];                      //功能码

            byte[] bytes = new byte[data.Length - 1]; //正文数据
            Array.Copy(data, 1, bytes, 0, bytes.Length);
            string unBase64txt = Encoding.UTF8.GetString(bytes);

            byte[] unBase64Bytes = Convert.FromBase64String(unBase64txt);   //bas64解码
            if (!code.Equals(CODE_HEARTBEAT))
            {
                Console.WriteLine($"功能码:{code.ToString()},数据{Encoding.UTF8.GetString(unBase64Bytes)}");
            }
            try
            {
                switch (code)
                {
                case CODE_FACEUPLOAD:       //名单上传
                {
                    string     upLoadFaceStr = Encoding.UTF8.GetString(unBase64Bytes);
                    UpLoadFace upLoadFace    = SerializeHelper.SerializeJsonToObject <UpLoadFace>(upLoadFaceStr);
                    byte[]     imgBytes      = Convert.FromBase64String(upLoadFace.imagebytes);
                    FileReadWriteHelper.WriteBytesToFile($@"D:\Test\{DateTime.Now.ToString("yyyyMMddHHmmssfff")}.jpg", imgBytes);          //保存图片

                    ServerControl.GetInstance().faceList.Add(new FaceInfo()
                        {
                            filename     = upLoadFace.filename,
                            idnumber     = upLoadFace.idnumber,
                            imagebytes   = upLoadFace.imagebytes,
                            name         = upLoadFace.name,
                            sex          = upLoadFace.sex,
                            serialnumber = upLoadFace.serialnumber,
                            type         = upLoadFace.type
                        });
                    ServerControl.GetInstance().ServerSendMsg(CODE_FACEUPLOAD, new byte[] { SUCCESS });
                    Console.WriteLine($"名单上传成功,列表还有白名单{ServerControl.GetInstance().faceList.Where(p => p.type.Equals("white")).Count()}个,和名单{ServerControl.GetInstance().faceList.Where(p => p.type.Equals("black")).Count()}个!");
                    break;
                }

                case CODE_FACESELECT:       //名单查询
                {
                    SelectFace selectFace = new SelectFace();
                    switch (unBase64Bytes[0])
                    {
                    case WHITEFACE:
                        selectFace.faceList = ServerControl.GetInstance().faceList.Where(p => p.type.Equals("white")).ToList();
                        break;

                    case BLACKFACE:
                        selectFace.faceList = ServerControl.GetInstance().faceList.Where(p => p.type.Equals("black")).ToList();
                        break;

                    case ALLFACE:
                        selectFace.faceList = ServerControl.GetInstance().faceList;
                        break;
                    }
                    string jsonStr = SerializeHelper.SerializeObjectToJson(selectFace);
                    byte[] tBytes  = Encoding.UTF8.GetBytes(jsonStr);
                    ServerControl.GetInstance().ServerSendMsg(CODE_FACESELECT, tBytes);
                    Console.WriteLine($"名单查询成功,一共查到{selectFace.faceList.Count}个名单!");
                    break;
                }

                case CODE_FACEDELETE:       //名单删除
                {
                    string     deleteFaceStr = Encoding.UTF8.GetString(unBase64Bytes);
                    DeleteFace deleteFace    = SerializeHelper.SerializeJsonToObject <DeleteFace>(deleteFaceStr);

                    var dFace = ServerControl.GetInstance().faceList.Where(p => p.type.Equals(deleteFace.type) && p.serialnumber.Equals(deleteFace.serialnumber)).First();
                    ServerControl.GetInstance().faceList.Remove(dFace);

                    ServerControl.GetInstance().ServerSendMsg(CODE_FACEDELETE, new byte[] { SUCCESS });
                    Console.WriteLine($"名单删除成功,列表还有白名单{ServerControl.GetInstance().faceList.Where(p => p.type.Equals("white")).Count()}个,和名单{ServerControl.GetInstance().faceList.Where(p => p.type.Equals("black")).Count()}个!");
                    break;
                }

                case CODE_FACECLEAR:        //名单清除
                {
                    List <FaceInfo> clList = new List <FaceInfo>();
                    switch (unBase64Bytes[0])
                    {
                    case WHITEFACE:
                        clList = ServerControl.GetInstance().faceList.Where(p => p.type.Equals("black")).ToList();
                        break;

                    case BLACKFACE:
                        clList = ServerControl.GetInstance().faceList.Where(p => p.type.Equals("black")).ToList();
                        break;

                    case ALLFACE:
                        clList = ServerControl.GetInstance().faceList;
                        break;
                    }
                    foreach (var item in clList)
                    {
                        ServerControl.GetInstance().faceList.Remove(item);
                    }

                    ServerControl.GetInstance().ServerSendMsg(CODE_FACECLEAR, new byte[] { SUCCESS });
                    Console.WriteLine($"名单清除成功,列表还有白名单{ServerControl.GetInstance().faceList.Where(p => p.type.Equals("white")).Count()}个,和名单{ServerControl.GetInstance().faceList.Where(p => p.type.Equals("black")).Count()}个!");
                    break;
                }

                case CODE_FACCONTRAST:        //人脸对比
                {
                    switch (unBase64Bytes[0])
                    {
                    case START:
                        ServerControl.GetInstance().ServerSendMsg(CODE_FACCONTRAST, new byte[] { SUCCESS });
                        IsSend = false;
                        Console.WriteLine("启动人脸对比成功,抓图中。。。");
                        SendImg();
                        break;

                    case STOP:
                        ServerControl.GetInstance().ServerSendMsg(CODE_FACCONTRAST, new byte[] { STOPSUCCESS });
                        IsSend = false;
                        Console.WriteLine("关闭人脸对比成功!");
                        break;
                    }
                    break;
                }

                case CODE_FOLLOW:       //跟随
                {
                    switch (unBase64Bytes[0])
                    {
                    case START:
                        ServerControl.GetInstance().ServerSendMsg(CODE_FOLLOW, new byte[] { SUCCESS });
                        Console.WriteLine("启动跟随成功!");
                        break;

                    case STOP:
                        ServerControl.GetInstance().ServerSendMsg(CODE_FOLLOW, new byte[] { STOPSUCCESS });
                        Console.WriteLine("关闭跟随成功!");
                        break;

                    case RESTART:
                        ServerControl.GetInstance().ServerSendMsg(CODE_FOLLOW, new byte[] { RESTARTSUCCESS });
                        Console.WriteLine("重新跟随成功!");
                        break;
                    }
                    break;
                }

                case CODE_GETPOINT:     //获取黑体坐标
                {
                    BlackBodyPoint blackBodyPoint = new BlackBodyPoint()
                    {
                        xpoint = 55,
                        ypoint = 105
                    };
                    string jsonStr = SerializeHelper.SerializeObjectToJson(blackBodyPoint);
                    byte[] body    = Encoding.UTF8.GetBytes(jsonStr);
                    ServerControl.GetInstance().ServerSendMsg(CODE_SETPOINT, body);
                    Console.WriteLine("校准黑体坐标成功!");
                    break;
                }

                case CODE_FACEIDENTIFY:     //人脸识别
                    break;

                case CODE_FACEALARM:        //人脸报警
                    break;

                case CODE_HEARTBEAT:        //心跳
                    break;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteError(ex);
                Console.WriteLine($"解析接收数据异常:{ex.ToString()}");
            }
        }
Example #12
0
 public SiteConfig LoadConfig(string configPath)
 {
     return((SiteConfig)SerializeHelper.DeSerialize(typeof(SiteConfig), configPath));
 }
Example #13
0
 public void Save()
 {
     SerializeHelper <IgnoreStorage> .Save(this, _fileName);
 }
 public void Serialize()
 {
     internalDaysOfWeek   = SerializeHelper.SerializeJson(DaysOfWeek);
     internalMonthsOfYear = SerializeHelper.SerializeJson(MonthsOfYear);
 }
Example #15
0
    //This method will load the dialogue from the DialogueAssign component sent.
    bool Load(string dName)
    {
        playerNodes = new List <CommentSet>();
        npcNodes    = new List <Answer>();
        actionNodes = new List <ActionNode>();

        if (Resources.Load("Dialogues/" + dName) == null)
        {
            return(false);
        }

        Dictionary <string, object> dict = SerializeHelper.ReadFromFile(dName) as Dictionary <string, object>;

        int pDiags = (int)((long)dict["playerDiags"]);
        int nDiags = (int)((long)dict["npcDiags"]);
        int aDiags = 0;

        if (dict.ContainsKey("actionNodes"))
        {
            aDiags = (int)((long)dict["actionNodes"]);
        }

        startPoint = (int)((long)dict["startPoint"]);


        //Create first...
        for (int i = 0; i < pDiags; i++)
        {
            string tagt = "";

            if (dict.ContainsKey("pd_pTag_" + i.ToString()))
            {
                tagt = (string)dict["pd_pTag_" + i.ToString()];
            }


            addSet(
                (int)((long)dict["pd_comSize_" + i.ToString()]),
                (int)((long)dict["pd_ID_" + i.ToString()]),
                tagt
                );
        }

        for (int i = 0; i < nDiags; i++)
        {
            string tagt = "";

            if (dict.ContainsKey("nd_tag_" + i.ToString()))
            {
                tagt = (string)dict["nd_tag_" + i.ToString()];
            }

            addAnswer(
                (string)dict["nd_text_" + i.ToString()],
                (int)((long)dict["nd_ID_" + i.ToString()]),
                (string)dict["nd_extraData_" + i.ToString()],
                tagt
                );
        }
        for (int i = 0; i < aDiags; i++)
        {
            float pFloat;
            var   pfl = dict["ac_pFloat_" + i.ToString()];
            if (pfl.GetType() == typeof(System.Double))
            {
                pFloat = System.Convert.ToSingle(pfl);
            }
            else
            {
                pFloat = (float)(long)pfl;
            }


            actionNodes.Add(new ActionNode(
                                (int)((long)dict["ac_ID_" + i.ToString()]),
                                (string)dict["ac_meth_" + i.ToString()],
                                (string)dict["ac_goName_" + i.ToString()],
                                (bool)dict["ac_pause_" + i.ToString()],
                                (bool)dict["ac_pBool_" + i.ToString()],
                                (string)dict["ac_pString_" + i.ToString()],
                                (int)((long)dict["ac_pInt_" + i.ToString()]),
                                pFloat
                                ));
        }

        //Connect now...
        for (int i = 0; i < playerNodes.Count; i++)
        {
            for (int ii = 0; ii < playerNodes[i].comment.Count; ii++)
            {
                playerNodes[i].comment[ii].text = (string)dict["pd_" + i.ToString() + "_com_" + ii.ToString() + "text"];

                if (dict.ContainsKey("pd_" + i.ToString() + "_com_" + ii.ToString() + "extraD"))
                {
                    playerNodes[i].comment[ii].extraData = (string)dict["pd_" + i.ToString() + "_com_" + ii.ToString() + "extraD"];
                }

                int index = (int)((long)dict["pd_" + i.ToString() + "_com_" + ii.ToString() + "iSet"]);

                if (index != -1)
                {
                    playerNodes[i].comment[ii].inputSet = playerNodes[index];
                }

                index = (int)((long)dict["pd_" + i.ToString() + "_com_" + ii.ToString() + "oAns"]);

                if (index != -1)
                {
                    playerNodes[i].comment[ii].outputAnswer = npcNodes[index];
                }

                index = -1;
                if (dict.ContainsKey("pd_" + i.ToString() + "_com_" + ii.ToString() + "oAct"))
                {
                    index = (int)((long)dict["pd_" + i.ToString() + "_com_" + ii.ToString() + "oAct"]);
                }

                if (index != -1)
                {
                    playerNodes[i].comment[ii].outAction = actionNodes[index];
                }
            }
        }

        for (int i = 0; i < npcNodes.Count; i++)
        {
            int index = (int)((long)dict["nd_oSet_" + i.ToString()]);
            if (index != -1)
            {
                npcNodes[i].outputSet = playerNodes[index];
            }

            if (dict.ContainsKey("nd_oNPC_" + i.ToString()))
            {
                int index2 = (int)((long)dict["nd_oNPC_" + i.ToString()]);
                if (index2 != -1)
                {
                    npcNodes[i].outputNPC = npcNodes[index2];
                }
            }

            if (dict.ContainsKey("nd_oAct_" + i.ToString()))
            {
                index = -1;
                index = (int)((long)dict["nd_oAct_" + i.ToString()]);
                if (index != -1)
                {
                    npcNodes[i].outAction = actionNodes[index];
                }
            }
        }

        for (int i = 0; i < actionNodes.Count; i++)
        {
            actionNodes[i].paramType = (int)((long)dict["ac_paramT_" + i.ToString()]);

            int index = -1;
            index = (int)((long)dict["ac_oSet_" + i.ToString()]);

            if (index != -1)
            {
                actionNodes[i].outPlayer = playerNodes[index];
            }

            if (dict.ContainsKey("ac_oNPC_" + i.ToString()))
            {
                index = -1;
                index = (int)((long)dict["ac_oNPC_" + i.ToString()]);
                if (index != -1)
                {
                    actionNodes[i].outNPC = npcNodes[index];
                }
            }

            if (dict.ContainsKey("ac_oAct_" + i.ToString()))
            {
                index = -1;
                index = (int)((long)dict["ac_oAct_" + i.ToString()]);
                if (index != -1)
                {
                    actionNodes[i].outAction = actionNodes[index];
                }
            }
        }

        return(true);
    }
Example #16
0
    public void ChangeRoomState(RoomActorState state)
    {
        byte[]          message         = new byte[] { };
        RoomActorUpdate roomActorUpdate = new RoomActorUpdate();

        Log4Debug("房间更改状态为:" + CurState + "->" + state);
        CurState = state;
        switch (CurState)
        {
        case RoomActorState.NoReady:
            foreach (var item in ActorList)
            {
                if (item.Value == null)
                {
                    continue;
                }
                //初始化房间玩家部分信息
                item.Value.InitActor();
                //广播房间用户准备状态为未准备
                roomActorUpdate = new RoomActorUpdate()
                {
                    userIndex = item.Key,
                    update    = (int)item.Value.CurState + ""
                };
                UpdateState(roomActorUpdate);
            }
            break;

        case RoomActorState.Ready:
            Log4Debug("玩家都准备了。");
            //设置所有玩家默认值
            foreach (var item in ActorList)
            {
                if (item.Value == null)
                {
                    continue;
                }
                item.Value.MyModelInfo.pos    = (NetVector3)GameTypeManager.BackStandPos(RoomInfo.RoomType, item.Key);
                item.Value.MyModelInfo.rotate = new NetVector3(0, GameTypeManager.BackLookAt(RoomInfo.RoomType, item.Key), 0);
                roomActorUpdate = new RoomActorUpdate()
                {
                    userIndex = item.Key,
                    update    = (int)RoomActorState.PrepareModel + ""
                };
                UpdateState(roomActorUpdate);    //广播,修改玩家状态用来准备本机数据
            }
            //方块初始化
            BoxList = new ConcurrentDictionary <int, BoxInfo>();

            //倒计时进入游戏
            ChangeRoomState(RoomActorState.WaitForStart);
            break;

        case RoomActorState.WaitForStart:
            //
            Log4Debug("开始倒计时");
            //时间初始化
            PassedCountDownTime = 0;
            CountDownTimer      = new Timer(new TimerCallback(GameCountDowning), null, 0, 1 * 1000);

            break;

        case RoomActorState.Gaming:
            Log4Debug("开始游戏:" + FrameIndex);

            foreach (var item in ActorList)
            {
                if (item.Value == null)
                {
                    continue;
                }
                if (item.Value.CurState == RoomActorState.WaitForStart)
                {
                    roomActorUpdate = new RoomActorUpdate()
                    {
                        userIndex = item.Key,
                        update    = (int)RoomActorState.Gaming + ""
                    };
                    UpdateState(roomActorUpdate);    //广播,修改玩家状态用来准备本机数据
                }
                else
                {
                    Log4Debug("用户:" + item.Value.Register.name + "在倒计时期间内未准备好模型。");
                }
            }

            //保存帧同步
            FrameIndex = 0;
            FrameCount = (int)(RoomInfo.GameTime / RoomInfo.frameTime);
            FrameGroup = new ConcurrentDictionary <int, FrameInfo>();
            //FrameGroup = new Dictionary<int, FrameInfo>();
            //for (int i = 0; i < FrameCount; i++)
            //{
            //    FrameGroup.Add(i, new FrameInfo() { frameIndex = i, frameData = new List<byte[]>() });
            //}
            //线程池调用时间间隔逻辑
            ThFrameCount = new Thread(GameFrameReconding);
            ThFrameCount.IsBackground = true;
            ThFrameCount.Start();
            //ThreadPool.QueueUserWorkItem(new WaitCallback(GameFrameReconding), null);
            //
            string starttime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
            byte[] start     = SerializeHelper.ConvertToByte(starttime);
            BoardcastMessage(MessageConvention.startGaming, start);
            //发送游戏时间
            PassedGameTime = 0;
            break;

        case RoomActorState.GameEnd:
            Log4Debug("退出计数");
            TeamType winTeam = GetWinnerTeam();
            Log4Debug("游戏结束" + winTeam + "胜利");
            message = SerializeHelper.ConvertToByte((int)winTeam + "");
            BoardcastMessage(MessageConvention.endGaming, message);
            //
            InitRoom();
            break;
        }
    }
Example #17
0
        /// <summary>
        /// 订单支付操作
        /// </summary>
        /// <param name="orderNo">加密后的订单号</param>
        /// <returns></returns>
        public ActionResult JsApi(string orderNo)
        {
            int order_id = ChangeId(orderNo);

            if (order_id <= 0)
            {
                return(Json(new { result = -1, msg = "订单号错误" }, JsonRequestBehavior.AllowGet));
            }
            var order_item = OrderService.LoadEntities(n => n.id == order_id).FirstOrDefault();

            if (order_item == null)
            {
                return(Json(new { result = -1, msg = "未找到该订单" }, JsonRequestBehavior.AllowGet));
            }
            if (order_item.pay_state == (int)Pay_state.已支付)
            {
                return(Json(new { result = -1, msg = "该订单已支付过" }, JsonRequestBehavior.AllowGet));
            }

            string body = $"感谢您购买{order_item.product.name}";

            if (order_item.product.name.Length > 20)
            {
                body = $"感谢您购买{order_item.product.name.Substring(0, 17)}";
            }

            int price     = (int)(order_item.order_money * 100);
            var timeStamp = TenPayV3Util.GetTimestamp();
            var nonceStr  = TenPayV3Util.GetNoncestr();
            var openId    = order_item.user.wx_user.gzh_openid;
            TenPayV3UnifiedorderRequestData xmlDataInfo = new TenPayV3UnifiedorderRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, body, order_item.order_number, price, Request.UserHostAddress, TenPayV3Info.TenPayV3Notify, TenPayV3Type.JSAPI, openId, TenPayV3Info.Key, nonceStr, "WEB", DateTime.Now, null, "");
            var result = TenPayV3.Unifiedorder(xmlDataInfo);            //调用统一订单接口

            if (result.return_code.Equals("SUCCESS") && result.result_code.Equals("SUCCESS"))
            {
                //var package = $"prepay_id={result.prepay_id}";
                var    package = string.Format("prepay_id={0}", result.prepay_id);
                string paySign = string.Empty;
                paySign = TenPayV3.GetJsPaySign(TenPayV3Info.AppId, timeStamp, nonceStr, package,
                                                TenPayV3Info.Key);
                PayEntity payEntity = new PayEntity()
                {
                    goodsId   = order_item.product_id.ToString(),
                    category  = "0",
                    userId    = openId,
                    appId     = TenPayV3Info.AppId,
                    timeStamp = timeStamp,
                    nonceStr  = nonceStr,
                    package   = package,
                    paySign   = paySign,
                    prepay_id = result.prepay_id,
                    orderNo   = orderNo                  //加密后的orderid
                };
                order_item.wx_order_num = result.prepay_id;
                OrderService.EditEntity(order_item);
                return(Json(new { result = 0, msg = "下单成功", data = payEntity }, JsonRequestBehavior.AllowGet));
            }

            SaveSyslog("用户微信下单发送错误:" + SerializeHelper.SerializeToString(result), SysLogType.前台日志, "支付系统");

            return(Json(new { result = -1, msg = "微信下单时发生错误,请联系客服~!", data = "??" }, JsonRequestBehavior.AllowGet));
        }
Example #18
0
    // 會員加入房間
    public bool Join(AsyncUserToken userToken, out int UniqueID)
    {
        UniqueID = -1;
        lock (ActorList)
        {
            foreach (KeyValuePair <int, RoomActor> item in ActorList)
            {
                if (item.Value.Register == null)
                {
                    UniqueID            = item.Key;
                    item.Value.Register = userToken.userInfo.Register;//先占位,放开lock,允许其他人加入。
                    break;
                }
            }
        }
        if (UniqueID != -1)
        {
            Log4Debug("账号->" + userToken.userInfo.Register.userID + " 用户名->" + userToken.userInfo.Register.name + " 加入房间->" + RoomInfo.RoomID + " 站位为->" + UniqueID);
            //
            TeamType myTeam = TeamType.Both;
            switch (RoomInfo.RoomType)
            {
            case GameModel.组队模式:
                if (UniqueID % 2 == 0)    //红蓝两队
                {
                    myTeam = TeamType.Blue;
                }
                else
                {
                    myTeam = TeamType.Red;
                }
                break;

            case GameModel.Boss模式:
                myTeam = TeamType.Blue;
                break;
            }
            //

            RoomActor actor = new RoomActor(RoomInfo.RoomID, UniqueID, userToken.userInfo.Register, myTeam);
            actor.MyModelInfo.pos       = (NetVector3)GameTypeManager.BackStandPos(RoomInfo.RoomType, UniqueID);
            actor.MyModelInfo.rotate    = new NetVector3(0, GameTypeManager.BackLookAt(RoomInfo.RoomType, UniqueID), 0);
            actor.MyModelInfo.animation = 0;

            userToken.userInfo = actor;
            lock (UserTokenInfo)
            {
                UserTokenInfo[UniqueID] = userToken;
            }
            lock (ActorList)
            {
                ActorList[UniqueID] = actor;
            }
            BoardcastActorInfo(UniqueID);
            //广播房间信息
            byte[]       message = SerializeHelper.Serialize <RoomInfo>(RoomInfo);
            MessageXieYi xieyi   = new MessageXieYi((byte)MessageConvention.getRoomInfo, 0, message);
            AsyncIOCPServer.instance.SendSave(userToken, xieyi.ToBytes());
            return(true);
        }
        else
        {
            return(false);
        }
    }
        private void WsServer_OnMessage(string cid, WebSocket.Model.WSProtocal msg)
        {
            if (msg != null)
            {
                if (_dic1.ContainsKey(cid) && msg.Content != null && msg.Content.Any())
                {
                    var json = Encoding.UTF8.GetString(msg.Content);

                    var requestData = SerializeHelper.Deserialize <RequestData>(json);

                    if (requestData == null)
                    {
                        return;
                    }

                    if (requestData.IsCpu)
                    {
                        Task.Factory.StartNew(() =>
                        {
                            while (_dic1.ContainsKey(cid))
                            {
                                try
                                {
                                    var data = SerializeHelper.Serialize(ServerInfoDataHelper.GetInfo(requestData.Name, true));

                                    _wsServer.Reply(cid, new WSProtocal(WSProtocalType.Text, Encoding.UTF8.GetBytes(data)));
                                }
                                catch
                                {
                                    _dic1.TryRemove(cid, out DateTime v);
                                    break;
                                }
                                ThreadHelper.Sleep(1000);
                            }
                        });
                    }
                    else
                    {
                        Task.Factory.StartNew(() =>
                        {
                            while (_dic1.ContainsKey(cid))
                            {
                                try
                                {
                                    var data = SerializeHelper.Serialize(ServerInfoDataHelper.GetInfo(requestData.Name, false));

                                    _wsServer.Reply(cid, new WSProtocal(WSProtocalType.Text, Encoding.UTF8.GetBytes(data)));
                                }
                                catch
                                {
                                    _dic1.TryRemove(cid, out DateTime v);
                                    break;
                                }

                                ThreadHelper.Sleep(1100);
                            }
                        });
                    }

                    return;
                }
                else
                {
                    if (msg.Content != null && msg.Content.Any())
                    {
                        var s = Encoding.UTF8.GetString(msg.Content);

                        if (s == "getinfo")
                        {
                            _dic1.TryAdd(cid, DateTimeHelper.Now);

                            return;
                        }
                        else
                        {
                            return;
                        }
                    }
                }
            }
        }
Example #20
0
    //public void ShootBullet(BulletInfo bullet)
    //{
    //    //子弹的拥有者的旋转角度
    //    Vector3 bulletRotate = ActorList[bullet.userIndex].myRotationInfo.Rotation;
    //    Vector2 bullet2D = new Vector2(bullet.pos.x, bullet.pos.z);
    //    //子弹相对落地点(半径以内的x,y)
    //    Vector2 sPos = new Vector2(
    //        RoomActor.ShootRadius * Mathf.Sin((Mathf.PI / 180) * bulletRotate.y),
    //        RoomActor.ShootRadius * Mathf.Cos((Mathf.PI / 180) * bulletRotate.y));
    //    //子弹世界落地点
    //    Vector2 bulletWorldPos = sPos + bullet2D;


    //    foreach (var item in ActorList)//遍历是否射中其他玩家
    //    {
    //        bool isShooted = false;
    //        if (item.Value == null)
    //            continue;
    //        if (item.Value.UniqueID == bullet.userIndex)//子弹不检测自身
    //            continue;
    //        RoomActor actor = item.Value;
    //        //待碰撞人物的顶视图世界坐标
    //        Vector2 cP = new Vector2(actor.MyMoveInfo.Pos.x, actor.MyMoveInfo.Pos.z);
    //        //子弹发射点和待碰撞人物距离
    //        float bscDistance = Vector2.Distance(bullet2D, cP);

    //        //子弹射击方向世界角度
    //        float shootRotate = bulletRotate.y;
    //        shootRotate = 90 - shootRotate;//转换模型旋转角度到世界坐标角度
    //        BackPositiveOfAngle(ref shootRotate);//转换负数角度成正数角度
    //        //射击点到人物的世界角度
    //        float middleAngle = Mathf.Atan2(actor.MyMoveInfo.Pos.z - bullet.pos.z, actor.MyMoveInfo.Pos.x - bullet.pos.x) * 180 / Mathf.PI;
    //        BackPositiveOfAngle(ref middleAngle);
    //        //射击点到人物边缘的世界角度
    //        float sideAngle = Mathf.Atan2(RoomActor.ModelRadius, bscDistance) * 180 / Mathf.PI;
    //        BackPositiveOfAngle(ref sideAngle);
    //        float angleMin = (middleAngle - sideAngle) > (middleAngle + sideAngle) ? (middleAngle + sideAngle) : (middleAngle - sideAngle);
    //        float angleMax = (middleAngle - sideAngle) > (middleAngle + sideAngle) ? (middleAngle - sideAngle) : (middleAngle + sideAngle);


    //        //判断待射击人物的夹角(计算射击点到人物边缘的角度)子弹在朝向模型
    //        if (shootRotate > angleMin && shootRotate < angleMax)
    //        {
    //            if (bscDistance <= RoomActor.ShootRadius)//待检测人物的中心点在射击半径上或内
    //            {
    //                isShooted = true;
    //            }
    //            else if (bscDistance < RoomActor.ShootRadius + RoomActor.ModelRadius)//子弹落在2个人物之间,正好是射击待碰撞人物中心点,最短距离
    //            {
    //                //判断子弹落地点是否在待检测人物半径内
    //                if (Vector2.Distance(bulletWorldPos, cP) <= RoomActor.ModelRadius)
    //                {
    //                    isShooted = true;
    //                }
    //            }
    //        }
    //        //射中人物
    //        if (isShooted)
    //        {
    //            Log4Debug("射中人物:" + actor.UniqueID);
    //            TeamType bulletType = BackTeamTypeByUnique(bullet.userIndex);
    //            RoomActorUpdate hit = new RoomActorUpdate() { userIndex = actor.UniqueID, update = (int)bulletType + "" };
    //            byte[] message = SerializeHelper.ConvertToByte(hit.GetSendInfo());
    //            //广播
    //            BoardcastMessage(MessageConvention.shootBullet, message);
    //            return;
    //        }
    //    }
    //    //Log4Debug("子弹落地点:" + bulletWorldPos);
    //    //子弹碰撞方块
    //    foreach (KeyValuePair<int, BoxInfo> item in BoxList)
    //    {
    //        Vector2 boxPos = new Vector2(item.Value.position.x, item.Value.position.z);
    //        Vector2 boxScale = new Vector2(item.Value.scale.x, item.Value.scale.z);

    //        if (
    //            bulletWorldPos.x > boxPos.x - (float)(boxScale.x / 2) &&
    //            bulletWorldPos.x <= boxPos.x + (float)(boxScale.x / 2) &&
    //            bulletWorldPos.y > boxPos.y - (float)(boxScale.y / 2) &&
    //            bulletWorldPos.y <= boxPos.y + (float)(boxScale.y / 2)
    //            )//顶视图看是在方格内的
    //        {
    //            Log4Debug("子弹落点:(" + bulletWorldPos.x + "," + bulletWorldPos.y + ") 射中方块坐标:(" + item.Value.position.x + "," + item.Value.position.z + ")");
    //            //设置色块拥有者
    //            item.Value.ownerIndex = bullet.userIndex;
    //            //广播发送消息
    //            RoomActorUpdate hit = new RoomActorUpdate() { userIndex = bullet.userIndex, update = item.Key + "" };
    //            byte[] message = SerializeHelper.ConvertToByte(hit.GetSendInfo());
    //            //射中地板方块
    //            BoardcastMessage(MessageConvention.updateBox, message);
    //            return;
    //        }
    //    }
    //    //
    //}
    public void UpdateBulletInfo(BulletInfo bulletInfo)
    {
        byte[]       message  = null;
        MessageXieYi xieyi    = null;
        int          boxIndex = -1;

        //
        switch (bulletInfo.shootTag)
        {
        case ShootTag.Box:
            //设置色块拥有者
            lock (BoxList)
            {
                boxIndex = int.Parse(bulletInfo.shootInfo);

                BoxInfo boxInfo = new BoxInfo()
                {
                    ownerIndex = -1, myIndex = boxIndex
                };
                BoxList.AddOrUpdate(boxIndex, boxInfo, (key, oldValue) => boxInfo);

                if (BoxList[boxIndex].ownerIndex < 0)
                {
                    BoxList[boxIndex].ownerIndex = bulletInfo.userIndex;
                    //生成buff
                    BuffInfo buffInfo = new BuffInfo()
                    {
                        ownerIndex = -1, myIndex = BuffIndex
                    };
                    lock (BuffList)
                    {
                        buffInfo.boxIndex = boxIndex;
                        buffInfo.type     = RandomBuffType();//随机一个buff类型
                        BuffList.AddOrUpdate(BuffIndex, buffInfo, (key, oldValue) => buffInfo);
                        BuffIndex++;
                    }
                    Log4Debug("在盒子编号->" + boxIndex + " 掉落Buff,编号->" + buffInfo.myIndex + ",类型->" + buffInfo.type);
                    //保存子弹消息
                    message = SerializeHelper.Serialize <BulletInfo>(bulletInfo);
                    xieyi   = new MessageXieYi((byte)MessageConvention.bulletInfo, 0, message);
                    SetRecondFrame(xieyi.ToBytes());
                    //保存Buff消息
                    message = SerializeHelper.Serialize <BuffInfo>(buffInfo);
                    xieyi   = new MessageXieYi((byte)MessageConvention.createBuff, 0, message);
                    SetRecondFrame(xieyi.ToBytes());
                }
                else    //该色块已被其他人击碎
                {
                    return;
                }
            }
            break;

        case ShootTag.Character:
            //
            int shootedIndex = int.Parse(bulletInfo.shootInfo);
            if (ActorList[shootedIndex].MyTeam == ActorList[bulletInfo.userIndex].MyTeam)
            {
                return;
            }
            if (ActorList[shootedIndex].CurState == RoomActorState.Gaming)
            {
                //增加击杀数
                ActorList[bulletInfo.userIndex].KillCount++;
                if (CurState == RoomActorState.Gaming)
                {
                    message = SerializeHelper.Serialize <List <RoomActor> >(new List <RoomActor>(ActorList.Values));
                    BoardcastMessage(MessageConvention.getRoommateInfo, message);
                }
                //改变被射击者状态
                RoomActorUpdate dead = new RoomActorUpdate()
                {
                    userIndex = shootedIndex,
                    update    = (int)RoomActorState.Dead + ""
                };
                UpdateState(dead);
            }
            else if (ActorList[shootedIndex].CurState == RoomActorState.Invincible)
            {
                Log4Debug("射击者站位:" + bulletInfo.userIndex + " 攻击无敌站位:->" + shootedIndex);
            }
            else
            {
                Log4Debug("射击者站位:" + bulletInfo.userIndex + " 正在鞭尸位置->" + shootedIndex);
            }
            //保存子弹消息
            message = SerializeHelper.Serialize <BulletInfo>(bulletInfo);
            xieyi   = new MessageXieYi((byte)MessageConvention.bulletInfo, 0, message);
            SetRecondFrame(xieyi.ToBytes());
            break;

        case ShootTag.Wall:
            //打中墙的消息就不存了
            break;

        case ShootTag.Buff:
            int buffIndex = int.Parse(bulletInfo.shootInfo);
            //Log4Debug("站位:" + bulletInfo.userIndex + " 请求拾取Buff->" + buffIndex);
            lock (BuffList)
            {
                if (BuffList[buffIndex].ownerIndex < 0)
                {
                    BuffList[buffIndex].ownerIndex = bulletInfo.userIndex;
                    Log4Debug("站位:" + bulletInfo.userIndex + " 拾取了Buff->" + buffIndex);
                }
                else    //该buff已被其他人加成
                {
                    return;
                }
            }
            //保存Buff消息
            message = SerializeHelper.Serialize <BuffInfo>(BuffList[buffIndex]);
            xieyi   = new MessageXieYi((byte)MessageConvention.getBuff, 0, message);
            SetRecondFrame(xieyi.ToBytes());
            break;
        }


        //广播发送消息
        //byte[] message = SerializeHelper.ConvertToByte(bulletInfo));
        //BoardcastMessage(MessageConvention.bulletInfo, message);
    }
        public void ProcessRequest(HttpContext context)
        {
            string _actionType = context.Request.Params["action"].ToStringOrDefault("UnKown");

            if (_actionType.CompareIgnoreCase("getLocationList"))
            {
                int _pageIndex = context.Request.Params["PageIndex"].ToInt32OrDefault(1),
                    _pageSize  = context.Request.Params["PageSize"].ToInt32OrDefault(10);
                SqlServerDataOperator _helper     = new SqlServerDataOperator(@"Server=YANZHIWEI-IT-PC\SQLEXPRESS;database=Northwind;user id=sa;Password=sasa");
                PagedList <Order>     _pageResult = _helper.ExecutePageQuery <Order>("[Orders]", "*", "OrderID", OrderType.Desc, string.Empty, _pageSize, _pageIndex);
                AjaxResult            _result     = new AjaxResult(string.Empty, AjaxResultType.Success, _pageResult);
                string _json = SerializeHelper.JsonSerialize(new JsonPagedList <Order>(_pageResult)).ParseJsonDateTime();
                context.Response.Write(_json);
            }
            else if (_actionType.CompareIgnoreCase("exportLocationExcel"))
            {
                SqlServerDataOperator _helper     = new SqlServerDataOperator(@"Server=YANZHIWEI-IT-PC\SQLEXPRESS;database=JooWMS;user id=sa;Password=sasa");
                PagedList <Location>  _pageResult = _helper.ExecutePageQuery <Location>("[Location]", "*", "ID", OrderType.Desc, string.Empty, 10, 1);
                DataTable             _result     = GeneralMapper.ToDataTable <Location>(_pageResult, new string[4] {
                    "LocalNum", "LocalBarCode", "LocalName", "StorageNum"
                });
                string _filePath = context.Server.MapPath("~/UploadFiles/");

                if (!Directory.Exists(_filePath))
                {
                    Directory.CreateDirectory(_filePath);
                }

                string _filename = string.Format("库位管理{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmss"));
                NPOIExcel.ToExcel(_result, "库位管理", "库位", Path.Combine(_filePath, _filename));
                context.CreateResponse(("/UploadFiles/" + _filename).Escape(), AjaxResultType.Success, string.Empty);
            }
            else
            {
                context.ExecutePageQuery <Person>((pageLength, pageIndex, orderIndex, orderBy) =>
                {
                    var persons = GetPersons();
                    Func <Person, object> order = p =>
                    {
                        if (orderIndex == 0)
                        {
                            return(p.Id);
                        }

                        return(p.Name);
                    };

                    if ("desc" == orderBy)
                    {
                        persons = persons.OrderByDescending(order);
                    }
                    else
                    {
                        persons = persons.OrderBy(order);
                    }

                    //错误测试
                    //DataTablePageResult result = new DataTablePageResult();
                    //result.ExecuteMessage = "测试错误";
                    //result.ExecuteState = HttpStatusCode.BadGateway;
                    //正确测试
                    DataTablePageResult result  = new DataTablePageResult();
                    result.iTotalDisplayRecords = persons.Count();
                    List <Person> _personList   = new List <Person>();
                    result.iTotalRecords        = persons.Count();
                    result.aaData       = persons.Skip(pageIndex).Take(pageLength);
                    result.ExecuteState = HttpStatusCode.OK;
                    return(result);
                });
                // // Those parameters are sent by the plugin
                // var iDisplayLength = int.Parse(context.Request["iDisplayLength"]);
                // var iDisplayStart = int.Parse(context.Request["iDisplayStart"]);
                // var iSortCol = int.Parse(context.Request["iSortCol_0"]);
                // var iSortDir = context.Request["sSortDir_0"];
                // // Fetch the data from a repository (in my case in-memory)
                // var persons = GetPersons();
                // // Define an order function based on the iSortCol parameter
                // Func<Person, object> order = p =>
                // {
                //     if (iSortCol == 0)
                //     {
                //         return p.Id;
                //     }
                //     return p.Name;
                // };
                // // Define the order direction based on the iSortDir parameter
                // if ("desc" == iSortDir)
                // {
                //     persons = persons.OrderByDescending(order);
                // }
                // else
                // {
                //     persons = persons.OrderBy(order);
                // }
                // // prepare an anonymous object for JSON serialization
                // var result = new
                // {
                //     iTotalRecords = persons.Count(),
                //     iTotalDisplayRecords = persons.Count(),
                //     aaData = persons
                //         .Skip(iDisplayStart)
                //         .Take(iDisplayLength)
                // };
                // //var serializer = new JavaScriptSerializer();
                //// var json = SerializationHelper.JsonSerialize(result);// serializer.Serialize(result);
                //  context.CreateResponse(result, System.Net.HttpStatusCode.OK);
                // //context.Response.ContentType = "application/json";
                // //context.Response.Write(json);
            }
        }
Example #22
0
 protected string Serialize <T>(T t, bool expended = false)
 {
     return(SerializeHelper.Serialize(t, expended));
 }
Example #23
0
    public byte[] SelectMessage(udpUser user, byte[] data)
    {
        byte[]       newBuffer = null;
        MessageXieYi xieyi     = MessageXieYi.FromBytes(data);

        if (xieyi == null)
        {
            return(newBuffer);
        }

        byte[]             tempMessageContent = xieyi.MessageContent;
        ActorMoveDirection moveDirection      = null;
        SingleRoom         room  = null;
        UDPLogin           login = null;

        //该处RoomList没有加锁
        if (ServerDataManager.instance.allRoom.RoomList.ContainsKey(user.roomId))
        {
            room = ServerDataManager.instance.allRoom.RoomList[user.roomId];
        }

        switch ((MessageConvention)xieyi.XieYiFirstFlag)
        {
        case MessageConvention.setUDP:
            login       = SerializeHelper.Deserialize <UDPLogin>(tempMessageContent);
            user.roomId = login.roomID;
            user.unique = login.unique;
            ListUserKCP.AddOrUpdate(user.lastPoint, user, (key, oldValue) => user);
            ServerDataManager.instance.allRoom.RoomList[user.roomId].UpdateUDP(user.unique, user);
            Log4Debug("UDP login 房间号:" + login.roomID);
            newBuffer = SerializeHelper.Serialize <UDPLogin>(login);
            break;

        case MessageConvention.moveDirection:
            moveDirection = SerializeHelper.Deserialize <ActorMoveDirection>(tempMessageContent);
            if (room.ActorList[moveDirection.userIndex].CurState != RoomActorState.Dead)
            {
                //Log4Debug("将历史帧:" + moveDirection.frameIndex + "保存到" + (moveDirection.frameIndex + room.RoomInfo.frameInterval) + "/" + room.RoomInfo.FrameIndex);
                room.SetRecondFrame(xieyi.ToBytes());
                //Log4Debug("站位:" + moveDirection.userIndex + " 更新了方向:" + "["
                //    + moveDirection.direction.x + ","
                //    + moveDirection.direction.y + ","
                //    + moveDirection.direction.z + "]"
                //    + "/速度:" + moveDirection.speed);
            }
            else
            {
                Log4Debug("死亡用户不更新移动。");
            }
            break;

        case MessageConvention.rotateDirection:
            ActorRotateDirection netRotation = SerializeHelper.Deserialize <ActorRotateDirection>(tempMessageContent);
            if (room.ActorList[netRotation.userIndex].CurState != RoomActorState.Dead)
            {
                room.SetRecondFrame(xieyi.ToBytes());
                //Log4Debug("站位:" + netRotation.userIndex + " 更新了旋转:" + netRotation.rotateY);
            }
            else
            {
                Log4Debug("死亡用户不更新旋转。");
            }
            break;

        case MessageConvention.jump:
            ActorJump netJump = SerializeHelper.Deserialize <ActorJump>(tempMessageContent);
            if (room.ActorList[netJump.userIndex].CurState != RoomActorState.Dead)
            {
                room.SetRecondFrame(xieyi.ToBytes());
            }
            else
            {
                Log4Debug("死亡用户不更新跳跃。");
            }
            break;

        case MessageConvention.shootBullet:
            ShootInfo shootInfo = SerializeHelper.Deserialize <ShootInfo>(tempMessageContent);
            if (room.ActorList[shootInfo.userIndex].CurState != RoomActorState.Dead)
            {
                room.SetRecondFrame(xieyi.ToBytes());
                //Log4Debug("站位:" + netRotation.userIndex + " 更新了旋转:" + netRotation.rotateY);
            }
            else
            {
                Log4Debug("死亡用户不更新射击。");
            }
            break;

        case MessageConvention.bulletInfo:
            //
            BulletInfo bulletInfo = SerializeHelper.Deserialize <BulletInfo>(xieyi.MessageContent);
            room.UpdateBulletInfo(bulletInfo);    //更新
            //room.SetRecondFrame(xieyi.ToBytes());
            break;

        default:
            Log4Debug("检查协议->" + (MessageConvention)xieyi.XieYiFirstFlag);
            break;
        }

        byte[] sendBuffer = null;
        if (newBuffer != null)//用户需要服务器返回值给自己的话
        {
            xieyi      = new MessageXieYi(xieyi.XieYiFirstFlag, xieyi.XieYiSecondFlag, newBuffer);
            sendBuffer = xieyi.ToBytes();
        }
        return(sendBuffer);
    }
        public void FailureVideo()
        {
            try
            {
                //获取文件所在路径
                string workDir = AppDomain.CurrentDomain.BaseDirectory + ConfigHelper.ReadConfigByName("FailurePath");
                if (System.IO.Directory.Exists(workDir))
                {
                    var list = this._dbContext.FileDB.FindAll <FileDbContract>();
                    LogHelper.logError("读取失败json");
                    foreach (var entity in list)
                    {
                        if (!CommonDictionary.GetInstance().KafkaIsOnline)
                        {
                            continue;
                        }
                        if (!string.IsNullOrEmpty(entity.Id))
                        {
                            LogHelper.logInfo("读取json文件:" + entity.Id);
                            DirectoryInfo folder = new DirectoryInfo(workDir);
                            //回写数据库的上云路径
                            string osspath = "";
                            //本地全部上云
                            FileInfo[] fileList = folder.GetFiles(entity.Id + ".*");
                            for (int i = 0; i < fileList.Length; i++)
                            {
                                UploadContract contract  = SerializeHelper.deserializeToObject <UploadContract>(entity.data);
                                bool           imgupload = true;
                                string         imgurl    = "";

                                if (contract.IsUpload == true)
                                {
                                    KafKaContract kafka = new KafKaContract();
                                    kafka.MsgId   = entity.Id;
                                    kafka.MsgCode = KafkaMsgCodeEnum.Add;
                                    kafka.Msg     = SerializeHelper.serializeToString(contract);
                                    KafKaLogic.GetInstance().Push(kafka, KafkaTopic);
                                    continue;
                                }

                                if (CommonDictionary.GetInstance().VideoType.Count(d => d.ToLower() == contract.FileType.ToLower()) > 0)
                                {
                                    imgurl    = AliyunOSSHepler.GetInstance().GetPicFromVideo(workDir + fileList[i].Name, imgPath + Path.DirectorySeparatorChar + contract.FileId + ".jpg", "1");
                                    imgupload = AliyunOSSHepler.GetInstance().UploadFiles(imgPath, contract.FileId + ".jpg", ref imgurl);
                                }

                                if (imgupload)
                                {
                                    bool returnType = AliyunOSSHepler.GetInstance().UploadFiles(workDir, fileList[i].Name, ref osspath);

                                    if (returnType)
                                    {
                                        LogHelper.logInfo("上云封面地址:" + imgurl + "_______上云视频路径:" + osspath);
                                        try
                                        {
                                            contract.IsUpload     = true;
                                            contract.Url          = osspath;
                                            contract.ThumbnailUrl = imgurl;
                                            entity.data           = SerializeHelper.serializeToString(contract);
                                            this._dbContext.FileDB.Save <FileDbContract>(contract.FileId.ToString(), entity);
                                            KafKaContract kafka = new KafKaContract();
                                            kafka.MsgId   = entity.Id;
                                            kafka.MsgCode = KafkaMsgCodeEnum.Add;
                                            kafka.Msg     = SerializeHelper.serializeToString(contract);
                                            KafKaLogic.GetInstance().Push(kafka, KafkaTopic);
                                        }
                                        catch (Exception e)
                                        {
                                            LogHelper.logError("解析json数据推送kafka异常:文件名-" + fileList[i].Name + "__" + e.ToString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    LogHelper.logError("失败任务无数据,本次不执行");
                }
            }
            catch (Exception e)
            {
                LogHelper.logError("失败文件推送异常:" + e.Message + "__" + e.ToString());
            }
        }
Example #25
0
    public static VLanguage LoadSettings()
    {
        Dictionary <string, object> dict;

        if (!Application.isPlaying)
        {
            if (!File.Exists(Application.dataPath + "/../" + VIDE_EditorDB.videRoot + "/Resources/LocalizationSettings.json"))
            {
                if (File.Exists(Application.dataPath + "/../" + VIDE_EditorDB.videRoot + "/Resources/demo_loc.json"))
                {
                    dict = SerializeHelper.ReadFromFile("demo_loc" + ".json") as Dictionary <string, object>;
                }
                else
                {
                    return(SetDefault());
                }
            }
            else
            {
                dict = SerializeHelper.ReadFromFile("LocalizationSettings" + ".json") as Dictionary <string, object>;
            }
        }
        else
        {
            string jsonString = "";

            if (GameObject.Find("CanvasLocDemo") != null)
            {
                if (Resources.Load <TextAsset>("demo_loc") != null)
                {
                    jsonString = Resources.Load <TextAsset>("demo_loc").text;
                }
                else
                {
                    Debug.LogError("No demo_loc.json found in Resources!");
                }
            }

            if (jsonString == "")
            {
                if (Resources.Load <TextAsset>("LocalizationSettings") != null)
                {
                    jsonString = Resources.Load <TextAsset>("LocalizationSettings").text;
                }
                else
                {
                    return(null);
                }
            }
            dict = MiniJSON_VIDE.DiagJson.Deserialize(jsonString) as Dictionary <string, object>;
        }

        enabledInGame = (bool)dict["enabledInGame"];
        languages     = new List <VLanguage>();
        int langs = (int)((long)dict["langs"]);

        for (int i = 0; i < langs; i++)
        {
            languages.Add(new VLanguage());
            languages[i].enabled = (bool)dict["langEnabled_" + i.ToString()];
            languages[i].name    = (string)dict["lang_Name" + i.ToString()];
        }
        if ((int)((long)dict["current"]) != -1)
        {
            currentLanguage = languages[(int)((long)dict["current"])];
        }
        if ((int)((long)dict["default"]) != -1)
        {
            defaultLanguage = languages[(int)((long)dict["default"])];
        }

        if (defaultLanguage != null)
        {
            defaultLanguage.selected = true;
        }

        return(defaultLanguage);
    }
Example #26
0
 public static MqttConfig Parse(string json)
 {
     return(SerializeHelper.Deserialize <MqttConfig>(json));
 }
		protected override bool ShouldSerializeProperty(
			SerializeHelper helper,
			object obj,
			PropertyDescriptor prop,
			XtraSerializableProperty xtraSerializableProperty)
		{
			if (CheckFilter(obj.GetType(), prop.Name)) return false;
			return base.ShouldSerializeProperty(helper, obj, prop, xtraSerializableProperty);
		}
Example #28
0
        private void _client_OnReceive(byte[] data)
        {
            Actived = DateTimeHelper.Now;

            if (data != null)
            {
                this._messageContext.Unpacker.Unpack(data, (s) =>
                {
                    if (s.Content != null)
                    {
                        try
                        {
                            var cm = SerializeHelper.PBDeserialize <ChatMessage>(s.Content);

                            switch (cm.Type)
                            {
                            case ChatMessageType.LoginAnswer:
                                this.Logined = true;
                                break;

                            case ChatMessageType.SubscribeAnswer:
                                if (cm.Content == "1")
                                {
                                    _subscribed = true;
                                }
                                else
                                {
                                    _subscribed = false;
                                }
                                break;

                            case ChatMessageType.UnSubscribeAnswer:
                                if (cm.Content == "1")
                                {
                                    _unsubscribed = true;
                                }
                                else
                                {
                                    _unsubscribed = false;
                                }
                                break;

                            case ChatMessageType.ChannelMessage:
                                TaskHelper.Run(() => OnChannelMessage?.Invoke(cm.GetIMessage <ChannelMessage>()));
                                break;

                            case ChatMessageType.PrivateMessage:
                                TaskHelper.Run(() => OnPrivateMessage?.Invoke(cm.GetIMessage <PrivateMessage>()));
                                break;

                            case ChatMessageType.GroupMessage:
                                TaskHelper.Run(() => OnGroupMessage?.Invoke(cm.GetIMessage <GroupMessage>()));
                                break;

                            case ChatMessageType.PrivateMessageAnswer:
                                break;

                            case ChatMessageType.CreateGroupAnswer:
                            case ChatMessageType.RemoveGroupAnswer:
                            case ChatMessageType.AddMemberAnswer:
                            case ChatMessageType.RemoveMemberAnswer:
                                break;

                            case ChatMessageType.GroupMessageAnswer:
                                break;

                            default:
                                ConsoleHelper.WriteLine("cm.Type", cm.Type);
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            OnError?.Invoke(_messageContext.UserToken.ID, ex);
                        }
                    }
                }, null, null);
            }
        }
Example #29
0
        private void Button_Load_Click(object sender, RoutedEventArgs e)
        {
            #region Check if Table and Sheet has been selected first.
            if (this._TableInfo == null)
            {
                MessageBox.Show("Please select a Table from the dropdownlist.");
                return;
            }

            if (this._SheetInfo == null)
            {
                MessageBox.Show("Please select a sheet in an excel file.");
                return;
            }
            #endregion

            #region Select the mapping file and read it

            MappingFile mFileData = null;
            System.Windows.Forms.OpenFileDialog openFile = new System.Windows.Forms.OpenFileDialog();
            openFile.Filter           = @"XML Files|*.xml";
            openFile.RestoreDirectory = true;
            openFile.ShowDialog();

            if (File.Exists(openFile.FileName))
            {
                try
                {
                    string xml = File.ReadAllText(openFile.FileName);
                    mFileData = SerializeHelper.XmlDeserializeObject <MappingFile>(xml);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("DEBUG: " + ex.Message);
                    mFileData = null;
                }
            }
            else
            {
                mFileData = null;
            }

            #endregion

            #region Rebuild the list of FieldInfos with the data in the mapping file

            if (mFileData != null)
            {
                if (String.Compare(this._TableInfo.Name, mFileData.TableName, true) != 0)
                {
                    MessageBox.Show("The mapping file is configured for Table: " + mFileData.TableName + ", not for the selected one: " + this._TableInfo.Name);
                }
                else
                {
                    this._FieldInfos = this._TableInfo.GetFieldInfos();

                    foreach (FieldInfo fieldInfo in _FieldInfos)
                    {
                        FieldInfo mappingField = mFileData.GetFieldInfo(fieldInfo.Name);
                        if (mappingField != null)
                        {
                            fieldInfo.DefaultValue     = mappingField.DefaultValue;
                            fieldInfo.ExcelColumnIndex = mappingField.ExcelColumnIndex.HasValue ? mappingField.ExcelColumnIndex.Value > 0 ? mappingField.ExcelColumnIndex : null : null;
                            fieldInfo.FunctionIDs      = mappingField.FunctionIDs;
                            fieldInfo.FunctionArgs     = mappingField.FunctionArgs;
                            fieldInfo.IsUnique         = mappingField.IsUnique;
                        }
                    }
                }
            }

            #endregion

            #region Refresh the DataGrid_Fields

            DataGrid_Fields.ItemsSource = this._FieldInfos;

            #endregion
        }
Example #30
0
    public static List <VLanguage> PreloadLanguages(string dName)
    {
        Dictionary <string, object> dict;
        List <VLanguage>            langs = new List <VLanguage>();

        if (!Application.isPlaying)
        {
            if (!File.Exists(Application.dataPath + "/../" + VIDE_EditorDB.videRoot + "/Resources/LocalizationSettings.json"))
            {
                if (File.Exists(Application.dataPath + "/../" + VIDE_EditorDB.videRoot + "/Resources/demo_loc.json"))
                {
                    dict = SerializeHelper.ReadFromFile("demo_loc" + ".json") as Dictionary <string, object>;
                }
                else
                {
                    Debug.LogError("No localization settings found");
                    return(null);
                }
            }
            else
            {
                dict = SerializeHelper.ReadFromFile("LocalizationSettings" + ".json") as Dictionary <string, object>;
            }
        }
        else
        {
            return(null);
        }

        int langCount = (int)((long)dict["langs"]);

        for (int i = 0; i < langCount; i++)
        {
            langs.Add(new VLanguage());
            langs[i].enabled = (bool)dict["langEnabled_" + i.ToString()];
            langs[i].name    = (string)dict["lang_Name" + i.ToString()];
        }

        if (!Application.isPlaying)
        {
            if (!File.Exists(Application.dataPath + "/../" + VIDE_EditorDB.videRoot + "/Resources/Localized/" + "LOC_" + dName + ".json"))
            {
                //Debug.LogWarning("No localization file found");
                return(null);
            }
            else
            {
                string fileDataPath = Application.dataPath + "/../" + VIDE_EditorDB.videRoot + "/Resources/Localized/";
                string jsonString   = File.ReadAllText(fileDataPath + "LOC_" + dName + ".json");
                dict = DiagJson.Deserialize(jsonString) as Dictionary <string, object>;
            }
        }

        for (int d = 0; d < langs.Count; d++)
        {
            string        lang        = langs[d].name + "_";
            Sprite[]      sprites     = Resources.LoadAll <Sprite>("");
            AudioClip[]   audios      = Resources.LoadAll <AudioClip>("");
            List <string> spriteNames = new List <string>();
            List <string> audioNames  = new List <string>();
            foreach (Sprite t in sprites)
            {
                spriteNames.Add(t.name);
            }
            foreach (AudioClip t in audios)
            {
                audioNames.Add(t.name);
            }

            if (!dict.ContainsKey(lang + "playerDiags"))
            {
                continue;
            }

            int pDiags = (int)((long)dict[lang + "playerDiags"]);

            if (pDiags > 0)
            {
                langs[d].playerDiags = new List <VIDE_EditorDB.DialogueNode>();
            }

            for (int i = 0; i < pDiags; i++)
            {
                langs[d].playerDiags.Add(new VIDE_EditorDB.DialogueNode());
                VIDE_EditorDB.DialogueNode c = langs[d].playerDiags[i];

                if (!dict.ContainsKey(lang + "pd_pTag_" + i.ToString()))
                {
                    continue;
                }

                c.playerTag = (string)dict[lang + "pd_pTag_" + i.ToString()];
                int cSize = (int)((long)dict[lang + "pd_comSize_" + i.ToString()]);

                string name = Path.GetFileNameWithoutExtension((string)dict[lang + "pd_sprite_" + i.ToString()]);
                if (spriteNames.Contains(name))
                {
                    c.sprite = sprites[spriteNames.IndexOf(name)];
                }
                else if (name != string.Empty)
                {
                    Debug.LogError("'" + name + "' not found in any Resources folder!");
                }

                for (int ii = 0; ii < cSize; ii++)
                {
                    c.comment.Add(new VIDE_EditorDB.Comment());

                    c.comment[ii].text = (string)dict[lang + "pd_" + i.ToString() + "_com_" + ii.ToString() + "text"];

                    string namec = Path.GetFileNameWithoutExtension((string)dict[lang + "pd_" + i.ToString() + "_com_" + ii.ToString() + "sprite"]);

                    if (spriteNames.Contains(namec))
                    {
                        c.comment[ii].sprites = sprites[spriteNames.IndexOf(namec)];
                    }
                    else if (namec != "")
                    {
                        Debug.LogError("'" + namec + "' not found in any Resources folder!");
                    }

                    namec = Path.GetFileNameWithoutExtension((string)dict[lang + "pd_" + i.ToString() + "_com_" + ii.ToString() + "audio"]);

                    if (audioNames.Contains(namec))
                    {
                        c.comment[ii].audios = audios[audioNames.IndexOf(namec)];
                    }
                    else if (namec != "")
                    {
                        Debug.LogError("'" + namec + "' not found in any Resources folder!");
                    }
                }
            }
        }

        return(langs);
    }
Example #31
0
 public JsonResult(object model) : this(SerializeHelper.Serialize(model))
 {
 }
Example #32
0
 public void Save()
 {
     if (!Directory.Exists(_rootPath))
     {
         Directory.CreateDirectory(_rootPath);
     }
     File.WriteAllBytes(Path.Combine(_rootPath, _walletName), AESHelper.Encrypt(SerializeHelper.Serialize(this), _password));
 }
 public PowerConfig LoadConfig(string configPath)
 {
     return((PowerConfig)SerializeHelper.DeSerialize(typeof(PowerConfig), configPath));
 }