public void GetAgentCompanies(string SessionKey)
        {
            JSONHelper jhelper = new JSONHelper(Context);

            try
            {
                userKey = Authentication.ValidateKey(SessionKey);

                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);
            var query = (from C in dc.Companies
                         from P in dc.Provinces.Where(p => p.Index == C.Province).DefaultIfEmpty()
                         from O in dc.Countries.Where(o => o.Index == C.Country).DefaultIfEmpty()
                         where C.Type.ToUpper() == "A"
                         select new
                         {
                             ID = C.Index.ToString(),
                             C.Name,
                             C.Street1,
                             C.Street2,
                             C.City,
                             Province = C.Province.ToString(),
                             C.Postal,
                             Country = C.Country.ToString(),
                             C.Phone,
                             C.Fax,
                             C.EMail,
                             C.Twitter
                         }).Take(2000);

            // Log the query
            AddUsage("", query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                AgentCompanies = query.ToArray()
            };

            string result = JsonConvert.SerializeObject(wrapper);

            jhelper.WriteJSONResponse(result);
        }
Example #2
0
        //冻结锁和解冻锁
        //type 0 冻结锁   1 解冻锁
        public string freezeAndUnfreezeLock(string familyName, string type)
        {
            Dictionary <string, string> ret    = new Dictionary <string, string>();
            Dictionary <string, string> setRet = new Dictionary <string, string>();

            setRet.Add("appKey", appKey);
            setRet.Add("appSecret", appSecret);
            setRet.Add("familyName", familyName);
            setRet.Add("username", accountOpening);
            string url    = string.Empty;
            string menu   = string.Empty;
            string status = string.Empty;

            if (type == "1")
            {
                url    = unfreezeLockUrl;
                menu   = "解冻锁";
                status = "0";
            }
            else
            {
                url    = freezeLockUrl;
                menu   = "冻结锁";
                status = "3";
            }
            string getPostInfo = LigerRM.Common.WebRequestHelper.WebRequestPoster.JsonHttpPost(url, JSONHelper.ToJson(setRet), "parameters");  //调用远程
            Dictionary <string, object> returnInfo = new Dictionary <string, object>();

            returnInfo = JSONHelper.FromJson <Dictionary <string, object> >(getPostInfo);
            if (returnInfo["success"].ToString() == "True")
            {
                ret.Add("ret", "0");
                string sql = "update Rent_Locks set status='" + status + "' where DeviceID='" + familyName + "'";
                MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql));
            }
            else
            {
                ret.Add("ret", "1");
            }
            ret.Add("msg", returnInfo["msg"].ToString());
            AddLockNewLog(familyName, menu, returnInfo["msg"].ToString());   //增加新锁的log请求返回日志
            return(JSONHelper.ToJson(ret));
        }
Example #3
0
        public BasicResponse <KJ_AddresstypeInfo> GetKJ_AddresstypeById(Request.KJ_Addresstype.KJ_AddresstypeGetRequest kJ_AddresstypeRequest)
        {
            var responseStr = HttpClientHelper.Post(Webapi + "/v1/KJ_Addresstype/GetKJ_AddresstypeById?token=" + Token, JSONHelper.ToJSONString(kJ_AddresstypeRequest));

            return(JSONHelper.ParseJSONString <BasicResponse <KJ_AddresstypeInfo> >(responseStr));
        }
Example #4
0
        public Basic.Framework.Web.BasicResponse <System.Data.DataTable> GetDyxMac()
        {
            var responseStr = HttpClientHelper.Post(Webapi + "/v1/Control/GetDyxMac?token=" + Token, "");

            return(JSONHelper.ParseJSONString <BasicResponse <DataTable> >(responseStr));
        }
        public void GetGoalieStats(string SessionKey, string Filter)
        {
            JSONHelper jhelper = new JSONHelper(Context);

            try
            {
                userKey = Authentication.ValidateKey(SessionKey);

                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (string.IsNullOrEmpty(Filter))
            {
                jhelper.WriteJSONResponse("{'error':'No filter provided.'}", HttpStatusCode.Forbidden);
                AddUsage("Error: no filter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                return;
            }

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary object (default for an array shape)
            // THESE ARE THE FILTERS PROVIDED BY CALLER
            Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "playerid", null },
                { "seasonid", null },
                { "teamid", null },
            };

            // Check if any of the filters provided are bad.
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault();

            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);

            var query =
             from S in dc.Stats
             .Where(x => x.Goalie == true
                 && (filtersProcessed.Extract<int>("playerid") == null || filtersProcessed.Extract<int>("playerid") == x.Player)
                 && (filtersProcessed.Extract<int>("seasonid") == null || filtersProcessed.Extract<int>("seasonid") == x.Season)
                 && (filtersProcessed.Extract<int>("teamid") == null || filtersProcessed.Extract<int>("teamid") == x.Team)

                 )
                 .Take(2000)
             from G in dc.GoalieStats.Where(g => g.StatID == S.Index).DefaultIfEmpty()
             from E in dc.Seasons.Where(e => e.Index == S.Season).DefaultIfEmpty()
             from P in dc.Players.Where(p => p.Index == S.Player).DefaultIfEmpty()
             from O in dc.Positions.Where(o => o.Index == S.Position).DefaultIfEmpty()
             from T in dc.Teams.Where(t => t.Index == S.Team).DefaultIfEmpty()
             from U in dc.Tournaments.Where(u => u.Index == S.Tourn).DefaultIfEmpty()
             select new
             {
                 ID = S.Index.ToString(),
                 Season = E == null ? null : new { ID = E.Index.ToString(), Name = E.Name },
                 Player = P == null ? null : new { ID = P.Index.ToString(), Name = P.LastName + ", " + P.FirstName },
                 Position = O == null ? null : new { ID = O.Index.ToString(), O.Long },
                 Team = T == null ? null : new { ID = T.Index.ToString(), Name = T.LongName },
                 Tournament = U == null ? null : new
                 {
                     ID = U.Index.ToString(),
                     Name = U.Name,
                     IsPlayoff = U.Playoff
                 },
                 Jersey = S.Jersey,
                 PlayOffs = S.Playoffs,
                 StartDate = S.StartDate,
                 EndDate = S.EndDate,
                 Current = S.Current,
                 Notes = S.Notes,
                 Age = S.Age.ToString(),
                 GPI = G.GPI.ToString(),
                 Mins = G.Mins.ToString(),
                 GoalsAgainst = G.GA.ToString(),
                 ShootOuts = G.SO.ToString(),
                 Wins = G.Wins.ToString(),
                 Losses = G.Losses.ToString(),
                 SavePercentage = G.SVPct.ToString(),
                 GoalsAgainstAverage = G.Ave.ToString(),
                 OvertimeLosses = G.OTL.ToString(),
                 ShootOutLosses = G.SOL.ToString(),
                 ShootOutShotsAgainst = G.SoShots.ToString(),
                 ShootOutWins = G.SOW.ToString(),
                 ShootOutGoalsAgainst = G.SoGoals.ToString()
             };

            // Log the query
            AddUsage(Filter, query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                GoalieStats = query.ToArray()
            };

            string result = JsonConvert.SerializeObject(wrapper);

            jhelper.WriteJSONResponse(result);
        }
        public void GetAgents(string SessionKey, string Filter)
        {
            JSONHelper jhelper = new JSONHelper(Context);

            try
            {
                userKey = Authentication.ValidateKey(SessionKey);

                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (string.IsNullOrEmpty(Filter))
            {
                jhelper.WriteJSONResponse("{'error':'No filter provided.'}", HttpStatusCode.Forbidden);
                AddUsage("Error: no filter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                return;
            }

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary object (default for an array shape)
            // THESE ARE THE FILTERS PROVIDED BY CALLER
            Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "companyid", null }, // from getagentcompanies()
                { "agentid", null }
            };

            // Check if any of the filters provided are bad.
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault(); //filtersProvided.FirstOrDefault(x => !filtersAllowed.ContainsKey(x.Key)).Key;

            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            int? companyid = filtersProcessed.Extract<int>("companyid");
            int? agentid = filtersProcessed.Extract<int>("agentid");

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);
            var query = (
                from A in dc.Contacts
                from C in dc.Companies.Where(c => c.Index == A.Company).DefaultIfEmpty()
                where (A.Company == companyid || A.Index == agentid)
                select new
                {
                    ID = A.Index.ToString(),
                    Company = C == null ? null : new { ID = C.Index.ToString(), Name = C.Name },
                    A.Title,
                    A.FirstName,
                    A.LastName,
                    A.JobTitle,
                    A.Salutation,
                    A.Phone,
                    A.CellPhone,
                    A.Fax,
                    A.EMail,
                    A.LastUpDate
                }).Take(2000);

            // Log the query
            AddUsage(Filter, query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                Agents = query.ToArray()
            };

            string result = JsonConvert.SerializeObject(wrapper);

            jhelper.WriteJSONResponse(result);
        }
        public void GetInjuries(string SessionKey, string Filter)
        {
            JSONHelper jhelper = new JSONHelper(Context);
            try
            {
                userKey = Authentication.ValidateKey(SessionKey);
                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch
            {
                throw;
            }

            if (string.IsNullOrEmpty(Filter))
            {
                jhelper.WriteJSONResponse("{'error':'No filter provided.'}", HttpStatusCode.Forbidden);
                AddUsage("Error: no filter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                return;
            }

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary object (default for an array shape)
            // THESE ARE THE FILTERS PROVIDED BY CALLER
            //Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();

            Dictionary<string, object> filtersProvided = ser.Deserialize<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "teamids", null },
                { "playerids", null }
            };

            // Check if any of the filters provided are bad.
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault(); //filtersProvided.FirstOrDefault(x => !filtersAllowed.ContainsKey(x.Key)).Key;

            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            int[] teamids = filtersProcessed.ExtractArray<int>("teamids");
            int[] playerids = filtersProcessed.ExtractArray<int>("playerids");

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);
            var query = (from I in dc.Injuries
                         from P in dc.Players.Where(p => p.Index == I.Player).DefaultIfEmpty()
                         from T in dc.Teams.Where(t => t.Index == I.Team).DefaultIfEmpty()
                         from S in dc.Seasons.Where(s => s.Index == I.Season).DefaultIfEmpty()
                         from IT in dc.InjuryTypes.Where(it => it.Index == I.Nature).DefaultIfEmpty()

                         where (!playerids.Any() || playerids.Contains(I.Player.Value))
                                             && (!teamids.Any() || teamids.Contains(I.Team.Value))
                         select new
                                   {
                                       ID = I.Index.ToString(),
                                       Player = P == null ? null : new { ID = P.Index.ToString(), Name = P.LastName + ", " + P.FirstName },
                                       Team = T == null ? null : new { ID = T.Index.ToString(), Name = T.LongName },
                                       Season = S == null ? null : new { ID = S.Index.ToString(), Name = S.Name },
                                       InjuryType = IT == null ? null : new { ID = IT.Index.ToString(), Name = IT.Description },
                                       I.Date,
                                       GamesMissed = I.GamesMissed.ToString(),
                                       I.Notes,
                                       IsCurrentlyInjuried = I.CurInjured,
                                       I.Doctor,
                                       I.DrPhone,
                                       I.IR,
                                       DateReturned = I.DReturned
                                   }).Take(2000);

            AddUsage(string.Join(";", Filter), query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                Injuries = query.ToArray()
            };

            string strResponse = JsonConvert.SerializeObject(wrapper);
            jhelper.WriteJSONResponse(strResponse);
        }
        public void GetSeasons(string SessionKey, string Filter)
        {
            JSONHelper jhelper = new JSONHelper(Context);
            try
            {
                userKey = Authentication.ValidateKey(SessionKey);
                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch
            {
                throw;
            }

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary object (default for an array shape)
            // THESE ARE THE FILTERS PROVIDED BY CALLER
            //Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();

            Dictionary<string, object> filtersProvided = ser.Deserialize<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "ids", null }
            };

            // Check if any of the filters provided are bad.
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault(); //filtersProvided.FirstOrDefault(x => !filtersAllowed.ContainsKey(x.Key)).Key;

            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            int[] ids = filtersProcessed.ExtractArray<int>("ids");

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);
            var query = (from S in dc.Seasons
                         from Y in dc.Years.Where(y => y.Index == S.Year).DefaultIfEmpty()
                         where !ids.Any() || ids.Contains(S.Index)
                         select new
                         {
                             ID = S.Index.ToString(),
                             Name = S.Name,
                             ShortName = S.ShortName,
                             Year = Y == null ? null : new { ID = Y.Index.ToString(), Name = Y.Name },
                             StatsName = S.StatsName,
                             FrStatsName = S.FrStatsName,
                             S.StartDate,
                             S.EndDate,
                             IsCurrentSeason = S.Current,
                             IsTournament = S.Tournament,
                             IsRegularSeason = S.RegSea,
                             IsPlayoffs = S.Playoffs,
                             IsExhibition = S.Exhib
                         })
                .Take(2000);

            AddUsage(string.Join(";", ids), query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                Seasons = query.ToArray()
            };

            string strResponse = JsonConvert.SerializeObject(wrapper);
            jhelper.WriteJSONResponse(strResponse);
        }
        public string NewAddPasswordICcard(string newLockId, string type, string pwdAndCard, string startTime, string endTime, string userId)
        {
            if (!authentication.ValideLockUser())
            {
                return("{'headerError'}");
            }
            NewLockManager managerNew       = new NewLockManager();
            Dictionary <string, string> ret = new Dictionary <string, string>();
            //传值校验
            Dictionary <string, string> dic = new Dictionary <string, string>();

            dic.Add("newLockId", newLockId);
            dic.Add("type", type);
            if (type == "1" || type == "2")
            {
                if (pwdAndCard == string.Empty)
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "永久录入字段pwdAndCard不允许为空!");
                    return(JSONHelper.ToJson(ret));
                }
                else
                {
                    dic.Add("pwdAndCard", pwdAndCard);
                }
            }
            dic.Add("startTime", startTime);
            dic.Add("endTime", endTime);
            string returnFiled = managerNew.checkIsNullFild(dic);

            if (returnFiled != string.Empty)
            {
                ret.Add("ret", "1");
                ret.Add("msg", "字段" + returnFiled + "不允许为空!");
                return(JSONHelper.ToJson(ret));
            }
            //是否给公司授权
            if (managerNew.GetIsEnterprise(userId) == "2")
            {
                ret.Add("ret", "1");
                ret.Add("msg", "我公司暂无给贵公司授权,请核对再操做!");
                return(JSONHelper.ToJson(ret));
            }
            //判断接口是否授权
            if (!managerNew.GetIsInterfacePermissions("10", userId))
            {
                ret.Add("ret", "1");
                ret.Add("msg", "我公司暂无给贵公司授权该接口,请核对再操做!");
                return(JSONHelper.ToJson(ret));
            }
            string[] strArr = { "1", "2", "3", "4" };
            bool     exists = ((IList)strArr).Contains(type);

            if (!exists)
            {
                ret.Add("ret", "1");
                ret.Add("msg", "type参数值超出允许范围!");
                return(JSONHelper.ToJson(ret));
            }
            string deviceId = managerNew.getDeviceID(newLockId, "DeviceID");
            string UserId   = managerNew.getDeviceID(newLockId, "UserId");

            if (deviceId == string.Empty || userId == string.Empty)
            {
                ret.Add("ret", "1");
                ret.Add("msg", "未获取该家庭锁信息!");
                return(JSONHelper.ToJson(ret));
            }
            return(managerNew.GetPostInterface(deviceId, UserId, type, pwdAndCard, startTime, endTime));
        }
        public string UpdateNewFamilyInfo(string newLockId, string address, string familyName, string city, string ownerName, string ownerMobile, string ownerId, string ownerAddress, string homeStatus, string userId)
        {
            if (!authentication.ValideLockUser())
            {
                return("{'headerError'}");
            }
            NewLockManager managerNew       = new NewLockManager();
            Dictionary <string, string> ret = new Dictionary <string, string>();

            if (string.Empty == newLockId)
            {
                ret.Add("ret", "1");
                ret.Add("msg", "字段newLockId不允许为空!");
                return(JSONHelper.ToJson(ret));
            }
            //判断是否授权
            if (managerNew.GetIsEnterprise(userId) == "2")
            {
                ret.Add("ret", "1");
                ret.Add("msg", "我公司暂无给贵公司授权,请核对再操做!");
                return(JSONHelper.ToJson(ret));
            }
            //判断接口是否授权
            if (!managerNew.GetIsInterfacePermissions("8", userId))
            {
                ret.Add("ret", "1");
                ret.Add("msg", "我公司暂无给贵公司授权该接口,请核对再操做!");
                return(JSONHelper.ToJson(ret));
            }
            try
            {
                //字符串拼接
                Dictionary <string, string> dic = new Dictionary <string, string>();
                dic.Add("Address", address);
                dic.Add("FamilyName", familyName);
                dic.Add("City", city);
                dic.Add("EnterpriseHomeownerName", ownerName);
                dic.Add("EnterpriseHomeownerMobile", ownerMobile);
                dic.Add("EnterpriseHomeownerId", ownerId);
                dic.Add("EnterpriseHomeownerAddress", ownerAddress);
                dic.Add("EnterpriseHomeStatus", homeStatus);
                string   sqlDate  = string.Empty;
                string   sqlDateE = string.Empty;
                string[] strArr   = { "Address", "FamilyName", "City" };
                foreach (KeyValuePair <string, string> array in dic)
                {
                    if (array.Value != string.Empty)
                    {
                        if (((IList)strArr).Contains(array.Key))
                        {
                            sqlDate += array.Key + "='" + array.Value + "',";
                        }
                        else
                        {
                            if (array.Key == "EnterpriseHomeownerMobile" && !managerNew.IsTelephone(array.Value)) //手机号校验
                            {
                                ret.Add("ret", "1");
                                ret.Add("msg", "房主手机号格式(ownerMobile)校验错误!");
                                return(JSONHelper.ToJson(ret));
                            }
                            if (array.Key == "EnterpriseHomeownerId" && !managerNew.checkidcard(array.Value)) //身份证校验
                            {
                                ret.Add("ret", "1");
                                ret.Add("msg", "房主身份证号(ownerId)格式校验错误!");
                                return(JSONHelper.ToJson(ret));
                            }
                            if (array.Key == "EnterpriseHomeStatus" && array.Value != "1" && array.Value != "2") //房租类型校验
                            {
                                ret.Add("ret", "1");
                                ret.Add("msg", "homeStatus参数值超出允许范围!");
                                return(JSONHelper.ToJson(ret));
                            }
                            sqlDateE += array.Key + "='" + array.Value + "',";
                        }
                    }
                }
                if (sqlDate != string.Empty)
                {
                    sqlDate = sqlDate.Substring(0, sqlDate.Length - 1);
                    string sql = "update Rent_NewLock_Process set " + sqlDate + " where NewLockID='" + newLockId + "'";
                    MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql));
                }
                if (sqlDateE != string.Empty)
                {
                    sqlDateE = sqlDateE.Substring(0, sqlDateE.Length - 1);
                    string sql = "update Enterprise_Homeowner_Info set " + sqlDateE + " where NewLockID='" + newLockId + "'";
                    MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql));
                }
                ret.Add("ret", "0");
                ret.Add("msg", "修改成功!");
            }
            catch (Exception ex)
            {
                ret.Add("ret", "1");
                ret.Add("msg", ex.Message);
            }
            return(JSONHelper.ToJson(ret));
        }
        public string CreateHomeLock(string address, string familyName, string userId, string city, string ownerName, string ownerMobile, string ownerId, string ownerAddress, string homeStatus)
        {
            if (!authentication.ValideLockUser())
            {
                return("{'headerError'}");
            }
            Dictionary <string, string> ret = new Dictionary <string, string>();

            try
            {
                NewLockManager manager = new NewLockManager();
                //传值校验
                Dictionary <string, string> dic = new Dictionary <string, string>();
                dic.Add("address", address);
                dic.Add("familyName", familyName);
                dic.Add("userId", userId);
                dic.Add("city", city);
                dic.Add("ownerName", ownerName);
                dic.Add("ownerMobile", ownerMobile);
                dic.Add("ownerId", ownerId);
                dic.Add("ownerAddress", ownerAddress);
                dic.Add("homeStatus", homeStatus);
                string returnFiled = manager.checkIsNullFild(dic);
                if (returnFiled != string.Empty)
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "字段" + returnFiled + "不允许为空!");
                    return(JSONHelper.ToJson(ret));
                }
                if (manager.GetIsEnterprise(userId) == "2")
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "我公司暂无给贵公司授权,请核对再操做!");
                    return(JSONHelper.ToJson(ret));
                }
                //判断接口是否授权
                if (!manager.GetIsInterfacePermissions("1", userId))
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "我公司暂无给贵公司授权该接口,请核对再操做!");
                    return(JSONHelper.ToJson(ret));
                }
                if (!manager.checkidcard(ownerId)) //身份证格式校验
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "房主身份证号(ownerId)格式校验错误!");
                    return(JSONHelper.ToJson(ret));
                }
                if (!manager.IsTelephone(ownerMobile)) //手机号格式校验
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "房主手机号格式(ownerMobile)校验错误!");
                    return(JSONHelper.ToJson(ret));
                }
                if (homeStatus != "1" && homeStatus != "2")
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "homeStatus参数值超出允许范围!");
                    return(JSONHelper.ToJson(ret));
                }
                LogManager.WriteLog("Start......");
                string deviceID = Guid.NewGuid().ToString("N");
                string sql      = string.Empty;
                //请求远程创建家庭接口
                string familyReturn = manager.createHomeInfo(deviceID);
                LogManager.WriteLog("Start......" + familyReturn);
                Dictionary <string, object> returnInfo = new Dictionary <string, object>();
                returnInfo = JSONHelper.FromJson <Dictionary <string, object> >(familyReturn);
                if (returnInfo["ret"].ToString() == "0")
                {
                    string dateTime = DateTime.Now.ToString();
                    //信息记录
                    sql = "insert into Rent_NewLock_Process output inserted.NewLockId values('" + Guid.NewGuid().ToString() + "', '" + userId + "', '" + deviceID + "', '" + address + "', '','','true','','','','','" + dateTime + "','','" + familyName + "', '" + city + "')";
                    LogManager.WriteLog("SQL:" + sql);
                    DataTable dt = MySQLHelper.ExecuteDataset(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql)).Tables[0];
                    sql = "select * from Rent_NewLock_Process where NewLockID='" + dt.Rows[0]["NewLockID"].ToString() + "'";
                    LogManager.WriteLog("SQL:" + sql);
                    //锁房屋绑定
                    DataTable dtInfo = MySQLHelper.ExecuteDataset(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql)).Tables[0];
                    sql = "insert into Rent_Locks values('" + dtInfo.Rows[0]["DeviceID"].ToString() + "', 1, '0', 'NoConfiguration', '0', '" + dateTime + "', '0', '0', '" + dt.Rows[0]["NewLockID"].ToString() + "')";
                    LogManager.WriteLog("SQL:" + sql);
                    MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql));
                    //家庭信息创建
                    sql = "insert into Enterprise_Homeowner_Info values('" + Guid.NewGuid().ToString() + "', '" + ownerName + "', '" + ownerMobile + "',  '" + ownerId + "', '" + ownerAddress + "', '" + homeStatus + "', '" + userId + "', '" + dt.Rows[0]["NewLockID"].ToString() + "', '" + dateTime + "', '', '', '')";
                    LogManager.WriteLog("SQL:" + sql);
                    MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql));
                    ret.Add("ret", "0");
                    ret.Add("msg", dt.Rows[0]["NewLockID"].ToString());
                }
                else
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", returnInfo["msg"].ToString());
                }
            }
            catch (Exception ex)
            {
                ret.Add("ret", "1");
                ret.Add("msg", ex.Message);
            }
            return(JSONHelper.ToJson(ret));
        }
        public string DeleteGatewayLock(string newLockID, int type, string userId)
        {
            if (!authentication.ValideLockUser())
            {
                return("{'headerError'}");
            }
            Dictionary <string, string> ret = new Dictionary <string, string>();

            try
            {
                string         LockInfo   = string.Empty;
                NewLockManager managerNew = new NewLockManager();
                //传值校验
                Dictionary <string, string> dic = new Dictionary <string, string>();
                dic.Add("newLockID", newLockID);
                dic.Add("type", type.ToString());
                string returnFiled = managerNew.checkIsNullFild(dic);
                if (returnFiled != string.Empty)
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "字段" + returnFiled + "不允许为空!");
                    return(JSONHelper.ToJson(ret));
                }
                //判断是否授权
                if (managerNew.GetIsEnterprise(userId) == "2")
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "我公司暂无给贵公司授权,请核对再操做!");
                    return(JSONHelper.ToJson(ret));
                }
                //判断接口是否授权
                if (!managerNew.GetIsInterfacePermissions("5", userId))
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "我公司暂无给贵公司授权该接口,请核对再操做!");
                    return(JSONHelper.ToJson(ret));
                }
                if (type == 1) //删除网关
                {
                    LockInfo = managerNew.deleteGateway(newLockID);
                }
                else if (type == 2)   //删除锁
                {
                    LockInfo = managerNew.deleteAddLock(newLockID);
                }
                else if (type == 3)  //强制删除网关
                {
                    LockInfo = managerNew.forceDelGate(newLockID);
                }
                else if (type == 4)  //删除家庭
                {
                    LockInfo = managerNew.deleteFamily(newLockID);
                }
                else
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "type参数值超出允许范围!");
                    return(JSONHelper.ToJson(ret));
                }
                Dictionary <string, object> returnInfo = new Dictionary <string, object>();
                returnInfo = JSONHelper.FromJson <Dictionary <string, object> >(LockInfo);
                if (returnInfo["ret"].ToString() == "0")
                {
                    ret.Add("ret", "0");
                    string lockId = managerNew.getDeviceID(newLockID, "DeviceID");
                    //删除所有密码
                    string delSqlPass = "******" + lockId + "'";
                    MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(delSqlPass));
                    //删除所有卡片
                    string delSqlIc = "Update Rent_Locks_ICCards set IsValid='0' where LockID='" + lockId + "'";
                    MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(delSqlIc));
                    if (type == 2)
                    {
                        string delSqlLock = "Update Rent_NewLock_Process set IsDeleteLock='' where NewLockID='" + newLockID + "'";
                        MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(delSqlLock));
                    }
                    else if (type == 3)
                    {
                        string delSqlGate = "Update Rent_NewLock_Process set IsDeleteGateway='true', PinInfo='',IsCreateLock='', IsDeleteLock='' , IsCreateGateway='', GatewayId='', DevKey='' where NewLockID='" + newLockID + "'";
                        MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(delSqlGate));
                    }
                    else if (type == 4) //删除家庭
                    {
                        string delSql = string.Empty;
                        delSql = "delete from Rent_NewLock_Process where NewLockID='" + newLockID + "'";
                        MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(delSql));
                        delSql = "delete from Rent_Locks where Memo='" + newLockID + "'";
                        MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(delSql));
                        delSql = "delete from Enterprise_Homeowner_Info where NewLockID='" + newLockID + "'";
                        MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(delSql));
                    }
                }
                else
                {
                    ret.Add("ret", "1");
                }
                ret.Add("msg", returnInfo["msg"].ToString());
            }
            catch (Exception ex)
            {
                ret.Add("ret", "1");
                ret.Add("msg", ex.Message);
            }
            return(JSONHelper.ToJson(ret));
        }
        public string GetPinInfo(string newLockId, string userId)
        {
            if (!authentication.ValideLockUser())
            {
                return("{'headerError'}");
            }
            Dictionary <string, string> ret = new Dictionary <string, string>();

            try
            {
                NewLockManager managerNew = new NewLockManager();
                //传值校验
                Dictionary <string, string> dic = new Dictionary <string, string>();
                dic.Add("newLockId", newLockId);
                string returnFiled = managerNew.checkIsNullFild(dic);
                if (returnFiled != string.Empty)
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "字段" + returnFiled + "不允许为空!");
                    return(JSONHelper.ToJson(ret));
                }
                //判断是否授权
                if (managerNew.GetIsEnterprise(userId) == "2")
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "我公司暂无给贵公司授权,请核对再操做!");
                    return(JSONHelper.ToJson(ret));
                }
                //判断接口是否授权
                if (!managerNew.GetIsInterfacePermissions("4", userId))
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "我公司暂无给贵公司授权该接口,请核对再操做!");
                    return(JSONHelper.ToJson(ret));
                }
                //判断是否已经获取网关地址
                string    sql = "select * from Rent_NewLock_Process where NewLockID='" + newLockId + "'";
                DataTable dt  = MySQLHelper.ExecuteDataset(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql)).Tables[0];
                if (dt.Rows.Count <= 0)
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "未获取该家庭锁信息!");
                    return(JSONHelper.ToJson(ret));
                }
                if (dt.Rows[0]["GatewayId"].ToString() == "" || dt.Rows[0]["DevKey"].ToString() == "" || dt.Rows[0]["IsCreateGateway"].ToString() == "")
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "请先配置好网关,在获取PIN码");
                    return(JSONHelper.ToJson(ret));
                }
                //添加pin码
                string addLockInfo = managerNew.createAddLock(dt.Rows[0]["GatewayId"].ToString(), newLockId);
                Dictionary <string, object> returnInfo = new Dictionary <string, object>();
                returnInfo = JSONHelper.FromJson <Dictionary <string, object> >(addLockInfo);
                if (returnInfo["ret"].ToString() == "0")
                {
                    ret.Add("ret", "0");
                }
                else
                {
                    ret.Add("ret", "1");
                }
                ret.Add("msg", returnInfo["msg"].ToString());
            }
            catch (Exception ex)
            {
                ret.Add("ret", "1");
                ret.Add("msg", ex.Message);
            }
            return(JSONHelper.ToJson(ret));
        }
        public string AddGateway(string gatewayId, string devKey, string newLockID, string userId)
        {
            if (!authentication.ValideLockUser())
            {
                return("{'headerError'}");
            }
            Dictionary <string, string> ret = new Dictionary <string, string>();

            try
            {
                NewLockManager managerNew = new NewLockManager();
                //传值校验
                Dictionary <string, string> dic = new Dictionary <string, string>();
                dic.Add("gatewayId", gatewayId);
                dic.Add("devKey", devKey);
                dic.Add("newLockID", newLockID);
                string returnFiled = managerNew.checkIsNullFild(dic);
                if (returnFiled != string.Empty)
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "字段" + returnFiled + "不允许为空!");
                    return(JSONHelper.ToJson(ret));
                }
                //判断是否授权
                if (managerNew.GetIsEnterprise(userId) == "2")
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "我公司暂无给贵公司授权,请核对再操做!");
                    return(JSONHelper.ToJson(ret));
                }
                //判断接口是否授权
                if (!managerNew.GetIsInterfacePermissions("3", userId))
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "我公司暂无给贵公司授权该接口,请核对再操做!");
                    return(JSONHelper.ToJson(ret));
                }
                //网关查询
                string    selSql = "select * from Rent_NewLock_Process where GatewayId='" + gatewayId + "' and DevKey='" + devKey + "'and IsCreateGateway='true'";
                DataTable d1     = MySQLHelper.ExecuteDataset(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(selSql)).Tables[0];
                if (d1.Rows.Count > 0)
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "网关存在,请先解绑在绑定!");
                    return(JSONHelper.ToJson(ret));
                }
                //添加网关
                string addGatewayInfo = managerNew.createAddGateway(gatewayId, devKey, newLockID);
                Dictionary <string, object> returnInfo = new Dictionary <string, object>();
                returnInfo = JSONHelper.FromJson <Dictionary <string, object> >(addGatewayInfo);
                if (returnInfo["ret"].ToString() == "0")
                {
                    string sql = "Update Rent_NewLock_Process set GatewayId='" + gatewayId + "', DevKey='" + devKey + "', UpdatedOn='" + DateTime.Now.ToString() + "'where NewLockID='" + newLockID + "'";
                    MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql));
                    ret.Add("ret", "0");
                }
                else
                {
                    ret.Add("ret", "1");
                }
                ret.Add("msg", returnInfo["msg"].ToString());
            }
            catch (Exception ex)
            {
                ret.Add("ret", "1");
                ret.Add("msg", ex.Message);
            }
            return(JSONHelper.ToJson(ret));
        }
Example #15
0
        //添加网关
        //familyName   新锁ID
        public string createAddGateway(string gatewayId, string devKey, string familyName)
        {
            Dictionary <string, string> setRet = new Dictionary <string, string>();
            Dictionary <string, string> ret    = new Dictionary <string, string>();

            setRet.Add("appKey", appKey);
            setRet.Add("appSecret", appSecret);
            setRet.Add("username", accountOpening);
            setRet.Add("gatewayId", gatewayId);
            setRet.Add("devKey", devKey);
            setRet.Add("familyName", getDeviceID(familyName, "DeviceID"));
            string getPostInfo = LigerRM.Common.WebRequestHelper.WebRequestPoster.JsonHttpPost(createGatewayUrl, JSONHelper.ToJson(setRet), "parameters");
            Dictionary <string, object> returnInfo = new Dictionary <string, object>();

            returnInfo = JSONHelper.FromJson <Dictionary <string, object> >(getPostInfo);
            if (returnInfo["success"].ToString() == "True")
            {
                ret.Add("ret", "0");
            }
            else
            {
                ret.Add("ret", "1");
            }
            ret.Add("msg", returnInfo["msg"].ToString());
            AddLockNewLog(getDeviceID(familyName, "DeviceID"), "添加网关请求", returnInfo["msg"].ToString());   //增加新锁的log请求返回日志
            return(JSONHelper.ToJson(ret));
        }
 public BaseController()
     : base()
 {
     JsonHelper = new JSONHelper(ConfigurationManager.AppSettings["EnderecoAPIRemoto"]);
 }
        public string NewDelPasswordICcard(string id, string type, string userId)
        {
            if (!authentication.ValideLockUser())
            {
                return("{'headerError'}");
            }
            string         returnInfo       = string.Empty;
            NewLockManager managerNew       = new NewLockManager();
            Dictionary <string, string> ret = new Dictionary <string, string>();
            //传值校验
            Dictionary <string, string> dic = new Dictionary <string, string>();

            dic.Add("id", id);
            dic.Add("type", type);
            dic.Add("userId", userId);
            string returnFiled = managerNew.checkIsNullFild(dic);

            if (returnFiled != string.Empty)
            {
                ret.Add("ret", "1");
                ret.Add("msg", "字段" + returnFiled + "不允许为空!");
                return(JSONHelper.ToJson(ret));
            }
            if (managerNew.GetIsEnterprise(userId) == "2")
            {
                ret.Add("ret", "1");
                ret.Add("msg", "我公司暂无给贵公司授权,请核对再操做!");
                return(JSONHelper.ToJson(ret));
            }
            //判断接口是否授权
            if (!managerNew.GetIsInterfacePermissions("11", userId))
            {
                ret.Add("ret", "1");
                ret.Add("msg", "我公司暂无给贵公司授权该接口,请核对再操做!");
                return(JSONHelper.ToJson(ret));
            }
            if (type != "1" && type != "2")
            {
                ret.Add("ret", "1");
                ret.Add("msg", "type参数值超出允许范围!");
                return(JSONHelper.ToJson(ret));
            }
            string sql = string.Empty;

            //校验删除的密码和卡片是否属于该企业
            if (type == "1")
            {
                sql = "select * from v_RentPass_view where Status='0' and UserId='" + userId + "'and IsAdd is not null and len(IsAdd)>0 and ID='" + id + "'";
                DataTable dt = MySQLHelper.ExecuteDataset(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql)).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    returnInfo = managerNew.DeletePassword(id);
                }
                else
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "未查到该密码,无法删除!");
                    return(JSONHelper.ToJson(ret));
                }
            }
            else if (type == "2")
            {
                sql = "select ID from v_RentICCard_view where Status='0' and UserId='" + userId + "'and ICCard is not null and len(ICCard)>0 and ID='" + id + "'";
                DataTable dt = MySQLHelper.ExecuteDataset(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sql)).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    returnInfo = managerNew.DeleteICCard(id);
                }
                else
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "未查到该卡片,无法删除!");
                    return(JSONHelper.ToJson(ret));
                }
            }
            return(returnInfo);
        }
        public void GetArenas(string SessionKey, string Filter)
        {
            JSONHelper jhelper = new JSONHelper(Context);
            try
            {
                userKey = Authentication.ValidateKey(SessionKey);
                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch
            {
                throw;
            }

            if (string.IsNullOrEmpty(Filter))
            {
                jhelper.WriteJSONResponse("{'error':'No filter provided.'}", HttpStatusCode.Forbidden);
                AddUsage("Error: no filter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                return;
            }

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary object (default for an array shape)
            // THESE ARE THE FILTERS PROVIDED BY CALLER
            //Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();

            Dictionary<string, object> filtersProvided = ser.Deserialize<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "name", null },
                { "cityid", null }
            };

            // Check if any of the filters provided are bad.
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault(); //filtersProvided.FirstOrDefault(x => !filtersAllowed.ContainsKey(x.Key)).Key;

            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            string name = filtersProcessed.ExtractReference<string>("name");
            int? cityid = filtersProcessed.Extract<int>("cityid");

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);
            var query = (from A in dc.Arenas
                         from C in dc.Companies.Where(c => c.Index == A.Company).DefaultIfEmpty()
                         from I in dc.Cities.Where(i => i.Index == A.City).DefaultIfEmpty()
                         where
                        (name == null || A.ArenaName.StartsWith(name))
                     && (cityid == null || A.City >= cityid)

                         select new
                         {
                             ID = A.Index.ToString(),
                             ArenaName = A.ArenaName,
                             ShortName = A.ShortName,
                             Company = BuildIDNameObject(A.Company, C.Name),
                             City = BuildIDNameObject(A.City, I.CityName),
                             PassGate = A.PassGate,
                             Inactive = A.Inactive,
                             WebSite = A.WebSite,
                             Directions = A.Directions
                         })
            .Take(2000);

            AddUsage(string.Join(";", Filter), query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                Arenas = query.ToArray()
            };

            string strResponse = JsonConvert.SerializeObject(wrapper);
            jhelper.WriteJSONResponse(strResponse);
        }
        public string NewSelPasswordICcard(string newLockId, int type, string userId)
        {
            if (!authentication.ValideLockUser())
            {
                return("{'headerError'}");
            }
            NewLockManager managerNew       = new NewLockManager();
            Dictionary <string, string> ret = new Dictionary <string, string>();
            //传值校验
            Dictionary <string, string> dic = new Dictionary <string, string>();

            dic.Add("newLockId", newLockId);
            dic.Add("type", type.ToString());
            string returnFiled = managerNew.checkIsNullFild(dic);

            if (returnFiled != string.Empty)
            {
                ret.Add("ret", "1");
                ret.Add("msg", "字段" + returnFiled + "不允许为空!");
                return(JSONHelper.ToJson(ret));
            }
            //判断是否授权
            if (managerNew.GetIsEnterprise(userId) == "2")
            {
                ret.Add("ret", "1");
                ret.Add("msg", "我公司暂无给贵公司授权,请核对再操做!");
                return(JSONHelper.ToJson(ret));
            }
            //判断接口是否授权
            if (!managerNew.GetIsInterfacePermissions("12", userId))
            {
                ret.Add("ret", "1");
                ret.Add("msg", "我公司暂无给贵公司授权该接口,请核对再操做!");
                return(JSONHelper.ToJson(ret));
            }
            if (type != 1 && type != 2)
            {
                ret.Add("ret", "1");
                ret.Add("msg", "type参数值超出允许范围!");
                return(JSONHelper.ToJson(ret));
            }
            string lockId = managerNew.getDeviceID(newLockId, "DeviceID");
            string UserId = managerNew.getDeviceID(newLockId, "UserId");

            if (lockId == string.Empty || userId == string.Empty)
            {
                ret.Add("ret", "1");
                ret.Add("msg", "未获取该家庭锁信息!");
                return(JSONHelper.ToJson(ret));
            }
            RentInfoHelper helper = new RentInfoHelper();

            if (type == 1)
            {
                ret.Add("ret", "0");
                ret.Add("msg", helper.GetJSONInfo("select ID,LockID,ICCard,StartDate,EndDate,IsValid,UserId from v_RentICCard_view where LockID='" + lockId + " and Status='0' and UserId='" + UserId + "'and ICCard is not null and len(ICCard)>0"));
                return(JSONHelper.ToJson(ret));
            }
            else
            {
                ret.Add("ret", "0");
                ret.Add("msg", helper.GetJSONInfo("select ID,LockID,Password,StartDate,EndDate,IsValid,UserId from v_RentPass_view where LockID='" + lockId + "' and Status='0' and UserId='" + UserId + "'and IsAdd is not null and len(IsAdd)>0"));
                return(JSONHelper.ToJson(ret));
            }
        }
        public void GetPlayers(string SessionKey, string Filter)
        {
            JSONHelper jhelper = new JSONHelper(Context);
            try
            {
                userKey = Authentication.ValidateKey(SessionKey);

                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary
            // Determine which filter params are provided
            if (string.IsNullOrEmpty(Filter))
            {
                jhelper.WriteJSONResponse("{'error':'No filter provided.'}", HttpStatusCode.Forbidden);
                AddUsage("Error: no filter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                return;
            }
            Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            // Nulls will be populated with "filtersProvided"
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "team", null },
                { "playerid", null },
                { "league", null },
                { "isdrafteligible", null },
                { "isonreservelist", null },
                { "lastname", null },
                { "minheight", null },
                { "maxheight", null },
                { "minweight", null },
                { "maxweight", null },
                { "birthdateearliest", null },
                { "birthdatelatest", null },
                { "firstname", null },
                { "position", null },
                { "playerstatus", null },
                { "reservelistteam", null },
                { "reservelisttype", null },
                { "tournamentid", null }

            };

            // check for bad filters provided
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault();
            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            // Combine the filters provided into what's allowed.
            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            // Sanity checks
            if (filtersProcessed.Extract<DateTime>("birthdateearliest") > filtersProcessed.Extract<DateTime>("birthdatelatest"))
            {
                jhelper.WriteJSONResponse("{'error':'Maximum birthdate older than minimum.'}", HttpStatusCode.Forbidden);
                return;
            }
            else if (filtersProcessed.Extract<double>("minheight") > filtersProcessed.Extract<double>("maxheight"))
            {
                jhelper.WriteJSONResponse("{'error':'Maximum height shorter than minimum.'}", HttpStatusCode.Forbidden);
                return;
            }
            else if (filtersProcessed.Extract<double>("minweight") > filtersProcessed.Extract<double>("maxweight"))
            {
                jhelper.WriteJSONResponse("{'error':'Maximum weight shorter than minimum.'}", HttpStatusCode.Forbidden);
                return;
            }

            // Connect to the proper database before getting data
            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);

            DateTime t1 = DateTime.Now;

            //// Call our stored procedure with the provided parameters.  Unfortunately nulls indicate "do not search" at this time.
            //// There is no "search for null values" mechanism required as per JP (TK, 06/19/20140)
            var result = dc.spGetPlayerData(
                    playerID: filtersProcessed.Extract<int>("playerid"),
                    leagueFK: filtersProcessed.Extract<int>("league"),
                    teamFK: filtersProcessed.Extract<int>("team"),
                    lastName: filtersProcessed.ExtractReference<string>("lastname"),
                    firstName: filtersProcessed.ExtractReference<string>("firstname"),
                    isDraftEligible: filtersProcessed.Extract<bool>("isdrafteligible"),
                    isOnReserveList: filtersProcessed.Extract<bool>("isonreservelist"),
                    minHeight: filtersProcessed.Extract<double>("minheight"),
                    maxHeight: filtersProcessed.Extract<double>("maxheight"),
                    minWeight: filtersProcessed.Extract<double>("minweight"),
                    maxWeight: filtersProcessed.Extract<double>("maxweight"),
                    birthDateEarliest: filtersProcessed.Extract<DateTime>("birthdateearliest"),
                    birthDateLatest: filtersProcessed.Extract<DateTime>("birthdatelatest"),
                    position: filtersProcessed.Extract<int>("position"),
                    playerStatusDescription: filtersProcessed.ExtractReference<string>("playerstatus"),
                    reserveListTeamFK: filtersProcessed.Extract<int>("reservelistteam"),
                    reserveListTypeFK: filtersProcessed.Extract<int>("reservelisttype"),
                    tournamentID: filtersProcessed.Extract<int>("tournamentid")
                );

            // Project the results into the Player shape
            var query = result.Select(x => new
            {
                ID = x.ID.ToString(),
                FirstName = x.FirstName,
                LastName = x.LastName,
                CurrentTeam = BuildIDNameObject(x.CurrentTeamID, x.CurrentTeamName),
                JerseyNumber = x.JerseyNumber,
                Agent = BuildIDNameObject(x.AgentID, x.AgentName),
                BirthDate = x.BirthDate,
                Position = BuildIDNameObject(x.PositionID, x.PositionName),
                Height = x.Height,
                Weight = x.Weight,
                PlayerStatus = x.PlayerStatus,
                IsDraftEligible = x.IsDraftEligible,
                ReserveListTeam = BuildIDNameObject(x.ReserveListTeamID, x.ReserveListTeamName),
                ReserveListType = BuildIDNameObject(x.ReserveListTypeID, x.ReserveListTypeName),
                MasterDepthChartRating = BuildIDNameObject(x.MasterDepthChartRatingID, x.MasterDepthChartRatingName),
                MasterDepthChartQuality = BuildIDNameObject(x.MasterDepthChartQualityID, x.MasterDepthChartQualityName),
                MasterDepthChartPlayerType = BuildIDNameObject(x.MasterDepthChartPlayerTypeID, x.MasterDepthChartPlayerTypeName),
                ShotSide = x.ShotSide,
                CatchSide = x.CatchSide,
                HomeTown = x.HomeTown,
                Nationality = BuildIDNameObject(x.NationalityID, x.NationalityName),
                PriorityPlayerType = BuildIDNameObject(x.PriorityPlayerTypeID, x.PriorityPlayerTypeName),
                MinorProReserveList = BuildIDNameObject(x.MinorProReserveListID, x.MinorProReserveListName),
                ContractStatus = BuildIDNameObject(x.ContractStatusID, x.ContractStatusName),
                IsWaiverRequired = x.IsWaiverRequired,
                WaiverPrice = x.WaiverPrice,
                NHLGamesPlayed = x.NHLGamesPlayed,
                ProGamesPlayed = x.ProGamesPlayed,
                YearsUntilWaiversRequired = x.YearsUntilWaiversRequired,
                GamesUntilWaiversRequired = x.GamesUntilWaiversRequired,
                HowPlayerAcquired = x.HowPlayerAcquired,
                FreeAgentType = BuildIDNameObject(x.FreeAgentTypeID, x.FreeAgentTypeName),
                YearsPro = x.YearsPro,
                AgePlayerSigned = x.AgePlayerSigned,
                AgePlayerNHL = x.AgePlayerNHL,
                NHLExperience = x.NHLExperience,
                SignedFreeAgent = x.SignedFreeAgent,
                VeteranForAHL = x.VeteranForAHL,
                SalaryCapAmountXBonuses = x.SalaryCapAmountXBonuses,
                LastAmateurClub = BuildIDNameObject(x.LastAmateurClubID, x.LastAmateurClubName),
                ProjectedUnrestrictedFreeAgentYear = BuildIDNameObject(x.ProjectedUnrestrictedFreeAgentYearID, x.ProjectedUnrestrictedFreeAgentYearName),
                ProjectedUnrestrictedFreeAgentType = BuildIDNameObject(x.ProjectedUnrestrictedFreeAgentTypeID, x.ProjectedUnrestrictedFreeAgentTypeName),
                SecondaryTeam = BuildIDNameObject(x.SecondaryTeamID, x.SecondaryTeamName),
                YearSignedFirstContract = BuildIDNameObject(x.YearSignedFirstContractID, x.YearSignedFirstContractName),
                CapHitAmount = x.CapHitAmount,
                NextYearsCapHitAmount = x.NextYearsCapHitAmount,
                CollegeCommitmentTeam = BuildIDNameObject(x.CollegeCommitmentTeamID, x.CollegeCommitmentTeamName),
                CollegeYear = BuildIDNameObject(x.CollegeYearID, x.CollegeYearName),
                CollegeCommitmentDate = x.CollegeCommitmentDate,
                CollegeVerbalAgreement = x.CollegeVerbalAgreement,
                EuropeanContractDetails = x.EuropeanContractDetails,
                Bio = x.Bio
            })
            .Take(2000).ToArray();

            //            double ;

            // Log the query
            AddUsage(Filter, query.Count(), "GetPlayers", /*System.Reflection.MethodBase.GetCurrentMethod().Name*/ userKey.UserName);

            // Wrap the results into a Players node
            var wrapper = new
            {
                Players = query
                //, QueryTime = DateTime.Now.Subtract(t1).TotalMilliseconds
            };

            // serialize the results into JSON
            string strResponse = JsonConvert.SerializeObject(wrapper);

            // Write the results to our response
            jhelper.WriteJSONResponse(strResponse);
        }
Example #21
0
        protected void btnLogout_Click(object sender, EventArgs e)
        {
            WebServiceLog objServiceLog = new WebServiceLog();
            LoginRequest  objRequest    = new LoginRequest();
            ResponseBase  objResponse   = null;

            objServiceLog.RequestTime    = DateTime.Now;
            objServiceLog.ControllerName = this.GetType().Name;
            objServiceLog.MethodName     = System.Reflection.MethodBase.GetCurrentMethod().Name;
            try
            {
                objResponse = new ResponseBase();
                if (HttpContext.Current.Session["UserId"] != null && HttpContext.Current.Session["CompId"] != null)
                {
                    ActiveUsersCache  objSession     = new ActiveUsersCache();
                    List <ActiveUser> lstActiveUsers = new List <ActiveUser>();
                    if (Cache["ActiveUsers"] != null)
                    {
                        lstActiveUsers = (List <ActiveUser>)Cache["ActiveUsers"];
                    }
                    objSession.KillSession(lstActiveUsers, Session.SessionID, null);

                    objRequest.UserID = Convert.ToString(HttpContext.Current.Session["UserId"]);

                    DataSet ds = UserDAL.UserLogout(Convert.ToInt32(HttpContext.Current.Session["CompId"]), objRequest.UserID, Utility.GetClientIPaddress());
                    if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0 && ds.Tables[0].Rows[0]["ReturnCode"].ToString() == "1")
                    {
                        objResponse.ReturnCode    = "1";
                        objResponse.ReturnMessage = "User logout succesfully.";
                    }
                    else
                    {
                        objResponse.ReturnCode    = "2";
                        objResponse.ReturnMessage = "Unable to logout.";
                    }
                    objServiceLog.RequestString  = JSONHelper.ConvertJsonToString(objRequest);
                    objServiceLog.ResponseString = JSONHelper.ConvertJsonToString(objResponse);
                    objServiceLog.RequestType    = ConstantMessages.WebServiceLog.Success;

                    Utility.DestroyAllSession();

                    //This is to delete all cookies from client web browser
                    //HttpCookie myCookie = new HttpCookie("UserInfo");
                    //myCookie.Expires = DateTime.Now.AddDays(-1);
                    //Response.Cookies.Add(myCookie);

                    Response.Cookies["userid"].Expires = DateTime.Now.AddDays(-1);
                    //End


                    Response.Redirect("~/login.aspx", false);
                }
                else
                {
                    objServiceLog.RequestString  = JSONHelper.ConvertJsonToString(objRequest);
                    objServiceLog.ResponseString = JSONHelper.ConvertJsonToString(objResponse);
                    objServiceLog.RequestType    = ConstantMessages.WebServiceLog.Validation;
                }
            }
            catch (Exception ex)
            {
                objServiceLog.ResponseString = "Exception " + ex.Message + " | " + ex.StackTrace;
                objServiceLog.RequestType    = ConstantMessages.WebServiceLog.Exception;
            }
            finally
            {
                objServiceLog.ResponseTime = DateTime.Now;
                InsertRequestLog.SaveWebServiceLog(objServiceLog);
            }
        }
        public void GetDraftYears(string SessionKey, string IDs)
        {
            JSONHelper jhelper = new JSONHelper(Context);
            try
            {
                userKey = Authentication.ValidateKey(SessionKey);
                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch
            {
                throw;
            }

            // Deserialize the provided filter into a dictionary object (default for an array shape)

            int[] idsArray = new int[] { };
            if (!string.IsNullOrEmpty(IDs))
            {
                try
                {
                    idsArray = JsonConvert.DeserializeObject<int[]>(IDs);
                }
                catch
                {
                    jhelper.WriteJSONResponse("{'error':'Malformed JSON object.'}", HttpStatusCode.Forbidden);
                    AddUsage("Error: bad json parameter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                    return;
                }
            }

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);
            var query = dc.DraftYears
                .Where(x => !idsArray.Any() || idsArray.Contains(x.Index))
                .Select(x => new Objects.DraftYear
                {
                    ID = x.Index.ToString(),
                    Year = x.Year
                })
                .Take(2000);

            AddUsage(string.Join(";", idsArray), query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                DraftYears = query.ToArray()
            };

            string strResponse = JsonConvert.SerializeObject(wrapper);
            jhelper.WriteJSONResponse(strResponse);
        }
        private void SendEmailForSharedWishList(AspxCommonInfo aspxCommonObj, WishItemsEmailInfo wishlistObj)
        {
            string serverHostLoc = "http://" + HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/";
            string tdContent     = string.Empty;
            var    dataObj       = JSONHelper.Deserialise <List <WishItemEmailInfo> >(wishlistObj.MessageBody);
            int    length        = dataObj.Count();

            string[] tdContentArray    = new string[length];
            string   shareWishMailHtml = "";

            shareWishMailHtml += "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr><td>";
            shareWishMailHtml += "<table width='100%' border='0' cellspacing='0' cellpadding='0'><tr>";
            for (int i = 0; i <= length - 1; i++)
            {
                tdContent +=
                    "<td width='33%'><div style='border:1px solid #cfcfcf; background:#f1f1f1; padding:10px; text-align:center;'> <img src='" +
                    serverHostLoc + dataObj[i].src + "' alt='" + dataObj[i].alt + "' width='80' height='50' />";
                tdContent +=
                    "<p style='margin:0; padding:5px 0 0 0; font-family:Arial, Helvetica, sans-serif; font-size:12px; font-weight:normal; line-height:18px;'>";
                tdContent +=
                    "<span style='font-weight:bold; font-size:12px; font-family:Arial, Helvetica, sans-serif; text-shadow:1px 1px 0 #fff;'>" +
                    dataObj[i].title + "</span><br />"; //item name
                tdContent +=
                    "<span style='font-weight:bold; font-size:12px; font-family:Arial, Helvetica, sans-serif; text-shadow:1px 1px 0 #fff;'> <a href='" +
                    serverHostLoc + dataObj[i].href + "'>" + dataObj[i].hrefHtml + "</a></span><br />"; //item name
                tdContent +=
                    "<span style='font-weight:bold; font-size:11px; font-family:Arial, Helvetica, sans-serif; text-shadow:1px 1px 0 #fff;'>Price:</span>" +
                    dataObj[i].price + "<br />"; //price
                tdContent +=
                    "<span style='font-weight:bold; font-size:12px; font-family:Arial, Helvetica, sans-serif; text-shadow:1px 1px 0 #fff;'>Comments:</span> " +
                    dataObj[i].htmlComment + "</p></div></td>"; //comment
                tdContentArray[i] = tdContent;
                tdContent         = "";
            }
            for (int j = 0; j <= length - 1; j++)
            {
                if (j % 3 == 0)
                {
                    shareWishMailHtml += "</tr><tr>" + tdContentArray[j];
                }
                else
                {
                    shareWishMailHtml += tdContentArray[j];
                }
            }
            shareWishMailHtml += "</tr></table></td></tr></table>";
            StoreSettingConfig ssc     = new StoreSettingConfig();
            string             logosrc = ssc.GetStoreSettingsByKey(StoreSetting.StoreLogoURL, aspxCommonObj.StoreID,
                                                                   aspxCommonObj.PortalID, aspxCommonObj.CultureName);
            List <MessageManagementInfo> template =
                MessageManagementController.GetMessageTemplateByMessageTemplateTypeID(
                    SystemSetting.SHARED_WISHED_LIST, aspxCommonObj.PortalID);

            foreach (MessageManagementInfo messageToken in template)
            {
                string messageTemplate = messageToken.Body.ToString();
                string src             = HttpContext.Current.Request.ServerVariables["SERVER_NAME"] + "/";
                if (template != null)
                {
                    string[] tokens = GetAllToken(messageTemplate);
                    foreach (string token in tokens)
                    {
                        switch (token)
                        {
                        case "%DateTime%":
                            messageTemplate = messageTemplate.Replace(token,
                                                                      System.DateTime.Now.ToString("MM/dd/yyyy"));
                            break;

                        case "%Username%":
                            messageTemplate = messageTemplate.Replace(token, wishlistObj.SenderName);
                            break;

                        case "%UserEmail%":
                            messageTemplate = messageTemplate.Replace(token, wishlistObj.SenderEmail);
                            break;

                        case "%MessageDetails%":
                            messageTemplate = messageTemplate.Replace(token, wishlistObj.Message);
                            break;

                        case "%ItemDetailsTable%":
                            messageTemplate = messageTemplate.Replace(token, shareWishMailHtml);
                            break;

                        case "%LogoSource%":
                            string imgSrc = "http://" + src + logosrc;
                            messageTemplate = messageTemplate.Replace(token, imgSrc);
                            break;

                        case "%ServerPath%":
                            messageTemplate = messageTemplate.Replace(token, "http://" + src);
                            break;

                        case "%DateYear%":
                            messageTemplate = messageTemplate.Replace(token, System.DateTime.Now.Year.ToString());
                            break;
                        }
                    }
                }

                char[]   spliter     = { ',' };
                string[] receiverIDs = wishlistObj.ReceiverEmail.Split(spliter);

                for (int i = 0; i < receiverIDs.Length; i++)
                {
                    string          receiverEmailID = receiverIDs[i];
                    string          emailSuperAdmin;
                    string          emailSiteAdmin;
                    SageFrameConfig pagebase = new SageFrameConfig();
                    emailSuperAdmin = pagebase.GetSettingsByKey(SageFrameSettingKeys.SuperUserEmail);
                    emailSiteAdmin  = pagebase.GetSettingsByKey(SageFrameSettingKeys.SiteAdminEmailAddress);
                    MailHelper.SendMailNoAttachment(wishlistObj.SenderEmail, receiverEmailID, wishlistObj.Subject,
                                                    messageTemplate,
                                                    emailSiteAdmin, emailSuperAdmin);
                }
            }
        }
        public BasicResponse DeleteJC_AnalysistemplateconfigByTempleteId(AnalysisTemplateConfigGetByTempleteIdRequest jC_AnalysisTemplateConfigGetByTempleteIdRequest)
        {
            var responseStr = HttpClientHelper.Post(Webapi + "/v1/AnalysisTemplateConfig/DeleteJC_AnalysistemplateconfigByTempleteId?token=" + Token, JSONHelper.ToJSONString(jC_AnalysisTemplateConfigGetByTempleteIdRequest));

            return(JSONHelper.ParseJSONString <BasicResponse>(responseStr));
        }
        /// <summary>
        /// 社区活动
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public string CommunityActivitiesList(DataRow Row)
        {
            string result = "";

            #region 接受参数
            string strCommunityId = "";   //项目ID
            string strCurrPage    = "1";  //第几页
            string strPageSize    = "10"; //分页的大小

            if (Row.Table.Columns.Contains("CommunityId"))
            {
                strCommunityId = AppGlobal.ChkStr(Row["CommunityId"].ToString());
            }
            else
            {
                return(JSONHelper.FromString(false, "缺少参数CommID"));
            }
            if (Row.Table.Columns.Contains("CurrPage"))
            {
                strCurrPage = AppGlobal.ChkNum(Row["CurrPage"].ToString());
            }

            if (Row.Table.Columns.Contains("PageSize"))
            {
                strPageSize = AppGlobal.ChkNum(Row["PageSize"].ToString());
            }


            #endregion

            #region 变量定义
            string strErrMsg = "";
            string strCommID = "";

            string SQLContionString = "";

            int           PageCount    = 0;
            int           Counts       = 0;
            StringBuilder sListContent = new StringBuilder("");

            int iCurrPage = AppGlobal.StrToInt(strCurrPage);
            int iPageSize = AppGlobal.StrToInt(strPageSize);


            #endregion
            SQLContionString = ConnectionDb.GetConnection(Row["CommunityId"].ToString());
            MobileSoft.Model.Unified.Tb_Community Community = new MobileSoft.BLL.Unified.Bll_Tb_Community().GetModel(Row["CommunityId"].ToString());

            if (Community == null)
            {
                return(JSONHelper.FromString(false, "该小区不存在"));
            }

            #region 查询社区活动
            string strSQLCommAct = "";
            if (Community.CorpID == 1975)
            {
                strSQLCommAct = " and isnull(IsDelete,0)=0 And isnull(IsRun, 1)=1 AND (CommID = " + Community.CommID + " OR CHARINDEX('" + Community.CommID + "',CommIdNvarchar)>0) ";
            }
            else
            {
                strSQLCommAct = " and isnull(IsDelete, 0)=0 And isnull(IsRun, 1)=1 AND CommID = " + Community.CommID;
            }

            DataTable dTableCommAct = null;
            dTableCommAct = (new Business.TWBusinRule(SQLContionString)).HSPR_CommActivities_CutPage(out PageCount, out Counts, strSQLCommAct, iCurrPage, iPageSize);
            if (!pageHasData(iCurrPage, PageCount, Counts))
            {
                dTableCommAct.Dispose();
                dTableCommAct = new DataTable();
            }

            if (dTableCommAct.Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("InfoID", typeof(string)));
                dt.Columns.Add(new DataColumn("Heading", typeof(string)));
                dt.Columns.Add(new DataColumn("IssueDate", typeof(string)));
                dt.Columns.Add(new DataColumn("ImageUrl", typeof(string)));

                foreach (DataRow DRow in dTableCommAct.Rows)
                {
                    DataRow dr = dt.NewRow();
                    dr["InfoID"]    = DRow["ActivitiesID"].ToString();
                    dr["Heading"]   = DRow["ActivitiesTheme"].ToString();
                    dr["IssueDate"] = DRow["IssueDate"].ToString();
                    dr["ImageUrl"]  = string.IsNullOrEmpty(DRow["ActivitiesImages"].ToString()) ? "" : DRow["ActivitiesImages"].ToString().IndexOf("http") >= 0 ? DRow["ActivitiesImages"].ToString() : imageAddr + DRow["ActivitiesImages"].ToString();

                    dt.Rows.Add(dr);
                }
                result = JSONHelper.FromString(dt);
            }
            else
            {
                result = JSONHelper.FromString(dTableCommAct);
            }
            #endregion
            dTableCommAct.Dispose();
            return(result);
        }
Example #26
0
 public JournalFuelScoop(JObject evt) : base(evt, JournalTypeEnum.FuelScoop)
 {
     Scooped = JSONHelper.GetDouble(evt["Scooped"]);
     Total   = JSONHelper.GetDouble(evt["Total"]);
 }
        public string GetAll(DataRow Row)
        {
            string result = "";

            #region 接受参数
            string strCommunityId = "";   //项目ID
            string strCurrPage    = "1";  //第几页
            string strPageSize    = "10"; //分页的大小

            if (Row.Table.Columns.Contains("CommunityId"))
            {
                strCommunityId = AppGlobal.ChkStr(Row["CommunityId"].ToString());
            }
            else
            {
                return(JSONHelper.FromString(false, "缺少参数CommID"));
            }
            if (Row.Table.Columns.Contains("CurrPage"))
            {
                strCurrPage = AppGlobal.ChkNum(Row["CurrPage"].ToString());
            }

            if (Row.Table.Columns.Contains("PageSize"))
            {
                strPageSize = AppGlobal.ChkNum(Row["PageSize"].ToString());
            }


            #endregion

            #region 变量定义
            string strErrMsg = "";
            string strCommID = "";

            string SQLContionString = "";

            int           PageCount    = 0;
            int           Counts       = 0;
            StringBuilder sListContent = new StringBuilder("");

            int iCurrPage = AppGlobal.StrToInt(strCurrPage);
            int iPageSize = AppGlobal.StrToInt(strPageSize);


            #endregion
            SQLContionString = ConnectionDb.GetConnection(Row["CommunityId"].ToString());
            MobileSoft.Model.Unified.Tb_Community Community = new MobileSoft.BLL.Unified.Bll_Tb_Community().GetModel(Row["CommunityId"].ToString());

            if (Community == null)
            {
                return(JSONHelper.FromString(false, "该小区不存在"));
            }

            #region
            string strSQLNotiHis = " and isnull(IsAudit, 0)=0 AND CommID = " + Community.CommID + " AND (ShowEndDate is null or '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'< ShowEndDate) ";

            DataTable dTableNotiHis = null;
            dTableNotiHis = (new Business.TWBusinRule(SQLContionString)).HSPR_CommunityInfo_CutPage(out PageCount, out Counts, strSQLNotiHis, iCurrPage, iPageSize);

            if (!pageHasData(iCurrPage, PageCount, Counts))
            {
                dTableNotiHis.Dispose();
                dTableNotiHis = new DataTable();
            }

            if (dTableNotiHis.Rows.Count > 0)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("InfoID", typeof(string)));
                dt.Columns.Add(new DataColumn("Heading", typeof(string)));
                dt.Columns.Add(new DataColumn("IssueDate", typeof(string)));
                dt.Columns.Add(new DataColumn("ImageUrl", typeof(string)));

                foreach (DataRow DRow in dTableNotiHis.Rows)
                {
                    DataRow dr = dt.NewRow();
                    dr["InfoID"]    = DRow["InfoID"].ToString();
                    dr["Heading"]   = DRow["Heading"].ToString();
                    dr["IssueDate"] = DRow["IssueDate"].ToString();
                    dr["ImageUrl"]  = string.IsNullOrEmpty(DRow["ImageUrl"].ToString()) ? "" : DRow["ImageUrl"].ToString().IndexOf("http") >= 0 ? DRow["ImageUrl"].ToString() : imageAddr + DRow["ImageUrl"].ToString();

                    dt.Rows.Add(dr);
                }
                result += JSONHelper.FromString(dt);
            }
            else
            {
                result += JSONHelper.FromString(dTableNotiHis);
            }
            #endregion
            dTableNotiHis.Dispose();
            return(result);
        }
Example #28
0
        //删除卡、密码
        //type   永久密码、临时密码、永久卡片、临时卡片
        //recoverDelType  1  删除   2  解冻    3 冻结
        //时间为时间格式
        public string delAction(string userId, string type, string startTime, string endTime, string lockId, string recoverDelType)
        {
            string url       = string.Empty;
            string sqlSuffix = string.Empty;//确认数据后缀
            //string sqlDelSuffix = string.Empty; //删除,冻结,解冻后缀
            string operateType = string.Empty;

            if (recoverDelType == "1") //删除
            {
                url       = delCardPass;
                sqlSuffix = "IsValid='1'";
                //sqlDelSuffix = "IsValid='0'";
                operateType = "删除";
            }
            else if (recoverDelType == "2")  //解冻
            {
                url       = recoverPwdICCard;
                sqlSuffix = "Status='1'";
                //sqlDelSuffix = "Status='0'";
            }
            else //冻结
            {
                url       = delCardPass;
                sqlSuffix = "Status='0'";
                //sqlDelSuffix = "Status='1'";
                operateType = "冻结";
            }
            Dictionary <string, string> ret = new Dictionary <string, string>();
            string ICCardPass      = string.Empty;
            string tableUIP        = string.Empty;
            string tableIP         = string.Empty;
            string fieldIP         = string.Empty;
            string firldICCardPass = string.Empty;
            string isExistence     = string.Empty;
            string setICCardPass   = string.Empty;
            string ID = string.Empty;

            if (type == "临时卡片" || type == "永久卡片")
            {
                tableUIP = "v_RentICCard_view";
                //tableIP = "Rent_Locks_ICCards";
                fieldIP         = "ICCardId";
                firldICCardPass = "******";
                setICCardPass   = "******";
                isExistence     = "ICCard";
            }
            else
            {
                tableUIP = "v_RentPass_view";
                //tableIP = "Rent_Locks_Password";
                fieldIP         = "PassId";
                firldICCardPass = "******";
                setICCardPass   = "******";
                isExistence     = "IsAdd";
            }
            //确定数据库ICCard或者临时密码
            string    sqlUser = "******" + tableUIP + " where UserId='" + userId + "'and LockID='" + lockId + "' and StartDate='" + startTime + "' and EndDate='" + endTime + "' and " + sqlSuffix + "";
            DataTable dt1     = MySQLHelper.ExecuteDataset(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sqlUser)).Tables[0];

            if (dt1.Rows.Count > 0)
            {
                if (recoverDelType != "1" && dt1.Rows[0]["IsValid"].ToString() == "0")
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "该密码已被删除,不能进行操作");
                    return(JSONHelper.ToJson(ret));
                }
                if (string.Empty == dt1.Rows[0][isExistence].ToString().Trim())  // 判断密码和卡片是否被录入
                {
                    ret.Add("ret", "1");
                    ret.Add("msg", "该信息尚未被录入锁中,请重新添加!");
                    return(JSONHelper.ToJson(ret));
                }
                ICCardPass = dt1.Rows[0][firldICCardPass].ToString().Trim();
                ID         = dt1.Rows[0]["ID"].ToString().Trim();
            }
            if (string.Empty == ICCardPass)
            {
                ret.Add("ret", "0");
                ret.Add("msg", "暂无信息");
                return(JSONHelper.ToJson(ret));
            }
            Dictionary <string, string> delRet = new Dictionary <string, string>();

            delRet.Add("appKey", appKey);
            delRet.Add("appSecret", appSecret);
            delRet.Add("userid", userId);
            delRet.Add("type", type);
            delRet.Add("startTime", GetCreatetime(DateTime.Parse(startTime)));
            delRet.Add("endTime", GetCreatetime(DateTime.Parse(endTime)));
            delRet.Add(setICCardPass, ICCardPass);
            if (recoverDelType != "2")
            {
                delRet.Add("operate", operateType);
            }
            string json        = JSONHelper.ToJson(delRet);
            string getPostInfo = LigerRM.Common.WebRequestHelper.WebRequestPoster.JsonHttpPost(url, json, "parameters");  //调用远程
            Dictionary <string, object> returnInfo = new Dictionary <string, object>();

            returnInfo = JSONHelper.FromJson <Dictionary <string, object> >(getPostInfo);
            if (returnInfo["success"].ToString() == "True")
            {
                //修改数据库删除状态,冻结状态  IsValid  0  删除   1 不删除  Status 0 启用  1 禁用
                //string sqlDel = "update " + tableIP + " set " + sqlDelSuffix + " where ID=" + ID;
                //MySQLHelper.ExecuteNonQuery(MySQLHelper.SqlConnString, MySQLHelper.CreateCommand(sqlDel));
                ret.Add("ret", "0");
                ret.Add("msg", returnInfo["msg"].ToString());
            }
            else
            {
                ret.Add("ret", "1");
                ret.Add("msg", returnInfo["msg"].ToString());
            }
            AddLockNewLog(lockId, type, returnInfo["msg"].ToString());   //增加新锁的log请求返回日志
            return(JSONHelper.ToJson(ret));
        }
        /// <summary>
        /// 亲情提示、社区资讯
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public string CommunityNotificationTWList(DataRow Row)
        {
            string result = "";

            try
            {
                #region 接受参数
                string strUserId      = "";
                string strCommunityId = "";   //项目ID
                string strCurrPage    = "1";  //第几页
                string strPageSize    = "10"; //分页的大小

                if (Row.Table.Columns.Contains("CommunityId"))
                {
                    strCommunityId = AppGlobal.ChkStr(Row["CommunityId"].ToString());
                }
                else
                {
                    return(JSONHelper.FromString(false, "缺少参数CommID"));
                }
                if (Row.Table.Columns.Contains("UserID") && !string.IsNullOrEmpty(Row["UserID"].ToString()))
                {
                    strUserId = Row["UserID"].ToString();
                }
                if (Row.Table.Columns.Contains("CurrPage"))
                {
                    strCurrPage = AppGlobal.ChkNum(Row["CurrPage"].ToString());
                }

                if (Row.Table.Columns.Contains("PageSize"))
                {
                    strPageSize = AppGlobal.ChkNum(Row["PageSize"].ToString());
                }


                #endregion

                #region 变量定义
                string SQLContionString = "";

                int           PageCount    = 0;
                int           Counts       = 0;
                StringBuilder sListContent = new StringBuilder("");

                int iCurrPage = AppGlobal.StrToInt(strCurrPage);
                int iPageSize = AppGlobal.StrToInt(strPageSize);


                #endregion
                SQLContionString = ConnectionDb.GetConnection(Row["CommunityId"].ToString());
                MobileSoft.Model.Unified.Tb_Community Community = new MobileSoft.BLL.Unified.Bll_Tb_Community().GetModel(Row["CommunityId"].ToString());

                if (Community == null)
                {
                    return(JSONHelper.FromString(false, "该小区不存在"));
                }

                #region 查询亲情提示、社区咨询

                string strSQLNotiHis;


                switch (Community.CorpID)
                {
                case 1975:       // 华南城社区新闻设置了多选小区发放功能
                    strSQLNotiHis = " and isnull(IsDelete,0)=0 and isnull(IsAudit, 0)=0 AND (CommID=0 OR CommID = " + Community.CommID + " OR CHARINDEX('" + Community.CommID + "',CommIdNvarchar)>0) and (InfoType = 'qqts' or InfoType = 'dtzx') AND (ShowEndDate is null or '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'< ShowEndDate) ";

                    break;
                //case 1973:
                //    strSQLNotiHis = " and isnull(IsDelete,0)=0 and isnull(IsAudit, 0)=0 AND (CommID=0 OR CommID = " + Community.CommID + ") and InfoType = 'dtzx' AND (ShowEndDate is null or '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'< ShowEndDate) ";

                //    break;
                default:
                    strSQLNotiHis = " and isnull(IsDelete,0)=0 and isnull(IsAudit, 0)=0 AND (CommID=0 OR CommID = " + Community.CommID + ") and (InfoType = 'qqts' or InfoType = 'dtzx') AND (ShowEndDate is null or '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "'< ShowEndDate) ";

                    break;
                }


                DataTable dTableNotiHis = null;
                dTableNotiHis = (new Business.TWBusinRule(SQLContionString)).HSPR_CommunityInfo_CutPage(out PageCount, out Counts, strSQLNotiHis, iCurrPage, iPageSize);

                if (!pageHasData(iCurrPage, PageCount, Counts))
                {
                    dTableNotiHis.Dispose();
                    dTableNotiHis = new DataTable();
                }

                if (dTableNotiHis.Rows.Count > 0)
                {
                    using (IDbConnection conn = new SqlConnection(PubConstant.UnifiedContionString))
                    {
                        DataTable dt = new DataTable();
                        dt.Columns.Add(new DataColumn("InfoID", typeof(string)));
                        dt.Columns.Add(new DataColumn("Heading", typeof(string)));
                        dt.Columns.Add(new DataColumn("IssueDate", typeof(string)));
                        dt.Columns.Add(new DataColumn("ImageUrl", typeof(string)));
                        dt.Columns.Add(new DataColumn("IsRead", typeof(int)));

                        string sql = @"SELECT count(0) FROM Tb_BBS_ReadRecord WHERE InfoID=@InfoID AND UserID=@UserID";

                        foreach (DataRow DRow in dTableNotiHis.Rows)
                        {
                            DataRow dr = dt.NewRow();
                            dr["InfoID"]    = DRow["InfoID"].ToString();
                            dr["Heading"]   = DRow["Heading"].ToString();
                            dr["IssueDate"] = DRow["IssueDate"].ToString();
                            dr["ImageUrl"]  = string.IsNullOrEmpty(DRow["ImageUrl"].AsString()) ? "" : DRow["ImageUrl"].AsString().IndexOf("http") >= 0 ? DRow
                                              ["ImageUrl"].AsString() : imageAddr + DRow["ImageUrl"].AsString();

                            if (!string.IsNullOrEmpty(strUserId))
                            {
                                dr["IsRead"] = conn.Query <int>(sql, new { InfoID = DRow["InfoID"].ToString(), UserID = strUserId }).FirstOrDefault();
                            }
                            else
                            {
                                dr["IsRead"] = 0;
                            }

                            dt.Rows.Add(dr);
                        }
                        result += JSONHelper.FromString(dt);
                    }
                }
                else
                {
                    result += JSONHelper.FromString(dTableNotiHis);
                }
                #endregion
                dTableNotiHis.Dispose();
            }
            catch (Exception ex)
            {
                result = ex.Message + "\r\n" + ex.StackTrace;
            }
            return(result);
        }
Example #30
0
        //添加家庭
        public string createHomeInfo(string familyName)
        {
            Dictionary <string, string> setRet = new Dictionary <string, string>();
            Dictionary <string, string> ret    = new Dictionary <string, string>();

            setRet.Add("appKey", appKey);
            setRet.Add("appSecret", appSecret);
            setRet.Add("username", accountOpening);
            setRet.Add("familyName", familyName);
            string getPostInfo = LigerRM.Common.WebRequestHelper.WebRequestPoster.JsonHttpPost(createHomeUrl, JSONHelper.ToJson(setRet), "parameters");

            LogManager.WriteLog("Get:" + getPostInfo);
            Dictionary <string, object> returnInfo = new Dictionary <string, object>();

            returnInfo = JSONHelper.FromJson <Dictionary <string, object> >(getPostInfo);
            if (returnInfo["success"].ToString() == "True")
            {
                ret.Add("ret", "0");
            }
            else
            {
                ret.Add("ret", "1");
            }
            ret.Add("msg", returnInfo["msg"].ToString());
            AddLockNewLog(familyName, "添加家庭", returnInfo["msg"].ToString());   //增加新锁的log请求返回日志
            return(JSONHelper.ToJson(ret));
        }
Example #31
0
 /// <summary>
 /// 获取json响应
 /// </summary>
 /// <param name="responseData"></param>
 /// <returns></returns>
 public static string LoadResponseJSONStr(object responseData)
 {
     return(JSONHelper.GetJsonString(responseData));
 }
		public void Serialize()
		{
			Person p = new Person("Json", 23);
			JSONHelper helper = new JSONHelper();
			Assert.AreEqual("{\"Name\":\"Json\",\"Age\":23}", helper.ToJSON(p));
		}
Example #33
0
        public string GetAreaModelByMoveStockADF(int WareHouseID, string AreaNo, string ModelJson)
        {
            BaseMessage_Model <T_AreaInfo> messageModel = new BaseMessage_Model <T_AreaInfo>();

            try
            {
                int StockStatus = 0;

                if (string.IsNullOrEmpty(ModelJson))
                {
                    messageModel.HeaderStatus = "E";
                    messageModel.Message      = "客户端传来库存JSON为空!";
                    return(JSONHelper.ObjectToJson <BaseMessage_Model <T_AreaInfo> >(messageModel));
                }

                string     strError = string.Empty;
                T_AreaInfo model    = new T_AreaInfo();
                model.AreaNo      = AreaNo;
                model.WarehouseID = WareHouseID;
                bool bSucc = base.GetModelBySql(ref model, ref strError);

                if (bSucc == false)
                {
                    messageModel.HeaderStatus = "E";
                    messageModel.Message      = strError;
                    return(JSONHelper.ObjectToJson <BaseMessage_Model <T_AreaInfo> >(messageModel));
                }

                if (model.AreaStatus == 2)
                {
                    messageModel.HeaderStatus = "E";
                    messageModel.Message      = "该库位已被锁定";
                    return(JSONHelper.ObjectToJson <BaseMessage_Model <T_AreaInfo> >(messageModel));
                }

                List <T_StockInfo> lstStock = new List <T_StockInfo>();
                lstStock = JSONHelper.JsonToObject <List <T_StockInfo> >(ModelJson);
                T_Stock_DB tdb = new T_Stock_DB();
                StockStatus = tdb.GetMaterialStatusByAreaID(WareHouseID, AreaNo, lstStock[0].MaterialNoID, lstStock[0].BatchNo);

                if (lstStock[0].AreaType == 4)
                {
                    if (StockStatus == 0)
                    {
                        messageModel.HeaderStatus = "E";
                        messageModel.Message      = "该库位不存在扫描的条码!";
                        return(JSONHelper.ObjectToJson <BaseMessage_Model <T_AreaInfo> >(messageModel));
                    }
                }
                else
                {
                    if (StockStatus > 0)
                    {
                        if (lstStock[0].Status != StockStatus)
                        {
                            messageModel.HeaderStatus = "E";
                            messageModel.Message      = "条码当前库位存在不同质检状态,不能移库!";
                            return(JSONHelper.ObjectToJson <BaseMessage_Model <T_AreaInfo> >(messageModel));
                        }
                    }
                }

                if (StockStatus == 0)
                {
                    model.IsQuality = lstStock[0].Status;
                }
                else
                {
                    model.IsQuality = StockStatus;
                }

                messageModel.HeaderStatus = "S";
                messageModel.ModelJson    = model;

                return(JSONHelper.ObjectToJson <BaseMessage_Model <T_AreaInfo> >(messageModel));
            }
            catch (Exception ex)
            {
                messageModel.HeaderStatus = "E";
                messageModel.Message      = ex.Message;
                return(JSONHelper.ObjectToJson <BaseMessage_Model <T_AreaInfo> >(messageModel));
            }
        }
        public void GetContractDetails(string SessionKey, string Filter)
        {
            JSONHelper jhelper = new JSONHelper(Context);
            try
            {
                userKey = Authentication.ValidateKey(SessionKey);
                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch
            {
                throw;
            }

            if (string.IsNullOrEmpty(Filter))
            {
                jhelper.WriteJSONResponse("{'error':'No filter provided.'}", HttpStatusCode.Forbidden);
                AddUsage("Error: no filter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                return;
            }

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary object (default for an array shape)
            // THESE ARE THE FILTERS PROVIDED BY CALLER
            //Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();

            Dictionary<string, object> filtersProvided = ser.Deserialize<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "player", null },
                { "year", null }
            };

            // Check if any of the filters provided are bad.
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault(); //filtersProvided.FirstOrDefault(x => !filtersAllowed.ContainsKey(x.Key)).Key;

            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            int? player = filtersProcessed.Extract<int>("player");
            int? year = filtersProcessed.Extract<int>("year");

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);
            var query = (from C in dc.Contracts
                         from P in dc.Players.Where(p => p.Index == C.Player).DefaultIfEmpty()
                         from Y in dc.Years.Where(y => y.Index == C.Year).DefaultIfEmpty()
                         from U in dc.Countries.Where(u => u.Index == C.CurrID).DefaultIfEmpty()
                         from MU in dc.Countries.Where(mu => mu.Index == C.MinCurr).DefaultIfEmpty()
                         where
                     (player == null || player == C.Player)
                     && (year == null || C.Year >= year)
                         select new
                         {
                             ID = C.Index.ToString(),
                             Player = P == null ? null : new { ID = P.Index.ToString(), Name = P.LastName + ", " + P.FirstName },
                             Year = Y == null ? null : new { ID = Y.Index.ToString(), Name = Y.Name },
                             BaseSalary = C.BaseSal.ToString(),
                             Signing = C.Signing.ToString(),
                             Deferred = C.Deferred.ToString(),
                             Reporting = C.Reporting.ToString(),
                             Other = C.Other.ToString(),
                             AHL = C.AHL.ToString(),
                             IHL = C.IHL.ToString(),
                             ECHL = C.ECHL.ToString(),
                             Junior = C.Junior.ToString(),
                             Guarantee = C.Guarantee.ToString(),
                             TotComp = C.TotComp.ToString(),
                             OriginalAmount = C.OrigAmt.ToString(),
                             Bonus = C.Bonus.ToString(),
                             HasOptionYear = C.OptionYr,
                             OptionOF = C.OptionOF,
                             CountsTowardsCap = C.CntCap,
                             Currency = U == null ? null : new { ID = U.Index.ToString(), Name = U.Currency },
                             MinorCurrency = MU == null ? null : new { ID = MU.Index.ToString(), Name = MU.Currency },
                             Notes = C.Notes
                         })
            .Take(2000);

            AddUsage(string.Join(";", Filter), query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                ContractDetails = query.ToArray()
            };

            string strResponse = JsonConvert.SerializeObject(wrapper);
            jhelper.WriteJSONResponse(strResponse);
        }
        public Basic.Framework.Web.BasicResponse <DataContract.JC_AlarmNotificationPersonnelInfo> UpdateJC_AlarmNotificationPersonnel(Sys.Safety.Request.AlarmNotificationPersonnel.AlarmNotificationPersonnelUpdateRequest jC_AlarmNotificationPersonnelrequest)
        {
            var responseStr = HttpClientHelper.Post(Webapi + "/v1/AlarmNotificationPersonnel/UpdateJC_AlarmNotificationPersonnel?token=" + Token, JSONHelper.ToJSONString(jC_AlarmNotificationPersonnelrequest));

            return(JSONHelper.ParseJSONString <BasicResponse <JC_AlarmNotificationPersonnelInfo> >(responseStr));
        }
        public void GetTeams(string SessionKey, string Filter)
        {
            JSONHelper jhelper = new JSONHelper(Context);

            try
            {
                userKey = Authentication.ValidateKey(SessionKey);

                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (string.IsNullOrEmpty(Filter))
            {
                jhelper.WriteJSONResponse("{'error':'No filter provided.'}", HttpStatusCode.Forbidden);
                AddUsage("Error: no filter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                return;
            }

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary object (default for an array shape)
            // THESE ARE THE FILTERS PROVIDED BY CALLER
            //            Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();
            Dictionary<string, object> filtersProvided = ser.Deserialize<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "ids", null },
                { "leaguename", null },
                { "leagueid", null },
                { "teamname", null},
                { "active", null}
            };

            // Check if any of the filters provided are bad.
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault(); //filtersProvided.FirstOrDefault(x => !filtersAllowed.ContainsKey(x.Key)).Key;

            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            //string ids = filtersProcessed.ExtractReference<string>("ids");
            int[] idsArray = filtersProcessed.ExtractArray<int>("ids");

            string leaguename = filtersProcessed.ExtractReference<string>("leaguename"); ;
            int? leagueid = filtersProcessed.Extract<int>("leagueid");
            string teamname = filtersProcessed.ExtractReference<string>("teamname"); ;
            bool? active = filtersProcessed.Extract<bool>("active"); ;

            if (!idsArray.Any() && string.IsNullOrEmpty(leaguename) && string.IsNullOrEmpty(teamname) && !leagueid.HasValue)
            {
                jhelper.WriteJSONResponse("{'error':'No ID, LeagueID or LeagueName provided.'}", HttpStatusCode.Forbidden);
                AddUsage("Error: No ID, LeagueID, TeamName or LeagueName provided.", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                return;
            }

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);
            var query = (from T in dc.Teams
                         from L in dc.Leagues.Where(l => l.Index == T.League).DefaultIfEmpty()
                         where (!idsArray.Any()  || idsArray.Contains(T.Index))
                             && (leaguename == null || (T.LeagueRow != null && T.LeagueRow.LongName.ToLower() == leaguename))
                             && (teamname == null || (T.LeagueRow != null && T.LongName.ToLower().Contains(teamname)))
                             && (!leagueid.HasValue || T.League == leagueid)
                             && (!active.HasValue || T.InActive == !active) // Invert
                         select new
                         {
                             ID = T.Index.ToString(),
                             CityName = T.CityName,
                             League = L == null ? null : new { ID = T.League.ToString(), Name = L.LongName },
                             T.LongName,
                             T.ShortName,
                             Active = !T.InActive
                         }).Take(2000);

            //TeamContainer container = new TeamContainer(query.ToArray());
            AddUsage(string.Join(";", idsArray), query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                Teams = query.ToArray()
            };

            string strResponse = JsonConvert.SerializeObject(wrapper);
            jhelper.WriteJSONResponse(strResponse);
        }
        public Basic.Framework.Web.BasicResponse DeleteJC_AlarmNotificationPersonnel(AlarmNotificationPersonnelDeleteRequest jC_AlarmNotificationPersonnelrequest)
        {
            var responseStr = HttpClientHelper.Post(Webapi + "/v1/AlarmNotificationPersonnel/DeleteJC_AlarmNotificationPersonnel?token=" + Token, JSONHelper.ToJSONString(jC_AlarmNotificationPersonnelrequest));

            return(JSONHelper.ParseJSONString <BasicResponse>(responseStr));
        }
        public void GetFreeAgents(string SessionKey, string Filter = "")
        {
            JSONHelper jhelper = new JSONHelper(Context);

            try
            {
                userKey = Authentication.ValidateKey(SessionKey);

                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            //if (string.IsNullOrEmpty(Filter))
            //{
            //    jhelper.WriteJSONResponse("{'error':'No filter provided.'}", HttpStatusCode.Forbidden);
            //    AddUsage("Error: no filter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
            //    return;
            //}

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary object (default for an array shape)
            // THESE ARE THE FILTERS PROVIDED BY CALLER
            Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "playerid", null },
                { "freeagenttype", null }
            };

            // Check if any of the filters provided are bad.
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault(); //filtersProvided.FirstOrDefault(x => !filtersAllowed.ContainsKey(x.Key)).Key;

            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            int? playerid = filtersProcessed.Extract<int>("playerid");
            int? freeagenttypeid = filtersProcessed.Extract<int>("freeagenttypeid");

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);
            var query = (
                from F in dc.FreeAgents
                from P in dc.Players.Where(p => p.Index == F.Player).DefaultIfEmpty()
                from T in dc.FreeAgentTypes.Where(t => t.Index == F.Group).DefaultIfEmpty()
                from C in dc.Countries.Where(c => c.Index == F.SalCurr).DefaultIfEmpty()
                from MC in dc.Countries.Where(mc => mc.Index == F.MinCurr).DefaultIfEmpty()
                where (playerid == null || F.Player == playerid)
                    && (freeagenttypeid == null || F.Group == freeagenttypeid)
                select new
                {
                    ID = F.Index.ToString(),
                    Player = P == null ? null : new { ID = P.Index.ToString(), Name = P.LastName + ", " + P.FirstName },
                    FreeAgentType = T == null ? null : new { ID = P.Index.ToString(), Name = T.Description },
                    CurrentSalary = F.CurSal.ToString(),
                    SalaryCurrency = C == null ? null : new { ID = C.Index.ToString(), Name = C.Currency },
                    MinorSalary = F.MinorSal.ToString(),
                    MinorCurrency = MC == null ? null : new { ID = MC.Index.ToString(), Name = MC.Currency },
                    MinorOffer = F.MinOffer.ToString(),
                    SalaryArbitration = F.SalArb
                }).Take(2000);

            // Log the query
            AddUsage(Filter, query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                FreeAgents = query.ToArray()
            };

            string result = JsonConvert.SerializeObject(wrapper);

            jhelper.WriteJSONResponse(result);
        }
        public Basic.Framework.Web.BasicResponse <List <DataContract.JC_AlarmNotificationPersonnelInfo> > GetAlarmNotificationPersonnelByAnalysisModelId(Sys.Safety.Request.AlarmNotificationPersonnel.AlarmNotificationPersonnelGetListByAlarmConfigIdRequest jC_AlarmNotificationPersonnelListByAlarmConfigIdRequest)
        {
            var responseStr = HttpClientHelper.Post(Webapi + "/v1/AlarmNotificationPersonnel/GetAlarmNotificationPersonnelByAnalysisModelId?token=" + Token, JSONHelper.ToJSONString(jC_AlarmNotificationPersonnelListByAlarmConfigIdRequest));

            return(JSONHelper.ParseJSONString <BasicResponse <List <DataContract.JC_AlarmNotificationPersonnelInfo> > >(responseStr));
        }
        public void GetParticipations(string SessionKey, string Filter)
        {
            JSONHelper jhelper = new JSONHelper(Context);
            try
            {
                userKey = Authentication.ValidateKey(SessionKey);
                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch
            {
                throw;
            }

            if (string.IsNullOrEmpty(Filter))
            {
                jhelper.WriteJSONResponse("{'error':'No filter provided.'}", HttpStatusCode.Forbidden);
                AddUsage("Error: no filter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                return;
            }

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary object (default for an array shape)
            // THESE ARE THE FILTERS PROVIDED BY CALLER
            //Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            System.Web.Script.Serialization.JavaScriptSerializer ser = new System.Web.Script.Serialization.JavaScriptSerializer();

            Dictionary<string, object> filtersProvided = ser.Deserialize<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "player", null },
                { "participation", null }
            };

            // Check if any of the filters provided are bad.
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault(); //filtersProvided.FirstOrDefault(x => !filtersAllowed.ContainsKey(x.Key)).Key;

            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            int? player = filtersProcessed.Extract<int>("player");
            int? participation = filtersProcessed.Extract<int>("participation");

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);
            var query = (from A in dc.Particips
                         from P in dc.Players.Where(p => p.Index == A.Player).DefaultIfEmpty()
                         from Y in dc.Years.Where(y => y.Index == A.Year).DefaultIfEmpty()
                         from T in dc.ParticipTypes.Where(t => t.Index == A.ParticipType).DefaultIfEmpty()
                         where
                        (player == null || player == A.Player)
                     && (participation == null || A.ParticipType >= participation)

                         select new
                         {
                             ID = A.Index.ToString(),
                             Player = P == null ? null : new { ID = P.Index.ToString(), Name = P.LastName + ", " + P.FirstName },
                             Year = Y == null ? null : new { ID = Y.Index.ToString(), Name = Y.Name },
                             ParticipationType = T == null ? null : new { ID = T.Index.ToString(), Name = T.Description }
                         })
            .Take(2000);

            AddUsage(string.Join(";", Filter), query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                Participations = query.ToArray()
            };

            string strResponse = JsonConvert.SerializeObject(wrapper);
            jhelper.WriteJSONResponse(strResponse);
        }
        public BasicResponse <List <JC_AlarmNotificationPersonnelInfo> > AddJC_AlarmNotificationPersonnelList(AlarmNotificationPersonnelAddRequest jC_AlarmNotificationPersonnelrequest)
        {
            var responseStr = HttpClientHelper.Post(Webapi + "/v1/AlarmNotificationPersonnel/AddJC_AlarmNotificationPersonnelList?token=" + Token, JSONHelper.ToJSONString(jC_AlarmNotificationPersonnelrequest));

            return(JSONHelper.ParseJSONString <BasicResponse <List <DataContract.JC_AlarmNotificationPersonnelInfo> > >(responseStr));
        }
        public void SearchCustomerTransDetail()
        {
            try
            {
                using (ProxyBE p = new ProxyBE())
                {
                    SearchQuoteMainArgs args = new SearchQuoteMainArgs();
                    args.RowNumberFrom = pagingParm.RowNumberFrom;
                    args.RowNumberTo   = pagingParm.RowNumberTo;
                    args.OrderBy       = "Created desc";

                    if (!string.IsNullOrEmpty(Request["SolutionCode"]))
                    {
                        args.SolutionCode = Request["SolutionCode"].ToString();
                    }
                    if (!string.IsNullOrEmpty(Request["SolutionName"]))
                    {
                        args.SolutionName = Request["SolutionName"].ToString();
                    }
                    if (!string.IsNullOrEmpty(Request["CustomerName"]))
                    {
                        args.CustomerName = Request["CustomerName"].ToString();
                    }
                    if (!string.IsNullOrEmpty(Request["QuoteNo"]))
                    {
                        args.QuoteNo = Request["QuoteNo"].ToString();
                    }
                    if (!string.IsNullOrEmpty(Request["Status"]))
                    {
                        args.Status = Request["Status"].ToString();
                    }
                    if (CurrentUser.PartnerID != Guid.Empty)
                    {
                        args.PartnerID = CurrentUser.PartnerID;
                    }

                    SearchResult sr = p.Client.SearchQuote(SenderUser, args);
                    Response.Write(JSONHelper.Dataset2Json(sr.DataSet));

                    #region
                    //SearchOrderArgs
                    //SearchCustomerTransDetailArgs args = new SearchCustomerTransDetailArgs();
                    //args.RowNumberFrom = pagingParm.RowNumberFrom;
                    //args.RowNumberTo = pagingParm.RowNumberTo;
                    //args.OrderBy = "Created desc";

                    //if (CurrentUser.PartnerID!=Guid.Empty)
                    //{
                    //   args.PartnerID = CurrentUser.PartnerID;
                    //}
                    //if(!string.IsNullOrEmpty(Request["CustomerName"]))
                    //{
                    //    args.CustomerName = Request["CustomerName"].ToString();
                    //}
                    //if (!string.IsNullOrEmpty(Request["LinkMan"]))
                    //{
                    //    args.LinkMan = Request["LinkMan"].ToString();
                    //}
                    //if (!string.IsNullOrEmpty(Request["Mobile"]))
                    //{
                    //    args.Mobile = Request["Mobile"].ToString();
                    //}
                    //SearchResult sr = p.Client.SearchCustomerTransDetail(SenderUser,args);

                    #endregion
                }
            }
            catch (Exception ex)
            {
                WriteError(ex.Message, ex);
            }
        }
Example #43
0
        /// <summary>
        /// 获取社区广播信息,包含社区资讯、亲情提示、社区文化、服务指南、社区活动,只获取ERP数据
        /// </summary>
        private string GetERPTopNotice(DataRow row)
        {
            if (!row.Table.Columns.Contains("CommunityId") || string.IsNullOrEmpty(row["CommunityId"].AsString()))
            {
                return(new ApiResult(false, "缺少参数CommunityId").toJson());
            }

            var communityId = row["CommunityId"].AsString();

            var community = GetCommunity(communityId);

            if (community == null)
            {
                return(JSONHelper.FromString(false, "未查询到小区信息"));
            }

            PubConstant.hmWyglConnectionString = GetConnectionStr(community);

            using (var conn = new SqlConnection(PubConstant.hmWyglConnectionString))
            {
                // 是否使用10.0版本活动
                var sql = @"SELECT object_id(N'Tb_HSPR_CommActivities_New',N'U');";

                var v10 = (conn.Query <string>(sql).FirstOrDefault() != null);

                sql = @"SELECT TOP 5 * FROM
                        (
                            SELECT convert(varchar(36),InfoID) AS IID,0 AS IsActivity,IssueDate AS PubDate 
                            FROM Tb_HSPR_CommunityInfo 
                            WHERE isnull(IsDelete,0)=0 AND (CommID=@CommID OR CommID=0)
                            UNION ALL
                            SELECT convert(varchar(36),ActivitiesID) AS IID,1 AS IsActivity,isnull(IssueDate,ActivitiesStartDate) AS PubDate
                            FROM Tb_HSPR_CommActivities 
                            WHERE isnull(IsDelete,0)=0 AND (CommID=@CommID OR CommID=0)
                        ) AS t
                        ORDER BY t.PubDate DESC;";

                if (v10)
                {
                    sql = @"SELECT TOP 5 * FROM
                            (
                                SELECT convert(varchar(36),InfoID) AS IID,0 AS IsActivity,IssueDate AS PubDate 
                                FROM Tb_HSPR_CommunityInfo 
                                WHERE isnull(IsDelete,0)=0 AND (CommID=@CommID OR CommID=0)
                                UNION ALL
                                SELECT convert(varchar(36),ActivitiesID) AS IID,1 AS IsActivity,CreateTime AS PubDate 
                                FROM Tb_HSPR_CommActivities_New 
                                WHERE isnull(IsDelete,0)=0 AND (CommID=@CommID OR CommID=0)
                            ) AS t
                            ORDER BY t.PubDate DESC;";
                }

                var data = conn.Query(sql, new { CommID = community.CommID });

                var infos = new List <dynamic>();

                foreach (dynamic item in data)
                {
                    if (item.IsActivity == 0)
                    {
                        sql = @"SELECT convert(varchar(36),InfoID) AS IID,Heading AS Title,ImageUrl AS Image,IssueDate AS PubDate,
                                    InfoType AS Type,0 AS IsActivity,0 AS IsEnd,'5' AS Version  
                                FROM Tb_HSPR_CommunityInfo 
                                WHERE InfoID=@IID";
                    }
                    else
                    {
                        if (v10)
                        {
                            sql = @"SELECT convert(varchar(36),ActivitiesID) AS IID,a.ActivitiesTheme AS Title,a.ActivitiesImages AS Image,
                                        isnull(a.LastModifyTime,a.CreateTime) AS PubDate,
                                        null AS Type,1 AS IsActivity,ActivitiesStartDate,ActivitiesEndDate,
                                        CASE WHEN ActivitiesEndDate<getdate() THEN 1 ELSE 0 END AS IsEnd,
                                        '10' AS Version
                                    FROM Tb_HSPR_CommActivities_New a
                                    LEFT JOIN Tb_Dictionary_Activities b ON a.ActivitiesCategory=b.DictionaryCode
                                    WHERE a.ActivitiesID=@IID";
                        }
                        else
                        {
                            sql = @"SELECT convert(varchar(36),ActivitiesID) AS IID,ActivitiesTheme AS Title,ActivitiesImages AS Image,
                                        isnull(IssueDate,ActivitiesStartDate) AS PubDate,
                                        null AS Type,1 AS IsActivity,ActivitiesStartDate,ActivitiesEndDate,
                                        CASE WHEN ActivitiesEndDate<getdate() THEN 1 ELSE 0 END AS IsEnd,
                                        '5' AS Version 
                                    FROM Tb_HSPR_CommActivities WHERE isnull(IsDelete,0)=0
                                    WHERE a.ActivitiesID=@IID";
                        }
                    }

                    var tmp = conn.Query(sql, new { IID = item.IID }).FirstOrDefault();
                    if (tmp != null)
                    {
                        infos.Add(tmp);
                    }
                }

                infos.ForEach(obj =>
                {
                    if (obj.Image != null && string.IsNullOrEmpty(obj.Image.Trim(new char[] { ',' })))
                    {
                        obj.Image = obj.Image.ToString().Split(',')[0];
                    }
                });

                return(new ApiResult(true, infos).toJson());
            }
        }
        public void GetDraftTypes(string SessionKey)
        {
            JSONHelper jhelper = new JSONHelper(Context);
            try
            {
                userKey = Authentication.ValidateKey(SessionKey);
                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch
            {
                throw;
            }

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);
            var query = dc.DraftTypes
                .Select(x => new Objects.DraftType
                {
                    ID = x.Index.ToString(),
                    Name = x.Description
                })
                .Take(2000);

            AddUsage(string.Join(";", ""), query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                DraftTypes = query.ToArray()
            };

            string strResponse = JsonConvert.SerializeObject(wrapper);
            jhelper.WriteJSONResponse(strResponse);
        }
        public BasicResponse <JC_AnalysisTemplateConfigInfo> GetJC_AnalysistemplateconfigById(AnalysisTemplateConfigGetRequest jC_Analysistemplateconfigrequest)
        {
            var responseStr = HttpClientHelper.Post(Webapi + "/v1/AnalysisTemplateConfig/GetJC_AnalysistemplateconfigById?token=" + Token, JSONHelper.ToJSONString(jC_Analysistemplateconfigrequest));

            return(JSONHelper.ParseJSONString <BasicResponse <JC_AnalysisTemplateConfigInfo> >(responseStr));
        }
        public void GetDraftInfo(string SessionKey, string Filter)
        {
            JSONHelper jhelper = new JSONHelper(Context);

            try
            {
                userKey = Authentication.ValidateKey(SessionKey);

                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (string.IsNullOrEmpty(Filter))
            {
                jhelper.WriteJSONResponse("{'error':'No filter provided.'}", HttpStatusCode.Forbidden);
                AddUsage("Error: no filter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                return;
            }

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary object (default for an array shape)
            // THESE ARE THE FILTERS PROVIDED BY CALLER
            Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "playerid", null },
                { "year", null },
                { "drafttype", null },
                { "roundnumber", null },
                { "selectedbyteam", null },
                { "selectedfromteam", null }
            };

            // Check if any of the filters provided are bad.
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault(); //filtersProvided.FirstOrDefault(x => !filtersAllowed.ContainsKey(x.Key)).Key;

            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);

            var query =
                        (from D in dc.DraftDetails
                        from P in dc.Players.Where(p => p.Index == D.Player).DefaultIfEmpty()
                        from DT in dc.DraftTypes.Where(dt => dt.Index == D.Type).DefaultIfEmpty()
                        from DTT in dc.Teams.Where(sbt => sbt.Index == D.Team).DefaultIfEmpty() // Drafted To Team
                        from DFT in dc.Teams.Where(dft => dft.Index == D.TeamFrom).DefaultIfEmpty() // Drafted From Team
                        from DY in dc.DraftYears.Where(dy => dy.Index == D.Year).DefaultIfEmpty()
                         where
                            (filtersProcessed.Extract<int>("playerid") == null || D.Player == filtersProcessed.Extract<int>("playerid"))
                            && (filtersProcessed.Extract<int>("drafttype") == null || D.Type == filtersProcessed.Extract<int>("drafttype"))
                            && (filtersProcessed.Extract<int>("year") == null || D.Year == filtersProcessed.Extract<int>("year"))
                            && (filtersProcessed.Extract<int>("roundnumber") == null || D.Round == filtersProcessed.Extract<int>("roundnumber"))
                            && (filtersProcessed.Extract<int>("selectedbyteam") == null || D.Team == filtersProcessed.Extract<int>("selectedbyteam"))
                            && (filtersProcessed.Extract<int>("selectedfromteam") == null || D.TeamFrom == filtersProcessed.Extract<int>("selectedfromteam"))
                            orderby D.Overall ascending
                         select new
                         {
                             DraftType = new { ID = DT.Index.ToString(), Name = DT.Description },
                             Round = D.Round.HasValue ? D.Round.ToString() : null,
                             Overall = D.Overall.HasValue ? D.Overall.ToString() : null,
                             Player = new {ID = P.Index.ToString(), FirstName = P.FirstName, LastName = P.LastName},
                             SelectedByTeam = new { ID = D.Team.ToString(), City = DTT.CityName, Name = DTT.LongName },
                             SelectedFromTeam = new { ID = D.TeamFrom.ToString(), City = DFT.CityName, Name = DFT.LongName },
                             DraftYear = new { ID = D.Year.ToString(), Year = DY.Year }
                         })
                        .Take(2000);

            // Log the query
            AddUsage(Filter, query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                DraftInfo = query.ToArray()
            };

            string result = JsonConvert.SerializeObject(wrapper);

            jhelper.WriteJSONResponse(result);
        }
        public void GetSkaterStats(string SessionKey, string Filter)
        {
            JSONHelper jhelper = new JSONHelper(Context);

            try
            {
                userKey = Authentication.ValidateKey(SessionKey);

                if (userKey == null)
                {
                    jhelper.WriteJSONResponse("{'error':'Invalid or missing session key.'}", HttpStatusCode.Unauthorized);
                    AddUsage("Failed authentication", null, System.Reflection.MethodBase.GetCurrentMethod().Name, "");
                    return;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (string.IsNullOrEmpty(Filter))
            {
                jhelper.WriteJSONResponse("{'error':'No filter provided.'}", HttpStatusCode.Forbidden);
                AddUsage("Error: no filter", null, System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);
                return;
            }

            // lets allow caller to make case-insenstive calls.
            Filter = Filter.ToLower();

            // Deserialize the provided filter into a dictionary object (default for an array shape)
            // THESE ARE THE FILTERS PROVIDED BY CALLER
            Dictionary<string, object> filtersProvided = JsonConvert.DeserializeObject<Dictionary<string, object>>(Filter);

            // THESE ARE THE FILTERS ALLOWED BY THIS METHOD
            Dictionary<string, object> filtersAllowed = new Dictionary<string, object>
            {
                { "playerid", null },
                { "seasonid", null },
                { "teamid", null },
            };

            // Check if any of the filters provided are bad.
            string badFilterFound = GetBadFilters(filtersAllowed, filtersProvided).FirstOrDefault();

            if (badFilterFound != null)
            {
                jhelper.WriteJSONResponse("{'error':'Invalid filter {" + badFilterFound + "} provided.'}", HttpStatusCode.Forbidden);
                return;
            }

            Dictionary<string, object> filtersProcessed = CombineFilters(filtersAllowed, filtersProvided);

            TeamDataContext dc = TeamDataContext.GetTeamDataContextByDBID(userKey.DatabaseID);

            var query =
             from S in dc.Stats
             .Where(x => x.Goalie == false
                 && (filtersProcessed.Extract<int>("playerid") == null || filtersProcessed.Extract<int>("playerid") == x.Player)
                 && (filtersProcessed.Extract<int>("seasonid") == null || filtersProcessed.Extract<int>("seasonid") == x.Season)
                 && (filtersProcessed.Extract<int>("teamid") == null || filtersProcessed.Extract<int>("teamid") == x.Team)
                 )
                 .Take(2000)
             from G in dc.SkaterStats.Where(g => g.StatID == S.Index).DefaultIfEmpty()
             from E in dc.Seasons.Where(e => e.Index == S.Season).DefaultIfEmpty()
             from P in dc.Players.Where(p => p.Index == S.Player).DefaultIfEmpty()
             from O in dc.Positions.Where(o => o.Index == S.Position).DefaultIfEmpty()
             from T in dc.Teams.Where(t => t.Index == S.Team).DefaultIfEmpty()
             from U in dc.Tournaments.Where(u => u.Index == S.Tourn).DefaultIfEmpty()
             select new
             {
                 ID = S.Index.ToString(),
                 Season = E == null ? null : new { ID = E.Index.ToString(), Name = E.Name },
                 Player = P == null ? null : new { ID = P.Index.ToString(), Name = P.LastName + ", " + P.FirstName },
                 Position = O == null ? null : new { ID = O.Index.ToString(), O.Long },
                 Team = T == null ? null : new { ID = T.Index.ToString(), Name = T.LongName },
                 Tournament = U == null ? null : new
                 {
                    ID = U.Index.ToString(),
                    Name = U.Name,
                    IsPlayoff = U.Playoff
                 },
                 Jersey = S.Jersey,
                 PlayOffs = S.Playoffs,
                 StartDate = S.StartDate,
                 EndDate = S.EndDate,
                 Current = S.Current,
                 Notes = S.Notes,
                 Age = S.Age.ToString(),
                 GamesPlayed = G.GP.ToString(),
                 Goals = G.G.ToString(),
                 Assists = G.A.ToString(),
                 Points = G.Pts.ToString(),
                 PenaltyMinutes = G.Pim.ToString(),
                 PlusMinus = G.PlusMinus.ToString(),
                 PointsPerGame = G.PPG.ToString(),
                 ShortHandedGoals = G.SHG.ToString(),
                 TimeOnIceMinutes = G.TOIM.ToString(),
                 TimeOnIceSeconds = G.TOIS.ToString(),
                 PowerPlayTimeOnIceMinutes = G.PPTOIM.ToString(),
                 PowerPlayTimeOnIceSeconds = G.PPTOIS.ToString(),
                 PenaltyKillTimeOnIceMinutes = G.PKTOIM.ToString(),
                 PenaltyKillTimeOnIceSeconds = G.PKTOIS.ToString(),
                 FaceOffWins = G.FoW.ToString(),
                 FaceOffLosses = G.FoL.ToString(),
                 BlockedShots = G.BlkSh.ToString(),
                 Hits = G.Hits.ToString(),
                 HomeGamesPlayed = G.HGP.ToString(),
                 HomeGoals = G.HG.ToString(),
                 HomeAssists = G.HA.ToString(),
                 HomePoints = G.HPts.ToString(),
                 HomePenaltyMinutes = G.HPim.ToString(),
                 HomePlusMinus = G.HPlusMinus.ToString(),
                 AwayGamesPlayed = G.AGP.ToString(),
                 AwayGoals = G.AG.ToString(),
                 AwayAssists = G.AA.ToString(),
                 AwayPoints = G.APts.ToString(),
                 AwayPenaltyMinutes = G.APim.ToString(),
                 AwayPlusMinus = G.APlusMinus.ToString(),
                 ShootoutShots = G.SoShots.ToString(),
                 ShootoutGoals = G.SoGoals.ToString(),
                 PowerPlayAssists = G.PPA.ToString(),
                 ShortHandedAssists = G.SHA.ToString(),
                 Shots = G.Shots.ToString(),
                 FullStrengthPPM = G.FSPPM.ToString()
             };

            // Log the query
            AddUsage(Filter, query.Count(), System.Reflection.MethodBase.GetCurrentMethod().Name, userKey.UserName);

            var wrapper = new
            {
                SkaterStats = query.ToArray()
            };

            string result = JsonConvert.SerializeObject(wrapper);

            jhelper.WriteJSONResponse(result);
        }