public JsonResult UpdateUser([FromBody] AppUserViewModel vm) { try { if (ModelState.IsValid) { var user = _userRepo.UpdateUser(vm.AppUserId, vm.FirstName, vm.LastName, vm.AdAssassinId); if (_userRepo.Base.SaveAll(User)) { Response.StatusCode = (int)HttpStatusCode.OK; var newVm = user.ToViewModel(); return(Json(newVm)); } else { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(MsgFactory.Error("Unable to save user!"))); } } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(MsgFactory.Error(ModelState))); } } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(MsgFactory.Error(ex))); } }
public Future <Message> ExecuteOperation(Message inMsg, Action <Message> onResult, Action <ushort, string> onError) { _requestId++; inMsg.AttachHeader(new OperationHeader(_requestId, OperationType.Request)); Channel.Send(inMsg); MsgFactory.Free(inMsg); var future = new Future <Message>(onResult, onError); _pendingOperation.Add(_requestId, future); return(future); }
/// <summary> /// 打包数据 /// </summary> /// <param name="packageData">被包装数据</param> /// <param name="uId">用户Id</param> /// <param name="msgId">数据Id</param> /// <returns></returns> private byte[] PackageData(byte[] packageData, int uId, int msgId) { byte[] result = null; packageData = ByteUtils.AddDataHead(packageData); // 将数据打包放入MsgHead的body中 var dataHead = MsgFactory.GetMsgHead(uId, msgId, packageData); result = SocketManager.Serialize(dataHead); return(result); }
public async Task <JsonResult> SignUp([FromBody] SignUpViewModel vm) { try { if (ModelState.IsValid) { // check if any values tracked in Auth0 have changed var extId = await _authAdapter.SignUpUser(vm); // save to our db now var user = new AppUser() { FirstName = vm.FirstName, LastName = vm.LastName, Email = vm.Email, ExternalId = extId, AvatarUrl = Avatars.GetAvatarUrl(vm.FirstName, vm.LastName, vm.Email), IsDeleted = false, IsSuspended = false, UserRoles = new List <AppUserRole> { new AppUserRole { RoleId = 2 } } // default to free user }; _userRepo.AddUser(user); if (_userRepo.Base.SaveAll(User)) { var newVm = user.ToViewModel(); Response.StatusCode = (int)HttpStatusCode.OK; return(Json(newVm)); } else { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(MsgFactory.Error("Unable to save new user"))); } } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(MsgFactory.Error(ModelState))); } } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(MsgFactory.Error(ex))); } }
/// <summary> /// 操作消息 /// </summary> /// <param name="headData"></param> private void MsgOptionalAction(MsgHead headData) { var opData = (byte[])headData.body.Clone(); opData = ReadMsg(opData); // 操作数据 var msgOp = SocketManager.DeSerialize <MsgOptional>(opData); Debug.Log("收到操作数据" + " opType:" + msgOp.OpType + "opPosX:" + msgOp.OpPosX + "opPosY:" + msgOp.OpPosY + ", opPosZ:" + msgOp.OpPosZ + ", opParams:" + msgOp.OpParams); // TODO 操作转化到本地行为 switch (msgOp.OpType) { case 1: // 唯一Id // 来自于对方的唯一ID 位移加标记 var opUniqueId = msgOp.OpUniqueNum; // 保存数据, 等待确认数据 PushBeComfirmData(msgOp); // 设置超时 var killTimer = new Timer(OperationTimeOut).OnCompleteCallback(() => { // 超时失败删除操作 opMsgBufferSend.Remove(opUniqueId); // 发送取消请求 Debug.LogError("操作超时,操作内容:" + opUniqueId + ", "); }).Start(); // 操作结束停止计时 opSendCallbackDic.Add(opUniqueId, () => { killTimer.Kill(); }); // TODO 如果是基地则不创建 var kvDic = GetParams(msgOp.OpParams); var sourceUserId = Convert.ToInt32(kvDic["UserId"]); // 创建确认发送消息 var cOpMsg = MsgFactory.GetMsgComfirmOperation(opUniqueId, sourceUserId, ""); var unitType = Convert.ToInt32(kvDic["UnitType"]); if (unitType != 1 && unitType != 2) { // 缓存发送确认操作 PushtBeSendData(cOpMsg, (int)MsgId.MsgComfirmOperation); } break; //couldDispatch = true; } }
/// <summary> /// 发送开始战斗请求 /// </summary> /// <param name="callback">消息发送成功回调</param> public void SendBattleStartMsg(Action callback) { // 创建请求战斗开始消息 var msgBattleStart = MsgFactory.GetMsgBattleStartRequest(""); // 数据放入缓冲 PushtBeSendData(msgBattleStart, (int)MsgId.MsgBattleStartRequest); if (callback != null) { callback(); } }
public JsonResult GetUsers() { try { var models = _userRepo.GetUsers(); var vms = models.Select(k => k.ToViewModel()); return(Json(vms)); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(MsgFactory.Error(ex))); } }
public JsonResult GetAdAccounts() { try { var email = UserClaimHelpers.Email(User.Identity); var models = _repo.GetAdAccountsByUserEmail(email); var vms = models.Select(k => k.ToViewModel()); return(Json(vms)); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(MsgFactory.Error(ex))); } }
public async Task <JsonResult> Refresh(string refreshToken) { try { LoginRefreshViewModel responseVM = await _authAdapter.RefreshAuth(refreshToken); Response.StatusCode = (int)HttpStatusCode.OK; return(Json(responseVM)); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(MsgFactory.Error(ex))); } }
/// <summary> /// 发送请求战斗消息 /// </summary> /// <param name="callback">消息发送成功回调</param> public void SendAskBattleMsg(Action callback) { // 创建请求战斗消息 var msgAskBattle = MsgFactory.GetMsgAskBattleRequest(GlobalData.UserData.BaseLevel, GlobalData.UserData.TurretLevel, GlobalData.UserData.Race, ""); // 数据放入缓冲 PushtBeSendData(msgAskBattle, (int)MsgId.MsgAskBattleRequest); if (callback != null) { callback(); } }
public static string[] DecodeInputMsg(string message) { if ((message.Length == 0) || (message == null)) { string[] strArray = new string[0x33b]; for (int i = 0; i < strArray.Length; i++) { strArray[i] = "0"; } return(strArray); } byte[] comByte = HelperFunctions.HexToByte(message); MsgFactory factory = new MsgFactory(ConfigurationManager.AppSettings["InstalledDirectory"] + @"\Protocols\Protocols_F.xml"); return(factory.ConvertRawToFieldsForInput(comByte).Split(new char[] { ',' })); }
/// <summary> /// news a account /// </summary> /// <param name="praiseDTO"></param> /// <returns></returns> public MsgDTO AddNewMsg(MsgDTO msgDTO) { //check preconditions if (msgDTO == null) { throw new ArgumentException(Messages.warning_CannotAddMsgWithEmptyInformation); } //Create the entity and the required associated data var msg = MsgFactory.CreateMsg(msgDTO.Context, msgDTO.MsType); //save entity SaveMsg(msg); //return the data with id and assigned default values return(msg.ProjectedAs <MsgDTO>()); }
public async Task <JsonResult> Login([FromBody] LoginViewModel vm) { try { if (ModelState.IsValid) { // check if any values tracked in Auth0 have changed LoginResponseViewModel responseVM = await _authAdapter.Authenticate(vm); var user = _userRepo.GetUserByExternalId(responseVM.ExternalId); if (user == null) { user = _userRepo.GetAppUserByEmail(vm.Email); if (user == null) { throw new Exception("Unable to locate user"); } else { //update with externalId user.ExternalId = responseVM.ExternalId; _userRepo.Base.SaveAll(User); } } responseVM.AppUserId = user.AppUserId; responseVM.AvatarUrl = user.AvatarUrl; responseVM.Email = user.Email; responseVM.FullName = user.FirstName + " " + user.LastName; responseVM.AdAssassinId = user.AdAssassinId; responseVM.Roles = user.UserRoles.Select(k => k.Role.Name).ToArray(); Response.StatusCode = (int)HttpStatusCode.OK; return(Json(responseVM)); } else { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(MsgFactory.Error(ModelState))); } } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(MsgFactory.Error(ex))); } }
public override string SetupNavSF45FromTTB(string fullMsg) { string str = string.Empty; if (fullMsg != "") { string str2 = fullMsg.Replace(" ", ""); int length = str2.Length; string message = "D705" + str2.Substring(14, length - 0x16); int num2 = message.Length / 2; str = "A0A2" + num2.ToString("X").PadLeft(4, '0') + message + utils_AutoReply.GetChecksum(message, false) + "B0B3"; if (MsgFactory.ConvertHexToDecimal(str2.Substring(14, 8), "UINT32", 1.0) == "0") { str = "Invalid: " + str; } } return(str); }
// ---------------------------消息相关------------------------------------- /// <summary> /// 添加操作数据 /// 状态, FSM数据, 单位属性, 单位位置, 单位方向, 目标点列表(路径), 目标(技能/攻击目标) /// 障碍物 /// 每个单位的当前数据(列表)(每个单位的,当前位置, 当前目标, 当前方向, 动作?) /// 攻击行为(带目标, 起点终点, 如果有) /// 技能行为(带目标, 起点终点, 如果有) /// 状态切换 /// 状态机FSM数据 /// </summary> public void AddOptionalData(DisplayOwner displayOwner) { if (userId < 0) { Start(); } // DisplayOwner转化为ObjectID // 封装, 放入列表 var objPos = displayOwner.GameObj; // 添加同步数据 var msgOp = MsgFactory.GetMsgOptional(1, objPos.transform.position.x, objPos.transform.position.y, objPos.transform.position.z, "UserId:" + userId + ",ObjectId:" + displayOwner.ClusterData.AllData.MemberData.ObjID.ID + ",UniqueId:" + displayOwner.ClusterData.AllData.MemberData.UniqueID + ",UnitType:" + (int)displayOwner.ClusterData.AllData.MemberData.ObjID.ObjType + //",CmName:" + objPos.name.Substring(0, objPos.name.IndexOf("(", StringComparison.Ordinal)) + ",Level:" + displayOwner.ClusterData.AllData.MemberData.ArmyLevel); // + //(displayOwner.MFAModelRender == null ? "" : //",MeshPackName:" + displayOwner.MFAModelRender.MeshPackName + //",TexturePackName:" + displayOwner.MFAModelRender.TexturePackName)); // 本地缓存 PushBeComfirmData(msgOp, true); // 超时回收被创建单位 var killTimer = new Timer(OperationTimeOut / 1000).OnCompleteCallback(() => { // 超时回收单位 DisplayerManager.Single.DelDisplay(displayOwner); }).Start(); // 操作结束停止计时 opSendCallbackDic.Add(msgOp.OpUniqueNum, () => { killTimer.Kill(); }); // 数据放入缓冲 PushtBeSendData(msgOp, (int)MsgId.MsgOptional); }
public void OnNetData(BinaryReader reader) { Message msg = MsgFactory.Deserialize(reader); var opHeader = msg.GetHeader <OperationHeader>(); if (opHeader != null && opHeader.Type == OperationType.Reply) { Future <Message> future; if (_pendingOperation.TryGetValue(opHeader.RequestId, out future)) { if (msg is InvalidOperation) { var inv = msg as InvalidOperation; future.SetError(inv.ErrorCode, inv.DebugDescription); } else { future.SetResult(msg); } _pendingOperation.Remove(opHeader.RequestId); } } else { NetContractDescription contractDesc = Dispatcher.GetContractForMessage(msg.Id); object handler; if (_handlersByNetContractId.TryGetValue(contractDesc.TypeId, out handler)) { Dispatcher.DispatchOneWay(handler, msg); } } MsgFactory.Free(msg); }
internal static string FieldList_to_HexString(bool isSLCRx, ArrayList fieldList, byte channelType) { string message = ""; int num = 0; if (fieldList.Count == 0) { return(string.Empty); } StringBuilder builder = new StringBuilder(); builder.Append(((SLCMsgStructure)fieldList[0]).defaultValue); for (int i = 1; i < fieldList.Count; i++) { if (string.IsNullOrEmpty(((SLCMsgStructure)fieldList[i]).defaultValue)) { builder.Append(","); builder.Append("0"); } else { builder.Append(","); builder.Append(((SLCMsgStructure)fieldList[i]).defaultValue); } } string[] strArray = builder.ToString().Split(new char[] { ',' }); StringBuilder builder2 = new StringBuilder(); for (int j = 0; j < fieldList.Count; j++) { builder2.Append(MsgFactory.ConvertDecimalToHex(strArray[j], ((SLCMsgStructure)fieldList[j]).datatype, ((SLCMsgStructure)fieldList[j]).scale)); num += ((SLCMsgStructure)fieldList[j]).bytes; } message = builder2.ToString(); return("A0A2" + num.ToString("X").PadLeft(4, '0') + message + GetChecksum(message, isSLCRx) + "B0B3"); }
public void ProcessRequest(HttpContext context) { //如果param为null,则实例化 param = param ?? new EnterParam { appid = System.Web.Configuration.WebConfigurationManager.AppSettings["appID"], EncodingAESKey = System.Web.Configuration.WebConfigurationManager.AppSettings["EncodingAESKey"], token = System.Web.Configuration.WebConfigurationManager.AppSettings["token"] }; //var ip = context.Request.UserHostAddress; //var ipEntity = BaseServices.GetIpArray("你的access_token"); //if (ipEntity!=null&&!ipEntity.ip_list.Contains(ip)) //{ // context.Response.Write("非法请求"); // return; //} if (context.Request.HttpMethod == "GET") { BaseServices.ValidUrl(param.token); } else { //判断MsgHandlerEntities是否为空,如果是,则实例化,并将各个消息类型的处理程序实体添加到此列表中 //因为MsgHandlerEntities是静态变量,只需绑定一次即可。免去了重复绑定的性能损耗。 if (MsgHandlerEntity.MsgHandlerEntities == null) { MsgHandlerEntity.MsgHandlerEntities = new List <MsgHandlerEntity>(); #region 文本消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.TEXT, Action = TextHandler }); #endregion #region 图片消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.IMAGE, Action = ImgHandler }); #endregion #region 语音消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.VOICE, Action = VoiceHandler }); #endregion #region 视频消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.VIDEO, Action = VideoHandler }); #endregion #region 地理位置消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.LOCATION, Action = LoctionHandler }); #endregion #region 链接消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.LINK, Action = linkHandler }); #endregion #region 群发消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.MASSSENDJOBFINISH, Action = GroupJobHandler }); #endregion #region 模板消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.TEMPLATESENDJOBFINISH, Action = TemplateJobHandler }); #endregion #region 扫描带参数二维码消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.SCAN, Action = SanQrEventHandler }); #endregion #region 自定义菜单Click消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.CLICK, Action = ClickEventHandler }); #endregion #region 自定义菜单View消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.VIEW, Action = ViewEventHandler }); #endregion #region 自定义菜单扫描二维码(scancode_push)消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.SCANCODE_PUSH, Action = MenuSanQrEventHandler }); #endregion #region 自定义菜单扫描二维码(scancode_waitmsg)消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.SCANCODE_WAITMSG, Action = MenuSanQrEventHandler }); #region 自定义菜单扫描二维码(scancode_waitmsg)消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.SCANCODE_WAITMSG, Action = MenuSanQrEventHandler }); #endregion #endregion #region 自定义菜单发送图片(pic_sysphoto)消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.PIC_SYSPHOTO, Action = MenuSendPicEventHandler }); #region 自定义菜单发送图片(pic_photo_or_album)消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.PIC_PHOTO_OR_ALBUM, Action = MenuSendPicEventHandler }); #endregion #region 自定义菜单发送图片(pic_weixin)消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.PIC_WEIXIN, Action = MenuSendPicEventHandler }); #endregion #endregion #region 创建多客服会话消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.KF_CREATE_SESSION, Action = KfHandler }); #endregion #region 关闭多客服会话消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.KF_CLOSE_SESSION, Action = KfHandler }); #endregion #region 转接多客服会话消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.KF_SWITCH_SESSION, Action = KfHandler }); #endregion #region 微信小店订单消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.MERCHANT_ORDER, Action = OrderHandler }); #endregion #region 门店审核处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.POI_CHECK_NOTIFY, Action = PoiNotifyHandler }); #endregion #region 卡券审核通过处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.CARD_PASS_CHECK, Action = CardCheckNotifyHandler }); #endregion #region 卡券审核未通过处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.CARD_NOT_PASS_CHECK, Action = CardCheckNotifyHandler }); #endregion #region 领取卡券处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.USER_GET_CARD, Action = UserGetCardHandler }); #endregion #region 关注事件处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.SUBSCRIBE, Action = SubscribeHandler }); #endregion #region 取消关注事件处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.UNSUBSCRIBE, Action = SubscribeHandler }); #endregion } MsgFactory.LoadMsg(param, MsgHandlerEntity.MsgHandlerEntities); } }
public UsersController() { userFactory = new UserFactory(); msgFactory = new MsgFactory(); comFactory = new ComFactory(); }
public void ExecuteOneWayOperation(Message inMsg) { Channel.Send(inMsg); MsgFactory.Free(inMsg); }
public JsonResult ProcessAds([FromBody] List <object> ads) { try { var email = UserClaimHelpers.Email(User.Identity); var user = _userRepo.GetAppUserByEmail(email); var dataSyncEntity = _userRepo.GetCurrentDataSync(user.AppUserId); var newAds = DataModel.ParseCollection <Ad>(ads); if (user == null) { throw new Exception("We don't seem to be able to locate your account. Please contact support for assistance."); } var dateRecorded = DateTime.UtcNow; foreach (var item in newAds) { item.AppUserDataSyncId = dataSyncEntity.Id; item.DateRecorded = dateRecorded; } var currentItems = _repo.GetAdsByUserId(user.AppUserId); var currIds = currentItems.Select(k => k.id).ToList(); var newIds = newAds.Select(k => k.id).ToList(); var toAddIds = newIds.Except(currIds).ToList(); var toUpdateIds = newIds.Intersect(currIds).ToList(); var toDeleteIds = currIds.Except(newIds).ToList(); var toAdd = newAds.Where(k => toAddIds.Contains(k.id)).ToList(); var toUpdate = newAds.Where(k => toUpdateIds.Contains(k.id)).ToList(); var toDelete = currentItems.Where(k => toDeleteIds.Contains(k.id)).ToList(); // create a copy for the history var historyItems = new List <_AdHistoryItem>(newAds.Count); foreach (var item in newAds) { historyItems.Add((_AdHistoryItem)item.CreateHistoryItem <_AdHistoryItem>()); } _repo.AddAdHistoryItems(historyItems); dataSyncEntity.AdsCompleted = true; _repo.AddAds(toAdd); _repo.UpdateAds(toUpdate); _userRepo.UpdateDataSync(dataSyncEntity); if (_repo.Base.SaveAll(User)) { Response.StatusCode = (int)HttpStatusCode.OK; return(Json(newIds)); } Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(MsgFactory.Error("Unable to process!"))); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(MsgFactory.Error(ex))); } }
public void ProcessRequest(HttpContext context) { // 测试时暂不使用 /*var ip = context.Request.UserHostAddress; * var ipEntity = BaseServices.GetIpArray("你的access_token"); * if(ipEntity!=null && !ipEntity.ip_list.Contains(ip)) * { * context.Response.Write("非法请求"); * return; * }*/ // var url = context.Request.RawUrl; if (context.Request.HttpMethod == "GET") { BaseServices.ValidUrl("skywalkerxl"); } else { //var xml = Utils.GetRequestData(); //System.Diagnostics.Debug.WriteLine("----------------------Receive the xml message Start----------------------"); //System.Diagnostics.Debug.WriteLine(xml); //System.Diagnostics.Debug.WriteLine("---------------------- Receive the xml message End ----------------------"); //context.Response.Write(""); string openid = context.Request.Params["openid"]; Utils.OutPrint(openid); if (SessionUtils.Get("openid") == null) { SessionUtils.Add("openid", openid); } // 判断MsgHandlerEntities是否为空,如果是,则实例化,并将各个消息类型的处理程序实体添加到此列表中 // 因为MsgHandlerEntities是静态变量,之需绑定一次即可,免去了重复绑定的性能损耗 if (MsgHandlerEntity.MsgHandlerEntities == null) { MsgHandlerEntity.MsgHandlerEntities = new List <MsgHandlerEntity>(); #region 文本消息绑定处理 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.TEXT, Action = TextHandler }); #endregion #region 图片消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.IMAGE, Action = ImgHandler }); #endregion #region 语音消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.VOICE, Action = VoiceHandler }); #endregion #region 视频消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.VIDEO, Action = VideoHandler }); #endregion #region 地理位置消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.LOCATION, Action = LocationHandler }); #endregion #region 链接消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.LINK, Action = linkHandler }); #endregion #region 点击事件处理程序 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.CLICK, Action = ClickEventHandler }); #endregion #region 图片事件处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.PIC_WEIXIN, Action = PicWeiXinHandler }); #endregion #region 订阅事件处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.SUBSCRIBE, Action = SubscribeEventHandler }); #endregion /*** * * * 其它一系列的事件处理 * * ***/ // TODO #region 获取地理位置信息事件处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.LOCATION, Action = LocationEventHandler }); #endregion #region 浏览事件处理程序绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.VIEW, Action = ViewEventHandler }); #endregion #region 扫码推送事件处理程序绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.SCANCODE_PUSH, Action = ScanCodePushEventHandler }); #endregion #region 扫码等待事件处理程序绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.SCANCODE_WAITMSG, Action = ScanCOdeWatingEventHandler }); #endregion #region 系统照相事件处理程序绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.PIC_SYSPHOTO, Action = PicSysphotoEventHandler }); #endregion #region 系统照相或相册事件处理程序绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.PIC_PHOTO_OR_ALBUM, Action = PicPhotoOrAlbumEventHandler }); #endregion #region 弹出地理位置选择器事件处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.LOCATION_SELECT, Action = LocationSelectEventHandler }); #endregion #region 模板消息事件处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.TEMPLATESENDJOBFINISH, Action = TEMPLATESENDJOBFINISHEventHandler }); #endregion #region 群发消息处理绑定 MsgHandlerEntity.MsgHandlerEntities.Add(new MsgHandlerEntity { MsgType = MsgType.EVENT, EventType = EventType.MASSSENDJOBFINISH, Action = GroupJobHandler }); #endregion } MsgFactory.LoadMsg(MsgHandlerEntity.MsgHandlerEntities); } }
/// <summary> /// 读取数据 /// </summary> private void ReadData() { lock (dataList) { // 循环每个人的数据 foreach (var head in dataList) { // 客户端UserID var userId = head.userId; // 是否转发到来消息方 var rotateFrom = false; // 是否转发去消息方 var rotateTo = false; // 复制数据 var copyData = (byte[])head.body.Clone(); // 判断数据类型 switch (head.msgId) { case (int)MsgId.MsgOptional: { // 转发给匹配玩家 rotateTo = true; // 解析数据 while (ByteUtils.CouldRead(copyData)) { // 操作数据 var opData = ByteUtils.ReadMsg(ref copyData); // 解析为类 var opMsg = SocketManager.DeSerialize <MsgOptional>(opData); AddLog(opMsg.OpPosX + "," + opMsg.OpPosY + "," + opMsg.OpPosZ + ", OpType:" + opMsg.OpType + ", OpParams:" + opMsg.OpParams); } break; } case (int)MsgId.MsgComfirmOperation: { // 转发两方 rotateFrom = true; rotateTo = true; // 解析数据 while (ByteUtils.CouldRead(copyData)) { // 操作数据 var cOpData = ByteUtils.ReadMsg(ref copyData); var cOp = SocketManager.DeSerialize <MsgComfirmOperation>(cOpData); AddLog(cOp.OpUniqueNum + "," + cOp.OpParams); } break; } // 战斗请求数据 case (int)MsgId.MsgAskBattleRequest: { // 读取匹配消息 byte[] msgAskBattleRequestData = ByteUtils.CouldRead(copyData) ? ByteUtils.ReadMsg(ref copyData) : null; if (msgAskBattleRequestData == null) { AddLog("Error:请求战斗数据为空"); continue; } // 反序列化战斗请求数据 var msgAskBattleRequest = SocketManager.DeSerialize <MsgAskBattleRequest>(msgAskBattleRequestData); // 匹配 // 检查是否在匹配列表里 if (!matchDic.ContainsKey(userId)) { // 检查未匹配列表中是否有单位 if (unmatchList.Count > 0) { var matchUserId = unmatchList[0]; if (matchUserId != userId) { // 加入匹配列表 unmatchList.RemoveAt(0); matchDic.Add(matchUserId, userId); matchDic.Add(userId, matchUserId); } AddLog("匹配成功:" + userId + ":" + matchUserId); // 给两方发送战斗匹配消息 // 获取缓存的匹配数据 var buffMsgAskBattleRequest = matchDataDic[matchUserId]; // 生成随机种子 var randomSeed = DateTime.Now.Millisecond; // 匹配单位的战斗回复消息 var msgAskBattleResponse1 = MsgFactory.GetMsgAskBattleResponse(msgAskBattleRequest.BaseLevel, msgAskBattleRequest.TurretLevel, msgAskBattleRequest.Race, buffMsgAskBattleRequest.BaseLevel, buffMsgAskBattleRequest.TurretLevel, buffMsgAskBattleRequest.Race, uniqueIdStartOne, randomSeed, ""); // 被匹配单位的的战斗回复消息 var msgAskBattleResponse2 = MsgFactory.GetMsgAskBattleResponse(buffMsgAskBattleRequest.BaseLevel, buffMsgAskBattleRequest.TurretLevel, buffMsgAskBattleRequest.Race, msgAskBattleRequest.BaseLevel, msgAskBattleRequest.TurretLevel, msgAskBattleRequest.Race, uniqueIdStartTwo, randomSeed, ""); // 消息 // 发送战斗请求回复消息给两方 SendMsg(idMapSocket[userId], PackageData(SocketManager.Serialize(msgAskBattleResponse1), userId, (int)MsgId.MsgAskBattleResponse)); SendMsg(idMapSocket[matchUserId], PackageData(SocketManager.Serialize(msgAskBattleResponse2), matchUserId, (int)MsgId.MsgAskBattleResponse)); } else { // 需要缓存匹配请求数据 matchDataDic.Add(userId, msgAskBattleRequest); // 加入为匹配列表 unmatchList.Add(userId); AddLog("等待匹配:" + userId); } } break; } // 战斗开始请求 case (int)MsgId.MsgBattleStartRequest: { byte[] msgBattleStartRequestData = ByteUtils.CouldRead(copyData) ? ByteUtils.ReadMsg(ref copyData) : null; if (msgBattleStartRequestData == null) { AddLog("Error:请求战斗数据为空"); continue; } // 反序列化战斗开始请求数据 var msgBattleStartRequest = SocketManager.DeSerialize <MsgBattleStartRequest>(msgBattleStartRequestData); if (matchDic.ContainsKey(userId)) { var matchId = matchDic[userId]; // 检查是否匹配方也发送了战斗开始请求 if (battleStartDataDic.ContainsKey(matchId)) { // 如果有则给两方发送战斗开始回复 // 匹配单位的战斗回复消息 var msgBattleStartResponse1 = MsgFactory.GetMsgBattleStartResponse(""); // 被匹配单位的的战斗回复消息 var msgBattleStartResponse2 = MsgFactory.GetMsgBattleStartResponse(""); // 消息 // 发送战斗请求回复消息给两方 SendMsg(idMapSocket[userId], PackageData(SocketManager.Serialize(msgBattleStartResponse1), userId, (int)MsgId.MsgBattleStartResponse)); SendMsg(idMapSocket[matchId], PackageData(SocketManager.Serialize(msgBattleStartResponse2), matchId, (int)MsgId.MsgBattleStartResponse)); } else { // 否则放入等待列表 battleStartDataDic.Add(userId, msgBattleStartRequest); } } else { AddLog("单位未匹配:" + userId); } break; } // TODO 应该在匹配后发送随机种子 //case (int) MsgId.MsgRequestRandomSeed: //{ // // 随机种子请求 // // 直接发送 // // 不转发数据 // rotateFrom = false; // rotateTo = false; // // 创建随机种子消息 // var msgRandomSeed = new MsgRandomSeed() // { // RandomSeed = DateTime.Now.Millisecond // }; // // 消息 // // 发送随机种子消息 // SendMsg(idMapSocket[head.userId], // PackageData(SocketManager.Serialize(msgRandomSeed), head.userId, (int) MsgId.MsgRandomSeed)); // break; //} case (int)MsgId.MsgString: { // 不转发 // 解析数据 while (ByteUtils.CouldRead(copyData)) { // 操作数据 var strData = ByteUtils.ReadMsg(ref copyData); // 解析为字符串 字符集: UTF8 var str = Encoding.UTF8.GetString(strData); AddLog(str); } break; } } // TODO 转发数据 // 判断是否已匹配, 如果匹配则转发数据, 否则不转发 if (matchDic.ContainsKey(userId)) { // 获取匹配的Id var matchUserId = matchDic[userId]; // 转发数据 // 序列化转发数据 var serializeData = Serialize(head); if (rotateTo) { // 转发去方 // 该Id对应的Socket var matchSocket = idMapSocket[matchUserId]; // 打包数据发送 SendMsg(matchSocket, serializeData); } if (rotateFrom) { // 转发来源方 var toSocket = idMapSocket[userId]; SendMsg(toSocket, serializeData); } AddLog("转发数据成功:" + userId + "," + matchUserId); } else { // 没匹配不转发, 输出log AddLog("没有匹配不转发, userId:" + userId); } } } // TODO 检查断线情况 foreach (var kv in idMapSocket) { if (!kv.Value.Connected) { // 断开 matchDelList.Add(kv.Key); } } // 删除匹配 foreach (var delMatch in matchDelList) { if (!matchDic.ContainsKey(delMatch)) { continue; } var matchId = matchDic[delMatch]; matchDic.Remove(matchId); matchDic.Remove(delMatch); // 链接关闭 idMapSocket[matchId].Close(); idMapSocket.Remove(matchId); } // 清空删除列表 matchDelList.Clear(); // 清空数据 dataList.Clear(); // 显示log if (!string.IsNullOrEmpty(log)) { TxtLog.Text += log; log = ""; } }
private string AI3_Request_ConvertFieldsToRaw(string csvMessage, ArrayList fieldList) { int num = 0; char[] separator = new char[] { ',' }; string[] strArray = new string[0x7d0]; strArray = csvMessage.Split(separator); int.Parse(strArray[0]); int.Parse(strArray[1]); if (fieldList.Count == 0) { return(string.Empty); } StringBuilder builder = new StringBuilder(); for (int i = 0; i < fieldList.Count; i++) { builder.Append(MsgFactory.ConvertDecimalToHex(strArray[i], ((SLCMsgStructure)fieldList[i]).datatype, ((SLCMsgStructure)fieldList[i]).scale)); } string str = string.Empty; string msg = builder.ToString().Replace(" ", ""); if (base.AutoReplyParams.AutoAid_Eph_fromTTB && (base.EphDataMsg != "")) { int num3 = msg.Length; string str3 = msg.Substring(0, 0x26); string str4 = msg.Substring(0xf26, num3 - 0xf26); int num4 = base.EphDataMsg.Length / 2; for (int k = 0; k < (0x780 - num4); k++) { base.EphDataMsg = base.EphDataMsg + "00"; } msg = str3 + base.EphDataMsg + str4; } if (base.AutoReplyParams.AutoAid_AcqData_fromTTB && (base.AcqAssistDataMsg != "")) { int num6 = msg.Length; string str5 = msg.Substring(0, 0x156c); string str6 = msg.Substring(0x1936, num6 - 0x1936); int num7 = base.AcqAssistDataMsg.Length / 2; for (int m = 0; m < (0x1e4 - num7); m++) { base.AcqAssistDataMsg = base.AcqAssistDataMsg + "00"; } msg = str5 + "01" + base.AcqAssistDataMsg + str6; } byte[] buffer = HelperFunctions.HexToByte(msg); buffer[0xcab] = 8; byte[] buffer2 = this.compressMsg(buffer, 0xcac); int length = buffer2.GetLength(0); byte num10 = (byte)(length / 0x3f8); int num11 = length % 0x3f8; if (0 < (length % 0x3f8)) { num10 = (byte)(num10 + 1); } byte[] input = new byte[0x3fc]; input[0] = 1; input[1] = 1; input[2] = num10; byte[] buffer4 = new byte[num11 + 4]; buffer4[0] = 1; buffer4[1] = 1; buffer4[2] = num10; for (byte j = 0; j < num10; j = (byte)(j + 1)) { if (j < (num10 - 1)) { input[3] = (byte)(j + 1); for (int n = 0; n < 0x3f8; n++) { input[n + 4] = buffer2[(j * 0x3f8) + n]; } num = 0x3fc; string message = HelperFunctions.ByteToHex(input); string str8 = "A0A2" + num.ToString("X").PadLeft(4, '0') + message + utils_AutoReply.GetChecksum(message, true) + "B0B3"; str = str + str8.Replace(" ", "") + "\r\n"; } else { buffer4[3] = (byte)(j + 1); for (int num14 = 0; num14 < num11; num14++) { buffer4[num14 + 4] = buffer2[(j * 0x3f8) + num14]; } num = num11 + 4; string str9 = HelperFunctions.ByteToHex(buffer4); string str10 = "A0A2" + num.ToString("X").PadLeft(4, '0') + str9 + utils_AutoReply.GetChecksum(str9, true) + "B0B3"; str = str + str10.Replace(" ", "") + "\r\n"; } } return(str); }
public JsonResult ProcessAdSets([FromBody] List <object> adsets) { try { // get sync entity var email = UserClaimHelpers.Email(User.Identity); var user = _userRepo.GetAppUserByEmail(email); var dataSyncEntity = _userRepo.GetCurrentDataSync(user.AppUserId); var newAdsets = DataModel.ParseCollection <AdSet>(adsets); var dateRecorded = DateTime.UtcNow; if (user == null) { throw new Exception("We don't seem to be able to locate your account. Please contact support for assistance."); } // create new regions if they do not exist in our system var newRegions = new Dictionary <int, Region>(); var currentItems = _repo.GetAdSetByUserId(user.AppUserId); // var targetings = currentItems.Select(k => k.targeting).ToDictionary(k => k.adset_id, m => m); //var newTargets = new Dictionary<long, Targeting>(); // var geolocations = targetings.Values.Select(k => k.geo_locations).ToDictionary(k => k.adset_id, m => m); var regions = _repo.GetRegions(); var toRemoveMaps = new List <GeolocationRegionMap>(10); foreach (var item in newAdsets) { item.AppUserDataSyncId = dataSyncEntity.Id; item.DateRecorded = dateRecorded; //if (!targetings.ContainsKey(item.id) && !newTargets.ContainsKey(item.id)) // newTargets.Add(item.id, item.targeting); item.targeting.adset_id = item.id; item.targeting.AppUserDataSyncId = dataSyncEntity.Id; item.targeting.DateRecorded = dateRecorded; item.targeting.geo_locations.adset_id = item.id; item.targeting.geo_locations.AppUserDataSyncId = dataSyncEntity.Id; item.targeting.geo_locations.DateRecorded = dateRecorded; //if (geolocations.ContainsKey(item.targeting.adset_id)) // item.targeting.geo_locations.adset_id = geolocations[item.targeting.adset_id].adset_id; item.targeting.geo_locations.region_maps = new List <GeolocationRegionMap>(10); foreach (var region in item.targeting.geo_locations.regions) { if (!regions.ContainsKey(region.key) && !newRegions.ContainsKey(region.key)) { newRegions.Add(region.key, region); } var currentItem = currentItems.FirstOrDefault(k => k.id == item.id); if (currentItem != null) { var currentRegions = currentItem.targeting.geo_locations.region_maps; var incomingRegions = item.targeting.geo_locations.regions; var curRegionKeys = currentRegions.Select(k => k.key).ToList(); var incomingRegKeys = incomingRegions.Select(k => k.key).ToList(); var toAddRegKeyMaps = incomingRegKeys.Except(curRegionKeys); var toRemoveRegKeyMaps = curRegionKeys.Except(incomingRegKeys); foreach (var keyMap in toAddRegKeyMaps) { item.targeting.geo_locations.region_maps.Add( new GeolocationRegionMap() { key = keyMap, AppUserDataSyncId = dataSyncEntity.Id, DateRecorded = dateRecorded }); } foreach (var keyMap in toRemoveRegKeyMaps) { var map = item.targeting.geo_locations.region_maps.FirstOrDefault(k => k.key == keyMap); if (map != null) { toRemoveMaps.Add(map); } } } else { item.targeting.geo_locations.region_maps.Add( new GeolocationRegionMap() { key = region.key, AppUserDataSyncId = dataSyncEntity.Id, DateRecorded = dateRecorded }); } } } var currIds = currentItems.Select(k => k.id).ToList(); var newIds = newAdsets.Select(k => k.id).ToList(); var toAddIds = newIds.Except(currIds).ToList(); var toUpdateIds = newIds.Intersect(currIds).ToList(); var toDeleteIds = currIds.Except(newIds).ToList(); var toAdd = newAdsets.Where(k => toAddIds.Contains(k.id)).ToList(); var toUpdate = newAdsets.Where(k => toUpdateIds.Contains(k.id)).ToList(); var toDelete = currentItems.Where(k => toDeleteIds.Contains(k.id)).ToList(); var historyItems = new List <_AdSetHistoryItem>(newAdsets.Count); var tgtHistoryItems = new List <_TargetingHistoryItem>(newAdsets.Count); var geolocHistoryItems = new List <_GeolocationHistoryItem>(newAdsets.Count); var geolocMapHistoryItems = new List <_GeolocationRegionMapHistoryItem>(newAdsets.Count); foreach (var item in newAdsets) { var newAsHi = (_AdSetHistoryItem)item.CreateHistoryItem <_AdSetHistoryItem>(); newAsHi.AppUserDataSyncId = dataSyncEntity.Id; newAsHi.DateRecorded = dateRecorded; historyItems.Add(newAsHi); var newTgtHi = (_TargetingHistoryItem)item.targeting.CreateHistoryItem <_TargetingHistoryItem>(); newTgtHi.AppUserDataSyncId = dataSyncEntity.Id; newTgtHi.DateRecorded = dateRecorded; tgtHistoryItems.Add(newTgtHi); var glocHi = (_GeolocationHistoryItem)item.targeting.geo_locations.CreateHistoryItem <_GeolocationHistoryItem>(); glocHi.AppUserDataSyncId = dataSyncEntity.Id; glocHi.DateRecorded = dateRecorded; geolocHistoryItems.Add(glocHi); foreach (var regMap in item.targeting.geo_locations.region_maps) { var geolocRegMapHi = (_GeolocationRegionMapHistoryItem)regMap.CreateHistoryItem <_GeolocationRegionMapHistoryItem>(); geolocRegMapHi.AppUserDataSyncId = dataSyncEntity.Id; geolocRegMapHi.DateRecorded = dateRecorded; geolocRegMapHi.adset_id = item.id; geolocMapHistoryItems.Add(geolocRegMapHi); } } _repo.AddSetHistoryItems(historyItems); _repo.AddTargetHistoryItems(tgtHistoryItems); _repo.AddGeolocationHistoryItems(geolocHistoryItems); _repo.AddGeolocationRegionMapHistoryItems(geolocMapHistoryItems); dataSyncEntity.AdSetsCompleted = true; _repo.RemoveGelocationRegionMaps(toRemoveMaps); _repo.AddRegions(newRegions.Values); _repo.AddAdSets(toAdd); _repo.UpdateAdSets(toUpdate); _userRepo.UpdateDataSync(dataSyncEntity); if (_repo.Base.SaveAll(User)) { Response.StatusCode = (int)HttpStatusCode.OK; return(Json(newIds)); } Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(MsgFactory.Error("Unable to process!"))); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.InternalServerError; return(Json(MsgFactory.Error(ex))); } }