Beispiel #1
0
        private IRights GetRights(IUser user)
        {
            if (user == null)
            {
                AppliactionContext.Log.Error(this, "Can't read rights for nulluser");
                return Rights.Rights.Empty;
            }

            if (user is MasterUser)
            {
                AppliactionContext.Log.Debug(this, string.Format("Master rights assigned for user '{0}'.", user.Username));
                return Rights.Rights.Master;
            }

            if (user is GuestUser)
            {
                AppliactionContext.Log.Debug(this, string.Format("Guest rights assigned for user '{0}'.", user.Username));
                return Rights.Rights.Guest;
            }

            string query = "from " + typeof(DbRights) + " r where r.FkUser = :UserId";
            QueryParams queryParams = new QueryParams(new QueryParam("UserId", user.Id));

            IList<DbRights> userRights = AppliactionContext.DbOperations.QueryDb<DbRights>(query, queryParams);

            if (userRights.Count != 1)
            {
                AppliactionContext.Log.Error(this, String.Format("Rights for User '{0}' wasn't found.", user.Username));
                return Rights.Rights.Empty;
            }

            return new Rights.Rights((Roles)userRights[0].Rights);
        }
Beispiel #2
0
        public IEnumerable<ArticleGroup> GetAllGroups(Func<ArticleGroup, object> order, int? skip = 0, int? take = 999)
        {
            var queryParams = new QueryParams<ArticleGroup>
            {
                Skip = skip,
                Take = take,
                Order = order
            };

            return _repository.GetAll(queryParams);
        }
Beispiel #3
0
        public IEnumerable<Plan> GetAllPlans(Func<Plan, object> order, int? skip = 0, int? take = 999)
        {
            var queryParams = new QueryParams<Plan>
            {
                Skip = skip,
                Take = take,
                Order = order
            };

            var result =  _repository.GetAll(queryParams).ToList();
            DeleteOldPlans(result);
            return result;
        }
Beispiel #4
0
        public IEnumerable<Plan> GetPlansByParams(Expression<Func<Plan, bool>> predicate, Func<Plan, object> order,
			int? skip = 0, int? take = 999)
        {
            var queryParams = new QueryParams<Plan>
            {
                Skip = skip,
                Take = take,
                Order = order
            };
            var result = _repository.GetByPredicate(predicate, queryParams).ToList();
            DeleteOldPlans(result);
            return result;
        }
Beispiel #5
0
        public virtual String GetAuthorizationFullUrl()
        {
            UriBuilder ub = new UriBuilder( this.AuthorizationUrl );

            QueryParams queryItems = new QueryParams();

            queryItems.Add( "client_id", this.ConsumerKey );
            queryItems.Add( "redirect_uri", this.CallbackUrl );
            queryItems.Add( "response_type", "code" );

            queryItems.Add( "scope", this.Scope );

            return ub.ToString() + "?" + queryItems.ToEncodedString();
        }
Beispiel #6
0
        public IUser CreateNewUser(string username, string password, string firstName, string lastName, string email, string phoneNumber)
        {
            CheckRights();

            if (String.IsNullOrEmpty(username))
            {
                AppliactionContext.Log.Warning(this, "Username is empty.");
                throw new UserManagementException(Resources.UsernameCantBeEmpty);
            }

            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password) ||
                String.IsNullOrEmpty(firstName) || String.IsNullOrEmpty(lastName) || String.IsNullOrEmpty(email))
            {
                AppliactionContext.Log.Debug(this, "Username or password or FirstName or LastName or Email is empty.");
                throw new UserManagementException(Resources.UsernameOrPasswordIsEmpty);
            }

            if (IsMaster(username) || IsGuest(username))
            {
                AppliactionContext.Log.Warning(this, $"User with username '{username}' already exist.");
                throw new UserManagementException(String.Format(Resources.UserAlreadyExists, username));
            }

            if (String.IsNullOrEmpty(password))
            {
                AppliactionContext.Log.Warning(this, $"Password for user '{username}' is empty.");
                throw new UserManagementException(Resources.PasswordCantBeEmpty);
            }

            string query = "from " + typeof(User) + " u where u.Username = :Username";
            QueryParams queryParams = new QueryParams(new QueryParam("Username", username));

            IList<User> users = AppliactionContext.DbOperations.QueryDb<User>(query, queryParams);

            if (users.Count != 0)
            {
                AppliactionContext.Log.Warning(this, $"User with username '{username}' already exist.");
                throw new UserManagementException(String.Format(Resources.UserAlreadyExists, username));
            }

            IDbModelObjectFactory modelFactory = AppliactionContext.GetModelObjectFactory<IDbModelObjectFactory>();
            IUser newUser = modelFactory.CreateUser(username, password, firstName, lastName, email, phoneNumber);
            AppliactionContext.Log.Debug(this, $"User with username '{username}' was created.");
            newUser.Save();

            _users.Add(newUser);

            return newUser;
        }
        public ActionResult List(QueryParams _params, string terms = "")
        {
            int total = 0;
            var query = context.Users.All().OrderBy(u => u.UserName);

            if (!string.IsNullOrEmpty(terms))
            {
                query = context.Users.Filter(u => u.UserName.Contains(terms) || u.Email.Contains(terms)).OrderBy(u => u.UserName);
            }

            var values = new List<dynamic>();
            total = query.Count();
            var members = _params.GetPageResult(query, true).ToList();

            foreach (var member in members)
            {
                var m = new
                {
                    id = member.UserName,
                    dispName = member.DefaultProfile.DisplayName,
                    email = member.Email,
                    created = member.CreationDate,
                    approved = member.IsApproved,
                    picture = string.IsNullOrEmpty(member.DefaultProfile.Avatar) ? "/content/images/no-avatar.gif" : member.DefaultProfile.Avatar,
                    roles = member.Roles.Select(r => r.Name).ToArray(),
                    validated = member.IsVaildMail
                };
                values.Add(m);
            }

            return Json(new ModelWrapper()
            {
                Model = values,
                Total = total
            }, JsonRequestBehavior.AllowGet);
        }
Beispiel #8
0
        internal async Task<Entity> RequestJson(string endpoint,
                                                QueryParams parameters = null,
                                                JToken data = null,
                                                HttpMethod httpMethod = null,
                                                Dictionary<string, string> additionalHeaders = null,
                                                string contentType = ContentType.JSON)
        {
            HttpRequestMessage request = new HttpRequestMessage(httpMethod ?? HttpMethod.Get, (endpoint.StartsWith("/") ? endpoint.Substring(1) : endpoint) + (parameters?.ToString() ?? string.Empty));
            if (data != null)
            {
                string serializedData = JsonConvert.SerializeObject(data);
                request.Content = new StringContent(serializedData, Encoding.UTF8, contentType);
            }

            return await ProcessRequest(request, additionalHeaders);
        }
Beispiel #9
0
 internal async Task<Entity> Delete(string endpoint,
                                    QueryParams parameters = null,
                                    Dictionary<string, string> additionalHeaders = null,
                                    string contentType = ContentType.JSON)
 {
     // TODO: review the DELETE problem
     // On Mac OS and Linux, DELETE requests will be sent as GET, which make it impossible for now
     // to delete documents and drop batches using the REST API.
     // This issue is documented here: https://github.com/dotnet/corefx/issues/4134
     return await RequestJson(endpoint, parameters, null, HttpMethod.Delete, additionalHeaders, contentType);
 }
Beispiel #10
0
 public IEnumerable <Article> GetAll(QueryParams <Article> param)
 {
     throw new NotImplementedException();
 }
 private bool _isGetAppData = true;//是否开始获取判读结果
 /// <summary>
 /// 获取判读结果
 /// </summary>
 private void WaitGetAppData()
 {
     while (true)
     {
         try
         {
             if (null == ConfigHelper.Cvur)
             {
                 var request = (HttpWebRequest)WebRequest.Create(ConfigHelper.UrlDistanceString + @"/token");
                 request.Method      = "post";
                 request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
                 var stream = request.GetRequestStream();
                 using (var writer = new StreamWriter(stream))
                 {
                     writer.Write("grant_type=password&username="******"&password="******"/api/AllInOne/Result", strReturn);
                         if (null != rresult)
                         {
                             Msg mg = rresult.State;
                             if (mg.IsOk)
                             {
                                 foreach (var result in rresult.Result)
                                 {
                                     UpdateApplicationStatus(result.ContractId, "3");
                                     UpdateApplicationDiagnosis(result.ContractId, result.BeginTime, result.Diagnosis);
                                     DataRow dr = ((DataRowView)gc_PatientManage.CurrentRow.DataBoundItem).Row;
                                     if (null != dr)
                                     {
                                         SelEcgList(dr["PatientId"].ToString());
                                     }
                                 }
                             }
                         }
                     }
                     else
                     {
                         _isGetAppData = false;
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             WatchDog.Write(@"获取判读结果:", ex);
         }
         Thread.Sleep(5000);
     }
 }
Beispiel #12
0
        public IEnumerable<ArticleGroup> GetGroupsByParams(Expression<Func<ArticleGroup, bool>> predicate, Func<ArticleGroup, object> order,
			int? skip = 0, int? take = 999)
        {
            var queryParams = new QueryParams<ArticleGroup>
            {
                Skip = skip,
                Take = take,
                Order = order
            };
            return _repository.GetByPredicate(predicate, queryParams);
        }
Beispiel #13
0
 public IEnumerable<User> GetUserByPredicate(Expression<Func<User, bool>> predicate, QueryParams<User> pars)
 {
     return _repository.GetByPredicate(predicate, pars);
 }
    public async Task <(int Total, IEnumerable <CashflowInfoViewModel> Items)> FindAsync(Guid userId,
                                                                                         QueryParams queryParams, CancellationToken cancellationToken)
    {
        const string queryTemplate      = @"
SELECT X.*, A.*, CA.* FROM (
    SELECT C.*, ROW_NUMBER() OVER (/**orderby**/) AS row_nb
    FROM cashflows C
    /**where**/
) AS X
INNER JOIN accounts A ON A.id = X.account_id
INNER JOIN categories CA on CA.id = X.category_id
WHERE row_nb BETWEEN @offset AND @limit
ORDER BY row_nb;
";
        const string queryCountTemplate = @"SELECT COUNT(*) FROM cashflows /**where**/";

        var builder        = new SqlBuilder();
        var selectTemplate =
            builder.AddTemplate(queryTemplate,
                                new { Offset = queryParams.Offset + 1, Limit = queryParams.Offset + queryParams.Limit });
        var countTemplate = builder.AddTemplate(queryCountTemplate);

        builder.Where($"user_id = @{nameof(userId)}", new {
            userId
        })
        .Filter(queryParams.Filter)
        .Sort(queryParams.Sort);

        var connection = _context.Connection;

        var cashflows = await connection
                        .QueryAsync <CashflowEntity, AccountEntity, CategoryEntity, CashflowEntity>(
            selectTemplate.RawSql,
            (cashflow, account, category) => cashflow with {
            Account = account, Category = category
        },
Beispiel #15
0
 static void PrintUnsubscribedInfo(QueryParams instInfo)
 {
     Console.WriteLine(string.Format("- OnUnsubscribed: {0}", instInfo.InstrumentID));
 }
Beispiel #16
0
        static void TradeTest()
        {
            if (!CreateAndOpenTrade6()) //CTP_v6.3.6_20160606版本
            {
                return;
            }
            //if (!CreateAndOpenTrade13()) //CTP_v6.3.13_20181119版本
            //    return;
            //if (!CreateAndOpenTrade15()) //CTP_v6.3.15_20190220版本
            //    return;

            /*
             * //连接成功后才能执行查询、委托等操作,检测方法有两种:
             * 1、ITrade.IsOpened()=true
             * 2、TradeListener.OnNotify中
             * (int)XFinApi.TradeApi.ActionKind.Open == notifyParams.ActionType &&
             *          (int)ResultKind.Success == notifyParams.ResultType
             */

            while (!trade.IsOpened())
            {
                Thread.Sleep(1000);
            }

            QueryParams qryParam = new QueryParams();

            qryParam.InstrumentID = Cfg.InstrumentID;

            //查询委托单
            Thread.Sleep(1000);//有些接口查询有间隔限制,如:CTP查询间隔为1秒
            Console.WriteLine("Press any key to QueryOrder.");
            Console.ReadKey();
            trade.QueryOrder(qryParam);

            //查询成交单
            Thread.Sleep(3000);
            Console.WriteLine("Press any key to QueryTradeOrder.");
            Console.ReadKey();
            trade.QueryTradeOrder(qryParam);

            //查询合约
            Thread.Sleep(3000);
            Console.WriteLine("Press any key to QueryInstrument.");
            Console.ReadKey();
            trade.QueryInstrument(qryParam);

            //查询持仓
            Thread.Sleep(3000);
            Console.WriteLine("Press any key to QueryPosition.");
            Console.ReadKey();
            trade.QueryPosition(qryParam);

            //查询账户
            Thread.Sleep(3000);
            Console.WriteLine("Press any key to QueryAccount.");
            Console.ReadKey();
            trade.QueryAccount(qryParam);

            //委托下单
            Thread.Sleep(1000);
            Console.WriteLine("Press any key to OrderAction.");
            Console.ReadKey();
            Order order = new Order();

            order.InstrumentID  = Cfg.InstrumentID;
            order.Price         = Cfg.SellPrice1;
            order.Volume        = 1;
            order.Direction     = DirectionKind.Buy;
            order.OpenCloseType = OpenCloseKind.Open;

            //下单高级选项,可选择性设置
            order.ActionType     = OrderActionKind.Insert;         //下单
            order.OrderType      = OrderKind.Order;                //标准单
            order.PriceCond      = PriceConditionKind.LimitPrice;  //限价
            order.VolumeCond     = VolumeConditionKind.AnyVolume;  //任意数量
            order.TimeCond       = TimeConditionKind.GFD;          //当日有效
            order.ContingentCond = ContingentCondKind.Immediately; //立即
            order.HedgeType      = HedgeKind.Speculation;          //投机
            order.ExecResult     = ExecResultKind.NoExec;          //没有执行

            trade.OrderAction(order);
        }
Beispiel #17
0
            public override void OnUnsubscribed(QueryParams instInfo)
            {
                PrintUnsubscribedInfo(instInfo);

                //ToDo ...
            }
 public void AddQueryParameter(string name, object value)
 {
     QueryParams.Add(name, value);
     request.AddParameter(name, value, ParameterType.QueryString);
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        ContentManager contentManager = new ContentManager();
        ContentData    cData          = new ContentData();

        long id = 0;

        try
        {
            long.TryParse(Request["id"].ToString(), out id);
        }
        catch
        {
            id = 0;
        }

        cData = contentManager.GetItem(id, true);

        ExtractEntities contentEnt = new ExtractEntities();

        Extracted.Entities.RootObject    entResults = contentEnt.init(cData.Html);
        List <Extracted.Entities.Entity> top2People = getRelevantContent(2, "Person", entResults);
        List <Extracted.Entities.Entity> top2Org    = getRelevantContent(2, "Organization", entResults);
        QueryParams parm = new QueryParams();


        // Populate related content based on most relevant entity
        IEnumerable <QueryResult> results = populateRelatedContent(id, parm, top2People[0].text, cData.Id, 5);

        morethreeList.DataSource = results;
        morethreeList.DataBind();
        morethreeList.Visible = true;
        if (results.Count() > 0)
        {
            morethree.Text    = "<h4>More on&nbsp;" + top2People[0].text + "</h4>";
            morethree.Visible = true;
        }

        // Populate related content based on most relevant entity
        IEnumerable <QueryResult> results2 = populateRelatedContent(id, parm, top2People[1].text, cData.Id, 3);

        morefourList.DataSource = results2;
        morefourList.DataBind();
        morefourList.Visible = true;
        if (results2.Count() > 0)
        {
            morefour.Text    = "<h4>More on&nbsp;" + top2People[1].text + "</h4>";
            morefour.Visible = true;
        }

        // Populate related content based on second most relevant entity
        IEnumerable <QueryResult> results3 = populateRelatedContent(id, parm, top2Org[0].text, cData.Id, 3);

        moreoneList.DataSource = results3;
        moreoneList.DataBind();
        moreoneList.Visible = true;
        if (results3.Count() > 0)
        {
            moreone.Text    = "<h4>More on&nbsp;" + top2Org[0].text + "</h4>";
            moreone.Visible = true;
        }

        // Populate related content based on second most relevant entity
        IEnumerable <QueryResult> results4 = populateRelatedContent(id, parm, top2Org[1].text, cData.Id, 3);

        moretwoList.DataSource = results4;
        moretwoList.DataBind();
        moretwoList.Visible = true;
        if (results4.Count() > 0)
        {
            moretwo.Text    = "<h4>More on&nbsp;" + top2Org[1].text + "</h4>";
            moretwo.Visible = true;
        }

        List <Related> people = getRelatedContent(top2People);

        peopleList.DataSource = people;
        peopleList.DataBind();
        List <Related> organizations = getRelatedContent(top2Org);

        orgList.DataSource = organizations;
        orgList.DataBind();

        string bannerhtml = createBannerHTML(cData);

        bannerImage.Text  = bannerhtml;
        phoneHeading.Text = cData.Title;

        string merchandiseSearch = top2People[0].text + " " + top2People[1].text + " " + top2Org[0].text + " " + top2Org[1].text;

        try
        {
            List <ContentType <Attraction> > relatedMerchandise = populateMerchandise(merchandiseSearch, 4);
            if (relatedMerchandise.Count > 0)
            {
                merchandiseList.DataSource = relatedMerchandise;
                merchandiseList.DataBind();
                merchandiseHeader.Visible = true;
                merchandiseHeader.Text    = "<h3 style=\"margin-top: 1em;\">RELATED MERCHANDISE</h3>";
            }
        }
        catch
        {
        }
    }
        public object Get_DSNhanVien_Dashboard(int id_phong, [FromQuery] QueryParams query)
        {
            try
            {
                PageModel pageModel = new PageModel();
                using (DpsConnection cnn = new DpsConnection("ConnectSQLMXH", true))
                {
                    string sqlq = @"   select IDNV,pb.ID_PHONG,TENPHONG,CHUCVU,HOTEN,DIACHI,NGAYSINH,SDT,GIOITINH,NGAYVAOLAM from TBL_NHANVIEN as nv ,TBL_PHONGBAN as pb where nv.ID_PHONG=pb.ID_PHONG";
                    var    dt   = cnn.CreateDataTable(sqlq);
                    if (cnn.LastError != null || dt == null)
                    {
                        return(JsonResultCommon.SQL(cnn.LastError.Message));
                    }
                    var temp = dt.AsEnumerable();
                    #region Sort/filter
                    Dictionary <string, string> sortableFields = new Dictionary <string, string> {
                        { "HOTEN", "HOTEN" },
                    };
                    if (!string.IsNullOrEmpty(query.sortField) && sortableFields.ContainsKey(query.sortField))
                    {
                        if ("asc".Equals(query.sortOrder))
                        {
                            temp = temp.OrderBy(x => x[sortableFields[query.sortField]]);
                        }
                        else
                        {
                            temp = temp.OrderByDescending(x => x[sortableFields[query.sortField]]);
                        }
                    }
                    var xaaaa = query.filter;
                    if (!string.IsNullOrEmpty(query.filter["HOTEN"]))
                    {
                        string keyword = query.filter["HOTEN"].ToLower();
                        temp = temp.Where(x => x["HOTEN"].ToString().ToLower().Contains(keyword));
                    }

                    #endregion
                    int i = temp.Count();
                    if (i == 0)
                    {
                        return(JsonResultCommon.ThanhCong(new List <string>(), pageModel, User.IsInRole("68")));
                    }
                    dt = temp.CopyToDataTable();
                    int total = dt.Rows.Count;
                    pageModel.TotalCount = total;
                    pageModel.AllPage    = (int)Math.Ceiling(total / (decimal)query.record);
                    pageModel.Size       = query.record;
                    pageModel.Page       = query.page;
                    if (query.more)
                    {
                        query.page   = 1;
                        query.record = pageModel.TotalCount;
                    }
                    // Phân trang
                    dt = dt.AsEnumerable().Skip((query.page - 1) * query.record).Take(query.record).CopyToDataTable();
                    var data = from r in dt.AsEnumerable()
                               where
                               r["ID_PHONG"].Equals(id_phong)
                               select new
                    {
                        id_NV    = r["IDNV"],
                        id_phong = r["ID_PHONG"],
                        hoten    = r["HOTEN"],
                        chucvu   = r["CHUCVU"],
                        diachi   = r["DIACHI"],
                        ngaysinh = r["NGAYSINH"],
                        sdt      = r["SDT"],
                        gioitinh = r["GIOITINH"],
                        // Roles = r["roles"],
                        tenphong   = r["TENPHONG"],
                        ngayvaolam = r["NGAYVAOLAM"],
                    };

                    return(JsonResultCommon.ThanhCong(data, pageModel, User.IsInRole("68")));
                }
            }
            catch (Exception ex)
            {
                return(JsonResultCommon.Exception(ex));
            }
        }
Beispiel #21
0
 internal async Task<Entity> RequestBin(string endpoint,
                                          QueryParams parameters = null,
                                          byte[] data = null,
                                          HttpMethod httpMethod = null,
                                          Dictionary<string, string> additionalHeaders = null,
                                          string contentType = ContentType.OCTETSTREAM)
 {
     HttpRequestMessage request = new HttpRequestMessage(httpMethod ?? HttpMethod.Get, (endpoint.StartsWith("/") ? endpoint.Substring(1) : endpoint) + (parameters?.ToString() ?? string.Empty));
     if (data != null)
     {
         request.Content = new ByteArrayContent(data);
     }
     request.Content.Headers.ContentType = new MediaTypeHeaderValue(ContentType.OCTETSTREAM);
     return await ProcessRequest(request, additionalHeaders);
 }
Beispiel #22
0
        //////////////////////////////////////////////////////////////////////////////////
        //交易测试
        static void TradeTest()
        {
            //创建 ITrade
            // char* path 指 xxx.exe 同级子目录中的 xxx.dll 文件
            int err = -1;

            trade = ITradeApi.XFinApi_CreateTradeApi("XTA_W32/Api/ESITap_v9.3.0.1_20160406/XFinApi.ESITapTradeApi.dll", out err);

            if (err > 0 || trade == null)
            {
                Console.WriteLine(string.Format("* Trade XFinApiCreateError={0};", StrCreateErrors[err]));
                return;
            }

            //注册事件
            tradeEvent = new TradeEvent();
            trade.SetListener(tradeEvent);

            //连接服务器
            OpenParams openParams = new OpenParams();

            openParams.HostAddress = Cfg.TradeAddress;
            openParams.UserID      = Cfg.TradeUserName;
            openParams.Password    = Cfg.TradePassword;
            openParams.IsUTF8      = true;
            trade.Open(openParams);

            /*
             * //连接成功后才能执行查询、委托等操作,检测方法有两种:
             * 1、ITrade.IsOpened()=true
             * 2、TradeListener.OnNotify中
             * (int)XFinApi.ActionType.Open == notifyParams.ActionType &&
             * (int)XFinApi.Result.Success == notifyParams.Result
             */

            while (!trade.IsOpened())
            {
                Thread.Sleep(1000);
            }

            QueryParams qryParam = new QueryParams();

            //查询委托单
            Thread.Sleep(1000);//有些接口查询有间隔限制,如:CTP查询间隔为1秒
            Console.WriteLine("Press any key to QueryOrder.");
            Console.ReadKey();
            trade.QueryOrder(qryParam);

            //查询成交单
            Thread.Sleep(3000);
            Console.WriteLine("Press any key to QueryTradeOrder.");
            Console.ReadKey();
            trade.QueryTradeOrder(qryParam);

            //查询合约
            Thread.Sleep(3000);
            qryParam.ExchangeID = Cfg.ExchangeID;
            qryParam.ProductID  = Cfg.ProductID;
            Console.WriteLine("Press any key to QueryInstrument.");
            Console.ReadKey();
            trade.QueryInstrument(qryParam);

            //查询持仓
            Thread.Sleep(3000);
            Console.WriteLine("Press any key to QueryPosition.");
            Console.ReadKey();
            trade.QueryPosition(qryParam);

            //查询账户
            Thread.Sleep(3000);
            Console.WriteLine("Press any key to QueryAccount.");
            Console.ReadKey();
            trade.QueryAccount(qryParam);

            //委托下单
            Thread.Sleep(1000);
            Console.WriteLine("Press any key to OrderAction.");
            Console.ReadKey();
            Order order = new Order();

            order.ExchangeID    = Cfg.ExchangeID;
            order.ProductID     = Cfg.ProductID;
            order.InstrumentID  = Cfg.InstrumentID;
            order.Price         = Cfg.SellPrice1;
            order.Volume        = 1;
            order.Direction     = DirectionKind.Buy;
            order.OpenCloseType = OpenCloseKind.Open;

            //下单高级选项,可选择性设置
            order.ActionType     = OrderActionKind.Insert;         //下单
            order.OrderType      = OrderKind.Order;                //标准单
            order.PriceCond      = PriceConditionKind.LimitPrice;  //限价
            order.VolumeCond     = VolumeConditionKind.AnyVolume;  //任意数量
            order.TimeCond       = TimeConditionKind.GFD;          //当日有效
            order.ContingentCond = ContingentCondKind.Immediately; //立即
            order.HedgeType      = HedgeKind.Speculation;          //投机
            order.ExecResult     = ExecResultKind.NoExec;          //没有执行

            trade.OrderAction(order);
        }
Beispiel #23
0
    } // End of the constructor

    #endregion

    #region Get methods

    /// <summary>
    /// Get a query string from query parameters
    /// </summary>
    /// <param name="parameters">A reference to query parameters</param>
    /// <returns>A query string</returns>
    public static string GetQueryString(QueryParams parameters)
    {
        // Create the string to return
        string queryString = "";

        // Create the string to return
        if(parameters != null)
        {
            queryString = "?kw=" + HttpContext.Current.Server.UrlEncode(parameters.keywords) + "&sf=" + parameters.sort_field + "&so=" + parameters.sort_order + "&pz=" + parameters.page_size
           + "&qp=" + parameters.current_page;
        }

        // Return the query string
        return queryString;

    } // End of the GetQueryString method
 public override IEnumerable<IForm> GetForms(QueryParams queryParams, out int total)
 {
     return InnerProvider.GetForms(queryParams, out total);
 }
Beispiel #25
0
 public List<QueryResults> Query(QueryParams queryParams, QuerySettings settings)
 {
     settings = settings ?? new QuerySettings();
     return _data.Query(queryParams, settings);
 }
Beispiel #26
0
 public IEnumerable <Article> GetByPredicate(Expression <Func <Article, bool> > predicate, QueryParams <Article> param)
 {
     throw new NotImplementedException();
 }
Beispiel #27
0
 static void PrintUnsubscribedInfo(QueryParams instInfo)
 {
     Console.WriteLine(string.Format("- OnUnsubscribed: {0} {1} {2}", instInfo.ExchangeID, instInfo.ProductID, instInfo.InstrumentID));
 }
 public ActionResult Followers(int id, QueryParams query)
 {
     var followers = App.Get().CurrentWeb.Lists[id].Followers;
     var results = query.GetPageResult(followers).ToList();
     var users = results.Select(p => new
     {
         id = p.UserName,
         dispName = p.DisplayName,
         name = new
         {
             firstName = p.FirstName,
             lastName = p.LastName
         },
         email = p.Email,
         picture = p.Avatar,
         link = Url.Content("~/profiles/" + p.UserName)
     }).ToList();
     string jsonStr = JsonConvert.SerializeObject(users);
     return Content(jsonStr, "application/json", Encoding.UTF8);
 }
Beispiel #29
0
 public static MLResult GetWorldRays(QueryParams query, ResultCallback callback)
 {
     return(MLResult.Create(MLResult.Code.UnspecifiedFailure));
 }
 public override IEnumerable<IForm> GetForms(QueryParams queryParams, out int total)
 {
     IEnumerable<IForm> forms = InnerProvider.GetForms(queryParams, out total);
     DecryptForms(forms);
     return forms;
 }
        public ActionResult Shares(string name, Guid id, QueryParams query)
        {
            if (id == Guid.Empty)
                throw new ArgumentNullException("id");

            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");

            var list = App.Get().CurrentWeb.Lists[name];
            if (list == null)
                throw new ContentListNotFoundException();

            var item = list.GetItem(id);
            if (item == null)
                throw new ContentDataItemNotFoundException();

            var results = query.GetPageResult(item.Reshares()).ToList().Select(r => App.Get().Wrap(r).ToObject()).ToList();
            var modal = new
            {
                Modal = results,
                Total = item.Reshares().Count()
            };

            string jsonStr = JsonConvert.SerializeObject(modal, new JsonSerializerSettings() { DateFormatHandling = DateFormatHandling.MicrosoftDateFormat });
            return Content(jsonStr, "application/json", Encoding.UTF8);
        }
        public override void Handle(HttpListenerRequest request, HttpListenerResponse response)
        {
            TimeSpan expires = m_NextVendorUpdate - DateTime.Now;
            response.ContentType = "application/json";

            SetCacheHeaders(response.Headers, expires);
            Stream outputStream = PrepareOutputStream(request, response);
            QueryParams queryParams = new QueryParams(request);

            int start = queryParams.Start;
            int end = start + queryParams.Limit;
            List<MyVendorItem> subList;
            string query = queryParams.Query;
            if (query != null && query.Trim().Length != 0)
            {
                subList = m_ItemCache.Get(queryParams.Query) as List<MyVendorItem>;
                if (subList == null)
                {
                    string[] qps = query.Split(' ');
                    IEnumerable<MyVendorItem> results = null;
                    Func<MyVendorItem, bool> currentFunc = null;
                    //FIXME make this more dynamic/cleaner
                    for(int i = 0, j = qps.Length; i < j; i++)
                    {
                        string q = qps[i].Trim();
                        if(q.Length < 3) // ignore queries less than 3 characters
                        {
                            continue;
                        }
                        char first = q[0];
                        if (first == '-')
                        {
                            currentFunc = NotContains(q.Substring(1));
                        }
                        else if (first == '+')
                        {
                            currentFunc = Contains(q.Substring(1));
                        }
                        else
                        {
                            currentFunc = Contains(q);
                        }
                        results = results == null ? m_VendorItems.Where(currentFunc) : results.Where(currentFunc);
                    }
                    subList = results.ToList();
                    m_ItemCache.Add(query, subList, null, m_NextVendorUpdate, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
                }
            }
            else
            {
                subList = m_VendorItems;
            }
            string sort = queryParams.Sort;
            QueryParams.SortDirection dir = queryParams.Direction;
            if (StringUtils.HasText(sort))
            {
                subList = dir.Equals(QueryParams.SortDirection.Ascending) ? subList.OrderBy(p => typeof(MyVendorItem).GetProperty(sort).GetValue(p, null)).ToList() : subList.OrderByDescending(p => typeof(MyVendorItem).GetProperty(sort).GetValue(p, null)).ToList();
            }
            int totalCount = subList.Count;
            if (start > subList.Count || subList.Count == 0)
            {
                sendResponse(outputStream, subList, queryParams.Callback, totalCount);
                return;
            }
            if (end > subList.Count)
            {
                end = subList.Count;
            }
            subList = subList.GetRange(start, end - start);
            sendResponse(outputStream, subList, queryParams.Callback, totalCount);

            response.StatusCode = 200;
            response.StatusDescription = "OK";
            response.Close();
        }
Beispiel #33
0
 /// <summary>
 /// Performs a RESTful request to the Nuxeo Server.
 /// </summary>
 /// <param name="type">The type of the request.</param>
 /// <param name="endpoint">The end point, following "api/v1/".</param>
 /// <param name="parameters">The query parameters to follow the url.</param>
 /// <param name="data">The JSON data to be send.</param>
 /// <param name="additionalHeaders">The additional request headers, besides those already specified in the client.</param>
 /// <param name="contentType">The type of the content to be sent.</param>
 /// <returns>Returns an <see cref="Entity"/> with the result from the request.</returns>
 public async Task<Entity> Request(RequestType type,
                                   string endpoint,
                                   QueryParams parameters = null,
                                   JToken data = null,
                                   Dictionary<string, string> additionalHeaders = null,
                                   string contentType = ContentType.JSON)
 {
     if (type == RequestType.GET)
     {
         return await Get(UrlCombiner.Combine(RestPath, endpoint), parameters, additionalHeaders, contentType);
     }
     else if (type == RequestType.POST)
     {
         return await Post(UrlCombiner.Combine(RestPath, endpoint), parameters, data, additionalHeaders, contentType);
     }
     else if (type == RequestType.PUT)
     {
         return await Put(UrlCombiner.Combine(RestPath, endpoint), parameters, data, additionalHeaders, contentType);
     }
     else if (type == RequestType.DELETE)
     {
         return await Delete(UrlCombiner.Combine(RestPath, endpoint), parameters, additionalHeaders, contentType);
     }
     else
     {
         throw new Exception("Invalid request type.");
     }
 }
Beispiel #34
0
        /// <summary>
        /// Get parameters from query string.
        /// </summary>
        /// <param name="helper">The url helper object.</param>
        /// <returns></returns>
        public static QueryParams GetQueryParams(this UrlHelper helper)
        {
            var queryStr = helper.RequestContext.HttpContext.Request.QueryString;
            var query = new QueryParams();

            if (!string.IsNullOrEmpty(queryStr["index"]))
                query.Index = int.Parse(queryStr["index"]);

            if (!string.IsNullOrEmpty(queryStr["size"]))
                query.Size = int.Parse(queryStr["size"]);

            return query;
        }
Beispiel #35
0
 internal async Task<Entity> PostBin(string endpoint,
                                     QueryParams parameters = null,
                                     byte[] data = null,
                                     Dictionary<string, string> additionalHeaders = null)
 {
     return await RequestBin(endpoint, parameters, data, HttpMethod.Post, additionalHeaders);
 }
Beispiel #36
0
 internal async Task<Entity> Put(string endpoint,
                                 QueryParams parameters = null,
                                 JToken data = null,
                                 Dictionary<string, string> additionalHeaders = null,
                                 string contentType = ContentType.JSON)
 {
     return await RequestJson(endpoint, parameters, data, HttpMethod.Put, additionalHeaders, contentType);
 }
        public async Task <HttpResponseMessage> Get(string endpoint, GetParams getParams, QueryParams queryParams, CancellationToken?token = null)
        {
            try
            {
                bool paramExists;
                var  url = new StringBuilder(GetUrl(endpoint, out paramExists));
                SetParamString(url, paramExists, (getParams?.Parameters ?? new NameValuePair[0]).Concat(queryParams?.Parameters ?? new NameValuePair[0]));

                using (var request = CreateRequestMessage(HttpMethod.Get, url.ToString()))
                    using (var tokenHelper = new CancellationTokenHelper(token, Timeout))
                    {
                        return(await HttpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead, tokenHelper.Token));
                    }
            }
            catch (BacklogException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new BacklogApiException("backlog api request failed.", ex);
            }
        }