Example #1
0
        public static IDictionary<string, object> ApplyFilter(IFilterDescriptor filter)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            string filerMessage = string.Empty;
            List<string> convertValue = new List<string>();
            string filerOperators = string.Empty;
            if (filter is CompositeFilterDescriptor)
            {
                foreach (IFilterDescriptor childFilter in ((CompositeFilterDescriptor)filter).FilterDescriptors)
                {
                    parameters.SafeAdd(ApplyFilter(childFilter));
                }
            }
            else
            {
                FilterDescriptor filterDescriptor = (FilterDescriptor)filter;
                filerMessage = filterDescriptor.Member;
                convertValue.Add(filterDescriptor.Value.ToSafeString());
                switch (filterDescriptor.Operator)
                {
                    case FilterOperator.IsEqualTo:
                        parameters.SafeAdd(filerMessage, filterDescriptor.Value);
                        break;
                    case FilterOperator.IsNotEqualTo:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0}<>'{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.StartsWith:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0} like '{1}%'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.Contains:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0} like '%{1}%'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.EndsWith:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0} like '%{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.IsLessThanOrEqualTo:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0} <='{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.IsLessThan:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0}<'{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.IsGreaterThanOrEqualTo:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0}>='{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                    case FilterOperator.IsGreaterThan:
                        parameters.SafeAdd(IdGenerator.NewComb().ToSafeString(), new Condition(string.Format("{0}>'{1}'", filerMessage, filterDescriptor.Value)));
                        break;
                }
            }

            return parameters;
        }
        public void Delete(string id)
        {
            string errorMsg = string.Empty;
            DoResult actionResult = DoResult.Failed;
            string actionMessage = string.Empty;

            try
            {
                string processDefID = Request.Form["ProcessDefID"];
                string activityID = id;
                ProcessDefine processDefine = wfEngine.GetProcessDefine(ProcessDefID);
                Activity activity = processDefine.Activities.FirstOrDefault(a => a.ID == activityID);
                processDefine.Activities.Remove(activity);

                foreach (var transition in processDefine.Transitions.Where(t => t.DestActivity == activityID || t.SrcActivity == activityID).ToList())
                {
                    processDefine.Transitions.Remove(transition);
                }

                // ProcessDefService processDefService = new ProcessDefService();
                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.SafeAdd("Name", processDefine.ID);
                parameters.SafeAdd("Version", processDefine.Version);
                ProcessDef processDef = repository.FindOne<ProcessDef>(parameters);
                processDef.Content = processDefine.ToXml();

                repository.SaveOrUpdate(processDef);

                wfEngine.ClearProcessCache();

                actionResult = DoResult.Success;
                //获取提示信息
                actionMessage = RemarkAttribute.GetEnumRemark(actionResult);

                //显示提示信息
                WebUtil.PromptMsg(actionMessage);

                //刷新页面
                Refresh();

            }
            catch (Exception ex)
            {
                //获取提示信息
                actionMessage = RemarkAttribute.GetEnumRemark(actionResult);
                log.Error(ex);
            }
        }
Example #3
0
        private Dictionary<string, List<int>> FindSameStrings(string text, int length, Dictionary<string, List<int>> indexes)
        {
            for (int startIndex = 0; startIndex < text.Length - length; startIndex++)
            {
                string cutString = text.Substring(startIndex, length);
                indexes.SafeAdd(cutString, startIndex);
            }

            indexes = indexes.Where(x => x.Value.Count > 1).ToDictionary(x => x.Key, x => x.Value);
            return indexes;
        }
Example #4
0
        /// <summary>
        /// 删除节点
        /// </summary>
        /// <param name="argument"></param>
        public string DeleteTreeNode(string argument)
        {
            AjaxResult ajaxResult = new AjaxResult();
            DoResult doResult = DoResult.Failed;
            string actionMessage = string.Empty;
            try
            {
                Organization org = repository.GetDomain<Organization>(argument);
                if (org != null)
                {
                    IDictionary<string, object> parameters = new Dictionary<string, object>();
                    parameters.SafeAdd("OrgID", org.ID);
                    IList<EmployeeOrg> employeeOrgList = repository.FindAll<EmployeeOrg>(parameters);
                    if (employeeOrgList.Count == 0)
                    {
                        repository.Delete<Organization>(org.ID);
                        doResult = DoResult.Success;
                    }
                    else
                    {
                        doResult = DoResult.Failed;
                        actionMessage = "请先删除该部门下面的操作员!";
                    }
                }
                else
                {
                    doResult = DoResult.Failed;
                }

                //获取提示信息
                actionMessage = string.Format("删除组织{0}", org.Name);

                //记录操作日志
                AddActionLog(org, doResult, actionMessage);

                ajaxResult.Result = doResult;
                ajaxResult.RetValue = org.ParentID;
                ajaxResult.PromptMsg = actionMessage;
            }
            catch (Exception ex)
            {
                log.Error(actionMessage, ex);
                AddActionLog<Organization>(actionMessage, DoResult.Failed);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
        public Dictionary<Dictionary<char, char>, List<Dictionary<char, char>>> GetMatchSubs(Dictionary<char, char>[] substitutions)
        {
            Dictionary<Dictionary<char, char>, List<Dictionary<char, char>>> matchSubs = new Dictionary<Dictionary<char, char>, List<Dictionary<char, char>>>();

            foreach (var subs1 in substitutions)
            {
                foreach (var subs2 in substitutions)
                {
                    if (TextAnalysis.AreSubstMatch(subs1, subs2))
                    {
                        matchSubs.SafeAdd(subs1, subs2);
                    }
                }
            }

            return matchSubs;
        }
Example #6
0
        public string Delete(string argument)
        {
            AjaxResult ajaxResult = new AjaxResult();

            string errorMsg = string.Empty;
            DoResult doResult = DoResult.Failed;
            string actionMessage = string.Empty;
            try
            {
                if (!string.IsNullOrWhiteSpace(argument))
                {
                    string roleID = argument;

                    IRepository<string> repository = new Repository<string>();
                    IDictionary<string, object> parameters = new Dictionary<string, object>();
                    parameters.SafeAdd("RoleID", roleID);
                    IList<ObjectRole> objectRoleList = repository.FindAll<ObjectRole>(parameters);
                    if (objectRoleList.Count == 0)
                    {
                        repository.Delete<Role>(roleID);
                        repository.ExecuteSql<RolePrivilege>(string.Format("Delete from AC_RolePrivilege where RoleID='{0}'", roleID));
                        doResult = DoResult.Success;
                        actionMessage = RemarkAttribute.GetEnumRemark(doResult);
                    }
                    else
                    {
                        doResult = DoResult.Failed;
                        actionMessage = "请先解除该角色与操作员的关联!";
                    }

                    ajaxResult.RetValue = CurrentId;
                    ajaxResult.PromptMsg = actionMessage;
                }

                ajaxResult.Result = doResult;
            }
            catch (Exception ex)
            {
                actionMessage = RemarkAttribute.GetEnumRemark(doResult);
                log.Error(actionMessage, ex);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
Example #7
0
        /// <summary>
        /// 初始化对象            
        /// </summary>
        /// <param name="xElem"></param>
        public override void Initilize(XElement xElem)
        {
            Attibutes = new Dictionary<string, object>();
            Properties = new Dictionary<string, object>();

            XElement basic = xElem.Element("basic");
            xElem.Attributes()
                  .ForEach(e => { if (!string.IsNullOrEmpty(e.Name.LocalName) && !string.IsNullOrEmpty(e.Value))Attibutes.SafeAdd(e.Name.LocalName, e.Value.Trim()); });

            basic.Elements()
                 .Where(e => e.Elements().Count() == 0)
                 .ForEach(e => { if (!string.IsNullOrEmpty(e.Name.LocalName) && !string.IsNullOrEmpty(e.Value)) Properties.SafeAdd(e.Name.LocalName, e.Value.Trim()); });

            TimeLimit = new TimeLimit(this, basic.Element("timeLimit"));
            var xInitiator = basic.Element("initiator");
            StarterType = xInitiator.Element("starterType").Value;
            Initiators = xInitiator.Elements("participantor").Select(o => new Participantor(this, o)).ToList();
            TriggerEvents = basic.Element("triggerEvents").Elements("triggerEvent").Select(o => new TriggerEvent(this, o)).ToList();
            Activities = xElem.Element("activities").Elements("activity").Select(e => ObejectFactory.CreateActivity(this, e)).ToList();
            Transitions = xElem.Element("transitions").Elements("transition").Select(e => new Transition(this, e)).ToList();

            XElement xResource = xElem.Element("resource");
            BizVariables = xResource.Element("bizVariables").Elements("bizVariable").Select(e => new BizVariable(this, e)).ToList();
            Notes = xResource.Element("notes").Elements("note").Select(e => new Note(this, e)).ToList();
        }
Example #8
0
        /// <summary>
        /// 获取当前流程实例待执行工作项及参与者字典
        /// </summary>
        /// <param name="processInstID">流程实例ID</param>
        /// <returns></returns>
        public IDictionary<WorkItem, IList<Operator>> GetActiveWorkItems(string processInstID)
        {
            IDictionary<WorkItem, IList<Operator>> result = new Dictionary<WorkItem, IList<Operator>>();

            var activeWorkItems = repository.Query<WorkItem>().Where(o => o.ProcessInstID == processInstID && o.CurrentState == (short)WorkItemStatus.WaitExecute);
            foreach (var item in activeWorkItems)
            {
                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("WorkItemID", item.ID);
                var participants = repository.ExecuteDataTable<WorkItem>(@"select * from AC_Operator where ID in (select ParticipantID from WF_Participant where WorkItemID=$WorkItemID and ParticipantType=1)
            union
            select * from AC_Operator where ID in (select ObjectID from OM_ObjectRole where RoleID in (select ParticipantID from WF_Participant where WorkItemID=$WorkItemID and ParticipantType=2))
            union
            select * from AC_Operator where ID in (select EmployeeID from OM_EmployeeOrg where OrgID in( select ParticipantID from WF_Participant where WorkItemID=$WorkItemID and ParticipantType=3))
            ", parameters).ToList<Operator>();

                result.SafeAdd(item, participants);
            }
            return result;
        }
Example #9
0
        /// <summary>
        /// 获取某参与者类型下的所有参与者
        /// </summary>
        /// <param name="parentType">父参与者类型</param>
        /// <param name="parentID">父参与者ID</param>
        /// <returns></returns>
        public IList<Participantor> GetPersonParticipantors(ParticipantorType parentType, string parentID)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.SafeAdd("ID", "none");
            if (parentType == ParticipantorType.Role)
            {
                parameters.SafeAdd("ID", new AgileEAP.Core.Data.Condition(string.Format("ID in (select b.ObjectID from OM_ObjectRole b where b.RoleID='{0}')", parentID)));
            }
            else if (parentType == ParticipantorType.Org)
            {
                parameters.SafeAdd("ID", new AgileEAP.Core.Data.Condition(string.Format("ID in (select b.EmployeeID from OM_EmployeeOrg b where b.OrgID='{0}')", parentID)));
            }

            int index = 0;
            return repository.FindAll<Employee>(parameters).Select(o => new Participantor()
            {
                ID = o.ID,
                Name = o.Name,
                ParticipantorType = ParticipantorType.Person,
                SortOrder = ++index,
                ParentID = parentID
            }).ToList();
        }
Example #10
0
        /// <summary>
        /// 保存资源
        /// </summary>
        /// <param name="entity">资源实体</param>
        public void SaveResource(Resource entity)
        {
            using (ITransaction trans = UnitOfWork.BeginTransaction(typeof(Resource)))
            {
                repository.Clear<Resource>();
                repository.SaveOrUpdate(entity);

                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add("ResourceID", entity.ID);
                parameters.Add("OperateID", string.Empty);
                Privilege privilege = repository.FindOne<Privilege>(parameters);
                if (privilege == null)
                {
                    repository.SaveOrUpdate(new Privilege()
                    {
                        ID = IdGenerator.NewComb().ToString(),
                        MetaDataID = string.Empty,
                        Name = entity.Text,
                        OperateID = string.Empty,
                        //AppID = entity.AppID,
                        //OwnerOrg = entity.OwnerOrg,
                        //ModuleID = entity.ModuleID,
                        //Description = entity.Description,
                        ResourceID = entity.ID,
                        SortOrder = entity.SortOrder,

                        Type = entity.Type,
                        CreateTime = DateTime.Now,
                        Creator = entity.Creator,
                    });
                }

                if (entity.Operates != null)
                {
                    string idList = "";
                    foreach (var operate in entity.Operates)
                    {
                        idList += string.Format(" '{0}',", operate.ID);
                    }
                    string sWhere = string.IsNullOrEmpty(idList.TrimEnd(',')) ? "" : string.Format(" and OperateID not in ({0}) ", idList.TrimEnd(','));
                    repository.ExecuteSql<Resource>(string.Format("delete from AC_Operate where id in (select OperateID from AC_Privilege where ResourceID='{0}' and (OperateID is not null and OperateID<>'') {1})", entity.ID, sWhere));
                    repository.ExecuteSql<Resource>(string.Format("delete from AC_Privilege where ResourceID='{0}' and (OperateID is not null and OperateID<>'') {1}", entity.ID, sWhere));

                    foreach (var operate in entity.Operates)
                    {
                        repository.SaveOrUpdate(operate);
                        parameters.Clear();
                        parameters.SafeAdd("ResourceID", entity.ID);
                        parameters.SafeAdd("OperateID", operate.ID);
                        IList<Privilege> privilegeList = repository.FindAll<Privilege>(parameters);
                        if (privilegeList.Count == 0)
                        {
                            repository.SaveOrUpdate(new Privilege()
                            {
                                ID = IdGenerator.NewComb().ToString(),
                                //AppID = entity.AppID,
                                MetaDataID = string.Empty,
                                Name = operate.OperateName,
                                OperateID = operate.ID,
                                //ModuleID = entity.ModuleID,
                                //OwnerOrg = entity.OwnerOrg,
                                //Description = entity.Description,
                                ResourceID = entity.ID,
                                SortOrder = operate.SortOrder,
                                Type = 3,
                                CreateTime = DateTime.Now,
                                Creator = entity.Creator,
                            });
                        }
                    }
                }

                trans.Commit();
            }

            repository.ClearCache<Resource>();
            repository.ClearCache<Privilege>();
            repository.ClearCache<Operate>();
        }
Example #11
0
        public static Dictionary<uint, Client.GameState> SafeReturn()
        {
            Dictionary<uint, Client.GameState> toReturn = new Dictionary<uint, Client.GameState>();

            try
            {
                lock (Kernel.GamePool)
                {
                    foreach (Client.GameState c in Kernel.GamePool.Values)
                        if (c != null)
                            if (c.Entity != null)
                                toReturn.SafeAdd(c.Entity.UID, c);
                }
            }
            catch { Console.WriteLine("Error at safe return"); }

            return toReturn;
        }
Example #12
0
        public string Delete(string operatorID)
        {
            AjaxResult ajaxResult = new AjaxResult();

            string errorMsg = string.Empty;
            DoResult doResult = DoResult.Failed;
            string actionMessage = string.Empty;
            try
            {
                if (!string.IsNullOrWhiteSpace(operatorID))
                {
                    IRepository<string> repository = new Repository<string>();

                    UnitOfWork.ExecuteWithTrans<Operator>(() =>
                        {
                            repository.Delete<Operator>(operatorID);

                            IDictionary<string, object> parameters = new Dictionary<string, object>();
                            parameters.SafeAdd("OperatorID", operatorID);
                            Employee employee = repository.FindOne<Employee>(parameters);
                            repository.Delete<Employee>(parameters);

                            parameters.Clear();
                            parameters.SafeAdd("EmployeeID", employee.ID);
                            repository.Delete<EmployeeOrg>(parameters);

                            parameters.Clear();
                            parameters.SafeAdd("ObjectID", operatorID);
                            repository.Delete<ObjectRole>(parameters);
                        });


                    doResult = DoResult.Success;

                    //获取提示信息
                    actionMessage = RemarkAttribute.GetEnumRemark(doResult);

                    ajaxResult.RetValue = CurrentId;
                    ajaxResult.PromptMsg = actionMessage;
                }

                ajaxResult.Result = doResult;
            }
            catch (Exception ex)
            {
                actionMessage = RemarkAttribute.GetEnumRemark(doResult);
                log.Error(actionMessage, ex);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
Example #13
0
        /// <summary>
        /// 获取员工所在部门名称
        /// </summary>
        /// <param name="orgID">组织ID</param>
        /// <returns></returns>
        public IList<Organization> GetOrgNameByUserID(string userID)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.SafeAdd("ID", new Condition(string.Format("ID in (select b.OrgID from OM_EmployeeOrg b where b.EmployeeID='{0}')", userID)));

            return repository.FindAll<Organization>(parameters);
        }
		private void OnProcessPositions(long transactionId, string[] data)
		{
			var f = Wrapper.FieldsPositions;
			var portfChangeMessages = new Dictionary<string, PortfolioChangeMessage>();

			foreach (var str in data)
			{
				var cols = str.ToColumns();

				var portfolioName = GetPortfolioName(f.AccCode.GetValue(cols), this.GetBoardCode(f.PlaceCode.GetValue(cols)));
				var secCode = f.PaperCode.GetValue(cols);

				if (secCode == "money")
				{
					var changesMsg = portfChangeMessages.SafeAdd(portfolioName, this.CreatePortfolioChangeMessage);

					changesMsg.Add(PositionChangeTypes.RealizedPnL, f.PnL.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.UnrealizedPnL, f.ProfitVol.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.CurrentPrice, f.RealVol.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.BeginValue, f.IncomeRest.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.CurrentValue, f.RealRest.GetValue(cols));
				}
				else
				{
					var secId = new SecurityId { Native = f.PaperNo.GetValue(cols) };

					SendOutMessage(new PositionMessage
					{
						PortfolioName = portfolioName,
						SecurityId = secId
					});

					var changesMsg = this.CreatePositionChangeMessage(portfolioName, secId);

					changesMsg.Add(PositionChangeTypes.RealizedPnL, f.PnL.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.UnrealizedPnL, f.ProfitVol.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.CurrentPrice, f.RealVol.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.CurrentValue, f.ForwordRest.GetValue(cols));
					changesMsg.Add(PositionChangeTypes.AveragePrice, f.BalancePrice.GetValue(cols));

					var varMargin = f.VarMargin.GetValue(cols);
					changesMsg.Add(PositionChangeTypes.VariationMargin, varMargin);

					if (varMargin != 0)
					{
						var portfChangesMsg = portfChangeMessages.SafeAdd(portfolioName, this.CreatePortfolioChangeMessage);
						var oldVm = portfChangesMsg.Changes.TryGetValue(PositionChangeTypes.VariationMargin);

						if(oldVm == null)
							portfChangesMsg.Changes[PositionChangeTypes.VariationMargin] = varMargin;
						else
							portfChangesMsg.Changes[PositionChangeTypes.VariationMargin] = (decimal)oldVm + varMargin;
					}

					SendOutMessage(changesMsg);
				}	
			}

			portfChangeMessages.Values.ForEach(SendOutMessage);

			if (transactionId > 0)
			{
				SendOutMessage(new PortfolioLookupResultMessage
				{
					OriginalTransactionId = transactionId,
				});	
			}
		}
 /// <summary>
 /// 显示列表信息
 /// </summary>
 /// <param name="gvList">GridView对象</param>
 /// <param name="pageInfo">分页信息</param>
 public void ShowList(PagedGridView gvList, PageInfo pageInfo)
 {
     IDictionary<string, object> parameters = new Dictionary<string, object>();
     parameters.SafeAdd("CatalogID", CurrentId);
     parameters.SafeAdd("dataFilter", new Condition(GetFilterString()));
     IPageOfList<UploadFile> result = uploadFileService.FindAll(parameters, "Order By FileName", pageInfo);
     gvList.ItemCount = result.PageInfo.ItemCount;
     gvList.DataSource = result;
     gvList.DataBind();
 }
Example #16
0
		static NamespaceDom[] MergeNamespaces(IEnumerable<NamespaceDom> namespaces)
		{
			var nsDict = new Dictionary<string, NamespaceDom>();
			
			foreach (var ns in namespaces)
			{
				var curNs = nsDict.SafeAdd(ns.Name, name => new NamespaceDom(name));
				curNs.Types.AddMany(ns.Types);
			}

			return nsDict.Values.OrderBy(_ => _.Name).ToArray();
		}
Example #17
0
        public ActionResult Form()
        {
            try
            {
                string processDefID = Request.QueryString["processDefID"];
                string eFormID = Request.QueryString["eFormID"];
                string entry = Request.QueryString["Entry"];
                eForm formInfo = null;
                if (string.IsNullOrEmpty(processDefID) && !string.IsNullOrEmpty(eFormID))
                {
                    formInfo = repository.GetDomain<eForm>(eFormID);
                }
                if (formInfo != null && !string.IsNullOrEmpty(formInfo.Content))
                {
                    Form form = JsonConvert.DeserializeObject<Form>(formInfo.Content);
                    string processInstID = Request.QueryString["processInstID"];
                    //ProcessForm processForm = null;
                    IDictionary<string, object> values = new Dictionary<string, object>();
                    //if (!string.IsNullOrEmpty(processInstID))
                    //{
                    //    IDictionary<string, object> parameters = new Dictionary<string, object>();
                    //    parameters.SafeAdd("processInstID", processInstID);
                    //    processForm = repository.FindOne<ProcessForm>(parameters);
                    //    if (processForm != null)
                    //    {
                    //        parameters.Clear();
                    //        parameters.Add("ID", processForm.BizID);
                    //        DataTable dt = repository.ExecuteDataTable<ProcessForm>(string.Format("select * from {0}", processForm.BizTable), parameters);
                    //        if (dt != null && dt.Rows.Count > 0)
                    //        {

                    //            foreach (DataRow row in dt.Rows)
                    //            {
                    //                foreach (var field in form.Fields)//manualActivity.Form.Fields)
                    //                {

                    //                    if (field.ControlType == ControlType.SysVariable)
                    //                    {
                    //                        switch (field.DefaultValue.ToInt())
                    //                        {
                    //                            case (short)SystemControlType.OrgID:
                    //                                Organization org = repository.Query<Organization>().FirstOrDefault(o => o.Code == workContext.User.OrgID);
                    //                                values.SafeAdd(field.Name, org.Name);
                    //                                if (!string.IsNullOrEmpty(field.ExtendData))
                    //                                {
                    //                                    values.SafeAdd(field.ExtendData, workContext.User.OrgID);
                    //                                }
                    //                                break;
                    //                            case (short)SystemControlType.UserID:
                    //                                values.SafeAdd(field.Name, workContext.User.Name);
                    //                                if (!string.IsNullOrEmpty(field.ExtendData))
                    //                                {
                    //                                    values.SafeAdd(field.ExtendData, workContext.User.ID);
                    //                                }
                    //                                break;
                    //                            case (short)SystemControlType.CurrentDate:
                    //                                values.SafeAdd(field.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    //                                break;
                    //                        }

                    //                    }
                    //                    else if (dt.Columns.Contains(field.Name))
                    //                    {
                    //                        if (!string.IsNullOrEmpty(row[field.Name].ToSafeString()))
                    //                        {
                    //                            values.SafeAdd(field.Name, row[field.Name]);
                    //                        }
                    //                        else
                    //                        {
                    //                            if (!string.IsNullOrEmpty(field.DefaultValue))
                    //                                values.SafeAdd(field.Name, field.DefaultValue);
                    //                        }
                    //                    }

                    //                }
                    //            }
                    //        }
                    //    }
                    //}
                    //if (processForm == null)
                    //{
                        foreach (var field in form.Fields)//manualActivity.Form.Fields)
                        {
                            if (field.ControlType == ControlType.SysVariable)
                            {
                                switch (field.DefaultValue.ToInt())
                                {
                                    case (short)SystemControlType.OrgID:
                                        Organization org = repository.Query<Organization>().FirstOrDefault(o => o.Code == workContext.User.OrgID);
                                        values.SafeAdd(field.Name, org.Name);
                                        if (!string.IsNullOrEmpty(field.ExtendData))
                                        {
                                            values.SafeAdd(field.ExtendData, workContext.User.OrgID);
                                        }
                                        break;
                                    case (short)SystemControlType.UserID:
                                        values.SafeAdd(field.Name, workContext.User.Name);
                                        if (!string.IsNullOrEmpty(field.ExtendData))
                                        {
                                            values.SafeAdd(field.ExtendData, workContext.User.ID);
                                        }
                                        break;
                                    case (short)SystemControlType.CurrentDate:
                                        values.SafeAdd(field.Name, DateTime.Now.ToSafeDateTime());
                                        break;
                                }
                            }
                            else if (field.ControlType != ControlType.SysVariable && field.ControlType != ControlType.HiddenInput)
                            {
                                if (!string.IsNullOrEmpty(field.DefaultValue))
                                    values.SafeAdd(field.Name, field.DefaultValue);
                            }
                            else
                            {
                                // values.SafeAdd(field.Name, workContext.);
                            }
                        }
                    //}
                    //ViewData["Values"] = values;
                    //ViewData["Form"] = form;//manualActivity.Form;
                        FormModel formModel = new FormModel()
                        {
                            Form = form,
                            Values = values
                        };

                }
            }
            catch (Exception ex)
            {
                log.Error("初始化表单失败" + ex);
            }
            return View();
        }
Example #18
0
        /// <summary>
        /// 返回查询条件
        /// </summary>
        /// <param name="filterValues"></param>
        public override KeyValuePair<string, IDictionary<string, object>> GetFilterCondition(IDictionary<string, object> filterValues)
        {
            string paramValue = GetFilterValue<string>(filterValues, Field.Name + "data").Trim(',').Trim();
            string inputValue = GetFilterValue<string>(filterValues, Field.Name).Trim(',').Trim();

            if (inputValue == "批量值" && !string.IsNullOrEmpty(paramValue))
            {
                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.Add(new KeyValuePair<string, object>(ParamChar + Field.Name, paramValue));

                return new KeyValuePair<string, IDictionary<string, object>>(string.Format(" And {0} in (select value from DD_BatchValue where BatchDataID={1}{0}) ", Field.Name, ParamChar), parameters);
            }

            if (Field.DataType == DataType.String)
            {
                Dictionary<string, object> parameters = new Dictionary<string, object>();

                if (HasValue(filterValues))
                {
                    KeyValuePair<string, object> parameter = NewParameter(Field.Name, filterValues);
                    parameters.SafeAdd(parameter.Key, parameter.Value);
                }

                return new KeyValuePair<string, IDictionary<string, object>>(string.Format(" And {0}={1}{0}", Field.Name, ParamChar), parameters);
                //  return new KeyValuePair<string, IDictionary<string, object>>(string.Format(" And {0} like '%'{2}{1}{0}{2}'%' ", Field.Name, ParamChar, ParamChar == "@" ? "+" : "||"), parameters);
            }

            return base.GetFilterCondition(filterValues);
        }
Example #19
0
        public string Save(string argument)
        {
            AjaxResult ajaxResult = new AjaxResult();

            string errorMsg = string.Empty;
            DoResult doResult = DoResult.Failed;
            string actionMessage = string.Empty;
            string parentID = string.Empty;
            try
            {
                Organization org = JsonConvert.DeserializeObject<Organization>(argument);
                string actionType = Request.Form["ActionType"];
                if (actionType.Equals("Add"))
                //if (PageContext.Action == ActionType.Add)
                {
                    IDictionary<string, object> parameter = new Dictionary<string, object>();
                    parameter.SafeAdd("Name", org.Name);
                    parameter.SafeAdd("Code", org.Code);
                    IList<Organization> listOrganization =repository.FindAll<Organization>(parameter);
                    if (listOrganization.Count == 0)
                    {
                        org.ID = string.IsNullOrWhiteSpace(CurrentId) ? IdGenerator.NewComb().ToString() : CurrentId;
                        org.ParentID = ParentID;
                        parentID = ParentID;
                        org.Creator = User.ID;
                        //org.Modifier = org.Creator;
                        //org.ModifyTime = org.CreateTime;
                    }
                    else
                    {
                        doResult = DoResult.Failed;
                        //获取提示信息
                        actionMessage = "部门名称已存在";

                        //记录操作日志
                        log.Error(string.Format("新增部门:{0}", actionMessage));
                        ajaxResult.Result = doResult;
                        ajaxResult.PromptMsg = actionMessage;
                        return JsonConvert.SerializeObject(ajaxResult);
                    }
                }
                else if (actionType.Equals("Update"))
                //else if (PageContext.Action == ActionType.Update)
                {
                    Organization orgDetail =repository.GetDomain<Organization>(CurrentId);
                    org.ParentID = orgDetail.ParentID;
                    parentID = org.ParentID;
                    org.ID = orgDetail.ID;
                }

                string areaCode = Configure.Get("AreaCode", "GDProvince");
                if (parentID == areaCode)
                {
                    org.OwnerOrg = string.Format("{0}/{1}/{2}", areaCode, org.Area, org.Code);
                }
                else if (parentID == "-1")
                {
                    org.OwnerOrg = areaCode;
                }
                else
                {
                    Organization parentOrg =repository.GetDomain<Organization>(parentID);
                    org.OwnerOrg = string.Format("{0}/{1}", parentOrg.OwnerOrg, org.Code);
                }

                repository.SaveOrUpdate(org);

                doResult = DoResult.Success;
                //获取提示信息
                actionMessage = RemarkAttribute.GetEnumRemark(doResult);

                //记录操作日志
                AddActionLog(org, doResult, actionMessage);

                ajaxResult.Result = doResult;
                ajaxResult.RetValue = org.ID;
                ajaxResult.PromptMsg = actionMessage;

            }
            catch (Exception ex)
            {
                actionMessage = RemarkAttribute.GetEnumRemark(doResult);
                log.Error(actionMessage, ex);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
Example #20
0
        public static GridFilter GetFilter(this DataSourceRequest command)
        {
            if (command.PageSize == 0)
            {
                command.PageSize = Configure.Get<int>("PageSize", 15);
            }

            IDictionary<string, object> parameters = new Dictionary<string, object>();
            string sortcommand = null;
            if (command.Sorts != null && command.Sorts.Count > 0)
            {
                string sortDirection = ListSortDirection.Ascending == command.Sorts[0].SortDirection ? "asc" : "desc";
                sortcommand = string.Format("order by {0} {1}", command.Sorts[0].Member, sortDirection);
            }

            if (command.Filters != null)
            {
                foreach (IFilterDescriptor filterDescriptor in command.Filters)
                {
                    parameters.SafeAdd(ApplyFilter(filterDescriptor));
                }
            }

            return new GridFilter()
            {

                PageInfo = new PageInfo() { PageIndex = command.Page, PageSize = command.PageSize },
                Parameters = parameters,
                SortCommand = sortcommand
            };
        }
Example #21
0
        /// <summary>
        /// 返回查询条件
        /// </summary>
        /// <param name="filterValues"></param>
        public override KeyValuePair<string, IDictionary<string, object>> GetFilterCondition(IDictionary<string, object> filterValues)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();

            if (HasValue(filterValues))
            {
                KeyValuePair<string, object> parameter = NewCustomParameter(Field.Name, filterValues);
                parameters.SafeAdd(parameter.Key, parameter.Value);
            }

            return new KeyValuePair<string, IDictionary<string, object>>(string.Format(" And {0}={1}{0} ", Field.Name, ParamChar), parameters);
        }
Example #22
0
        /*qlj 2013.1.8改  将表单独立于流程之外*/
        public ActionResult Index()
        {
            //IWorkflowEngine engine = new WorkflowEngine();
            try
            {
                string processDefID = Request.QueryString["processDefID"];
                string entry = Request.QueryString["Entry"];
                string eFormID = Request.QueryString["eFormID"];
                ManualActivity manualActivity = null;
                eForm formInfo = null;
                if (string.IsNullOrEmpty(processDefID) && !string.IsNullOrEmpty(eFormID))
                {
                    formInfo = repository.GetDomain<eForm>(eFormID);
                }
                else
                {
                    if (!string.IsNullOrEmpty(processDefID) && entry.EqualIgnoreCase("StartProcess"))
                    {
                        Activity startActivity = workflowEngine.Persistence.GetStartActivity(processDefID);
                        manualActivity = workflowEngine.Persistence.GetOutActivities(processDefID, startActivity.ID)[0] as ManualActivity;
                    }
                    else
                    {
                        string workItemID = Request.QueryString["workItemID"];
                        WorkItem workItem = repository.GetDomain<WorkItem>(workItemID);
                        ActivityInst activityInst = workflowEngine.Persistence.GetActivityInst(workItem.ActivityInstID);
                        manualActivity = workflowEngine.Persistence.GetActivity(workItem.ProcessID, activityInst.ActivityDefID) as ManualActivity;
                    }
                }
                if (manualActivity != null && manualActivity.eForm != null)
                {
                    formInfo = repository.GetDomain<eForm>(manualActivity.eForm);
                }
                   if (formInfo != null&&!string.IsNullOrEmpty(formInfo.Content))
                   {
                     Form  form=JsonConvert.DeserializeObject<Form>(formInfo.Content);
                       string processInstID = Request.QueryString["processInstID"];
                       ProcessForm processForm = null;
                       IDictionary<string, object> values = new Dictionary<string, object>();
                       if (!string.IsNullOrEmpty(processInstID))
                       {
                           IDictionary<string, object> parameters = new Dictionary<string, object>();
                           parameters.SafeAdd("processInstID", processInstID);
                           processForm = repository.FindOne<ProcessForm>(parameters);
                           if (processForm != null)
                           {
                               parameters.Clear();
                               parameters.Add("ID", processForm.BizID);
                               DataTable dt = repository.ExecuteDataTable<ProcessForm>(string.Format("select * from {0}", processForm.BizTable), parameters);
                               if (dt != null && dt.Rows.Count > 0)
                               {

                                   foreach (DataRow row in dt.Rows)
                                   {
                                       foreach (var field in form.Fields)//manualActivity.Form.Fields)
                                       {

                                           if (field.ControlType == ControlType.SysVariable || field.ControlType == ControlType.HiddenInput)
                                           {
                                               switch (field.DefaultValue.ToInt())
                                               {
                                                   case (short)SystemControlType.OrgID:
                                                       Organization org = repository.Query<Organization>().FirstOrDefault(o => o.Code == workContext.User.OrgID);
                                                       values.SafeAdd(field.Name, org.Name);
                                                       if (!string.IsNullOrEmpty(field.ExtendData))
                                                       {
                                                           values.SafeAdd(field.ExtendData, workContext.User.OrgID);
                                                       }
                                                       break;
                                                   case (short)SystemControlType.UserID:
                                                       values.SafeAdd(field.Name, workContext.User.Name);
                                                       if (!string.IsNullOrEmpty(field.ExtendData))
                                                       {
                                                           values.SafeAdd(field.ExtendData, workContext.User.ID);
                                                       }
                                                       break;
                                                   case (short)SystemControlType.CurrentDate:
                                                       values.SafeAdd(field.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                                                       break;
                                               }

                                           }
                                           else if (dt.Columns.Contains(field.Name))
                                           {
                                               if (!string.IsNullOrEmpty(row[field.Name].ToSafeString()))
                                               {
                                                   values.SafeAdd(field.Name, row[field.Name]);
                                               }
                                               else
                                               {
                                                   if (!string.IsNullOrEmpty(field.DefaultValue))
                                                       values.SafeAdd(field.Name, field.DefaultValue);
                                               }
                                           }

                                       }
                                   }
                               }
                           }
                       }
                       if (processForm == null)
                       {
                           foreach (var field in form.Fields)//manualActivity.Form.Fields)
                           {
                               if (field.ControlType == ControlType.SysVariable||field.ControlType==ControlType.HiddenInput)
                               {
                                   switch (field.DefaultValue.ToInt())
                                   {
                                       case (short)SystemControlType.OrgID:
                                           Organization org = repository.Query<Organization>().FirstOrDefault(o => o.Code == workContext.User.OrgID);
                                           values.SafeAdd(field.Name, org.Name);
                                           if (!string.IsNullOrEmpty(field.ExtendData))
                                           {
                                               values.SafeAdd(field.ExtendData, workContext.User.OrgID);
                                           }
                                           break;
                                       case (short)SystemControlType.UserID:
                                           values.SafeAdd(field.Name, workContext.User.Name);
                                           if (!string.IsNullOrEmpty(field.ExtendData))
                                           {
                                               values.SafeAdd(field.ExtendData, workContext.User.ID);
                                           }
                                           break;
                                       case (short)SystemControlType.CurrentDate:
                                           values.SafeAdd(field.Name, DateTime.Now.ToSafeDateTime());
                                           break;
                                   }
                               }
                               else if (field.ControlType != ControlType.SysVariable && field.ControlType != ControlType.HiddenInput)
                               {
                                   if (!string.IsNullOrEmpty(field.DefaultValue))
                                       values.SafeAdd(field.Name, field.DefaultValue);
                               }
                               else
                               {
                                   // values.SafeAdd(field.Name, workContext.);
                               }
                           }
                       }
                       ViewData["Values"] = values;
                       ViewData["Form"] = form;//manualActivity.Form;
                   }
                //}
            }
            catch (Exception ex)
            {
                log.Error("初始化表单失败" + ex);
            }
            return View();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string workItemID = Request.QueryString["workItemID"];
                WorkItem workItem = engine.Persistence.Repository.GetDomain<WorkItem>(workItemID);
                ActivityInst activityInst = engine.Persistence.GetActivityInst(workItem.ActivityInstID);
                ManualActivity manualActivity = engine.Persistence.GetActivity(workItem.ProcessID, activityInst.ActivityDefID) as ManualActivity;

                AgileEAP.EForm.FormView formView = new AgileEAP.EForm.FormView();
                formView.Form = manualActivity.Form;
                hidDataSource.Value = manualActivity.Form.DataSource;

                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.SafeAdd("processInstID", Request.QueryString["processInstID"]);
                ProcessForm processForm = engine.Persistence.Repository.FindOne<ProcessForm>(parameters);
                if (processForm != null)
                {
                    parameters.Clear();
                    parameters.Add("ID", processForm.BizID);
                    DataTable dt = engine.Persistence.Repository.ExecuteDataTable<ProcessForm>(string.Format("select * from {0}", processForm.BizTable), parameters);

                    if (dt != null && dt.Rows.Count > 0)
                    {
                        IDictionary<string, object> values = new Dictionary<string, object>();

                        foreach (DataRow row in dt.Rows)
                        {
                            foreach (DataColumn column in dt.Columns)
                            {
                                values.SafeAdd(column.ColumnName, row[column.ColumnName]);
                            }
                        }

                        formView.Values = values;
                    }
                }

                eForm.Controls.Add(formView);
            }
        }
Example #24
0
        public string IsExist(string argument)
        {
            AjaxResult ajaxResult = new AjaxResult();

            try
            {
                string dataID = Request.Form["DataID"].Trim();
                IDictionary<string, object> para = new Dictionary<string, object>();
                para.SafeAdd("ID", dataID);
                Operator operatorInfo =repository.FindOne<Operator>(para);
                if (operatorInfo != null)
                {
                    ajaxResult.PromptMsg = "该用户已经存在!";
                }

                ajaxResult.RetValue = string.Empty;
                ajaxResult.Result = DoResult.Success;


            }
            catch (Exception ex)
            {
                ajaxResult.Result = DoResult.Failed;
                ajaxResult.PromptMsg = "获取信息出错,请联系管理员!";
                log.Error(ex);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
Example #25
0
        private void ConvertFile(string fileName, IStorageRegistry registry, StorageFormats format, ExchangeBoard board)
        {
            if (!_isStarted)
                return;

            var fileNameKey = format + "_" + fileName;

            if (_convertedFiles.Contains(fileNameKey))
                return;

            _logManager.Application.AddInfoLog("Конвертация файла {0}.", fileName);

            const int maxBufCount = 1000;

            var data = new Dictionary<Security, Tuple<List<QuoteChangeMessage>, List<ExecutionMessage>, List<Level1ChangeMessage>, List<ExecutionMessage>>>();

            using (var qr = QshReader.Open(fileName))
            {
                var currentDate = qr.CurrentDateTime;

                for (var i = 0; i < qr.StreamCount; i++)
                {
                    var stream = (ISecurityStream)qr[i];
                    var security = GetSecurity(stream.Security, board);
                    var priceStep = security.PriceStep ?? 1;
                    var securityId = security.ToSecurityId();
                    var lastTransactionId = 0L;

                    var secData = data.SafeAdd(security, key => Tuple.Create(new List<QuoteChangeMessage>(), new List<ExecutionMessage>(), new List<Level1ChangeMessage>(), new List<ExecutionMessage>()));

                    switch (stream.Type)
                    {
                        case StreamType.Stock:
                        {
                            ((IStockStream)stream).Handler += (key, quotes, spread) =>
                            {
                                var quotes2 = quotes.Select(q =>
                                {
                                    Sides side;

                                    switch (q.Type)
                                    {
                                        case QuoteType.Unknown:
                                        case QuoteType.Free:
                                        case QuoteType.Spread:
                                            throw new ArgumentException(q.Type.ToString());
                                        case QuoteType.Ask:
                                        case QuoteType.BestAsk:
                                            side = Sides.Sell;
                                            break;
                                        case QuoteType.Bid:
                                        case QuoteType.BestBid:
                                            side = Sides.Buy;
                                            break;
                                        default:
                                            throw new ArgumentOutOfRangeException();
                                    }

                                    return new QuoteChange(side, priceStep * q.Price, q.Volume);
                                }).ToArray();

                                var md = new QuoteChangeMessage
                                {
                                    SecurityId = securityId,
                                    ServerTime = currentDate.ApplyTimeZone(TimeHelper.Moscow),
                                    Bids = quotes2.Where(q => q.Side == Sides.Buy),
                                    Asks = quotes2.Where(q => q.Side == Sides.Sell),
                                };

                                //if (md.Verify())
                                //{
                                secData.Item1.Add(md);

                                if (secData.Item1.Count > maxBufCount)
                                {
                                    registry.GetQuoteMessageStorage(security).Save(secData.Item1);
                                    secData.Item1.Clear();
                                }
                                //}
                                //else
                                //	_logManager.Application.AddErrorLog("Стакан для {0} в момент {1} не прошел валидацию. Лучший бид {2}, Лучший офер {3}.", security, qr.CurrentDateTime, md.BestBid, md.BestAsk);
                            };
                            break;
                        }
                        case StreamType.Deals:
                        {
                            ((IDealsStream)stream).Handler += deal =>
                            {
                                secData.Item2.Add(new ExecutionMessage
                                {
                                    ExecutionType = ExecutionTypes.Tick,
                                    SecurityId = securityId,
                                    OpenInterest = deal.OI == 0 ? (long?)null : deal.OI,
                                    ServerTime = deal.DateTime.ApplyTimeZone(TimeHelper.Moscow),
                                    Volume = deal.Volume,
                                    TradeId = deal.Id == 0 ? (long?)null : deal.Id,
                                    TradePrice = (decimal)deal.Price,
                                    OriginSide =
                                        deal.Type == DealType.Buy
                                            ? Sides.Buy
                                            : (deal.Type == DealType.Sell ? Sides.Sell : (Sides?)null)
                                });

                                if (secData.Item2.Count > maxBufCount)
                                {
                                    registry.GetTickMessageStorage(security).Save(secData.Item2);
                                    secData.Item2.Clear();
                                }
                            };
                            break;
                        }
                        case StreamType.OrdLog:
                        {
                            ((IOrdLogStream)stream).Handler += (key, ol) =>
                            {
                                var currTransactionId = ol.DateTime.Ticks;

                                if (lastTransactionId < currTransactionId)
                                    lastTransactionId = currTransactionId;
                                else if (lastTransactionId >= currTransactionId)
                                    lastTransactionId++;

                                var msg = new ExecutionMessage
                                {
                                    ExecutionType = ExecutionTypes.OrderLog,
                                    SecurityId = securityId,
                                    OpenInterest = ol.OI == 0 ? (long?)null : ol.OI,
                                    OrderId = ol.OrderId,
                                    Price = priceStep * ol.Price,
                                    ServerTime = ol.DateTime.ApplyTimeZone(TimeHelper.Moscow),
                                    Volume = ol.Amount,
                                    Balance = ol.AmountRest,
                                    TradeId = ol.DealId == 0 ? (long?)null : ol.DealId,
                                    TradePrice = ol.DealPrice == 0 ? (decimal?)null : priceStep * ol.DealPrice,
                                    TransactionId = lastTransactionId
                                };

                                var status = 0;

                                if (ol.Flags.Contains(OrdLogFlags.Add))
                                {
                                    msg.OrderState = OrderStates.Active;
                                }
                                else if (ol.Flags.Contains(OrdLogFlags.Fill))
                                {
                                    msg.OrderState = OrderStates.Done;
                                }
                                else if (ol.Flags.Contains(OrdLogFlags.Canceled))
                                {
                                    msg.OrderState = OrderStates.Done;
                                    status |= 0x200000;
                                }
                                else if (ol.Flags.Contains(OrdLogFlags.CanceledGroup))
                                {
                                    msg.OrderState = OrderStates.Done;
                                    status |= 0x400000;
                                }
                                else if (ol.Flags.Contains(OrdLogFlags.Moved))
                                {
                                    status |= 0x100000;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.Buy))
                                {
                                    msg.Side = Sides.Buy;
                                }
                                else if (ol.Flags.Contains(OrdLogFlags.Sell))
                                {
                                    msg.Side = Sides.Sell;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.FillOrKill))
                                {
                                    msg.TimeInForce = TimeInForce.MatchOrCancel;
                                    status |= 0x00080000;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.Quote))
                                {
                                    msg.TimeInForce = TimeInForce.PutInQueue;
                                    status |= 0x01;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.Counter))
                                {
                                    status |= 0x02;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.CrossTrade))
                                {
                                    status |= 0x20000000;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.NonSystem))
                                {
                                    msg.IsSystem = false;
                                    status |= 0x04;
                                }

                                if (ol.Flags.Contains(OrdLogFlags.EndOfTransaction))
                                {
                                    status |= 0x1000;
                                }

                                msg.OrderStatus = (OrderStatus)status;

                                secData.Item4.Add(msg);

                                if (secData.Item4.Count > maxBufCount)
                                {
                                    registry.GetOrderLogMessageStorage(security).Save(secData.Item4);
                                    secData.Item4.Clear();
                                }
                            };
                            break;
                        }
                        case StreamType.AuxInfo:
                        {
                            ((IAuxInfoStream)stream).Handler += (key, info) =>
                            {
                                secData.Item3.Add(new Level1ChangeMessage
                                {
                                    SecurityId = securityId,
                                    ServerTime = info.DateTime.ApplyTimeZone(TimeHelper.Moscow),
                                }
                                .TryAdd(Level1Fields.LastTradePrice, priceStep * info.Price)
                                .TryAdd(Level1Fields.BidsVolume, (decimal)info.BidTotal)
                                .TryAdd(Level1Fields.AsksVolume, (decimal)info.AskTotal)
                                .TryAdd(Level1Fields.HighPrice, priceStep * info.HiLimit)
                                .TryAdd(Level1Fields.LowPrice, priceStep * info.LoLimit)
                                .TryAdd(Level1Fields.OpenInterest, (decimal)info.OI));

                                if (secData.Item3.Count > maxBufCount)
                                {
                                    registry.GetLevel1MessageStorage(security).Save(secData.Item3);
                                    secData.Item3.Clear();
                                }
                            };
                            break;
                        }
                        case StreamType.Orders:
                        case StreamType.Trades:
                        case StreamType.Messages:
                        case StreamType.None:
                        {
                            continue;
                        }
                        default:
                            throw new ArgumentOutOfRangeException("Неподдерживаемый тип потока {0}.".Put(stream.Type));
                    }
                }

                while (qr.CurrentDateTime != DateTime.MaxValue && _isStarted)
                    qr.Read(true);
            }

            if (!_isStarted)
                return;

            foreach (var pair in data)
            {
                if (pair.Value.Item1.Any())
                {
                    registry.GetQuoteMessageStorage(pair.Key, format: format).Save(pair.Value.Item1);
                }

                if (pair.Value.Item2.Any())
                {
                    registry.GetTickMessageStorage(pair.Key, format: format).Save(pair.Value.Item2);
                }

                if (pair.Value.Item3.Any())
                {
                    registry.GetLevel1MessageStorage(pair.Key, format: format).Save(pair.Value.Item3);
                }

                if (pair.Value.Item4.Any())
                {
                    registry.GetOrderLogMessageStorage(pair.Key, format: format).Save(pair.Value.Item4);
                }
            }

            File.AppendAllLines(_convertedFilesFile, new[] { fileNameKey });
            _convertedFiles.Add(fileNameKey);
        }
        /// <summary>
        /// Vrátí slova, která mají stejný vzor
        /// </summary>
        /// <param name="testWords"></param>
        /// <param name="templates"></param>
        /// <returns></returns>
        private Dictionary<string, List<string>> GetWordsWithSamePatterns(Dictionary<string, string> testWordsHashes, Dictionary<string, string> templatesHashes)
        {
            Dictionary<string, List<string>> samePattern = new Dictionary<string, List<string>>();

            foreach (var testWordHash in testWordsHashes)
            {
                foreach (var templateHash in templatesHashes)
                {
                    if (testWordHash.Value == templateHash.Value)
                    {
                        samePattern.SafeAdd(testWordHash.Key, templateHash.Key);
                    }
                }
            }

            return samePattern;
        }
Example #27
0
		/// <summary>
		/// To generate the report.
		/// </summary>
		public override void Generate()
		{
			var hasTemplate = Template.IsEmpty();

			using (var worker = hasTemplate ? new ExcelWorker() : new ExcelWorker(Template))
			{
				foreach (var strategy in Strategies)
				{
					if (Template.IsEmpty())
					{
						worker.RenameSheet(strategy.Name);
					}
					else
					{
						if (worker.ContainsSheet(strategy.Name))
							worker.AddSheet(strategy.Name);
					}

					worker
						.SetCell(0, 0, LocalizedStrings.Str1331)

						.SetCell(0, 1, LocalizedStrings.Security + ":")
						.SetCell(1, 1, strategy.Security != null ? strategy.Security.Id : string.Empty)

						.SetCell(0, 2, LocalizedStrings.Portfolio + ":")
						.SetCell(1, 2, strategy.Portfolio != null ? strategy.Portfolio.Name : string.Empty)

						.SetCell(0, 3, LocalizedStrings.Str1334)
						.SetCell(1, 3, Format(strategy.TotalWorkingTime))

						.SetCell(0, 4, LocalizedStrings.Str1335)
						//.SetCell(1, 4, FormatTime(base.Strategy.TotalCPUTime))

						.SetCell(0, 5, LocalizedStrings.Str862 + ":")
						.SetCell(1, 5, strategy.Position)

						.SetCell(0, 6, LocalizedStrings.PnL + ":")
						.SetCell(1, 6, strategy.PnL)

						.SetCell(0, 7, LocalizedStrings.Str159 + ":")
						.SetCell(1, 7, strategy.Commission)

						.SetCell(0, 8, LocalizedStrings.Str163 + ":")
						.SetCell(1, 8, strategy.Slippage)

						.SetCell(0, 9, LocalizedStrings.Str161 + ":")
						.SetCell(1, 9, Format(strategy.Latency));

					var rowIndex = 11;

					foreach (var parameter in strategy.StatisticManager.Parameters.SyncGet(c => c.ToArray()))
					{
						var value = parameter.Value;

						if (value is TimeSpan)
							value = Format((TimeSpan)value);
						else if (value is decimal)
							value = MathHelper.Round((decimal)value, Decimals);

						worker
							.SetCell(0, rowIndex, parameter.Name)
							.SetCell(1, rowIndex, value);

						rowIndex++;
					}

					rowIndex += 2;
					worker.SetCell(0, rowIndex, LocalizedStrings.Str1340);
					rowIndex++;

					foreach (var strategyParam in strategy.Parameters.SyncGet(c => c.ToArray()))
					{
						var value = strategyParam.Value;

						if (value is TimeSpan)
							value = Format((TimeSpan)value);
						else if (value is decimal)
							value = MathHelper.Round((decimal)value, Decimals);

						worker
							.SetCell(0, rowIndex, strategyParam.Name)
							.SetCell(1, rowIndex, value);

						rowIndex++;
					}

					//rowIndex += 2;
					//worker.SetCell(0, rowIndex, "Комиссия по типам:");
					//rowIndex++;

					//foreach (var group in Strategy.CommissionManager.Rules.SyncGet(c => c.ToArray()).GroupBy(c => c.GetType().GetDisplayName()))
					//{
					//	var commission = group.Sum(r => r.Commission);

					//	if (commission == 0)
					//		continue;

					//	worker
					//		.SetCell(0, rowIndex, group.Key)
					//		.SetCell(1, rowIndex, commission);

					//	rowIndex++;
					//}

					var columnShift = 3;

					worker
						.SetCell(columnShift + 0, 0, LocalizedStrings.Str985)

						.SetCell(columnShift + 0, 1, LocalizedStrings.Str1192).SetStyle(columnShift + 0, typeof(long))
						.SetCell(columnShift + 1, 1, LocalizedStrings.Transaction).SetStyle(columnShift + 1, typeof(long))
						.SetCell(columnShift + 2, 1, LocalizedStrings.Time).SetStyle(columnShift + 2, "HH:mm:ss.fff")
						.SetCell(columnShift + 3, 1, LocalizedStrings.Price).SetStyle(columnShift + 3, typeof(decimal))
						.SetCell(columnShift + 4, 1, LocalizedStrings.Str1341).SetStyle(columnShift + 4, typeof(decimal))
						.SetCell(columnShift + 5, 1, LocalizedStrings.Volume).SetStyle(columnShift + 5, typeof(decimal))
						.SetCell(columnShift + 6, 1, LocalizedStrings.Str128)
						.SetCell(columnShift + 7, 1, LocalizedStrings.Str1190).SetStyle(columnShift + 7, typeof(long))
						.SetCell(columnShift + 8, 1, LocalizedStrings.Str163).SetStyle(columnShift + 8, typeof(decimal))
						.SetCell(columnShift + 9, 1, LocalizedStrings.Str135)
						.SetCell(columnShift + 10, 1, LocalizedStrings.Str1342).SetStyle(columnShift + 11, typeof(decimal))
						.SetCell(columnShift + 11, 1, LocalizedStrings.Str1343).SetStyle(columnShift + 12, typeof(decimal))
						.SetCell(columnShift + 12, 1, LocalizedStrings.Str1344).SetStyle(columnShift + 13, typeof(decimal))
						.SetCell(columnShift + 13, 1, LocalizedStrings.Str1345).SetStyle(columnShift + 14, typeof(decimal))
						.SetCell(columnShift + 14, 1, LocalizedStrings.Str862).SetStyle(columnShift + 15, typeof(decimal));

					worker
						.SetConditionalFormatting(columnShift + 10, ComparisonOperator.Less, "0", null, Colors.Red)
						.SetConditionalFormatting(columnShift + 11, ComparisonOperator.Less, "0", null, Colors.Red)
						.SetConditionalFormatting(columnShift + 12, ComparisonOperator.Less, "0", null, Colors.Red)
						.SetConditionalFormatting(columnShift + 13, ComparisonOperator.Less, "0", null, Colors.Red);

					var totalPnL = 0m;
					var position = 0m;

					var queues = new Dictionary<Security, PnLQueue>();

					rowIndex = 2;
					foreach (var trade in strategy.MyTrades.ToArray())
					{
						var info = strategy.PnLManager.ProcessMessage(trade.ToMessage());

						totalPnL += info.PnL;
						position += trade.GetPosition();

						var queue = queues.SafeAdd(trade.Trade.Security, key => new PnLQueue(key.ToSecurityId()));

						var localInfo = queue.Process(trade.ToMessage());

						worker
							.SetCell(columnShift + 0, rowIndex, trade.Trade.Id)
							.SetCell(columnShift + 1, rowIndex, trade.Order.TransactionId)
							.SetCell(columnShift + 2, rowIndex, Format(trade.Trade.Time))
							.SetCell(columnShift + 3, rowIndex, trade.Trade.Price)
							.SetCell(columnShift + 4, rowIndex, trade.Order.Price)
							.SetCell(columnShift + 5, rowIndex, trade.Trade.Volume)
							.SetCell(columnShift + 6, rowIndex, Format(trade.Order.Direction))
							.SetCell(columnShift + 7, rowIndex, trade.Order.Id)
							.SetCell(columnShift + 8, rowIndex, trade.Slippage)
							.SetCell(columnShift + 9, rowIndex, trade.Order.Comment)
							.SetCell(columnShift + 10, rowIndex, MathHelper.Round(info.PnL, Decimals))
							.SetCell(columnShift + 11, rowIndex, MathHelper.Round(localInfo.PnL, Decimals))
							.SetCell(columnShift + 12, rowIndex, MathHelper.Round(totalPnL, Decimals))
							.SetCell(columnShift + 13, rowIndex, MathHelper.Round(queue.RealizedPnL, Decimals))
							.SetCell(columnShift + 14, rowIndex, position);

						rowIndex++;
					}

					if (IncludeOrders)
					{
						columnShift += 17;

						worker
							.SetCell(columnShift + 0, 0, LocalizedStrings.Orders)

							.SetCell(columnShift + 0, 1, LocalizedStrings.Str1190).SetStyle(columnShift + 0, typeof(long))
							.SetCell(columnShift + 1, 1, LocalizedStrings.Transaction).SetStyle(columnShift + 1, typeof(long))
							.SetCell(columnShift + 2, 1, LocalizedStrings.Str128)
							.SetCell(columnShift + 3, 1, LocalizedStrings.Str1346).SetStyle(columnShift + 3, "HH:mm:ss.fff")
							.SetCell(columnShift + 4, 1, LocalizedStrings.Str1347).SetStyle(columnShift + 4, "HH:mm:ss.fff")
							.SetCell(columnShift + 5, 1, LocalizedStrings.Str1348)
							.SetCell(columnShift + 6, 1, LocalizedStrings.Price).SetStyle(columnShift + 6, typeof(decimal))
							.SetCell(columnShift + 7, 1, LocalizedStrings.Str1323).SetStyle(columnShift + 7, typeof(decimal))
							.SetCell(columnShift + 8, 1, LocalizedStrings.Str1324)
							.SetCell(columnShift + 9, 1, LocalizedStrings.State)
							.SetCell(columnShift + 10, 1, LocalizedStrings.Str1325).SetStyle(columnShift + 10, typeof(decimal))
							.SetCell(columnShift + 11, 1, LocalizedStrings.Volume).SetStyle(columnShift + 11, typeof(decimal))
							.SetCell(columnShift + 12, 1, LocalizedStrings.Type)
							.SetCell(columnShift + 13, 1, LocalizedStrings.Str1326)
							.SetCell(columnShift + 14, 1, LocalizedStrings.Str1327)
							.SetCell(columnShift + 15, 1, LocalizedStrings.Str135);

						worker
							.SetConditionalFormatting(columnShift + 9, ComparisonOperator.Equal, "\"{0}\"".Put(LocalizedStrings.Str1329), null, Colors.Green)
							.SetConditionalFormatting(columnShift + 9, ComparisonOperator.Equal, "\"{0}\"".Put(LocalizedStrings.Str238), null, Colors.Red);

						rowIndex = 2;
						foreach (var order in strategy.Orders.ToArray())
						{
							worker
								.SetCell(columnShift + 0, rowIndex, order.Id)
								.SetCell(columnShift + 1, rowIndex, order.TransactionId)
								.SetCell(columnShift + 2, rowIndex, Format(order.Direction))
								.SetCell(columnShift + 3, rowIndex, Format(order.Time))
								.SetCell(columnShift + 4, rowIndex, Format(order.LastChangeTime))
								.SetCell(columnShift + 5, rowIndex, Format(order.LastChangeTime - order.Time))
								.SetCell(columnShift + 6, rowIndex, order.Price)
								.SetCell(columnShift + 7, rowIndex, MathHelper.Round(order.GetAveragePrice(strategy.Connector), Decimals))
								.SetCell(columnShift + 8, rowIndex, Format(order.State))
								.SetCell(columnShift + 9, rowIndex, order.IsMatched() ? LocalizedStrings.Str1328 : (order.IsCanceled() ? LocalizedStrings.Str1329 : LocalizedStrings.Str238))
								.SetCell(columnShift + 10, rowIndex, order.Balance)
								.SetCell(columnShift + 11, rowIndex, order.Volume)
								.SetCell(columnShift + 12, rowIndex, Format(order.Type))
								.SetCell(columnShift + 13, rowIndex, Format(order.LatencyRegistration))
								.SetCell(columnShift + 14, rowIndex, Format(order.LatencyCancellation))
								.SetCell(columnShift + 15, rowIndex, order.Comment);

							rowIndex++;
						}

						var stopOrders = strategy.StopOrders.ToArray();

						if (stopOrders.Length > 0)
						{
							rowIndex += 2;

							worker
								.SetCell(columnShift + 0, rowIndex - 1, LocalizedStrings.Str1351)

								.SetCell(columnShift + 0, rowIndex, LocalizedStrings.Str1190).SetStyle(columnShift + 0, typeof(long))
								.SetCell(columnShift + 1, rowIndex, LocalizedStrings.Transaction).SetStyle(columnShift + 1, typeof(long))
								.SetCell(columnShift + 2, rowIndex, LocalizedStrings.Str128)
								.SetCell(columnShift + 3, rowIndex, LocalizedStrings.Time).SetStyle(columnShift + 3, "HH:mm:ss.fff")
								.SetCell(columnShift + 4, rowIndex, LocalizedStrings.Price).SetStyle(columnShift + 4, typeof(decimal))
								.SetCell(columnShift + 5, rowIndex, LocalizedStrings.Str1324)
								.SetCell(columnShift + 6, rowIndex, LocalizedStrings.State)
								.SetCell(columnShift + 7, rowIndex, LocalizedStrings.Volume).SetStyle(columnShift + 7, typeof(decimal))
								.SetCell(columnShift + 8, rowIndex, LocalizedStrings.Str1326)
								.SetCell(columnShift + 9, rowIndex, LocalizedStrings.Str1327)
								.SetCell(columnShift + 10, rowIndex, LocalizedStrings.Str1352).SetStyle(columnShift + 9, typeof(long));

							var stopParams = stopOrders[0].Condition.Parameters.Keys.ToArray();

							for (var i = 0; i < stopParams.Length; i++)
								worker.SetCell(columnShift + 11 + i, rowIndex, stopParams[i]);

							foreach (var order in stopOrders)
							{
								worker
									.SetCell(columnShift + 0, rowIndex, order.Id)
									.SetCell(columnShift + 1, rowIndex, order.TransactionId)
									.SetCell(columnShift + 2, rowIndex, Format(order.Direction))
									.SetCell(columnShift + 3, rowIndex, Format(order.Time))
									.SetCell(columnShift + 4, rowIndex, order.Price)
									.SetCell(columnShift + 5, rowIndex, Format(order.State))
									.SetCell(columnShift + 6, rowIndex, order.IsMatched() ? LocalizedStrings.Str1328 : (order.IsCanceled() ? LocalizedStrings.Str1329 : string.Empty))
									.SetCell(columnShift + 7, rowIndex, order.Volume)
									.SetCell(columnShift + 8, rowIndex, Format(order.LatencyRegistration))
									.SetCell(columnShift + 9, rowIndex, Format(order.LatencyCancellation))
									.SetCell(columnShift + 10, rowIndex, order.DerivedOrder != null ? (object)order.DerivedOrder.Id : string.Empty);

								for (var i = 0; i < stopParams.Length; i++)
									worker.SetCell(columnShift + 11 + i, rowIndex, order.Condition.Parameters[stopParams[i]] ?? string.Empty);

								rowIndex++;
							}
						}
					}
				}

				worker.Save(FileName, true);
			}
		}
Example #28
0
        /// <summary>
        /// 获取组织下的所有员工
        /// </summary>
        /// <param name="orgID">组织ID</param>
        /// <returns></returns>
        public IList<Employee> GetEmployees(string orgID)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.SafeAdd("ID", new Condition(string.Format("ID in (select b.EmployeeID from OM_EmployeeOrg b where b.OrgID='{0}')", orgID)));

            return repository.FindAll<Employee>(parameters);
        }
        public string Save(string argument)
        {
            AjaxResult ajaxResult = new AjaxResult();
            string errorMsg = string.Empty;
            DoResult actionResult = DoResult.Failed;
            string actionMessage = string.Empty;
            string processInstID = Request.QueryString["processInstID"];
            ProcessForm processForm;
            try
            {
                Dictionary<string, object> formValues = JsonConvert.DeserializeObject<Dictionary<string, object>>(argument);

                string table = Request.Form["DataSource"];
                StringBuilder sbFields = new StringBuilder();
                StringBuilder sbValues = new StringBuilder();
                string cmdText = string.Empty;
                StringBuilder sbUpdateValues = new StringBuilder();

                IDictionary<string, object> parameters = new Dictionary<string, object>();
                parameters.SafeAdd("ProcessInstID", processInstID);
                processForm = engine.Persistence.Repository.FindOne<ProcessForm>(parameters);
                if (processForm != null)
                {
                    foreach (var item in formValues)
                    {
                        if (sbUpdateValues.Length > 0)
                            sbUpdateValues.Append(",");
                        sbUpdateValues.AppendFormat("{0} = :{0}", item.Key);
                    }
                    cmdText = string.Format("update {0} set {1} where ID ='{2}'", table, sbUpdateValues.ToString(), processForm.BizID);
                }
                else
                {
                    string bizID = IdGenerator.NewComb().ToString();
                    formValues.SafeAdd("ID", bizID);
                    foreach (var item in formValues)
                    {
                        sbFields.Append(item.Key).Append(",");
                        sbValues.Append(":").Append(item.Key).Append(",");
                    }

                    processForm = new ProcessForm()
                    {
                        ID = IdGenerator.NewComb().ToString(),
                        BizID = bizID,
                        BizTable = table,
                        CreateTime = DateTime.Now,
                        Creator = User.ID,
                        ProcessInstID = processInstID,
                        KeyWord = sbValues.ToString()
                    };
                    cmdText = string.Format("insert into {0}({1}) values({2})", table, sbFields.ToString().TrimEnd(','), sbValues.ToString().TrimEnd(','));
                }

                string workItemID = Request.QueryString["workItemID"];
                UnitOfWork.ExecuteWithTrans<WorkItem>(() =>
                {
                    engine.Persistence.Repository.ExecuteSql<WorkItem>(cmdText, formValues);
                    engine.Persistence.Repository.SaveOrUpdate(processForm);
                    engine.CompleteWorkItem(workItemID, formValues);
                });

                actionResult = DoResult.Success;
                //获取提示信息
                actionMessage = string.Format("启动工作流实例{0}工作项{1}", processForm.ProcessInstID, workItemID);

                //记录操作日志
                AddActionLog(processForm, actionResult, actionMessage);

                ajaxResult.Result = actionResult;
                ajaxResult.RetValue = processForm.BizID;
                ajaxResult.PromptMsg = actionMessage;
            }
            catch (Exception ex)
            {
                actionMessage = RemarkAttribute.GetEnumRemark(actionResult);
                log.Error(actionMessage, ex);
            }

            return JsonConvert.SerializeObject(ajaxResult);
        }
        /// <summary>
        /// 获取某个活动实例的所有工作项
        /// </summary>
        /// <param name="activityInstID">活动实例ID</param>
        /// <returns></returns>
        public IList<WorkItem> GetWorkItems(string activityInstID)
        {
            IDictionary<string, object> parameters = new Dictionary<string, object>();
            parameters.SafeAdd("ActivityInstID", activityInstID);

            return repository.FindAll<WorkItem>(parameters);
        }