public void ParseShouldParseVoidMethodsWithParameters()
        {
            var requestModel = new RequestModel();
            Expression<Action<WebApiController>> expression = c => c.EmptyActionWithParameters(1, requestModel);
            var result = RouteExpressionParser.Parse<WebApiController>(expression);

            Assert.IsNotNull(result);
            Assert.AreEqual(typeof(WebApiController), result.Controller);
            Assert.AreEqual("EmptyActionWithParameters", result.Action);
            Assert.AreEqual(2, result.Arguments.Count);
            Assert.AreEqual(1, result.Arguments["id"].Value);
            Assert.AreEqual(requestModel, result.Arguments["model"].Value);
        }
        public void ParseShouldParseReturningMethodsWithParameters()
        {
            var requestModel = new RequestModel();
            Expression<Func<WebApiController, IHttpActionResult>> expression = c => c.OkResultActionWithRequestBody(1, requestModel);
            var result = RouteExpressionParser.Parse<WebApiController>(expression);

            Assert.IsNotNull(result);
            Assert.AreEqual(typeof(WebApiController), result.Controller);
            Assert.AreEqual("OkResultActionWithRequestBody", result.Action);
            Assert.AreEqual(2, result.Arguments.Count);
            Assert.AreEqual(1, result.Arguments["id"].Value);
            Assert.AreEqual(requestModel, result.Arguments["model"].Value);
        }
示例#3
0
        public List<DemoGrid> ReadTests(RequestModel model)
        {
            if (model == null) return new List<DemoGrid>();


            //must have at least one from each

            if (model.CampusIds == null || model.SubjectIds == null
                || model.CategoryDetailIds == null || model.DemographicDetailIds == null)
            {
                return new List<DemoGrid>();
            }

            try
            {

                var x = _ctx.StaarTests.Where(s =>
                    model.CampusIds.Contains(s.Campus_Id)
                    && model.SubjectIds.Contains(s.Subject_Id)
                    && (model.CategoryDetailIds.Contains(s.CategoryDetail_Id) || model.CategoryDetailIds.Contains(s.CategoryDetail.PartnerDetail.Id))
                    && model.DemographicDetailIds.Contains(s.DemographicDetail_Id))
                    .Select(s => new
                    {
                        s.Value,
                        SubjectDescription = s.Subject.Description,
                        DemographicName = s.DemographicDetail.Demographic.Name,
                        CategoryName = s.CategoryDetail.Category.Name,
                        DemoDetailDescription = s.DemographicDetail.Description,
                        CatDetailDescription = s.CategoryDetail.Description,
                        CampusName = s.Campus.Name,
                        CountId = s.CategoryDetail.PartnerDetail == null ? 0 : s.CategoryDetail.PartnerDetail.Id,
                        CategoryDetailId = s.CategoryDetail_Id,
                        s.CategoryDetail.CategoryType
                    })
                    .Take(500) //take at most 500 at a time
                    .ToList(); ;

                var list = new List<DemoGrid>(x.Count);
                list.AddRange(from s in x
                              where s.CategoryType != CategoryType.Count
                              let count = x.FirstOrDefault(d => d.CategoryDetailId == s.CountId)
                              let value = count == null ? 0 : count.Value
                              select new DemoGrid
                              {
                                  Count = value,
                                  Percent = s.Value, //this gets the percent value
                                  Subject = s.SubjectDescription,
                                  Demographic = s.DemographicName + ": " + s.DemoDetailDescription,
                                  Category = s.CategoryName + ": " + s.CatDetailDescription,
                                  CampusName = s.CampusName
                              });

                return list;
            }
            catch (Exception ex)
            {

                throw;
            }
            return null;
        }
        /// <summary>
        /// 扩展签名方法
        /// </summary>
        /// <param name="httpWebRequest">当前请求客户端</param>
        /// <param name="credentials">认证参数信息</param>
        /// <param name="bodyContent"></param>
        /// <param name="serviceName"></param>
        /// <param name="signType"></param>
        /// <param name="overrideDate"></param>
        /// <param name="isWriteBody"></param>
        /// <returns></returns>
        public static HttpWebRequest DoSign(this HttpWebRequest httpWebRequest, Credential credentials, string serviceName = null, object bodyContent = null, bool isWriteBody = false, JDCloudSignVersionType?signType = null, DateTime?overrideDate = null)
        {
            var byteContent = new byte[0];

            if (bodyContent != null)
            {
                if (isWriteBody)
                {
                    if (bodyContent is byte[])
                    {
                        byteContent = (byte[])bodyContent;
                    }
                    else if (bodyContent is string)
                    {
                        byteContent = System.Text.Encoding.UTF8.GetBytes((string)bodyContent);
                        //  httpWebRequest.ContentLength = byteContent.Length;
                        //  httpRequestWrite.Write(byteContent, 0, byteContent.Length);
                    }
                    else if (bodyContent is int || bodyContent is long || bodyContent is bool || bodyContent is float || bodyContent is double)
                    {
                        if (bodyContent is int)
                        {
                            byteContent = BitConverter.GetBytes((int)bodyContent);
                        }
                        else if (bodyContent is long)
                        {
                            byteContent = BitConverter.GetBytes((long)bodyContent);
                        }
                        else if (bodyContent is bool)
                        {
                            byteContent = BitConverter.GetBytes((bool)bodyContent);
                        }
                        else if (bodyContent is float)
                        {
                            byteContent = BitConverter.GetBytes((float)bodyContent);
                        }
                        else if (bodyContent is double)
                        {
                            byteContent = BitConverter.GetBytes((double)bodyContent);
                        }
                    }

                    else
                    {
                        var requestJson = JsonConvert.SerializeObject(bodyContent);
                        if (!requestJson.IsNullOrWhiteSpace())
                        {
                            byteContent = System.Text.Encoding.UTF8.GetBytes((string)bodyContent);
                        }
                    }
                }
            }
            var headers        = httpWebRequest.Headers;
            var requestUri     = httpWebRequest.RequestUri;
            var queryString    = requestUri.Query;
            var requestPath    = requestUri.AbsolutePath;
            var requestContent = bodyContent;

            var          requestMethod = httpWebRequest.Method;
            string       apiVersion    = requestUri.GetRequestVersion();
            RequestModel requestModel  = new RequestModel();

            requestModel.Content    = (byte[])byteContent.Clone();
            requestModel.ApiVersion = apiVersion;

            if (!httpWebRequest.ContentType.IsNullOrWhiteSpace())
            {
                requestModel.ContentType = httpWebRequest.ContentType.ToString();
            }
            requestModel.HttpMethod = requestMethod.ToString().ToUpper();
            var pathRegion = requestUri.GetRequestVersion();

            if (!pathRegion.IsNullOrWhiteSpace())
            {
                requestModel.RegionName = pathRegion;
            }
            else
            {
                requestModel.RegionName = ParameterConstant.DEFAULT_REGION;
            }

            requestModel.ResourcePath = requestPath;
            if (!serviceName.IsNullOrWhiteSpace())
            {
                requestModel.ServiceName = serviceName;
            }
            else
            {
                serviceName = requestUri.GetServiceName();
                if (serviceName.IsNullOrWhiteSpace())
                {
                    throw new Exception("service name not config , if you not use default endpoint please config service in sign");
                }
                requestModel.ServiceName = serviceName;
            }
            JDCloudSignVersionType jDCloudSignVersionType = GlobalConfig.GetInstance().SignVersionType;

            if (signType != null && signType.HasValue)
            {
                jDCloudSignVersionType = signType.Value;
            }
            requestModel.SignType        = jDCloudSignVersionType;
            requestModel.Uri             = requestUri;
            requestModel.QueryParameters = queryString;
            requestModel.OverrddenDate   = overrideDate;
            if (!(requestUri.Scheme.ToLower() == "http" && requestUri.Port == 80) &&
                !(requestUri.Scheme.ToLower() == "https" && requestUri.Port == 443))
            {
                requestModel.RequestPort = requestUri.Port;
            }
            foreach (string headerKeyValue in headers.Keys)
            {
                requestModel.AddHeader(headerKeyValue, headers.Get(headerKeyValue));
            }
            IJDCloudSigner     jDCloudSigner      = SignUtil.GetJDCloudSigner(jDCloudSignVersionType);
            SignedRequestModel signedRequestModel = jDCloudSigner.Sign(requestModel, credentials);
            var signedHeader = signedRequestModel.RequestHead;

            foreach (var key in signedHeader.Keys)
            {
                if (httpWebRequest.Headers.GetValues(key) == null)
                {
                    var value = signedHeader[key];
                    httpWebRequest.Headers.Add(key, value);
                }
            }
            if (byteContent.Length > 0)
            {
                httpWebRequest.ContentLength = byteContent.Length;
                using (var httpRequestWrite = httpWebRequest.GetRequestStream())
                {
                    httpRequestWrite.Write(byteContent, 0, byteContent.Length);
                }
            }
            return(httpWebRequest);
        }
示例#5
0
 public ViewModel Execute(RequestModel model)
 {
     return new ViewModel();
 }
 public FullPocoController(RequestModel requestModel)
 {
     this.InjectedRequestModel = requestModel;
 }
 public void EmptyActionWithParameters(int id, RequestModel model)
 {
 }
        public IActionResult ModelStateCheck(RequestModel model)
        {
            if (ModelState.IsValid)
            {
                return this.Ok(model);
            }

            return this.Ok(model);
        }
 /// <summary>
 /// 实体赋值
 /// </summary>
 /// <param name="json"></param>
 public override void SetData(RequestModel json)
 {
     base.SetData(json);
 }
示例#10
0
 public ResponseModel NewEncryptionKey(AutomationKeyModel automationModel, string Email, string UserName, string PlatformCode)
 {
     //Generate IV
     AesCryptoServiceProvider cryptoProvider = new AesCryptoServiceProvider();
     cryptoProvider.KeySize = 256;
     cryptoProvider.GenerateIV();
     string IV = Convert.ToBase64String(cryptoProvider.IV);
     //Encrypt Model
     byte[] data = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(automationModel));
     byte[] key = Convert.FromBase64String(provisionerKey);
     string hash = Convert.ToBase64String(new HMACSHA512(key).ComputeHash(data));
     string data2 = Encrypt(key, Convert.FromBase64String(IV), Newtonsoft.Json.JsonConvert.SerializeObject(automationModel));
     //Construct the request model
     RequestModel requestModel = new RequestModel
     {
         UserName = UserName,
         PlatformCode = PlatformCode,
         IV = IV,
         Data = data2,
         Hash = hash
     };
     var req = new HttpClient();
     req.BaseAddress = new Uri("https://provisioning.datamotion.com:8888/company/NewEncryptionKey");
     req.DefaultRequestHeaders.Accept.Clear();
     req.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
     req.DefaultRequestHeaders.Add(Headers.Email, Email);
     req.DefaultRequestHeaders.Add(Headers.Iv, IV);
     var request = req.PostAsJsonAsync("https://provisioning.datamotion.com:8888/company/NewEncryptionKey", requestModel);
     if (request.Result.IsSuccessStatusCode)
     {
         DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ResponseModel));
         ResponseModel response = new ResponseModel();
         response = (ResponseModel)serializer.ReadObject(request.Result.Content.ReadAsStreamAsync().Result);
         response.Data = Decrypt(key, Convert.FromBase64String(response.IV), response.Data);
         return response;
     }
     else
     {
         throw new Exception(request.Result.Content.ReadAsStringAsync().Result);
     }
 }
示例#11
0
        public IHttpActionResult Add([FromBody] RequestModel req)
        {
            try
            {
                //真实的参数
                var parameters = Common.AesDecryp.GetAesDecryp(req.data, req.secret);

                using (dbDataContext db = new dbDataContext())
                {
                    var UserID = Convert.ToInt32(parameters["UserID"]);        //用户ID
                    var user   = db.Users.FirstOrDefault(x => x.ID == UserID); //用户
                    if (user != null)
                    {
                        PrivateLine pl = new PrivateLine();
                        pl.AddTime        = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//添加时间
                        pl.CompanyAddress = parameters["CompanyAddress"];
                        pl.CompanyName    = parameters["CompanyName"];
                        pl.CompanyScale   = parameters["CompanyScale"];
                        pl.LastTime       = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //最近更新时间
                        pl.Remark         = parameters["Remark"];                         //备注
                        pl.Users          = user;
                        pl.State          = Convert.ToInt32(parameters["State"]);
                        #region 联系人
                        //联系人数量
                        var ContactsNum  = Convert.ToInt32(parameters["ContactsNum"]);
                        var Contacts     = new List <PlContacts>();    //联系人列表
                        var ContactsName = parameters["ContactsName"]; //联系人姓名(逗号隔开的多个)
                        var ContactsTel  = parameters["ContactsTel"];  //联系人电话(逗号隔开的多个)
                        var ContactsPost = parameters["ContactsPost"]; //联系人岗位(逗号隔开的多个)
                        //分割后
                        var ContactsNameList = ContactsName.Split(',');
                        var ContactsTelList  = ContactsTel.Split(',');
                        var ContactsPostList = ContactsPost.Split(',');
                        //遍历
                        for (int i = 0; i < ContactsNum; i++)
                        {
                            var contact = new PlContacts();
                            contact.Name        = ContactsNameList[i];
                            contact.Tel         = ContactsTelList[i];
                            contact.Post        = ContactsPostList[i];
                            contact.PrivateLine = pl;
                            Contacts.Add(contact);
                        }
                        #endregion
                        #region 专线信息
                        var PlInfoNum  = Convert.ToInt32(parameters["PlInfoNum"]); //专线信息数量
                        var PlInfoList = new List <PlInfo>();                      //专线信息列表
                        //分割前
                        var Type            = parameters["Type"];                  //类型 1专线  2电路 3,天翼云
                        var Operator        = parameters["Operator"];              //运营商
                        var WeekPrice       = parameters["WeekPrice"];             //周价
                        var BandWidth       = parameters["BandWidth"];             //带宽
                        var PayType         = parameters["PayType"];               //付费方式
                        var OverTime        = parameters["OverTime"];              //到期时间
                        var ServerBerSys    = parameters["ServerBerSys"];          //服务器承载系统
                        var ServerUsingTime = parameters["ServerUsingTime"];       //现服务器开始使用时间
                        var IsCloudPlan     = parameters["IsCloudPlan"];           //是否有上云计划
                        //分割后
                        var TypeList            = Type.Split(',');                 //类型
                        var OperatorList        = Operator.Split(',');             //运营商
                        var WeekPriceList       = WeekPrice.Split(',');            //周价
                        var BandWidthList       = BandWidth.Split(',');            //带宽
                        var PayTypeList         = PayType.Split(',');              // 付费方式
                        var OverTimeList        = OverTime.Split(',');             //到期时间
                        var ServerBerSysList    = ServerBerSys.Split(',');         //服务器承载系统
                        var ServerUsingTimeList = ServerUsingTime.Split(',');      //现服务器开始使用时间
                        var IsCloudPlanList     = IsCloudPlan.Split(',');          //是否有上云计划
                        for (int i = 0; i < PlInfoNum; i++)
                        {
                            var plinfo = new PlInfo();
                            plinfo.Type            = Convert.ToInt32(TypeList[i]);//类型
                            plinfo.Operator        = OperatorList[i];
                            plinfo.WeekPrice       = WeekPriceList[i];
                            plinfo.BandWidth       = BandWidthList[i];
                            plinfo.PayType         = PayTypeList[i];
                            plinfo.OverTime        = !string.IsNullOrEmpty(OverTimeList[i]) ? Convert.ToDateTime(OverTimeList[i]).ToString("yyyy-MM-dd") : "";
                            plinfo.ServerBerSys    = ServerBerSysList[i];                                          //服务器承载系统
                            plinfo.ServerUsingTime = ServerUsingTimeList[i];
                            plinfo.IsCloudPlan     = IsCloudPlanList[i] != "" ? int.Parse(IsCloudPlanList[i]) : 0; //是否有上云计划
                            plinfo.State           = 0;
                            plinfo.PrivateLine     = pl;
                            PlInfoList.Add(plinfo);
                        }
                        #endregion
                        #region 走访记录
                        var plvisit = new PlVisit();
                        plvisit.AddTime       = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");//添加时间
                        plvisit.IsAgain       = Convert.ToInt32(parameters["IsAgain"]);
                        plvisit.IsNeed        = Convert.ToInt32(parameters["IsNeed"]);
                        plvisit.State         = 0;
                        plvisit.VisitTime     = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //本次拜访时间
                        plvisit.NextTime      = parameters["NextTime"];
                        plvisit.IsOther       = Convert.ToInt32(parameters["IsOther"]);       //是否有其他业务
                        plvisit.OtherDesc     = parameters["OtherDesc"];                      //其他业务描述
                        plvisit.VisitContents = parameters["VisitContents"];                  //
                        plvisit.PrivateLine   = pl;
                        #endregion

                        db.PrivateLine.InsertOnSubmit(pl);
                        db.PlContacts.InsertAllOnSubmit(Contacts);
                        db.PlInfo.InsertAllOnSubmit(PlInfoList);
                        db.PlVisit.InsertOnSubmit(plvisit);
                        db.SubmitChanges();

                        return(Json(new { state = 1, msg = "添加成功" }));
                    }
                    return(Json(new { state = 0, msg = "用户不存在" }));
                }
            }
            catch (Exception ex)
            {
                //return Json(new { state = 0, msg = "请求失败" });
                throw ex;
            }
        }
示例#12
0
        public IHttpActionResult Modify([FromBody] RequestModel req)
        {
            try
            {
                //真实的参数
                var parameters = Common.AesDecryp.GetAesDecryp(req.data, req.secret);

                using (dbDataContext db = new dbDataContext())
                {
                    var UserID = Convert.ToInt32(parameters["UserID"]);                  //用户ID
                    var user   = db.Users.FirstOrDefault(x => x.ID == UserID);           //用户

                    var PlID = Convert.ToInt32(parameters["PlID"]);                      //专线ID
                    var pl   = db.PrivateLine.Where(x => x.ID == PlID).FirstOrDefault(); //专线
                    if (pl != null)
                    {
                        pl.CompanyAddress = parameters["CompanyAddress"];
                        pl.CompanyName    = parameters["CompanyName"];
                        pl.CompanyScale   = parameters["CompanyScale"];
                        pl.LastTime       = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); //最近更新时间
                        pl.Remark         = parameters["Remark"];                         //备注

                        #region 联系人
                        //联系人数量
                        var ContactsNum  = Convert.ToInt32(parameters["ContactsNum"]);
                        var Contacts     = new List <PlContacts>();    //联系人列表
                        var ContactsName = parameters["ContactsName"]; //联系人姓名(逗号隔开的多个)
                        var ContactsTel  = parameters["ContactsTel"];  //联系人电话(逗号隔开的多个)
                        var ContactsPost = parameters["ContactsPost"]; //联系人岗位(逗号隔开的多个)
                        //分割后
                        var ContactsNameList = ContactsName.Split(',');
                        var ContactsTelList  = ContactsTel.Split(',');
                        var ContactsPostList = ContactsPost.Split(',');
                        //遍历
                        for (int i = 0; i < ContactsNum; i++)
                        {
                            var contact = new PlContacts();
                            contact.Name        = ContactsNameList[i];
                            contact.Tel         = ContactsTelList[i];
                            contact.Post        = ContactsPostList[i];
                            contact.PrivateLine = pl;
                            Contacts.Add(contact);
                        }
                        #endregion
                        #region 专线信息
                        var PlInfoNum  = Convert.ToInt32(parameters["PlInfoNum"]);                                         //专线信息数量
                        var PlInfoList = new List <PlInfo>();                                                              //专线信息列表(新增)
                        //分割前
                        var PlInfoID        = parameters["PlInfoID"];                                                      //专线信息ID
                        var Type            = parameters["Type"];                                                          //类型
                        var Operator        = parameters["Operator"];                                                      //运营商
                        var WeekPrice       = parameters["WeekPrice"];                                                     //周价
                        var BandWidth       = parameters["BandWidth"];                                                     //带宽
                        var PayType         = parameters["PayType"];                                                       //付费方式
                        var OverTime        = parameters["OverTime"];                                                      //到期时间
                        var ServerBerSys    = parameters["ServerBerSys"];                                                  //是否有上云计划
                        var ServerUsingTime = parameters["ServerUsingTime"];                                               //现服务器开始使用时间
                        var IsCloudPlan     = parameters["IsCloudPlan"];                                                   //是否有上云计划
                        //分割后
                        var PlInfoIDList        = PlInfoID.Split(',');                                                     //专线信息ID
                        var TypeList            = Type.Split(',');                                                         //类型
                        var OperatorList        = Operator.Split(',');                                                     //运营商
                        var WeekPriceList       = WeekPrice.Split(',');                                                    //周价
                        var BandWidthList       = BandWidth.Split(',');                                                    //带宽
                        var PayTypeList         = PayType.Split(',');                                                      // 付费方式
                        var OverTimeList        = OverTime.Split(',');                                                     //到期时间
                        var ServerBerSysList    = ServerBerSys.Split(',');                                                 //服务器承载系统
                        var ServerUsingTimeList = ServerUsingTime.Split(',');                                              //现服务器开始使用时间
                        var IsCloudPlanList     = IsCloudPlan.Split(',');                                                  //是否有上云计划
                        //原有的专线信息ID
                        var oldPlInfoIDList = db.PlInfo.Where(x => x.PlID == pl.ID).Select(x => x.ID.ToString()).ToList(); //
                        for (int i = 0; i < PlInfoNum; i++)                                                                //遍历最新数据
                        {
                            if (PlInfoIDList[i] == "0")                                                                    //新增的
                            {
                                var plinfo = new PlInfo();
                                plinfo.Type            = Convert.ToInt32(TypeList[i]);//类型
                                plinfo.Operator        = OperatorList[i];
                                plinfo.WeekPrice       = WeekPriceList[i];
                                plinfo.BandWidth       = BandWidthList[i];
                                plinfo.PayType         = PayTypeList[i];
                                plinfo.OverTime        = !string.IsNullOrEmpty(OverTimeList[i]) ? Convert.ToDateTime(OverTimeList[i]).ToString("yyyy-MM-dd") : "";
                                plinfo.ServerBerSys    = ServerBerSysList[i];                                                //服务器承载系统
                                plinfo.ServerUsingTime = ServerUsingTimeList[i];
                                plinfo.IsCloudPlan     = IsCloudPlanList[i] != "" ? Convert.ToInt32(IsCloudPlanList[i]) : 0; //是否有上云计划
                                plinfo.State           = 0;
                                plinfo.PrivateLine     = pl;
                                PlInfoList.Add(plinfo);
                            }
                            else//修改的
                            {
                                //专线信息
                                var plinfo = db.PlInfo.Where(x => x.ID == Convert.ToInt32(PlInfoIDList[i])).FirstOrDefault();
                                plinfo.Type            = Convert.ToInt32(TypeList[i]);//类型
                                plinfo.Operator        = OperatorList[i];
                                plinfo.WeekPrice       = WeekPriceList[i];
                                plinfo.BandWidth       = BandWidthList[i];
                                plinfo.PayType         = PayTypeList[i];
                                plinfo.OverTime        = !string.IsNullOrEmpty(OverTimeList[i]) ? Convert.ToDateTime(OverTimeList[i]).ToString("yyyy-MM-dd") : "";
                                plinfo.ServerBerSys    = ServerBerSysList[i];                                            //服务器承载系统
                                plinfo.ServerUsingTime = ServerUsingTimeList[i];
                                plinfo.IsCloudPlan     = IsCloudPlanList[i] != ""?Convert.ToInt32(IsCloudPlanList[i]):0; //是否有上云计划
                                #region 状态判断
                                if (plinfo.State == 0)                                                                   //正常
                                {
                                    //正常修改不处理
                                }
                                else if (plinfo.State == 1)//已提醒
                                {
                                    var plremind = db.PlRemind.Where(x => x.PlID == PlID && x.PlInfoID == Convert.ToInt32(PlInfoIDList[i])).Where(x => x.Type == 1).OrderByDescending(x => x.AddTime).FirstOrDefault();
                                    if (plremind != null)
                                    {
                                        plremind.State = 2;//未处理
                                    }
                                }
                                else if (plinfo.State == 2)//已回执
                                {
                                    plinfo.State = 0;
                                }
                                #endregion
                                #region  除的
                                ////最新的数据中不包含原有的数据,则删除原有的数据
                                //新旧差集
                                var strID = oldPlInfoIDList.Except(PlInfoIDList);
                                if (strID.Count() > 0)
                                {
                                    foreach (var item in strID)//删除
                                    {
                                        var oldPlInfo = db.PlInfo.Where(x => x.ID == Convert.ToInt32(item)).FirstOrDefault();
                                        if (oldPlInfo != null)
                                        {
                                            var plremind = db.PlRemind.Where(x => x.PlInfoID == oldPlInfo.ID);

                                            db.PlInfo.DeleteOnSubmit(oldPlInfo);     //删除旧的专线数据
                                            db.PlRemind.DeleteAllOnSubmit(plremind); //删除原有的的提醒记录
                                        }
                                    }
                                }
                                #endregion
                            }
                        }

                        #endregion
                        db.PlContacts.DeleteAllOnSubmit(db.PlContacts.Where(x => x.PlID == pl.ID)); //删除旧的联系人
                        db.PlContacts.InsertAllOnSubmit(Contacts);                                  //添加最新的联系人
                        if (PlInfoList.Count > 0)
                        {
                            db.PlInfo.InsertAllOnSubmit(PlInfoList);//添加新的
                        }

                        db.SubmitChanges();

                        return(Json(new { state = 1, msg = "修改成功" }));
                    }
                    return(Json(new { state = 0, msg = "专线信息不存在" }));
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#13
0
        public ResponseList <List <BookingModel> > GetBookings(RequestModel model)
        {
            string ReturnLink = string.Empty;

            string queryString   = string.Empty;
            string queryCount    = string.Empty;
            int    TotalRecords  = 0;
            string orderbyString = string.Empty;
            int    recoardFrom   = ((model.page - 1) * 10) + 1;
            int    recoardTo     = model.page * 10;

            ResponseList <List <BookingModel> > returnModel = new ResponseList <List <BookingModel> >();

            try
            {
                using (SqlConnection DB = new SqlConnection(SiteKey.ConnectionString))
                {
                    if (!string.IsNullOrEmpty(model.sortby))
                    {
                        if (model.sortby == "newtoold")
                        {
                            orderbyString = " order by booking.created desc";
                        }
                        if (model.sortby == "oldtonew")
                        {
                            orderbyString = " order by booking.created";
                        }
                    }
                    else
                    {
                        orderbyString = " order by booking.created desc";
                    }



                    queryCount = @"SELECT count(booking.id) totalrecord FROM booking
                                    left join customer on customer.id = customer_id
                                    left join provider on provider.id = provider_id
                                    left join service_category on service_category.id = service_id
                                    where booking.is_deleted = 0 ";

                    queryString = @"select * from (SELECT ROW_NUMBER() OVER (" + orderbyString + @") row_num, booking.id, LTRIM(RTRIM(booking.booking_code)) as booking_code, coupon_id, booking_amount, address_title, 
                                    landmark, booking.longitude, booking.latitude, booking.description, booking.booking_status, provider_cancellation_fee, 
                                    booking.status, booking.created, booking.payment_type,
                                    service_category.name service_name, LTRIM(RTRIM((CONCAT(provider.first_name,' ',provider.last_name)))) provider_name,
                                    CONCAT(customer.first_name,' ',customer.last_name) customer_name,
                                    provider_rating, provider_rating_description, distance
                                    from booking
                                    left join customer on customer.id = customer_id
                                    left join provider on provider.id = provider_id
                                    left join service_category on service_category.id = service_id
                                    where booking.is_deleted = 0 ";


                    if (model != null)
                    {
                        if (model.filterby == "booking_code")
                        {
                            queryString += " and booking.booking_code like @keyword ";
                            queryCount  += " and booking.booking_code like @keyword ";
                        }
                        else if (model.filterby == "provider_name")
                        {
                            queryString += " and ((provider.first_name+' '+provider.last_name like @keyword) or provider.first_name like @keyword or provider.last_name like @keyword) ";
                            queryCount  += " and ((provider.first_name+' '+provider.last_name like @keyword) or provider.first_name like @keyword or provider.last_name like @keyword) ";
                        }
                        else if (model.filterby == "customer_name")
                        {
                            queryString += " and ((customer.first_name+' '+customer.last_name like @keyword) or customer.first_name like @keyword or customer.last_name like @keyword) ";
                            queryCount  += " and ((customer.first_name+' '+customer.last_name like @keyword) or customer.first_name like @keyword or customer.last_name like @keyword) ";
                        }
                        else if (model.filterby == "service_name")
                        {
                            queryString += " and service_category.name like @keyword ";
                            queryCount  += " and service_category.name like @keyword ";
                        }

                        if (model.filterby2 == "provider_id")
                        {
                            queryString += " and booking.provider_id = @keyword2 ";
                            queryCount  += " and booking.provider_id = @keyword2 ";
                        }
                    }

                    queryString += " ) t where row_num between " + recoardFrom + " and " + recoardTo;

                    returnModel.result = DB.QuerySql <BookingModel>(queryString, new { keyword = "%" + model.keyword + "%", keyword2 = model.keyword2 }).ToList();
                    TotalRecords       = DB.QuerySql <int>(queryCount, new { keyword = "%" + model.keyword + "%", keyword2 = model.keyword2 }).FirstOrDefault();

                    if (returnModel.result != null)
                    {
                        foreach (var item in returnModel.result)
                        {
                            item.booking_receipts = DB.QuerySql <BookingReceiptModel>("select receipt_status, receipt_amount, customer_receipt_description, provider_receipt_description from booking_receipt where is_deleted = 0 and booking_id = @BookingId ", new { BookingId = item.id }).ToList();
                        }
                    }

                    returnModel.totalDocs     = TotalRecords;
                    returnModel.limit         = 10;
                    returnModel.totalPages    = (TotalRecords / 10) + ((TotalRecords % 10) > 0 ? 1 : 0);
                    returnModel.hasNextPage   = model.page < returnModel.totalPages;
                    returnModel.hasPrevPage   = returnModel.totalPages > 1 && model.page > 1;
                    returnModel.page          = model.page;
                    returnModel.nextPage      = model.page + 1;
                    returnModel.pagingCounter = recoardFrom;
                    returnModel.prevPage      = model.page - 1;
                }

                returnModel.status  = (int)EnumClass.ResponseState.Success;
                returnModel.msg     = "Booking List";
                returnModel.success = true;
            }
            catch (Exception ex)
            {
                returnModel.msg     = ex.Message;
                returnModel.status  = (int)EnumClass.ResponseState.ResposityError;
                returnModel.success = false;
                LoggingRepository.SaveException(ex);
            }
            return(returnModel);
        }
        /// <summary>
        /// 发现金
        /// </summary>
        /// <returns></returns>
        public ActionResult GiveMoney(RequestModel request, string guid)
        {
            //Common.Helper.Logger.Info(guid);
            ActionResult empty = new EmptyResult();

            try
            {
                //扫码计数-所有
                scanCountDi.getBll().CountByNameAndId(request.activityId, request.activityName);


                #region 数据库日志记录  公共部分

                TRP_ClientLog entity = new TRP_ClientLog();
                entity.CreateTime = DateTime.Now;
                entity.DeleteMark = false;
                entity.Enable     = true;
                entity.PageUrl    = HttpContext.Request.Url.AbsoluteUri ?? money_url;
                entity.IPAddress  = HttpContext.Request.UserHostAddress ?? "127.0.0.1";
                entity.ActivityId = Convert.ToInt32(request.activityId);

                #endregion


                //获取微信用户信息
                wxUserInfoModel wxUser = GetWxUserInfo(request.code);

                if (wxUser == null)
                {
                    Response.Redirect(request.url + "&flag=1&guid=" + guid + "");
                    return(empty);
                }

                //微信用户openid
                string openid = wxUser.Openid;

                //保存微信信息
                if (!isExistOpenId(wxUser.Openid))
                {
                    //保存用户微信信息
                    saveUserInfo(wxUser);
                }

                TRP_AwardReceive receivedModel = null;

                #region 今天已参加活动

                if (isAttendToday(request.activityId, wxUser.Openid))
                {
                    //判断奖品是否已领
                    receivedModel = awardDi.getBll().hadTakeAward(wxUser.Openid, request.activityId);

                    #region 奖品已核销

                    //奖品已领
                    if (receivedModel == null)
                    {
                        Response.Redirect(request.url + "&flag=1&guid=" + guid + "");
                        return(empty);
                    }

                    #endregion

                    #region 奖品还未核销

                    //奖品还未领取
                    else
                    {
                        //获取奖品ID  int
                        string awardId = receivedModel.AwardDetailId.ToString();

                        //获取奖品详情
                        TRP_AwardDetail detailModel = detailDi.getBll().GetEntityById(awardId);

                        //奖品名称
                        string awardsName = "";

                        //加密奖品id
                        string ecodeAwardId = DESEncrypt.Encrypt(awardId, _key);

                        if (detailModel != null)
                        {
                            //奖品名称
                            awardsName = detailModel.AwardName;
                        }
                        else
                        {
                            Response.Redirect(request.url + "&flag=1&guid=" + guid + "");
                            return(empty);
                        }

                        //奖品类型
                        if (!string.IsNullOrWhiteSpace(awardsName))
                        {
                            GiveCash(awardsName, wxUser.Openid, request);
                        }
                        else
                        {
                            Response.Redirect(request.url + "&flag=1&guid=" + guid + "");
                            return(empty);
                        }

                        entity.Description = string.Format("用户在{0}点击红包,现金红包(为重复扫码,上次未核销奖品)", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                        entity.PageDesc    = "现金扫码,上次未核销奖品";
                        entity.ActivityId  = Convert.ToInt32(request.activityId);
                        logDi.getBll().SaveLog(entity);
                        return(View("GiveMoney"));
                    }
                    #endregion
                }

                #endregion


                #region 今天还未参加活动  则请求奖品

                AwardsInfoModel awardsModel = new AwardsInfoModel();

                //请求奖品
                awardsModel = GetAwardsInfo(request.activityId);

                //奖品实体的类型为null
                if (awardsModel.Class != null)
                {
                    //奖品实体的类型为""
                    if (awardsModel.Class == "")
                    {
                        //return View("Nogift");
                        Response.Redirect(request.url + "&flag=1&guid=" + guid + "");
                        return(empty);
                    }
                }
                else
                {
                    //return View("Nogift");
                    Response.Redirect(request.url + "&flag=1&guid=" + guid + "");
                    return(empty);
                }

                #endregion

                //发钱
                if (GiveCash(awardsModel.Class, openid, request))
                {
                    //保存领奖信息-测试
                    saveScanInfo(wxUser.Openid, awardsModel.id);
                    saveUserAwardReceiveInfo(wxUser.Openid, awardsModel.id);
                    return(View("GiveMoney"));
                }
                else
                {
                    //return View("Nogift");
                    Response.Redirect(request.url + "&flag=1&guid=" + guid + "");
                    return(empty);
                }
            }
            catch (Exception ex)
            {
                Common.Helper.Logger.Info(string.Format("获取用户微信Openid,发现金异常,异常信息:{0}", ex.ToString()));
                Response.Redirect(request.url + "&flag=1&guid=" + guid + "");
                //return View("Nogift");
                return(empty);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="data"></param>
        private static void Client_RequestContentDataHandler(ref object data)
        {
            //var rpcId = string.Empty;
            //var requestHeader = TracingContextData.GetRequestHeader();
            //if (requestHeader == null)
            //{
            //    requestHeader = TracingContextData.GetDefaultRequestHeader();
            //    TracingContextData.SetRequestHeader(requestHeader);
            //    //HttpContentData.SetSubRpcID(modelHeader.RpcID + ".0");
            //    //rpcId = requestHeader.RpcID + ".0";
            //}
            ////else
            ////{
            ////    rpcId = Util.VersionIncr(TracingContextData.GetSubRpcID());
            ////}
            //rpcId = Util.VersionIncr(TracingContextData.GetSubRpcID());
            //TracingContextData.SetSubRpcID(rpcId);

            if (data == null)
            {
                data = new RequestModel();
            }

            //var reqModel = data as IRequestModel<Header>;
            //if (reqModel != null)
            //{
            //    if (reqModel.Header == null)
            //    {
            //        reqModel.Header = new Header();
            //    }

            //    reqModel.Header.TraceID = requestHeader.TraceID;
            //    reqModel.Header.TraceID = rpcId;
            //}
        }
 public IHttpActionResult PostMethodWithModel(RequestModel someModel)
 {
     return this.Ok();
 }
示例#17
0
 public bool rejectRequest(RequestModel request, string currentUser)
 {
     return(_setStatusOfRequest(request, currentUser, RequestStatus.REJECTED));
 }
 public IHttpActionResult PostMethodWithQueryStringAndModel(string value, RequestModel someModel)
 {
     return this.Ok();
 }
示例#19
0
        public bool updateRequestChanges(RequestModel newRequest)
        {
            if (RequestStatus.requestHasHadStatus(newRequest, RequestStatus.APPROVED))
            {
                throw new RequestAlreadyApprovedException("Already approved or rejected.");
                //return false;
            }
            DateTime timestamp = DateTime.Now;

            using (var transaction = context.Database.BeginTransaction())
            {
                //try
                //{
                Request targetRequest = context.Requests.Find(newRequest.RequestId);

                List <Request_Details> targetDetails = targetRequest.Request_Details.ToList();

                RequestModel targetRequestModel = findRequestById(newRequest.RequestId);
                foreach (var item in targetRequestModel.Items)
                {
                    if (!newRequest.Items.ContainsKey(item.Key))
                    { // New requestModel does not contain old key
                      // So add it in, but set quantity to 0
                        newRequest.Items.Add(item.Key, 0);
                    }
                }

                foreach (KeyValuePair <ItemModel, int> itemAndQty in newRequest.Items)
                {
                    //Request_Event newEvent = new Request_Event();
                    //newEvent.deleted = "N";
                    //newEvent.date_time = timestamp;
                    //newEvent.quantity = itemAndQty.Value;
                    //newEvent.status = EventStatus.UPDATED;
                    //newEvent.username = newRequest.UserModel.Username;

                    // Establish relationships
                    Request_Details targetDetail = targetDetails.Where(x => x.item_code == itemAndQty.Key.ItemCode && x.deleted != "Y").DefaultIfEmpty(null).FirstOrDefault();
                    if (targetDetail == null)
                    {
                        // Need to insert new detail and event
                        Request_Details newDetail = new Request_Details();
                        newDetail.deleted       = "N";
                        newDetail.item_code     = itemAndQty.Key.ItemCode;
                        newDetail.orig_quantity = itemAndQty.Value;

                        Request_Event newEvent = new Request_Event();
                        newEvent.deleted   = "N";
                        newEvent.date_time = timestamp;
                        newEvent.quantity  = itemAndQty.Value;
                        newEvent.status    = EventStatus.PENDING;
                        newEvent.username  = newRequest.UserModel.Username;

                        newDetail.Request_Event.Add(newEvent);
                        newDetail.request_id = newRequest.RequestId;
                        context.Request_Details.Add(newDetail);
                    }
                    else
                    {
                        // Edit db
                        context.Request_Details.Find(targetDetail.request_detail_id).orig_quantity = itemAndQty.Value;
                        Request_Event existingEvent = targetDetail.Request_Event.Where(w => w.deleted != "Y").First();
                        context.Request_Event.Find(existingEvent.request_event_id).quantity  = itemAndQty.Value;
                        context.Request_Event.Find(existingEvent.request_event_id).date_time = timestamp;
                        context.Request_Event.Find(existingEvent.request_event_id).status    = EventStatus.UPDATED;
                    }

                    //targetDetail.Request_Event.Add(newEvent);
                }

                // Update Status
                context.Requests.Find(newRequest.RequestId).current_status = RequestStatus.UPDATED;
                context.Requests.Find(newRequest.RequestId).reason         = newRequest.Reason;
                //}
                //catch (Exception exec)
                //{
                //transaction.Rollback();
                //throw exec;
                //}

                transaction.Commit();
            }
            return(true);
        }
 public IActionResult ActionWithMultipleParameters(int id, string text, RequestModel model)
 {
     return null;
 }
示例#21
0
 public static void AddLastModifiedResponseHeader(this HttpResponse response, RequestModel model)
 {
     response.Headers[HttpConstants.LastModified] = model.LastFileWriteTime.ToUniversalTime().ToString(HttpConstants.HttpDateFormat);
 }
 public MvcController(IInjectedService injectedService, RequestModel requestModel)
     : this(injectedService)
 {
     this.InjectedRequestModel = requestModel;
 }
示例#23
0
 public async Task Execute(ApiRequest.ApiRequest execTask, RequestModel model)
 {
     await execTask.YahooCompanies();
 }
        public IActionResult TryValidateModelAction()
        {
            var model = new RequestModel();
            this.TryValidateModel(model);
            if (this.ModelState.IsValid)
            {
                return this.Ok();
            }

            return this.BadRequest();
        }
        public HttpResponseMessage TraceLastLocation(RequestModel rm)
        {
            try
            {
                string RequiredValue = "";
                using (FileStream fs = new FileStream(AmazonServer + "\\UserLocation.txt", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite))
                {
                    using (var file = new StreamReader(fs))
                    {
                        string allLocations = file.ReadToEnd();
                        if (allLocations != null)
                        {
                            int uniqueIdIndex;
                            uniqueIdIndex = allLocations.LastIndexOf("\"" + "UniqueId" + "\":" + rm.LocationsObject.UniqueId.ToString() + ",");

                            if (uniqueIdIndex == -1)
                            {
                                RequiredValue = "N\\A";
                            }

                            else
                            {
                                int startingIndex = allLocations.LastIndexOf("{", uniqueIdIndex);
                                int lastIndex = allLocations.IndexOf("}", uniqueIdIndex);
                                RequiredValue = allLocations.Substring(startingIndex, lastIndex - startingIndex + 1);
                            }
                        }
                        file.Close();
                    }
                    fs.Close();
                }

                if (RequiredValue == "N\\A")
                {
                    return Request.CreateResponse(HttpStatusCode.NoContent, RequiredValue, "application/json");
                }

                object objectData = JsonConvert.DeserializeObject(RequiredValue);
                return Request.CreateResponse(HttpStatusCode.OK, objectData, "application/json");
            }
            catch (Exception ex)
            {
                throw;
            }
        }
 public IActionResult OkResultActionWithRequestBody(int id, RequestModel model)
 {
     return new OkResult();
 }
示例#27
0
 public async Task <ResponseMessageModel> ModifyMerchatsStatus([FromBody] RequestModel model)
 {
     modifyMerchatsStatusService.SetData(model);
     return(await Task.Run(() => modifyMerchatsStatusService.Execute()));
 }
示例#28
0
 public async Task Execute(ApiRequest.ApiRequest execTask, RequestModel model)
 {
     await execTask.YahooExchanges();
 }
        public HttpResponseMessage LastLocation(RequestModel rm)
        {
            try
            {

                int deviceId = rm.LocationsObject.UniqueId;
                string RequiredValue = "";
                List<Coordinates> encryptedData = new List<Coordinates>();
                using (FileStream fs = new FileStream(AmazonServer + "\\UserLocation.txt", FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite))
                {
                    using (var file = new StreamReader(fs))
                    {
                        string allLocations = file.ReadToEnd();
                        if (allLocations != null)
                        {
                            int uniqueIdIndex;
                            uniqueIdIndex = allLocations.LastIndexOf("\"" + "UniqueId" + "\":" + rm.LocationsObject.UniqueId.ToString() + ",");

                            if (uniqueIdIndex == -1)
                            {
                                RequiredValue = "N\\A";
                            }

                            else
                            {
                                int lastIndex = allLocations.IndexOf("}", uniqueIdIndex);
                                int startingIndex = allLocations.LastIndexOf("{", uniqueIdIndex);
                                //int startIndex = -1;
                                //System.Text.StringBuilder specifiedLine = new System.Text.StringBuilder();
                                //for (int i = uniqueIdIndex; i >= 0; i--)
                                //{
                                //    if (allLocations.ElementAt(i) == '{')
                                //    {
                                //        startIndex = i;
                                //        break;
                                //    }

                                //    else
                                //    {
                                //        specifiedLine.Append(allLocations.ElementAt(i));
                                //    }
                                //}

                                //char[] arr = specifiedLine.ToString().ToCharArray();
                                //Array.Reverse(arr);

                                //If opening curly braces not found
                                //if (startIndex == -1)
                                //{
                                //    RequiredValue = "Starting Index not found";
                                //}

                                //else
                                //{
                                RequiredValue = allLocations.Substring(startingIndex, lastIndex - startingIndex + 1);
                                encryptedData.Add(JsonConvert.DeserializeObject<Coordinates>(RequiredValue));
                                //}
                            }
                        }
                        file.Close();
                    }
                    fs.Close();
                }

                if (RequiredValue == "N\\A")
                {
                    return Request.CreateResponse(HttpStatusCode.NoContent, RequiredValue, "application/json");
                }

                object objectData = JsonConvert.SerializeObject(encryptedData);
                return Request.CreateResponse(HttpStatusCode.OK, encryptedData, "application/json");
            }
            catch (Exception ex)
            {

                throw;
            }
        }
示例#30
0
 public async Task <ResponseMessageModel> QueryMerchatsInfo([FromBody] RequestModel model)
 {
     queryMerchatsInfoService.SetData(model);
     return(await Task.Run(() => queryMerchatsInfoService.Execute()));
 }
示例#31
0
 public async Task Execute(ApiRequest.ApiRequest execTask, RequestModel model)
 {
     var cancellation = new CancellationTokenSource(Timeout.Infinite);
     await execTask.ImportCompanies(TimeSpan.FromSeconds(7), cancellation.Token);
 }
示例#32
0
 public async Task <ResponseMessageModel> UpdateMerchatsInfoForJava([FromBody] RequestModel model)
 {
     updateMerchatsInfoForJavaService.SetData(model);
     return(await Task.Run(() => updateMerchatsInfoForJavaService.Execute()));
 }
示例#33
0
 public async Task Execute(ApiRequest.ApiRequest execTask, RequestModel model)
 {
     await execTask.ImportCurrencies();
 }
        private IRequestBuilder InitRequestBuilder(RequestModel requestModel, bool pathOrUrlRequired)
        {
            IRequestBuilder requestBuilder = Request.Create();

            if (requestModel.ClientIP != null)
            {
                if (requestModel.ClientIP is string clientIP)
                {
                    requestBuilder = requestBuilder.WithClientIP(clientIP);
                }
                else
                {
                    var clientIPModel = JsonUtils.ParseJTokenToObject <ClientIPModel>(requestModel.ClientIP);
                    if (clientIPModel?.Matchers != null)
                    {
                        requestBuilder = requestBuilder.WithPath(clientIPModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray());
                    }
                }
            }

            bool pathOrUrlmatchersValid = false;

            if (requestModel.Path != null)
            {
                if (requestModel.Path is string path)
                {
                    requestBuilder         = requestBuilder.WithPath(path);
                    pathOrUrlmatchersValid = true;
                }
                else
                {
                    var pathModel = JsonUtils.ParseJTokenToObject <PathModel>(requestModel.Path);
                    if (pathModel?.Matchers != null)
                    {
                        requestBuilder         = requestBuilder.WithPath(pathModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray());
                        pathOrUrlmatchersValid = true;
                    }
                }
            }
            else if (requestModel.Url != null)
            {
                if (requestModel.Url is string url)
                {
                    requestBuilder         = requestBuilder.WithUrl(url);
                    pathOrUrlmatchersValid = true;
                }
                else
                {
                    var urlModel = JsonUtils.ParseJTokenToObject <UrlModel>(requestModel.Url);
                    if (urlModel?.Matchers != null)
                    {
                        requestBuilder         = requestBuilder.WithUrl(urlModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray());
                        pathOrUrlmatchersValid = true;
                    }
                }
            }

            if (pathOrUrlRequired && !pathOrUrlmatchersValid)
            {
                _logger.Error("Path or Url matcher is missing for this mapping, this mapping will not be added.");
                return(null);
            }

            if (requestModel.Methods != null)
            {
                requestBuilder = requestBuilder.UsingMethod(requestModel.Methods);
            }

            if (requestModel.Headers != null)
            {
                foreach (var headerModel in requestModel.Headers.Where(h => h.Matchers != null))
                {
                    requestBuilder = requestBuilder.WithHeader(headerModel.Name, headerModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray());
                }
            }

            if (requestModel.Cookies != null)
            {
                foreach (var cookieModel in requestModel.Cookies.Where(c => c.Matchers != null))
                {
                    requestBuilder = requestBuilder.WithCookie(cookieModel.Name, cookieModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray());
                }
            }

            if (requestModel.Params != null)
            {
                foreach (var paramModel in requestModel.Params.Where(c => c.Matchers != null))
                {
                    bool ignoreCase = paramModel?.IgnoreCase ?? false;
                    requestBuilder = requestBuilder.WithParam(paramModel.Name, ignoreCase, paramModel.Matchers.Select(MatcherMapper.Map).Cast <IStringMatcher>().ToArray());
                }
            }

            if (requestModel.Body?.Matcher != null)
            {
                var bodyMatcher = MatcherMapper.Map(requestModel.Body.Matcher);
                requestBuilder = requestBuilder.WithBody(bodyMatcher);
            }

            return(requestBuilder);
        }
示例#35
0
 public async Task Execute(ApiRequest.ApiRequest execTask, RequestModel model)
 {
     var cancellation = new CancellationTokenSource(Timeout.Infinite);
     await execTask.StockExchangeTask(TimeSpan.FromMilliseconds(900), cancellation.Token);
 }
 public IHttpActionResult PostMethodWithParameterAndModel(int id, RequestModel someModel)
 {
     return this.Ok();
 }
示例#37
0
 public async Task Execute(ApiRequest.ApiRequest execTask, RequestModel model)
 {
     await execTask.StockExchangeParseCsv();
 }
 public IHttpActionResult SameAction(RequestModel model)
 {
     return this.Ok();
 }
示例#39
0
 public async Task Execute(ApiRequest.ApiRequest execTask, RequestModel model)
 {
     await execTask.YahooHistoricalDataCsv(model);
 }
示例#40
0
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            var sql = string.Format("update Mapping set ImportedMaxIndendity={0} where ID={1}", _maxId, _rule.ID);
            AccessHelper.ExecuteSql(sql, AppConsts.AppConnectionString);

            MessageBox.Show("导入成功");
            var model = this.ListView1.ItemsSource as List<TargetModel.GongFenModel>;

            this.ListView1.ItemsSource = null;

            var reqModel = new RequestModel<object>();
            reqModel.TableType = _rule.TargetTableType;
            reqModel.Model = model;

            var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
            var json = JsonConvert.SerializeObject(reqModel, jSetting);
            MessageBox.Show(json);
        }
        /// <summary>
        /// Handles the Click event of the SaveUserDetails control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RoutedEventArgs"/> instance containing the event data.</param>
        private void SaveUserDetails_Click(object sender, RoutedEventArgs e)
        {
            if (FormValidation())
            {
                ComboBoxItem ComboItem = (ComboBoxItem)UserTypeComboBox.SelectedItem;

                WellKnownUserType userType = (WellKnownUserType)Enum.Parse(typeof(WellKnownUserType), ComboItem.Name);

                if (IsAddNewRecord)
                {
                    RequestModel requestModel = new RequestModel()
                    {
                        UserModel = new UserModel()
                        {
                            UserId   = UserId,
                            Name     = NameTextBox.Text,
                            Username = UsernameTextBox.Text,
                            UserType = (byte)userType,
                            Password = PasswordTextBox.SecurePassword,
                        },

                        WellKnownModificationType = Core.Enums.WellKnownModificationType.Add,
                    };

                    ResponseModel response = App.BaseUserControl.InternalService.ModifyUser(requestModel);

                    if (response.IsOperationSuccess)
                    {
                        App.ShowMessage(true, string.Empty);
                    }
                    else
                    {
                        App.ShowMessage(false, response.ErrorMessage);
                    }
                }
                else
                {
                    RequestModel requestModel = new RequestModel()
                    {
                        UserModel = new UserModel()
                        {
                            UserId   = UserId,
                            Name     = NameTextBox.Text,
                            Username = UsernameTextBox.Text,
                            UserType = (byte)userType,
                        },

                        WellKnownModificationType = Core.Enums.WellKnownModificationType.Edit,
                    };

                    ResponseModel response = App.BaseUserControl.InternalService.ModifyUser(requestModel);

                    if (response.IsOperationSuccess)
                    {
                        App.ShowMessage(true, string.Empty);
                    }
                    else
                    {
                        App.ShowMessage(false, response.ErrorMessage);
                    }
                }
            }
            else
            {
                App.ShowMessage(false, "Fill all the fields.");
            }
        }
示例#42
0
 public WebApiController(RequestModel requestModel)
 {
     this.InjectedRequestModel = requestModel;
 }
 public void EmptyActionWithParameters(int id, RequestModel model)
 {
 }
 public MvcController(RequestModel requestModel)
 {
     this.InjectedRequestModel = requestModel;
 }
 public MvcController(RequestModel requestModel)
 {
     this.InjectedRequestModel = requestModel;
 }
 public IActionResult OkResultActionWithRequestBody(int id, RequestModel model)
 {
     return this.Ok(this.responseModel);
 }
 public MvcController(IInjectedService injectedService, IAnotherInjectedService anotherInjectedService, RequestModel requestModel)
     : this(injectedService, anotherInjectedService)
 {
     this.InjectedRequestModel = requestModel;
 }
        public IActionResult BadRequestWithModelState(RequestModel model)
        {
            if (this.ModelState.IsValid)
            {
                return this.Ok();
            }

            return this.BadRequest(this.ModelState);
        }
 public IActionResult OkResultActionWithRequestBody(int id, RequestModel model)
 {
     return(this.Ok(this.responseModel));
 }
 public async Task<IActionResult> TryUpdateModelAction()
 {
     var model = new RequestModel();
     await this.TryUpdateModelAsync<RequestModel>(model);
     return this.Ok();
 }
示例#51
0
 /// <summary>
 /// Default class constructor that initializes a new instance of the class.
 /// </summary>
 /// <param name="requestModel">The request model.</param>
 public Request(RequestModel requestModel)
 {
     RequestModel = requestModel;
 }
示例#52
0
 public ResponseModel Provision(CompanyModel companyModel, string UserName, string PlatformCode, Command Command, string Email)
 {
     //Generate IV
     AesCryptoServiceProvider cryptoProvider = new AesCryptoServiceProvider();
     cryptoProvider.KeySize = 256;
     cryptoProvider.GenerateIV();
     string IV = Convert.ToBase64String(cryptoProvider.IV);
     //Encrypt Model
     byte[] data = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(companyModel));
     byte[] key = Convert.FromBase64String(provisionerKey);
     string hash = Convert.ToBase64String(new HMACSHA512(key).ComputeHash(data));
     string data2 = Encrypt(key, Convert.FromBase64String(IV), Newtonsoft.Json.JsonConvert.SerializeObject(companyModel));
     //Construct the request model
     RequestModel requestModel = new RequestModel
     {
         UserName = UserName,
         PlatformCode = PlatformCode,
         Command = Command,
         IV = IV,
         Data = data2,
         Hash = hash
     };
     var req = new WebClient();
     req.BaseAddress = "https://provisioning.datamotion.com:8888";
     req.Headers.Clear();
     req.Headers.Add("Accept", "application/json");
     req.Headers.Add(Headers.Email, Email);
     req.Headers.Add(Headers.Iv, IV);
     try
     {
         var request = req.UploadData("https://provisioning.datamotion.com:8888", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(requestModel)));
         ResponseModel response = JsonConvert.DeserializeObject<ResponseModel>(Encoding.UTF8.GetString(request));
         response.Data = Decrypt(key, Convert.FromBase64String(response.IV), response.Data);
         return response;
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
示例#53
0
 public IActionResult Post([FromBody] RequestModel model)
 {
     return(this.Created("GetRequestById", 1));
 }
        public IActionResult ModelStateCheck(RequestModel model)
        {
            if (this.CustomControllerContext.ModelState.IsValid)
            {
                return new OkResult();
            }

            return new OkResult();
        }
示例#55
0
 public IActionResult Put(int id, [FromBody] RequestModel model)
 {
     return(this.Ok());
 }
 public FullPocoController(IInjectedService injectedService, IAnotherInjectedService anotherInjectedService, RequestModel requestModel)
     : this(injectedService, anotherInjectedService)
 {
     this.InjectedRequestModel = requestModel;
 }
示例#57
0
 public async Task <ResponseMessageModel> GoldEditInterestRateForJava([FromBody] RequestModel model)
 {
     goldEditInterestRateForJavaService.SetData(model);
     return(await Task.Run(() => goldEditInterestRateForJavaService.Execute()));
 }
示例#58
0
 public async Task <ResponseMessageModel> RegisteredUser([FromBody] RequestModel model)
 {
     registeredUserService.SetData(model);
     return(await Task.Run(() => registeredUserService.Execute()));
 }
 public IViewComponentResult Invoke(int id, RequestModel model) => this.Content($"{id},{model?.RequiredString}");