Ejemplo n.º 1
0
        //***********************SEARCH*************************************
        public virtual ResponseModel <TVm> GeneralSearch(PagingDataType status, BaseRequestModel <TEntity> requestModel)
        {
            int count;
            ResponseModel <TVm> response;

            switch (status)
            {
            case PagingDataType.All:
                count          = Repository.GetAll().Where(requestModel.GetExpression()).Count();
                response       = GetAll(requestModel);
                response.Count = count;
                return(response);

            case PagingDataType.Active:
                count          = Repository.GetAllActive().Where(requestModel.GetExpression()).Count();
                response       = GetAllActive(requestModel);
                response.Count = count;
                return(response);

            case PagingDataType.Inactive:
                count          = Repository.GetAllInactive().Where(requestModel.GetExpression()).Count();
                response       = GetAllInactive(requestModel);
                response.Count = count;
                return(response);

            default:
                throw new ArgumentOutOfRangeException(nameof(status), status, null);
            }
        }
Ejemplo n.º 2
0
        private IEnumerator _sendRequest(string url, WWWForm data, OnRequestCompleted complete = null, OnRequestError error = null)
        {
            var request = new WWW(url, data); // Create WWW Request

            yield return(request);            // Send Request

            // Work with Response
            if (request.error != null)  // Request has error
            {
                throw new Exception("Не удалось отправить запрос к серверу VK API. Проверьте соединение с интернетом и попробуйте снова.");
            }
            else                                                                                   // No Errors
            {
                BaseRequestModel response = JsonUtility.FromJson <BaseRequestModel>(request.text); // Get Base Model from Response Text
                if (response.error.error_code == -1)
                {                                                                                  // Response not has an errors
                    if (complete != null)
                    {
                        complete(request.text); // Return Complete
                    }
                }
                else
                { // Reponse has errors
                    if (error != null)
                    {
                        error(response.error); // Show Error
                    }
                    if (settings.debug_mode)
                    {
                        Debug.Log("VK SDK Error: " + response.error.error_msg);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Disconnects the client from the server and stops all threads for client.
        /// </summary>
        public void DisconnectClient()
        {
            //Console Message.
            Console.WriteLine("Disconnecting: " + Me.IpAddress + " Name: " + Me.Name);

            //Removes client from server.
            ParentServer.Clients.Remove(this);

            //Call Handlers for disconect user
            BaseRequestModel model = new BaseRequestModel
            {
                Flag = (ushort)RequestFlag.Disconnect
            };

            _dispatcher.Handle(model, Me, this);

            //Closes Stream.
            MscClient.Close();

            //Starts an abort thread.
            AbortThread = new Thread(new ThreadStart(delegate
            {
                Abort();
            }));
            Console.WriteLine("Aborting threads on client.");
            AbortThread.Start();
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> DeActivate([FromBody] BaseRequestModel model)
        {
            if (model.Id == default(long))
            {
                throw new BadRequestException("Business is required");
            }

            bool result = await _businessManager.Deactivate(model.Id);

            if (result)
            {
                return(Ok(new ResponseModel <object>
                {
                    RequestSuccessful = true,
                    ResponseCode = ResponseCodes.Successful,
                    Message = "Business has been deactivated successfully."
                }));
            }
            else
            {
                return(BadRequest(new ResponseModel <object>
                {
                    ResponseCode = ResponseCodes.Failed,
                    Message = "Failed. Please try again or contact your administrator"
                }));
            }
        }
Ejemplo n.º 5
0
        private bool Invoke(BaseRequestModel model, UserModel user, SocketHelper socket, Dictionary <string, string> data)
        {
            var middlewaresForThisDispatcher = socket.myMiddlewares
                                               .Where(x => x.Key == Id)
                                               //.Select(xx => xx.Value)
                                               .SelectMany(x => x.Value.FindAll(m =>
                                                                                m.Flags.Contains((ushort)RequestFlag.ForAll) ||
                                                                                m.Flags.Contains(model.Flag)));


            //Logger.Debug($"{Name} PreProcess midlewares start");
            foreach (var middleware in middlewaresForThisDispatcher)
            {
                middleware.PreProcess(model, user, socket, data);
            }
            //Logger.Debug($"{Name} PreProcess midlewares finish");

            //Logger.Debug($"{Name} Handlers start");
            var handled = InvokeHandlers(model, user, socket, data);

            //Logger.Debug($"{Name} Handlers finish");

            //Logger.Debug($"{Name} PostProcess midlewares start");
            foreach (var middleware in middlewaresForThisDispatcher)
            {
                middleware.PostProcess(model, user, socket, data);
            }
            //Logger.Debug($"{Name} PostProcess midlewares finish");


            return(handled);
        }
        public GetHouseEstateResultEntity Post(BaseRequestModel Req)
        {
            Logger.LogDebug("GetAllHouseEstateInfo Request:" + JsonHelper.SerializeObject(Req), "GetAllHouseEstateInfoController", "Post");
            var ret = new GetHouseEstateResultEntity()
            {
                Code   = 0,
                ErrMsg = ""
            };

            try
            {
                var _houseEstateList = _houseEstateBLL.GetModelsByPage(Req.PageSize, Req.PageIndex, true, p => p.ID, x => 1 == 1);
                var _hseList         = new List <HouseEstateEntity>();
                foreach (var DBhe in _houseEstateList)
                {
                    var he = new HouseEstateEntity()
                    {
                        HouseEstateID   = DBhe.ID,
                        ProjectNumber   = DBhe.Project.Number,
                        ProjectName     = DBhe.Project.Name,
                        HouseEstateName = DBhe.Name
                    };
                    _hseList.Add(he);
                }
                ret.HouseEstateList = _hseList;
                ret.RecordCount     = _houseEstateBLL.GetModels(x => 1 == 1).Count();
            }
            catch (Exception ex)
            {
                Logger.LogException("获取所有楼盘信息时发生异常!", "GetAllHouseEstateInfoController", "Post", ex);
                ret.Code   = 999;
                ret.ErrMsg = ex.Message;
            }
            return(ret);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Listener da request
 /// </summary>
 private void OnRequestCompleted(BaseRequestModel request)
 {
     _platformDataReceived = request.svo as GetPlatformDataSVO;
     if (callbackRequestCompleted != null)
     {
         callbackRequestCompleted.Invoke();
     }
 }
        public static KeyValuePair <string, string> PathParameter(this BaseRequestModel baseRequestModel, string path)
        {
            if (IsNullableObject(path))
            {
                return(NullKeyValuePair());
            }

            return(new KeyValuePair <string, string>("path", WebUtility.UrlEncode(path)));
        }
Ejemplo n.º 9
0
        public virtual ResponseModel <TVm> GetAllInactive(BaseRequestModel <TEntity> requestModel)
        {
            var queryable = GetQuery(Repository.GetAllInactive(), requestModel);
            var entities  = GetEntries(queryable);
            var response  = new ResponseModel <TVm>(entities, Repository.GetAllInactive().Count());

            //Repository.Dispose();
            return(response);
        }
Ejemplo n.º 10
0
        public Dictionary <string, string> Process(BaseRequestModel model, UserBaseModel user, SocketHelper mySocket, Dictionary <string, string> data)
        {
            var resp = BaseResponseModel.Model <PlayersCountModelResponse>((ushort)MyResponseFlag.PlayersCount);

            resp.Count = mySocket.ParentServer.Clients.Count;

            mySocket.SendMessageToAll(resp);

            return(data);
        }
Ejemplo n.º 11
0
        // --------------------------------------------------------
        // --------------------------------------------------------

        private void CurrentRequestFinalized()
        {
            try{
                //isso serve pra debugar a request (so pro desenvolvedor)
                //coloquei no try pq nao sei se vai ter algum louco que vai jogar isso ate o fim da vida
                _oldRequests = "time_" + (int)Time.realtimeSinceStartup + "___" + _currentRequestModel.functionName + "\n" + _oldRequests;
            }catch {}
            _currentRequestModel = null;
            tryCallNextResquest();
        }
        public static async Task ExecuteAPI(HttpContext context, System.Net.WebSockets.WebSocket webSocket)
        {
            var buffer = new byte[1024 * 20];
            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

            while (!result.CloseStatus.HasValue)
            {
                string strRequest = Encoding.UTF8.GetString(buffer);
                string str        = strRequest.Replace("\0", string.Empty);
                string jsonStr    = string.Empty;

                try
                {
                    //Method
                    APIModel    apiModel = JsonSerializer.Deserialize <APIModel>(str);
                    string      apiName  = apiModel.Method;
                    BaseCommand command  = Activator.CreateInstance(CommandsDict[apiName]) as BaseCommand;
                    command.WebSocket = webSocket;
                    jsonStr           = command.Execute(str);
                    buffer            = Encoding.UTF8.GetBytes(jsonStr);
                    BaseRequestModel requestModel = JsonSerializer.Deserialize <BaseRequestModel>(str);
                    if (!string.IsNullOrEmpty(requestModel.Token))
                    {
                        if (command is UserLogoutCommand)
                        {
                            //do nothing
                        }
                        else
                        {
                            UserInfo userInfo = UserInfoDict[requestModel.Token];
                            userInfo.ActionTime = DateTime.Now;
                        }
                    }
                    else if (command is UserLoginCommand)
                    {
                        //do nothing
                    }
                }
                catch (Exception ex)
                {
                    ErrorResponseModel responseModel = new ErrorResponseModel();
                    responseModel.StatusCode = 0;
                    responseModel.ErrorCode  = "500";
                    responseModel.Message    = ex.Message;
                    jsonStr = JsonSerializer.Serialize(responseModel);
                    buffer  = Encoding.UTF8.GetBytes(jsonStr);
                }

                await webSocket.SendAsync(new ArraySegment <byte>(buffer, 0, jsonStr.Length), result.MessageType, result.EndOfMessage, CancellationToken.None);

                buffer = new byte[1024 * 20];
                result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);
            }
            await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);
        }
Ejemplo n.º 13
0
        public IHttpActionResult SendMessage(SendRequest req)
        {
            if (string.IsNullOrEmpty(req.UUID))
            {
                return(Json(new { Code = 1, Message = "UUID为空" }));
            }

            if (string.IsNullOrWhiteSpace(req.Message))
            {
                return(Json(new { Code = 2, Message = "发送内容为空" }));
            }

            try
            {
                UserManager um = UserPool.Instance[req.UUID];
                if (um != null && um.UserInfo != null)
                {
                    SendModel sm = new SendModel()
                    {
                        BaseRequest = BaseRequestModel.Create(um.UserInfo),
                        Msg         = new MessageSendModel()
                        {
                            FromUserName = um.UserInfo.User.UserName,
                            Content      = req.Message,
                            Type         = 1,
                            LocalID      = um.UserInfo.LocalID.ToString(),
                        },
                        Scene = 0
                    };
                    sm.Msg.ClientMsgId = sm.Msg.LocalID;

                    foreach (KeyValuePair <string, BaseContactModel> item in um.UserInfo)
                    {
                        sm.Msg.ToUserName = item.Key;

                        string j = JsonConvert.SerializeObject(sm);

                        string path = System.AppDomain.CurrentDomain.BaseDirectory + "\\data\\send.txt";
                        using (StreamWriter sw = new StreamWriter(path, true))
                        {
                            sw.WriteLine(j);
                        }

                        string value = HttpHelper.GetResponseValue(um.UserInfo.SendUrl, HttpMethod.POST, j, um.UserInfo.Cookies);
                    }
                }

                return(Json(new { Code = 0, Message = "消息发送成功" }));
            }
            catch (Exception ex)
            {
                return(Json(new { Code = -1, Message = "消息发送出现异常" }));
            }
        }
Ejemplo n.º 14
0
        public dynamic Login(string userName, string password)
        {
            LoginInfo objLogin    = new LoginInfo();
            Response  objResponse = new Response();

            if (userName != null && password != null)
            {
                try
                {
                    objLogin.UserName = userName;
                    objLogin.Password = password;
                    MembershipUser   user           = Membership.GetUser(objLogin.UserName);
                    bool             userValidate   = Membership.ValidateUser(objLogin.UserName, objLogin.Password);
                    BaseRequestModel objBaseRequest = new BaseRequestModel();

                    if (user != null && user.IsLockedOut)
                    {
                        objResponse.Message = Messages.UserLockedMessage;
                    }
                    if (user != null && userValidate == true)
                    {
                        //Roles.AddUserToRole(userName,"Admin");
                        //bool isUserInRole = Roles.IsUserInRole("Admin");
                        string[] rolesForUser = Roles.GetRolesForUser(objLogin.UserName);
                        if (rolesForUser.Length > 0)
                        {
                            var UserName = user.UserName;
                            //var Password = user.GetPassword;
                            if (UserName == objLogin.UserName)
                            {
                                objResponse.Message = Messages.LoginSuccess;
                                objResponse.Status  = 1;
                            }
                            else
                            {
                                objResponse.Message = Messages.LoginFailure;
                                objResponse.Status  = 0;
                            }
                        }
                        else
                        {
                            objResponse.Message = Messages.InvalidCredentials;
                            objResponse.Status  = 0;
                        }
                    }
                }
                catch (Exception ex)
                {
                    objResponse.Message = Messages.LoginFailure;
                    objResponse.Status  = 0;
                }
            }
            return(objResponse);
        }
Ejemplo n.º 15
0
        public IQueryable <T> SearchQueryable(BaseRequestModel <T> request)
        {
            IQueryable <T> queryable = repository.Get();
            Expression <Func <T, bool> > expression = request.GetExpression();

            queryable = queryable.Where(expression);
            queryable = request.OrderByFunc()(queryable);
            queryable = request.SkipAndTake(queryable);
            queryable = request.IncludeParents(queryable);
            return(queryable);
        }
Ejemplo n.º 16
0
        //----------------------------------------------------------
        // UTILS // UTILS // UTILS // UTILS // UTILS // UTILS //
        //----------------------------------------------------------
        private IEnumerator startRequest(BaseRequestModel requestModel)
        {
            _currentRequestModel = requestModel;
            requestModel.OnRequestStart();

            //torna a chamada assincrona
            yield return(new WaitForSeconds(0.2f));

            if (RequestHelper.platformModeOn)
            {
                Application.ExternalCall("sendToFlash", requestModel.functionName, requestModel.cvo.getJsonData());
            }
            else
            {
                //verifico se a request foi cadastrada
                if (_currentRequestModel is GetMinigameRankingRM == false && _currentRequestModel is GetPlatformDataRM == false &&
                    _currentRequestModel is GetPlayerHistoryRM == false && _currentRequestModel is SavePlayerScoreRM == false)
                {
                    string error = "Request not registered";
                    Debug.LogError(this.GetType() + error);
                    OnRequestError(error);
                }
                else
                {
                    if (_currentRequestModel is GetMinigameRankingRM)
                    {
                        OnRequestError("Request available only for minigames integrated with the platform");
                    }
                    else if (_currentRequestModel is GetPlatformDataRM)
                    {
                        OnRequestSuccess("{" +
                                         createField("idUser", "-1", true) +
                                         createField("idMinigame", "-1", true) +
                                         createField("nickName", "null", true) +
                                         createField("firstName", "null", true) +
                                         createField("lastName", "null", true) +
                                         createField("grade", "-1", true) +
                                         createField("backendUrl", "null", true) +
                                         createField("minigameFolder", ExternalResources.getInstance().getResourcesPath() + "../", false) +
                                         "}");
                    }
                    else if (_currentRequestModel is GetPlayerHistoryRM)
                    {
                        OnRequestSuccess(LocalDataManager.getPlayerHistoryJson());
                    }
                    else if (_currentRequestModel is SavePlayerScoreRM)
                    {
                        LocalDataManager.savePlayerScore((_currentRequestModel as SavePlayerScoreRM).cvo);
                        OnRequestSuccess("{}");
                    }
                }
            }
        }
Ejemplo n.º 17
0
 private static void setupRequest(BaseRequestModel __r,
                                  RequestHelper.RequestHandlerDelegate __callbackRequestCompleted = null,
                                  RequestHelper.RequestHandlerDelegate __callbackRequestError     = null,
                                  RequestHelper.RequestHandlerDelegate __callbackRequestStarted   = null,
                                  RequestHelper.RequestHandlerDelegate __callbackRequestFinalized = null)
 {
     __r.callbackRequestCompleted += __callbackRequestCompleted;
     __r.callbackRequestError     += __callbackRequestError;
     __r.callbackRequestStarted   += __callbackRequestStarted;
     __r.callbackRequestFinalized += __callbackRequestFinalized;
     ExternalCommunicator.instance.addRequest(__r);
 }
Ejemplo n.º 18
0
 private void tryCallNextResquest()
 {
     if (_requestList.Count > 0 && _currentRequestModel == null)
     {
         BaseRequestModel requestModel = _requestList[0] as BaseRequestModel;
         if (requestModel.requestInProgress == false)
         {
             //torna a chamada assincrona
             StartCoroutine(startRequest(requestModel));
             _requestList.RemoveAt(0);
         }
     }
 }
Ejemplo n.º 19
0
        private IEnumerator _getAuthCode(string scopes, OnAuthCodeCompleted complete = null, OnAuthCodeError error = null)
        {
            string _url = _oauth_uri + "get_auth_code?"; // Get Auth Code

            _url += "scope=" + scopes;                   // Set Scopes
            _url += "&client_id=" + application.app_id;  // Set Application ID
            var request = new WWW(_url);                 // Create WWW Request

            yield return(request);                       // Send Request

            // Work with Response
            if (request.error != null)  // Request has error
            {
                throw new Exception("Не удалось отправить запрос к серверу VK API. Проверьте соединение с интернетом и попробуйте снова.");
            }
            else                             // No Errors
            {
                if (request.text.Length < 1) // Error
                {
                    BaseErrorModel _error = new BaseErrorModel();
                    _error.error_code = 999;
                    _error.error_msg  = "Не удалось получить код авторизации VK API. Попробуйте изменить ваш запрос.";
                    error(_error);                                                                     // Call Error
                }
                else                                                                                   // All Right
                {
                    BaseRequestModel response = JsonUtility.FromJson <BaseRequestModel>(request.text); // Get Base Model from Response Text
                    if (response.error.error_code == -1)                                               // Response not has an errors
                    {
                        AuthCodeModel auth_code = JsonUtility.FromJson <AuthCodeModel>(request.text);  // Get Authentication Model from Response
                        if (complete != null)
                        {
                            complete(auth_code);                   // Return Complete
                        }
                    }
                    else     // Reponse has errors
                    {
                        if (error != null)
                        {
                            error(response.error);                // Show Error
                        }
                        if (settings.debug_mode)
                        {
                            Debug.Log("VK SDK Error: " + response.error.error_msg);
                        }
                    }
                }
            }
        }
Ejemplo n.º 20
0
        public async Task <IActionResult> Deactivate(BaseRequestModel model)
        {
            if (model.Id == default(long))
            {
                throw new BadRequestException("Invalid Permission");
            }
            var result = await _businessAccountMgr.Deactivate(model.Id);

            return(Ok(new ResponseModel <bool>
            {
                RequestSuccessful = true,
                ResponseCode = ResponseCodes.Successful,
                ResponseData = result
            }));
        }
Ejemplo n.º 21
0
 public BaseRequest(string apptoken, string appkey, TReqModel reqModel)
 {
     req          = new BaseRequestModel();
     ecClient     = new EcClient();
     req.appKey   = appkey;
     req.appToken = apptoken;
     try
     {
         req.paramsJson = JsonConvert.SerializeObject(reqModel);;
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Ejemplo n.º 22
0
        protected void RemoveWatermarkButton_Click(object sender, EventArgs e)
        {
            UploadFile((file) =>
            {
                BaseRequestModel baseRequestModel = new BaseRequestModel();
                baseRequestModel.id       = FolderNameHidden.Value;
                baseRequestModel.FileName = FileNameHidden.Value;



                var response           = asposeSlides.RemoveWatermark(baseRequestModel);
                SuccessLabel.InnerText = Resources["WatermarkRemovedSuccessMessage"];
                PerformResponse(response, WatermarkMessage, ShowDownloadPage);
            }, Guid.NewGuid().ToString());
        }
        public static KeyValuePair <string, string> SortParameter(this BaseRequestModel baseRequestModel, SortBy?sortBy, SortDirection direction)
        {
            if (IsNullableObject(sortBy))
            {
                return(NullKeyValuePair());
            }

            string sort = sortBy.ToString();

            if (direction == SortDirection.Descending)
            {
                sort = "-" + sort;
            }

            return(new KeyValuePair <string, string>("sort", sort));
        }
Ejemplo n.º 24
0
        public Dictionary <string, string> Process(BaseRequestModel model, UserBaseModel user, SocketHelper mySocket, Dictionary <string, string> data)
        {
            var thisModel = model.ToModel <PingModelRequest>();

            Console.WriteLine($"user float from ping {thisModel.Ping}");
            //Send ping return to client.
            var responseModel = BaseResponseModel.Model <PingModelResponse>((ushort)MyResponseFlag.Ping);

            responseModel.msg  = "abrakadabra";
            responseModel.Ping = thisModel.Ping;

            Console.WriteLine($"Received ping from {user.Name}");
            mySocket.SendMessage(responseModel);

            return(data);
        }
Ejemplo n.º 25
0
        public ActionResult Index(BaseRequestModel request)
        {
            //var testAsync = new AsyncTest();
            //testAsync.Test();
            //HomeService.testhttpcontext(this.HttpContext);

            request.MHString = MvcHtmlString.Create("<strong>strong</strong>");


            ViewData.Model = request;
            return(new ViewResult()
            {
                ViewName = "Test/Index1",
                ViewData = ViewData
            });
        }
Ejemplo n.º 26
0
        public void Handle(BaseRequestModel model, UserModel user, SocketHelper socket)
        {
            Dictionary <string, string> data = new Dictionary <string, string>();

            var handled = Invoke(model, user, socket, data);

            foreach (var disp in slavesDispatchers.Values.Where(x => x.IsEnabled))
            {
                //Logger.Debug($"{Name} dispatcher is proccessing");
                handled = disp.Invoke(model, user, socket, data);
            }

            if (!handled)
            {
                if (Handlers.TryGetValue((ushort)RequestFlag.Unhandled, out List <IHandler> hList))
                {
                    //var unhandled = new Unhandled();
                    //unhandled.Process(model, user, socket, data);
                    bool isStop = false;
                    hList.ForEach(x =>
                    {
                        try
                        {
                            if (!isStop)
                            {
                                //Logger.Debug($"Processing {x.GetType().Name}");
                                x.Process(model, user, socket, data);
                            }
                        }
                        catch (CancelHandlerException)
                        {
                            Logger.Debug($"{x.GetType().Name} skipped");
                        }
                        catch (StopProcessingException)
                        {
                            isStop = true;
                            Logger.Debug($"Invoking handlers stopped by {x.GetType().Name}");
                        }
                        catch (Exception ex)
                        {
                            Logger.Error(ex, "Error while invoking handlers");
                        }
                    });
                }
            }
        }
        public Dictionary <string, string> Process(BaseRequestModel model, UserBaseModel user, SocketHelper mySocket, Dictionary <string, string> data)
        {
            var thisModel = model.ToModel <NewConnectionModelRequest>();

            //Update client information.
            user.IpAddress = mySocket.MscClient.Client.RemoteEndPoint.ToString();
            user.Name      = thisModel.Name;

            //Console Message.
            Console.WriteLine(user.IpAddress + $" connected. Name: {thisModel.Name}");
            Console.WriteLine(Convert.ToString(mySocket.ParentServer.Clients.Count) + " clients online.");

            var resp = BaseResponseModel.Model <PlayersCountModelResponse>((ushort)MyResponseFlag.PlayersCount);

            resp.Count = mySocket.ParentServer.Clients.Count;

            mySocket.SendMessageToAll(resp);

            return(data);
        }
Ejemplo n.º 28
0
        public Dictionary <string, string> Process(BaseRequestModel model, UserBaseModel user, SocketHelper mySocket, Dictionary <string, string> data)
        {
            var this_model = model.ToModel <LogModelRequest>();

            foreach (var i in this_model.msg)
            {
                Console.WriteLine("msg is:" + i);
            }

            var resp = BaseResponseModel.Model <LogModelResponse>((ushort)MyResponseFlag.LogResponse);

            resp.msg = new List <string>()
            {
                "qwe", "asd"
            };                                             //mySocket.ParentServer.Clients.Count;

            mySocket.SendMessage(resp);

            return(data);
        }
Ejemplo n.º 29
0
        private async Task <T> RequestAsync <T>(string category, string action, BaseRequestModel requestModel)
        {
            using (NoKeepAlivesWebClient WC = new NoKeepAlivesWebClient())
            {
                WC.Proxy = null;

                var Serializer = new JavaScriptSerializer();

                requestModel.api_id         = _APIId;
                requestModel.api_partialkey = _APIKey.Substring(0, 64);
                string ModelData = Serializer.Serialize(requestModel);

                int    Nonce     = (int)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; // https://dzone.com/articles/get-unix-epoch-time-one-line-c
                string Signature = hash_hmac_sha512($"{category}/{action}/|{ModelData}|{Nonce.ToString()}", _APIKey);
                NameValueCollection RequestData = new NameValueCollection()
                {
                    { "req", ModelData },
                    { "signature", Signature },
                    { "nonce", Nonce.ToString() }
                };

                Uri    RequestUrl   = new Uri(DYNAMIC_URL.Replace("{CATEGORY}", category).Replace("{ACTION}", action));
                string ResponseText = Encoding.UTF8.GetString(await WC.UploadValuesTaskAsync(RequestUrl, "POST", RequestData));

                //if (Debugger.IsAttached)
                //{
                //    string LogFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lndapi.log");
                //    File.AppendAllText(LogFilename, $"{category}/{action}{Environment.NewLine}{ModelData}{Environment.NewLine}{ResponseText}{Environment.NewLine}{Environment.NewLine}");
                //}

                BaseResponseModel BRM = Serializer.Deserialize <BaseResponseModel>(ResponseText);
                if (BRM.success == "yes")
                {
                    return(Serializer.Deserialize <T>(ResponseText));
                }
                else
                {
                    throw new LNDException(BRM.error);
                }
            }
        }
Ejemplo n.º 30
0
        private bool InvokeHandlers(BaseRequestModel model, UserModel user, SocketHelper socket, Dictionary <string, string> data)
        {
            var handled = false;

            if (Handlers.TryGetValue(model.Flag, out List <IHandler> hList))
            {
                handled = true;
                bool isStop = false;
                hList.ForEach(x =>
                {
                    try
                    {
                        if (!isStop)
                        {
                            //Logger.Debug($"Processing {x.GetType().Name}");
                            x.Process(model, user, socket, data);
                        }
                    }
                    catch (CancelHandlerException)
                    {
                        Logger.Debug($"{x.GetType().Name} skipped");
                    }
                    catch (StopProcessingException)
                    {
                        isStop = true;
                        Logger.Debug($"Invoking handlers stopped by {x.GetType().Name}");
                    }
                    catch (Exception ex)
                    {
                        Logger.Error(ex, "Error while invoking handlers");
                    }
                });
            }

            /*else
             * {
             *  var unhandled = new Unhandled();
             *  unhandled.Process(model, user, socket, data);
             * }*/
            return(handled);
        }