Exemple #1
0
        private List <IGenreCategory> RetrieveGenreCategories()
        {
            var result = new List <IGenreCategory>();

            try
            {
                var retrieveGenreStationsRequest = new JSONRequest(MethodNames.station_getGenreStations, false, RequiredInfo);
                var res = new JSONResult(retrieveGenreStationsRequest.StringRequestAsync().Result);

                if (res.IsFault)
                {
                    Messenger.Default.Send(new FaultMessage(res.Fault.Message));
                    return(null);
                }

                var data = res.Result;
                //GenreStationsChecksum = data["checksum"].ToString();
                foreach (var station in data["categories"])
                {
                    result.Add(StationFactory.CreateGenreCategory(RequiredInfo, station));
                }
            }
            catch (Exception ex)
            {
                Messenger.Default.Send(new FaultMessage(ex.Message, ex));
                return(null);
            }

            return(result);
        }
Exemple #2
0
        public JsonResult CreateDeposit(CreateDepositModel model)
        {
            var result = new JSONResult();

            try
            {
                var userId         = AuthWrapper.GetUserIdByLogin(User.Identity.Name);
                var availableMoney = DataWrapper.AvailableMoneyByUserId(userId);

                if ((availableMoney < model.DepositAmount) || (model.DepositAmount < MIN_AMOUNT || model.DepositAmount > MAX_AMOUNT))
                {
                    if (availableMoney < model.DepositAmount)
                    {
                        result.SetNotSuccess(ErrorMessages.NotEnoughMoney);
                    }
                    else
                    {
                        result.SetNotSuccess(ErrorMessages.IncorrectAmount);
                    }
                }
                else
                {
                    var currentDate = DateTime.Now;
                    var percent     = model.Rate == Rates.Month ? ProfitValue.HighPercent : ProfitValue.BasePercent;
                    model.Rate = model.Rate == Rates.Unknown ? Rates.OneDay : model.Rate;

                    var deposit = new Deposit()
                    {
                        UserId        = userId,
                        StartDate     = currentDate,
                        EndDate       = currentDate.AddDays((int)model.Rate),
                        Percent       = percent,
                        StartAmount   = model.DepositAmount,
                        InterimAmount = model.DepositAmount,
                        EndAmount     = model.DepositAmount + (model.DepositAmount * percent / 100.0) * (int)model.Rate,
                        Status        = StatusDeposit.Active
                    };

                    var successAddNewDeposit = DataWrapper.AddNewDeposit(deposit);
                    var successTakeAmount    = DataWrapper.TakeMoneyByUserId(userId, model.DepositAmount);
                    var newBalanceUser       = DataWrapper.AvailableMoneyByUserId(userId);

                    if (successAddNewDeposit && successTakeAmount)
                    {
                        result.SetIsSuccess(newBalanceUser);
                    }
                    else
                    {
                        result.SetNotSuccess(ErrorMessages.UnknownError);
                    }
                }
            }
            catch (Exception ex)
            {
                result.SetNotSuccess(ErrorMessages.UnknownError);
                logger.Error("Method CreateDeposit: ", ex);
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Exemple #3
0
        public JsonResult Registration(RegistrationModel model)
        {
            JSONResult accountResult = new JSONResult();

            try
            {
                if (ModelState.IsValid && model.IsValid())
                {
                    if (!AuthWrapper.UserExist(model.PhoneNumber))
                    {
                        var newUser = new User
                        {
                            FirstName        = model.FirstName,
                            SecondName       = model.SecondName,
                            PhoneNumber      = model.PhoneNumber,
                            Password         = model.Password,
                            RegistrationDate = DateTime.Now
                        };

                        var isSaveUser = AuthWrapper.AddNewUser(newUser);

                        if (isSaveUser)
                        {
                            var userId = AuthWrapper.GetUserIdByLogin(model.PhoneNumber);

                            DataWrapper.AddCashUser(userId);
                            FormsAuthentication.SetAuthCookie(model.PhoneNumber, true);
                            accountResult.SetIsSuccess(GetUrlRedirect(model.PhoneNumber));
                        }
                        else
                        {
                            accountResult.SetNotSuccess(ErrorMessages.UnknownError);
                        }
                    }
                    else
                    {
                        accountResult.SetNotSuccess(ErrorMessages.ExistentPhoneNumber);
                    }
                }
                else
                {
                    if (!model.IsValid())
                    {
                        accountResult.SetNotSuccess(ErrorMessages.NotFullDataRegistration);
                    }
                    else
                    {
                        accountResult.SetNotSuccess(ErrorMessages.UnknownError);
                    }
                }
            }
            catch (Exception ex)
            {
                accountResult.SetNotSuccess(ErrorMessages.UnknownError);
                logger.Error("Method Registration: ", ex);
            }

            return(Json(accountResult, JsonRequestBehavior.AllowGet));
        }
Exemple #4
0
        public async Task <JSONResult <string> > CodeUserLogin([FromBody]  LoginParameter obj)
        {
            return(await Task.Run(() =>
            {
                return new BaseJsonResult().UnifiedFucn(() =>
                {
                    var model = new JSONResult <string>();
                    if (obj == null)
                    {
                        model.ret = 1;
                        model.Result = "参数错误,填写参数";
                        model.Content = "登录失败";
                        return model;
                    }
                    if (obj.LoginName == null || obj.LoginName == "")
                    {
                        model.ret = 1;
                        model.Result = "登录名不能为空";
                        model.Content = "登录失败";
                        return model;
                    }
                    if (obj.passWord == null || obj.passWord == "")
                    {
                        model.ret = 1;
                        model.Result = "密码不能为空";
                        model.Content = "登录失败";
                        return model;
                    }
                    var Model = new mb_UserService().GetUserLogin(obj.LoginName);

                    if (Model != null)
                    {
                        string UserKey = Md5.md5(obj.passWord, 32) + Md5.md5(Model.UserKeyStr, 32);
                        if (UserKey.Equals(Model.UserKey))
                        {
                            model.ret = 0;
                            model.Result = "登录成功";
                            model.Content = "登录成功";
                        }
                        else
                        {
                            model.ret = 2;
                            model.Result = "密码错误";
                            model.Content = "登录失败";
                        }
                    }
                    else
                    {
                        model.ret = 5;
                        model.Result = "不存在该用户";
                        model.Content = "登录失败";
                    }
                    return model;
                });
            }));
        }
Exemple #5
0
        public JSONResult DeleteUser([FromBody] User user)
        {
            int row = _userService.DeleteUser(user.Id);

            if (row == 0)
            {
                return(JSONResult.ErrorMsg(""));
            }
            return(JSONResult.Ok());
        }
        public JSONResult ToJSONResult()
        {
            JSONResult JSONResult = new JSONResult();

            JSONResult.IsPassed       = this.IsPassed;
            JSONResult.ReturnedObject = this.ReturnedObject;
            JSONResult.Message.Text   = this.Code.Message();
            JSONResult.Message.Type   = JSONResult.IsPassed ? ResultMessageType.Success.ToString() : ResultMessageType.Warning.ToString();

            return(JSONResult);
        }
 protected virtual void GetAll()
 {
     this.ShowSpinner();
     this.service.GetAll().then(p =>
     {
         JSONResult <T> res = p;
         this.scope.list    = res.DataList;
         this.ShowMessage(res.IsSuccess, res.Message);
         this.HideSpinner();
     });
 }
 public virtual void Update(T data)
 {
     this.ShowSpinner();
     this.service.Update(data).then(p =>
     {
         JSONResult <T> res = p;
         this.scope.message = res.Message;
         this.ShowMessage(res.IsSuccess, res.Message);
         this.HideSpinner();
         this.scope.isGrid = false;
     });
 }
Exemple #9
0
 /// <summary>
 /// We should receive the temperature from sever in the response
 /// </summary>
 /// <param name="coapResp">CoAPResponse</param>
 private static void OnCoAPResponseReceived(CoAPResponse coapResp)
 {
     if (coapResp.MessageType.Value == CoAPMessageType.ACK &&
         coapResp.Code.Value == CoAPMessageCode.CONTENT)
     {
         //We got the temperature..it will be in payload in JSON
         string    payload = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value);
         Hashtable keyVal  = JSONResult.FromJSON(payload);
         int       temp    = Convert.ToInt32(keyVal["temp"].ToString());
         //do something with the temperature now
     }
 }
 public virtual void Delete(T data)
 {
     this.ShowSpinner();
     this.service.Delete(data).then(p =>
     {
         this.OnAfterDeleted(data);
         JSONResult <T> res = p;
         this.scope.message = res.Message;
         this.ShowMessage(res.IsSuccess, res.Message);
         this.HideSpinner();
     });
 }
 public virtual void Insert(T data)
 {
     this.ShowSpinner();
     this.service.Insert(data).then(p =>
     {
         JSONResult <T> res = p;
         this.scope.message = res.Message;
         this.ShowMessage(res.IsSuccess, res.Message);
         this.HideSpinner();
         this.scope.isGrid = false;
         this.scope.list.Add(this.OnBeforeAddInList(res.DataObject));
     });
 }
Exemple #12
0
        public JSONResult Register([FromBody] User user)
        {
            if (user == null)
            {
                return(JSONResult.ErrorMsg("注册失败"));
            }
            int row = _userService.SaveUser(user);

            if (row == 0)
            {
                return(JSONResult.ErrorMsg("注册失败."));
            }
            return(JSONResult.Ok());
        }
Exemple #13
0
        //单用户登录
        private void CheckUserSingle(HttpActionContext actionContext, bool IsCheckUser)
        {
            if (IsCheckUser == false)
            {
                return;
            }
            else //单用户登录校验
            {
                try
                {
                    //如果是后台管理请求的数据则直接跳过 不做单用户校验
                    var CheckAdminNoUserSingle = actionContext.Request.Headers.GetValues("AdminNoUserSingle");
                    if (CheckAdminNoUserSingle != null)
                    {
                        return;
                    }
                }
                catch (Exception ex)
                {
                }

                var httpContext = HttpContext.Current;
                var json        = new JSONResult <string>();
                json.Result = "单用户登录";
                json.ret    = 3;

                if (actionContext.Request.Headers.Authorization == null)
                {
                    actionContext.Response = new System.Net.Http.HttpResponseMessage()
                    {
                        Content = new System.Net.Http.StringContent(ConvertJson.ToJson(json)),

                        StatusCode = System.Net.HttpStatusCode.Unauthorized
                    };
                    return;
                }

                var HeadersToken = actionContext.Request.Headers.Authorization.Parameter;
                var token        = _redis.HashGet <string>(RedisGroup.SingleUserGroup, HeadersToken);
                if (token == null || token == "" || token == "null")
                {
                    actionContext.Response = new System.Net.Http.HttpResponseMessage()
                    {
                        Content    = new System.Net.Http.StringContent(ConvertJson.ToJson(json)),
                        StatusCode = System.Net.HttpStatusCode.Unauthorized
                    };
                }
            }
        }
 protected virtual void GetPagedWhile(T data)
 {
     this.ShowSpinner();
     this.service.GetPagedWhile(this.pageNo, this.pageSize, data).then(p =>
     {
         JSONResult <T> res             = p;
         this.scope.gridOpts.totalItems = res.TotalRow;
         this.scope.message             = res.Message;
         if (isValid(res.DataList))
         {
             this.scope.list = this.OnPreLoadGrid(res.DataList);
         }
         this.ShowMessage(res.IsSuccess, res.Message);
         this.HideSpinner();
     });
 }
Exemple #15
0
        public async Task <JSONResult <string> > CodeUserLogin()
        {
            return(await Task.Run(() =>
            {
                return new BaseJsonResult().UnifiedFucn(() =>
                {
                    var model = new JSONResult <string>();

                    var Model = new mb_UserService().GetUserLogin("lrb");

                    model.Result = Model.CheckTime + Model.UserName + Model.QQ;

                    return model;
                });
            }));
        }
        public JSONResult Check([FromBody] Poll poll)
        {
            if (poll == null)
            {
                return(JSONResult.ErrorMsg(""));
            }
            User user = HttpContext.Session.Get <User>("user");

            poll.Uid = user.Id;
            bool flag = _pollService.CheckPoll(poll);

            if (flag)
            {
                return(JSONResult.ErrorMsg(""));
            }
            return(JSONResult.Ok());
        }
        public ActionResult Save(string chartType, string jsonVal)
        {
            JSONResult result = new JSONResult();

            if (iChart.Save(chartType, jsonVal) > 0)
            {
                result.Code    = "1";
                result.Message = SuccessMessage;
            }
            else
            {
                result.Code    = "0";
                result.Message = ErrorMessage;
            }

            return(Json(result));
        }
        public JSONResult Add([FromBody] Poll poll)
        {
            if (poll == null)
            {
                return(JSONResult.ErrorMsg("投票失败"));
            }
            User user = HttpContext.Session.Get <User>("user");

            poll.Uid = user.Id;
            Console.WriteLine(poll.Uid + " " + poll.Vid + "  " + poll.Oids[0]);
            int row = _pollService.SavePoll(poll);

            if (row == 0)
            {
                return(JSONResult.ErrorMsg("投票失败."));
            }
            return(JSONResult.Ok());
        }
        public ActionResult Remove(int id)
        {
            int        rows   = iProj.RemoveKBProjectById(id);
            JSONResult result = new JSONResult();

            if (rows > 0)
            {
                result.Message = SuccessMessage;
                result.Code    = "1";
            }
            else
            {
                result.Message = ErrorMessage;
                result.Code    = "0";
            }

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Exemple #20
0
        public JsonResult ChangeNotifySetting(NotificationMessageModel model)
        {
            var result = new JSONResult();

            try
            {
                var userId = AuthWrapper.GetUserIdByLogin(User.Identity.Name);
                model.UserId = userId;

                DataWrapper.AddOrUpdateNotification(model);
            }
            catch (Exception ex)
            {
                result.SetNotSuccess(ErrorMessages.UnknownError);
                logger.Error("Method ChangeNotifySetting: ", ex);
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
        public JSONResult login([FromBody] User user)
        {
            if (user.Username.Length == 0 || user.Password.Length == 0)
            {
                return(JSONResult.ErrorMsg(""));
            }
            SessionUser suser = _userService.CheckUser(user.Username, user.Password);

            if (suser == null)
            {
                return(JSONResult.ErrorMsg("用户名或密码错误"));
            }
            HttpContext.Session.Set("user", suser);
            if (suser.Type == true)
            {
                return(JSONResult.Ok(true));
            }
            return(JSONResult.Ok(false));
        }
 public async Task <JSONResult <DetailData> > GetGoodData([FromBody] int ID)
 {
     return(await Task.Run(() =>
     {
         return new BaseJsonResult().UnifiedFucn(() =>
         {
             var model = new JSONResult <DetailData>();
             model.Success = true;
             DetailData data = new DetailData()
             {
                 ID = ID, favorite = true, imgList = "测试", title = "纯种金毛幼犬活体有血统证书", title2 = "拆家小能手 你值得拥有"
             };
             model.ret = 0;
             model.Result = "请求成功";
             model.Content = data;
             return model;
         });
     }));
 }
        public ActionResult CreateURL(int id)
        {
            int          rows      = 0;
            RandomString randomStr = new RandomString();
            JSONResult   result    = new JSONResult();
            KBProject    project   = new KBProject();

            project.ProjectId = id;

            string val;
            string url = iProj.GetUrlById(project);

            if (string.IsNullOrEmpty(url))
            {
                val         = randomStr.GetRandomString();
                project.Url = val;

                try
                {
                    rows           = iProj.UpdateUrlById(project);
                    result.Code    = "0";
                    result.Message = project.Url;
                }
                catch (Exception err)
                {
                    result.Code    = "-1";
                    result.Message = err.Message;
                }
            }
            else
            {
                result.Code    = "0";
                result.Message = url;
            }

            result.ResponseData = string.Format("http://{0}{1}{2}",
                                                Request.Url.Authority,
                                                System.Web.Configuration.WebConfigurationManager.AppSettings["URL"],
                                                url);

            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Exemple #24
0
 /// <summary>
 /// Going forward, we will receive temperature notifications from
 /// server in a CON request
 /// </summary>
 /// <param name="coapReq">CoAPRequest</param>
 static void OnCoAPRequestReceived(CoAPRequest coapReq)
 {
     if (coapReq.MessageType.Value == CoAPMessageType.CON)
     {
         //Extract the temperature..but first, check if the notification is fresh
         //The server sends a 4-digit sequence number
         int newObsSeq = AbstractByteUtils.ToUInt16(coapReq.Options.GetOption(CoAPHeaderOption.OBSERVE).Value);
         if ((lastObsSeq < newObsSeq && ((newObsSeq - lastObsSeq) < (System.Math.Pow(2.0, 23.0)))) ||
             (lastObsSeq > newObsSeq && ((lastObsSeq - newObsSeq) > (System.Math.Pow(2.0, 23.0)))) ||
             DateTime.Today > lastObsRx.AddSeconds(128))
         {
             //The value received from server is new....read the new temperature
             //We got the temperature..it will be in payload in JSON
             string    payload = AbstractByteUtils.ByteToStringUTF8(coapReq.Payload.Value);
             Hashtable keyVal  = JSONResult.FromJSON(payload);
             int       temp    = Convert.ToInt32(keyVal["temp"].ToString());
             //do something with the temperature now
             Debug.WriteLine(coapReq.ToString());
         }
         //update how many notifications received
         countOfNotifications++;
         if (countOfNotifications > 5)
         {
             //We are no longer interested...send RST to de-register
             CoAPResponse resp = new CoAPResponse(CoAPMessageType.RST, CoAPMessageCode.EMPTY, coapReq.ID.Value);
             resp.RemoteSender = coapReq.RemoteSender;
             resp.Token        = coapReq.Token;//Do not forget this...this is how messages are correlated
             coapClient.Send(resp);
         }
         else
         {
             //we are still interested...send ACK
             CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK, CoAPMessageCode.EMPTY, coapReq.ID.Value);
             resp.RemoteSender = coapReq.RemoteSender;
             resp.Token        = coapReq.Token;//Do not forget this...this is how messages are correlated
             coapClient.Send(resp);
         }
         lastObsSeq = newObsSeq;
         lastObsRx  = DateTime.Today;
     }
 }
Exemple #25
0
        /// <summary>
        /// Called when a CoAP request is received...we will only support CON requests
        /// of type GET... the path is sensors/temp
        /// </summary>
        /// <param name="coapReq">CoAPRequest object</param>
        private static void OnCoAPRequestReceived(CoAPRequest coapReq)
        {
            string reqPath = (coapReq.GetPath() != null) ? coapReq.GetPath().ToLower() : "";

            if (coapReq.MessageType.Value == CoAPMessageType.CON)
            {
                if (coapReq.Code.Value != CoAPMessageCode.GET)
                {
                    CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK,
                                                         CoAPMessageCode.METHOD_NOT_ALLOWED,
                                                         coapReq /*Copy all necessary values from request in the response*/);
                    //When you use the constructor that accepts a request, then automatically
                    //the message id , token and remote sender values are copied over to the response
                    coapServer.Send(resp);
                }
                else if (reqPath != "sensors/temp")
                {
                    //We do not understand this..
                    CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK,
                                                         CoAPMessageCode.NOT_FOUND,
                                                         coapReq /*Copy all necessary values from request in the response*/);
                    coapServer.Send(resp);
                }
                else
                {
                    Debug.WriteLine(coapReq.ToString());
                    CoAPResponse resp = new CoAPResponse(CoAPMessageType.ACK,
                                                         CoAPMessageCode.CONTENT,
                                                         coapReq /*Copy all necessary values from request in the response*/);
                    //The payload will be JSON
                    Hashtable ht = new Hashtable();
                    ht.Add("temp", GetRoomTemperature());
                    string jsonStr = JSONResult.ToJSON(ht);
                    resp.AddPayload(jsonStr);
                    //Tell recipient about the content-type of the response
                    resp.AddOption(CoAPHeaderOption.CONTENT_FORMAT, AbstractByteUtils.GetBytes(CoAPContentFormatOption.APPLICATION_JSON));
                    //send it
                    coapServer.Send(resp);
                }
            }
        }
        /// <summary>
        /// Called when a response is received against a sent request
        /// </summary>
        /// <param name="coapResp">The CoAPResponse object</param>
        static void OnCoAPResponseReceived(CoAPResponse coapResp)
        {
            string tokenRx = (coapResp.Token != null && coapResp.Token.Value != null) ? AbstractByteUtils.ByteToStringUTF8(coapResp.Token.Value) : "";

            if (tokenRx == _mToken)
            {
                //This response is against the NON request for getting temperature we issued earlier
                if (coapResp.Code.Value == CoAPMessageCode.CONTENT)
                {
                    //Get the temperature
                    string    tempAsJSON = AbstractByteUtils.ByteToStringUTF8(coapResp.Payload.Value);
                    Hashtable tempValues = JSONResult.FromJSON(tempAsJSON);
                    int       temp       = Convert.ToInt32(tempValues["temp"].ToString());
                    //Now do something with this temperature received from the server
                }
                else
                {
                    //Will come here if an error occurred..
                }
            }
        }
Exemple #27
0
        public JsonResult Login(LoginModel model)
        {
            JSONResult accountResult = new JSONResult();

            try
            {
                if (ModelState.IsValid && model.IsValid())
                {
                    if (AuthWrapper.LoginUser(model.PhoneNumber, model.Password))
                    {
                        FormsAuthentication.SetAuthCookie(model.PhoneNumber, true);

                        accountResult.SetIsSuccess(GetUrlRedirect(model.PhoneNumber));
                    }
                    else
                    {
                        accountResult.SetNotSuccess(ErrorMessages.NotValidAuthData);
                    }
                }
                else
                {
                    if (!model.IsValid())
                    {
                        accountResult.SetNotSuccess(ErrorMessages.NotFullDataLogin);
                    }
                    else
                    {
                        accountResult.SetNotSuccess(ErrorMessages.UnknownError);
                    }
                }
            }
            catch (Exception ex)
            {
                accountResult.SetNotSuccess(ErrorMessages.UnknownError);
                logger.Error("Method Login: ", ex);
            }
            return(Json(accountResult, JsonRequestBehavior.AllowGet));
        }
Exemple #28
0
        private IEnumerable <ITrack> RetrievePlaylist(string stationToken)
        {
            var result = new List <ITrack>();

            try
            {
                var retrievePlaylistRequest = new JSONRequest(
                    MethodNames.station_getPlaylist,
                    false,
                    RequiredInfo,
                    new KeyValuePair <string, object>("stationToken", stationToken));
                var res = new JSONResult(retrievePlaylistRequest.StringRequestAsync().Result);

                if (res.IsFault)
                {
                    Messenger.Default.Send(new FaultMessage(res.Fault.Message));
                    return(null);
                }

                var data = res.Result;
                foreach (var item in data["items"])
                {
                    if (item["songName"] == null)
                    {
                        continue;
                    }

                    result.Add(TrackFactory.CreateTrack(RequiredInfo, item));
                }
            }
            catch (Exception ex)
            {
                Messenger.Default.Send(new FaultMessage(ex.Message, ex));
                return(null);
            }

            return(result);
        }
Exemple #29
0
        public JSONResult DeleteUsers([FromBody] List <User> users)
        {
            string delStr = "(";
            int    len    = users.Count();

            for (int i = 0; i < len; i++)
            {
                if (i != 0)
                {
                    delStr += ',';
                }
                delStr += users[i].Id;
            }
            delStr += ')';
            Console.WriteLine(delStr);
            int row = _userService.DeleteUsers(delStr);

            if (row == 0)
            {
                return(JSONResult.ErrorMsg(""));
            }
            return(JSONResult.Ok());
        }
Exemple #30
0
        public override IJsonValue Evaluate(IJSONDocument document)
        {
            JSONResult result = (JSONResult)document;

            if (result != null)
            {
                IAggregation aggregation = result.GetAggregation(Name);
                if (aggregation != null)
                {
                    FieldDataType dataType = JSONType.GetJSONType(aggregation.Value);
                    switch (dataType)
                    {
                    case FieldDataType.Number:
                        return(new NumberJsonValue(aggregation.Value));

                    case FieldDataType.String:
                        return(new StringJsonValue((string)aggregation.Value));

                    case FieldDataType.Null:
                        return(new NullValue());

                    case FieldDataType.Object:
                        return(new ObjectJsonValue((IJSONDocument)aggregation.Value));

                    case FieldDataType.DateTime:
                        return(new DateTimeJsonValue((DateTime)aggregation.Value));

                    case FieldDataType.Bool:
                        return(new BooleanJsonValue((bool)aggregation.Value));

                    case FieldDataType.Array:
                        return(new ArrayJsonValue((IJsonValue[])aggregation.Value));
                    }
                }
            }
            return(base.Evaluate(document));
        }
Exemple #31
0
        //Checks for fault returns.  If it's an Auth fault (auth timed out)
        //return false, which signals that a re-auth and retry needs to be done
        //otherwise return true signalling all clear.
        //All other faults will be thrown
        protected internal bool HandleFaults(JSONResult result, bool secondTry)
        {
            if (result.Fault)
            {
                if (result.FaultCode == ErrorCodes.INVALID_AUTH_TOKEN)
                    if (!secondTry)
                        return false; //auth fault, signal a re-auth

                Log.O("Fault: " + result.FaultString);
                throw new PandoraException(result.FaultCode); //other, throw the exception
            }

            return true; //no fault
        }
Exemple #32
0
        protected internal JSONResult CallRPC(string method, JObject request = null, 
                                          bool isAuth = false, bool useSSL = false)
        {
            string response = CallRPC_Internal(method, request, isAuth, useSSL);
            JSONResult result = new JSONResult(response);
            if (result.Fault)
            {
                if (!HandleFaults(result, false))
                {
                    Log.O("Reauth Required");
                    if (!AuthenticateUser())
                    {
                        HandleFaults(result, true);
                    }
                    else
                    {
                        response = CallRPC_Internal(method, request, isAuth, useSSL);
                        HandleFaults(result, true);
                    }
                }
            }

            return result;
        }