Ejemplo n.º 1
0
 /// <summary>
 /// 按照目录分页获取指定节点、本体的数据
 /// <remarks>
 /// 如果传入的目录为空则表示获取全部目录的数据
 /// </remarks>
 /// </summary>
 /// <param name="ontology"></param>
 /// <param name="selectElements"></param>
 /// <param name="filters">过滤器列表</param>
 /// <param name="pagingData"></param>
 /// <returns></returns>
 public DataTuple GetPlist(
     OntologyDescriptor ontology,
     OrderedElementSet selectElements,
     List <FilterData> filters,
     PagingInput pagingData)
 {
     return(this.GetPlistInfoItems(
                ontology, this.GetEntityDb(ontology),
                selectElements,
                filters, pagingData));
 }
Ejemplo n.º 2
0
 public DataTuple GetPlist(
     ArchiveState archive,
     OrderedElementSet selectElements,
     List <FilterData> filters,
     PagingInput pagingData)
 {
     return(this.GetPlistInfoItems(
                archive.Ontology, this.GetArchiveDb(archive.Ontology, archive),
                selectElements,
                filters, pagingData));
 }
Ejemplo n.º 3
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="columns"></param>
 /// <param name="rows"></param>
 public DataTuple(OrderedElementSet columns, object[][] rows)
 {
     if (columns == null || columns.Count == 0)
     {
         throw new ArgumentNullException("columns");
     }
     if (rows == null)
     {
         throw new ArgumentNullException("rows");
     }
     this.Columns = columns;
     this.Tuples = rows;
 }
Ejemplo n.º 4
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="columns"></param>
 /// <param name="rows"></param>
 public DataTuple(OrderedElementSet columns, object[][] rows)
 {
     if (columns == null || columns.Count == 0)
     {
         throw new ArgumentNullException("columns");
     }
     if (rows == null)
     {
         throw new ArgumentNullException("rows");
     }
     this.Columns = columns;
     this.Tuples  = rows;
 }
Ejemplo n.º 5
0
        /// <summary>
        /// 获取给定本体码和存储标识的本节点的数据
        /// <remarks>本节点通常是中心节点</remarks>
        /// </summary>
        /// <param name="ontology">本体</param>
        /// <param name="localEntityId"></param>
        /// <param name="selectElements"></param>
        /// <returns>数据记录,表现为字典形式,键是数据元素编码值是相应数据元素对应的数据项值</returns>
        public InfoItem[] Get(
            OntologyDescriptor ontology, string localEntityId, OrderedElementSet selectElements)
        {
            var topTwo = GetTopTwo(ontology, new InfoItem[] { InfoItem.Create(ontology.IdElement, localEntityId) }, selectElements);

            if (topTwo.BothHasValue || topTwo.BothNoValue)
            {
                return(new InfoItem[0]);
            }
            else
            {
                return(topTwo.SingleInfoTuple);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="archive"></param>
        /// <param name="localEntityId"></param>
        /// <param name="selectElements"></param>
        /// <returns></returns>
        public InfoItem[] Get(
            ArchiveState archive, string localEntityId, OrderedElementSet selectElements)
        {
            var topTwo = GetTop2InfoItemSet(archive, new InfoItem[] { InfoItem.Create(archive.Ontology.IdElement, localEntityId) }, selectElements);

            if (topTwo.BothHasValue || topTwo.BothNoValue)
            {
                return(new InfoItem[0]);
            }
            else
            {
                return(topTwo.SingleInfoTuple);
            }
        }
Ejemplo n.º 7
0
            /// <summary>
            /// 根据给定的接收成功的命令建造待分发命令
            /// </summary>
            /// <param name="tuple">已成功接收的命令类型的命令描述对象</param>
            /// <exception cref="AnycmdException">
            /// 当<seealso cref="ToNode"/>是自己时发生,不能建造分发向自己的命令消息
            /// </exception>
            /// <returns>待分发命令集合,可能为null</returns>
            public MessageEntity Build(MessageTuple tuple)
            {
                if (tuple == null)
                {
                    throw new ArgumentNullException("tuple");
                }
                #region 演出
                if (ToNode == ToNode.AcDomain.NodeHost.Nodes.ThisNode)
                {
                    throw new AnycmdException("不能建造分发向自己的命令消息");
                }
                if (tuple.Context.ClientAgent == ToNode)
                {
                    throw new AnycmdException("不能基于来源节点的命令建造分发向来源节点的命令");
                }
                var actionCode = tuple.Context.Command.Verb;
                if (actionCode == Verb.Create || actionCode == Verb.Update)
                {
                    var infoValueCares = new List <DataItem>();
                    foreach (var item in tuple.Context.InfoTuplePair.ValueTuple)
                    {
                        if (item.Element != tuple.Context.Ontology.IdElement &&
                            !item.Element.IsRuntimeElement &&
                            ToNode.IsCareforElement(item.Element))
                        {
                            infoValueCares.Add(new DataItem(item.Key, item.Value));
                        }
                    }
                    DataItem[] infoIdItems = null;
                    if (tuple.Tuple == null ||
                        ToNode.GetInfoIdElements().Any(a =>
                                                       a != tuple.Context.Ontology.IdElement &&
                                                       a.Element.IsInfoIdItem &&
                                                       !tuple.Tuple.Any(b => a.Element.Code.Equals(b.Key, StringComparison.OrdinalIgnoreCase))))
                    {
                        if (actionCode == Verb.Create)
                        {
                            var selectElements = new OrderedElementSet();
                            foreach (var item in ToNode.GetInfoIdElements())
                            {
                                if (item.Element.IsInfoIdItem)
                                {
                                    selectElements.Add(item);
                                }
                            }
                            infoIdItems = tuple.Context.Ontology.EntityProvider.GetTopTwo(tuple.Context.Ontology,
                                                                                          new InfoItem[] { InfoItem.Create(tuple.Context.Ontology.IdElement, tuple.Context.LocalEntityId) },
                                                                                          selectElements).SingleInfoTuple.Select(e => new DataItem(e.Key, e.Value)).ToArray();
                        }
                        else
                        {
                            infoIdItems = tuple.Context.TowInfoTuple.SingleInfoTuple
                                          .Where(e => e.Element.Element.IsInfoIdItem)
                                          .Select(e => new DataItem(e.Key, e.Value)).ToArray();
                        }
                    }
                    else
                    {
                        infoIdItems = tuple.Tuple.Where(e => e.Element.Element.IsInfoIdItem && ToNode.IsInfoIdElement(e.Element)).ToArray();
                    }
                    DataItemsTuple dataTuple = DataItemsTuple.Create(
                        ToNode.AcDomain,
                        infoIdItems,
                        infoValueCares.ToArray(),
                        tuple.Context.Command.DataTuple.QueryList,
                        tuple.Context.Command.DataTuple.InfoFormat);

                    if (infoValueCares.Count > 0)
                    {
                        return(new MessageEntity(MessageTypeKind.Distribute, Guid.NewGuid(), dataTuple)
                        {
                            ClientId = ToNode.Node.Id.ToString(),
                            Verb = tuple.Context.Command.Verb,
                            LocalEntityId = tuple.Context.LocalEntityId,
                            CatalogCode = tuple.Context.CatalogCode,
                            ReceivedOn = tuple.Context.Command.ReceivedOn,
                            CreateOn = DateTime.Now,
                            Ontology = tuple.Context.Command.Ontology,
                            ClientType = tuple.Context.Command.ClientType,
                            TimeStamp = tuple.Context.Command.TimeStamp,
                            MessageType = tuple.Context.Command.MessageType,
                            MessageId = tuple.Context.Command.MessageId,
                            Status = tuple.Context.Result.Status,
                            ReasonPhrase = tuple.Context.Result.ReasonPhrase,
                            Description = tuple.Context.Result.Description,
                            EventSourceType = tuple.Context.Command.EventSourceType,
                            EventSubjectCode = tuple.Context.Command.EventSubjectCode,
                            UserName = tuple.Context.Command.UserName,
                            IsDumb = tuple.Context.Command.IsDumb,
                            Version = tuple.Context.Command.Version
                        });
                    }
                }
                else if (actionCode == Verb.Delete)
                {
                    if (ToNode.IsCareForOntology(tuple.Context.Ontology))
                    {
                        DataItem[] infoIdItems = tuple.Context.TowInfoTuple.SingleInfoTuple
                                                 .Where(e => e.Element.Element.IsInfoIdItem)
                                                 .Select(e => new DataItem(e.Key, e.Value)).ToArray();
                        DataItemsTuple dataTuple = DataItemsTuple.Create(ToNode.AcDomain, infoIdItems, null, tuple.Context.Command.DataTuple.QueryList, tuple.Context.Command.DataTuple.InfoFormat);
                        return(new MessageEntity(MessageTypeKind.Distribute, Guid.NewGuid(), dataTuple)
                        {
                            ClientId = ToNode.Node.Id.ToString(),
                            Verb = tuple.Context.Command.Verb,
                            LocalEntityId = tuple.Context.LocalEntityId,
                            CatalogCode = tuple.Context.CatalogCode,
                            ReceivedOn = tuple.Context.Command.ReceivedOn,
                            CreateOn = DateTime.Now,
                            Ontology = tuple.Context.Command.Ontology,
                            ClientType = tuple.Context.Command.ClientType,
                            TimeStamp = tuple.Context.Command.TimeStamp,
                            MessageType = tuple.Context.Command.MessageType,
                            MessageId = tuple.Context.Command.MessageId,
                            Status = tuple.Context.Result.Status,
                            ReasonPhrase = tuple.Context.Result.ReasonPhrase,
                            Description = tuple.Context.Result.Description,
                            EventSubjectCode = tuple.Context.Command.EventSubjectCode,
                            EventSourceType = tuple.Context.Command.EventSourceType,
                            UserName = tuple.Context.Command.UserName,
                            IsDumb = tuple.Context.Command.IsDumb,
                            Version = tuple.Context.Command.Version
                        });
                    }
                }
                #endregion

                return(null);
            }
Ejemplo n.º 8
0
        public override void Handle(AddBatchCommand command)
        {
            var batchRepository = _acDomain.RetrieveRequiredService<IRepository<Batch>>();
            OntologyDescriptor ontology;
            if (!_acDomain.NodeHost.Ontologies.TryGetOntology(command.Input.OntologyId, out ontology))
            {
                throw new ValidationException("非法的本体标识" + command.Input.OntologyId);
            }
            BatchType type;
            if (!command.Input.Type.TryParse(out type))
            {
                throw new ValidationException("意外的批类型" + command.Input.Type);
            }
            
            var entity = Batch.Create(command.Input);

            var descriptor = new BatchDescriptor(_acDomain, entity);
            const int pageSize = 1000;
            const int pageIndex = 0;
            bool includeDescendants = entity.IncludeDescendants.HasValue && entity.IncludeDescendants.Value;
            NodeDescriptor toNode = null;
            if (!_acDomain.NodeHost.Nodes.TryGetNodeById(entity.NodeId.ToString(), out toNode))
            {
                throw new AnycmdException("意外的节点标识" + entity.NodeId);
            }

            string thisNodeId = _acDomain.NodeHost.Nodes.ThisNode.Node.Id.ToString();
            Verb actionCode;
            switch (descriptor.Type)
            {
                case BatchType.BuildCreateCommand:
                    actionCode = Verb.Create;
                    break;
                case BatchType.BuildUpdateCommand:
                    actionCode = Verb.Update;
                    break;
                case BatchType.BuildDeleteCommand:
                    actionCode = Verb.Delete;
                    break;
                default:
                    throw new AnycmdException("意外的批类型" + entity.Type);
            }
            var commandFactory = _acDomain.NodeHost.MessageProducer;
            bool goOn = true;
            int count = 0;
            var pagingData = new PagingInput(pageIndex, pageSize, ontology.IncrementIdElement.Element.Code, "asc");
            var selectElements = new OrderedElementSet {ontology.IdElement};
            foreach (var item in ontology.Elements.Values.Where(a => a.Element.IsEnabled == 1))
            {
                if (toNode.IsCareforElement(item) || toNode.IsInfoIdElement(item))
                {
                    selectElements.Add(item);
                }
            }
            var filters = new List<FilterData>();
            if (ontology.Ontology.IsCataloguedEntity && !string.IsNullOrEmpty(entity.CatalogCode))
            {
                filters.Add(includeDescendants
                    ? FilterData.Like("ZZJGM", entity.CatalogCode + "%")
                    : FilterData.EQ("ZZJGM", entity.CatalogCode));
            }
            do
            {
                IDataTuples entities = ontology.EntityProvider.GetPlist(ontology, selectElements, filters, pagingData);
                if (entities != null && entities.Columns != null)
                {
                    int idIndex = -1;
                    for (int i = 0; i < entities.Columns.Count; i++)
                    {
                        if (entities.Columns[i] == ontology.IdElement)
                        {
                            idIndex = i;
                            break;
                        }
                    }
                    if (entities.Columns.Count == 0)
                    {
                        throw new AnycmdException("意外的查询列数");
                    }
                    if (idIndex == -1)
                    {
                        throw new AnycmdException("未查询得到实体标识列");
                    }
                    var products = new List<MessageEntity>();
                    foreach (var item in entities.Tuples)
                    {
                        var idItems = new InfoItem[] { InfoItem.Create(ontology.IdElement, item[idIndex].ToString()) };
                        var valueItems = new InfoItem[entities.Columns.Count - 1];
                        for (int i = 0; i < entities.Columns.Count; i++)
                        {
                            if (i < idIndex)
                            {
                                valueItems[i] = InfoItem.Create(entities.Columns[i], item[i].ToString());
                            }
                            else if (i > idIndex)
                            {
                                valueItems[i - 1] = InfoItem.Create(entities.Columns[i], item[i].ToString());
                            }
                        }
                        var commandContext = new MessageContext(_acDomain,
                                new MessageRecord(
                                    MessageTypeKind.Received,
                                    Guid.NewGuid(),
                                    DataItemsTuple.Create(_acDomain, idItems, valueItems, null, "json"))
                                    {
                                        Verb = actionCode,
                                        ClientId = thisNodeId,
                                        ClientType = ClientType.Node,
                                        TimeStamp = DateTime.Now,
                                        CreateOn = DateTime.Now,
                                        Description = entity.Type,
                                        LocalEntityId = item[idIndex].ToString(),
                                        Ontology = ontology.Ontology.Code,
                                        CatalogCode = null,// 如果按照目录分片分发命令的话则目录为空的分发命令是由专门的分发器分发的
                                        MessageId = Guid.NewGuid().ToString(),
                                        MessageType = MessageType.Action,
                                        ReasonPhrase = "Ok",
                                        Status = 200,
                                        EventSourceType = string.Empty,
                                        EventSubjectCode = string.Empty,
                                        UserName = command.AcSession.Account.Id.ToString(),
                                        IsDumb = false,
                                        ReceivedOn = DateTime.Now,
                                        Version = ApiVersion.V1.ToName()
                                    });
                        products.AddRange(commandFactory.Produce(new MessageTuple(commandContext, valueItems), toNode));
                    }
                    ontology.MessageProvider.SaveCommands(ontology, products.ToArray());
                    count = count + products.Count;
                    pagingData.PageIndex++;// 注意这里不要引入bug。
                }
                if (entities == null || entities.Tuples.Length == 0)
                {
                    goOn = false;
                }
            } while (goOn);
            entity.Total = count;

            batchRepository.Add(entity);
            batchRepository.Context.Commit();

            _acDomain.PublishEvent(new BatchAddedEvent(command.AcSession, entity));
            _acDomain.CommitEventBus();
        }
Ejemplo n.º 9
0
            /// <summary>
            /// 根据给定的接收成功的命令建造待分发命令
            /// </summary>
            /// <param name="tuple">已成功接收的命令类型的命令描述对象</param>
            /// <exception cref="AnycmdException">
            /// 当<seealso cref="ToNode"/>是自己时发生,不能建造分发向自己的命令消息
            /// </exception>
            /// <returns>待分发命令集合,可能为null</returns>
            public MessageEntity Build(MessageTuple tuple)
            {
                if (tuple == null)
                {
                    throw new ArgumentNullException("tuple");
                }
                #region 演出
                if (ToNode == ToNode.AcDomain.NodeHost.Nodes.ThisNode)
                {
                    throw new AnycmdException("不能建造分发向自己的命令消息");
                }
                if (tuple.Context.ClientAgent == ToNode)
                {
                    throw new AnycmdException("不能基于来源节点的命令建造分发向来源节点的命令");
                }
                var actionCode = tuple.Context.Command.Verb;
                if (actionCode == Verb.Create || actionCode == Verb.Update)
                {
                    var infoValueCares = new List<DataItem>();
                    foreach (var item in tuple.Context.InfoTuplePair.ValueTuple)
                    {
                        if (item.Element != tuple.Context.Ontology.IdElement
                            && !item.Element.IsRuntimeElement
                            && ToNode.IsCareforElement(item.Element))
                        {
                            infoValueCares.Add(new DataItem(item.Key, item.Value));
                        }
                    }
                    DataItem[] infoIdItems = null;
                    if (tuple.Tuple == null
                        || ToNode.GetInfoIdElements().Any(a =>
                            a != tuple.Context.Ontology.IdElement
                            && a.Element.IsInfoIdItem
                            && !tuple.Tuple.Any(b => a.Element.Code.Equals(b.Key, StringComparison.OrdinalIgnoreCase))))
                    {
                        if (actionCode == Verb.Create)
                        {
                            var selectElements = new OrderedElementSet();
                            foreach (var item in ToNode.GetInfoIdElements())
                            {
                                if (item.Element.IsInfoIdItem)
                                {
                                    selectElements.Add(item);
                                }
                            }
                            infoIdItems = tuple.Context.Ontology.EntityProvider.GetTopTwo(tuple.Context.Ontology,
                                new InfoItem[] { InfoItem.Create(tuple.Context.Ontology.IdElement, tuple.Context.LocalEntityId) },
                                selectElements).SingleInfoTuple.Select(e => new DataItem(e.Key, e.Value)).ToArray();
                        }
                        else
                        {
                            infoIdItems = tuple.Context.TowInfoTuple.SingleInfoTuple
                                .Where(e => e.Element.Element.IsInfoIdItem)
                                .Select(e => new DataItem(e.Key, e.Value)).ToArray();
                        }
                    }
                    else
                    {
                        infoIdItems = tuple.Tuple.Where(e => e.Element.Element.IsInfoIdItem && ToNode.IsInfoIdElement(e.Element)).ToArray();
                    }
                    DataItemsTuple dataTuple = DataItemsTuple.Create(
                        ToNode.AcDomain,
                        infoIdItems,
                        infoValueCares.ToArray(),
                        tuple.Context.Command.DataTuple.QueryList,
                        tuple.Context.Command.DataTuple.InfoFormat);

                    if (infoValueCares.Count > 0)
                    {
                        return new MessageEntity(MessageTypeKind.Distribute, Guid.NewGuid(), dataTuple)
                        {
                            ClientId = ToNode.Node.Id.ToString(),
                            Verb = tuple.Context.Command.Verb,
                            LocalEntityId = tuple.Context.LocalEntityId,
                            CatalogCode = tuple.Context.CatalogCode,
                            ReceivedOn = tuple.Context.Command.ReceivedOn,
                            CreateOn = DateTime.Now,
                            Ontology = tuple.Context.Command.Ontology,
                            ClientType = tuple.Context.Command.ClientType,
                            TimeStamp = tuple.Context.Command.TimeStamp,
                            MessageType = tuple.Context.Command.MessageType,
                            MessageId = tuple.Context.Command.MessageId,
                            Status = tuple.Context.Result.Status,
                            ReasonPhrase = tuple.Context.Result.ReasonPhrase,
                            Description = tuple.Context.Result.Description,
                            EventSourceType = tuple.Context.Command.EventSourceType,
                            EventSubjectCode = tuple.Context.Command.EventSubjectCode,
                            UserName = tuple.Context.Command.UserName,
                            IsDumb = tuple.Context.Command.IsDumb,
                            Version = tuple.Context.Command.Version
                        };
                    }
                }
                else if (actionCode == Verb.Delete)
                {
                    if (ToNode.IsCareForOntology(tuple.Context.Ontology))
                    {
                        DataItem[] infoIdItems = tuple.Context.TowInfoTuple.SingleInfoTuple
                            .Where(e => e.Element.Element.IsInfoIdItem)
                            .Select(e => new DataItem(e.Key, e.Value)).ToArray();
                        DataItemsTuple dataTuple = DataItemsTuple.Create(ToNode.AcDomain, infoIdItems, null, tuple.Context.Command.DataTuple.QueryList, tuple.Context.Command.DataTuple.InfoFormat);
                        return new MessageEntity(MessageTypeKind.Distribute, Guid.NewGuid(), dataTuple)
                        {
                            ClientId = ToNode.Node.Id.ToString(),
                            Verb = tuple.Context.Command.Verb,
                            LocalEntityId = tuple.Context.LocalEntityId,
                            CatalogCode = tuple.Context.CatalogCode,
                            ReceivedOn = tuple.Context.Command.ReceivedOn,
                            CreateOn = DateTime.Now,
                            Ontology = tuple.Context.Command.Ontology,
                            ClientType = tuple.Context.Command.ClientType,
                            TimeStamp = tuple.Context.Command.TimeStamp,
                            MessageType = tuple.Context.Command.MessageType,
                            MessageId = tuple.Context.Command.MessageId,
                            Status = tuple.Context.Result.Status,
                            ReasonPhrase = tuple.Context.Result.ReasonPhrase,
                            Description = tuple.Context.Result.Description,
                            EventSubjectCode = tuple.Context.Command.EventSubjectCode,
                            EventSourceType = tuple.Context.Command.EventSourceType,
                            UserName = tuple.Context.Command.UserName,
                            IsDumb = tuple.Context.Command.IsDumb,
                            Version = tuple.Context.Command.Version
                        };
                    }
                }
                #endregion

                return null;
            }
Ejemplo n.º 10
0
        /// <summary>
        /// 命令响应。进入此方法标示者进入
        /// </summary>
        /// <returns></returns>
        public void Response(MessageContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            try
            {
                if (!context.Result.IsClosed)
                {
                    var requestType = context.Command.MessageType;
                    if (!context.IsValid)
                    {
                        if (!context.Result.ResultDataItems.Any(a => a.Key.Equals("Id", StringComparison.OrdinalIgnoreCase)))
                        {
                            context.Result.ResultDataItems.Add(new DataItem("Id", context.LocalEntityId));
                        }
                        if (context.Command is IEntity)
                        {
                            using (var cmdProviderAct = new WfAct(context.Host, context, context.Ontology.MessageProvider, "保存执行失败的命令"))
                            {
                                if (requestType == MessageType.Action || context.Command.CommandType == MessageTypeKind.Received)
                                {
                                    context.Ontology.MessageProvider.SaveCommand(context.Ontology, context.Command.ToExecuteFailing(context.Result));
                                }
                                else if (requestType == MessageType.Command)
                                {
                                    context.Ontology.MessageProvider.SaveCommand(context.Ontology, context.Command.ToUnaccepted(context.Result));
                                }
                            }
                            context.Ontology.MessageProvider.DeleteCommand(context.Command.CommandType, context.Ontology, context.Command.Id, context.Command.IsDumb);
                        }
                    }
                    else
                    {
                        if (!context.Result.ResultDataItems.Any(a => a.Key.Equals("Id", StringComparison.OrdinalIgnoreCase)))
                        {
                            context.Result.ResultDataItems.Add(new DataItem("Id", context.LocalEntityId));
                        }
                        if (Verb.Get.Equals(context.Command.Verb))
                        {
                            using (var act = new WfAct(context.Host, context, context.Ontology.EntityProvider, "填充get型命令的InfoValue字段"))
                            {
                                var selectElements = new OrderedElementSet();
                                foreach (var element in context.Ontology.Elements.Values.Where(a => a.Element.IsEnabled == 1))
                                {
                                    if (context.ClientAgent.GetElementPermission(element, Verb.Get) != AllowType.NotAllow)
                                    {
                                        selectElements.Add(element);
                                    }
                                }
                                IList<InfoItem> infoValues = context.Ontology.EntityProvider.Get(
                                    context.Ontology, context.LocalEntityId, selectElements);
                                context.Result.ResultDataItems = infoValues.Select(a => new DataItem(a.Key, a.Value)).ToList();
                            }
                        }
                        var nodeHost = context.Host.NodeHost;
                        // ApplyProcessingFilters 应用处理前过滤器
                        ProcessResult result = nodeHost.ApplyEdiMessageHandingFilters(context);
                        if (!result.IsSuccess)
                        {
                            context.Result.UpdateStatus(result.StateCode, result.Description);
                        }
                        if (!context.Result.IsClosed)
                        {
                            switch (requestType)
                            {
                                case MessageType.Action:
                                    HandleAction(context);
                                    break;
                                case MessageType.Command:
                                    HandleCommand(context);
                                    break;
                                case MessageType.Event:
                                    HandleEvent(context);
                                    break;
                                default:
                                    throw new AnycmdException("意外的请求类型" + context.Command.MessageType);
                            }

                            // ApplyProcessedFilters 应用处理后过滤器
                            result = nodeHost.ApplyEdiMessageHandledFilters(context);
                            if (!result.IsSuccess)
                            {
                                context.Result.UpdateStatus(result.StateCode, result.Description);
                            }
                        }
                    }
                }
                int stateCode = context.Result.Status;
                if (stateCode < 200)
                {
                    IInfoStringConverter converter;
                    if (!context.Host.NodeHost.InfoStringConverters.TryGetInfoStringConverter(context.Command.DataTuple.InfoFormat, out converter))
                    {
                        throw new AnycmdException("意外的信息格式" + context.Command.DataTuple.InfoFormat);
                    }
                    var anyLog = new AnyLog(Guid.NewGuid())
                    {
                        Req_Ontology = context.Ontology.Ontology.Code,
                        Req_Verb = context.Command.Verb.Code,
                        Req_ClientId = context.Command.ClientId,
                        Req_ClientType = context.Command.ClientType.ToName(),
                        CreateOn = context.Command.CreateOn,
                        Req_Description = context.Command.Description,
                        Req_EventSourceType = context.Command.EventSourceType,
                        Req_EventSubjectCode = context.Command.EventSubjectCode,
                        InfoFormat = context.Command.DataTuple.InfoFormat,
                        Req_InfoId = context.Command.DataTuple.IdItems.InfoString,
                        Req_InfoValue = context.Command.DataTuple.ValueItems.InfoString,
                        Req_UserName = context.Command.UserName,
                        Req_IsDumb = context.Command.IsDumb,
                        LocalEntityId = context.Command.LocalEntityId,
                        CatalogCode = context.Command.CatalogCode,
                        Req_ReasonPhrase = context.Command.ReasonPhrase,
                        ReceivedOn = context.Command.ReceivedOn,
                        Req_MessageId = context.Command.MessageId,
                        Req_MessageType = context.Command.MessageType.ToName(),
                        Req_QueryList = context.Command.DataTuple.QueryListString,
                        Req_Status = context.Command.Status,
                        Req_TimeStamp = context.Command.TimeStamp,
                        Req_Version = context.Command.Version,
                        Res_InfoValue = converter.ToInfoString(context.Result.ResultDataItems),
                        Res_Description = context.Result.Description,
                        Res_ReasonPhrase = context.Result.ReasonPhrase,
                        Res_StateCode = (int)context.Result.Status
                    };
                    context.Ontology.Host.LoggingService.Log(anyLog);
                }
            }
            catch (Exception ex)
            {
                context.Result.UpdateStatus(Status.InternalServerError, "服务器内部逻辑异常");
                context.Result.IsClosed = true;
                context.Exception = ex;
                throw;
            }
        }
Ejemplo n.º 11
0
 public ActionResult Export(GetPlistEntity requestModel, string elements, string limit, string exportType)
 {
     if (!ModelState.IsValid)
     {
         return ModelState.ToJsonResult();
     }
     OntologyDescriptor ontology;
     if (!AcDomain.NodeHost.Ontologies.TryGetOntology(requestModel.OntologyCode, out ontology))
     {
         throw new ValidationException("非法的本体码");
     }
     if (string.IsNullOrEmpty(requestModel.CatalogCode))
     {
         throw new ValidationException("没有选中目录");
     }
     CatalogState org;
     if (!AcDomain.CatalogSet.TryGetCatalog(requestModel.CatalogCode, out org))
     {
         throw new ValidationException("非法的目录码" + requestModel.CatalogCode);
     }
     var selectElements = new OrderedElementSet();
     if (string.IsNullOrEmpty(elements))
     {
         foreach (var element in ontology.Elements.Values.Where(a => a.Element.IsEnabled == 1))
         {
             selectElements.Add(element);
         }
     }
     else
     {
         string[] elementCodes = elements.Split(',');
         foreach (var elementCode in elementCodes)
         {
             ElementDescriptor element;
             if (!ontology.Elements.TryGetValue(elementCode, out element))
             {
                 throw new ValidationException("意外的本体元素码" + elementCode);
             }
             else
             {
                 if (element.Element.IsEnabled != 1)
                 {
                     continue;
                 }
                 selectElements.Add(element);
             }
         }
     }
     if (selectElements.Count == 0)
     {
         throw new ValidationException("selectElements为空");
     }
     if (string.IsNullOrEmpty(exportType))
     {
         exportType = "currentPage";
     }
     exportType = exportType.ToLower();
     switch (exportType)
     {
         case "allpage":
             requestModel.PageSize = int.MaxValue;
             break;
         case "temp":
             requestModel.PageSize = 0;
             break;
         default:
             break;
     }
     if (!string.IsNullOrEmpty(limit))
     {
         int size;
         if (int.TryParse(limit, out size))
         {
             requestModel.PageSize = size;
         }
     }
     IDataTuples infoValues = !requestModel.ArchiveId.HasValue ? GetInfoValues(requestModel, selectElements) : GetArchivedInfoValues(requestModel);
     const string contentType = "application/vnd.ms-excel";
     string fileName = org.Name + ontology.Ontology.Name + ".xls";
     if (Request.Browser.Type.IndexOf("IE", StringComparison.OrdinalIgnoreCase) > -1)
     {
         fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
     }
     Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", fileName));
     Response.Clear();
     //Excel功能
     var hssfworkbook = new HSSFWorkbook(); //新建一个xls文件
     #region Sheet1 数据
     ISheet sheet1 = hssfworkbook.CreateSheet(ontology.Ontology.Name); //创建一个sheet
     int rowIndex = 0;
     var headRow = sheet1.CreateRow(rowIndex);
     sheet1.CreateFreezePane(0, 1, 0, 1);
     rowIndex++;
     ICellStyle helderStyle = hssfworkbook.CreateCellStyle();
     IFont font = hssfworkbook.CreateFont();
     font.FontHeightInPoints = 14;
     helderStyle.SetFont(font);
     helderStyle.BorderBottom = BorderStyle.Thin;
     helderStyle.BorderLeft = BorderStyle.Thin;
     helderStyle.BorderRight = BorderStyle.Thin;
     helderStyle.BorderTop = BorderStyle.Thin;
     helderStyle.FillForegroundColor = HSSFColor.LightGreen.Index;
     helderStyle.FillPattern = FillPattern.SolidForeground;
     int i = 0;
     foreach (var element in selectElements)
     {
         ICell cell = headRow.CreateCell(i, CellType.String);
         if (element.IsCodeValue)
         {
             cell.SetCellValue(element.Element.Name + "码");
         }
         else
         {
             cell.SetCellValue(element.Element.Name);
         }
         if (!string.IsNullOrEmpty(element.Element.Description))
         {
             //添加批注
             IDrawing draw = sheet1.CreateDrawingPatriarch();
             IComment comment = draw.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 2, 4, 8));//里面参数应该是指示批注的位置大小吧
             comment.String = new HSSFRichTextString(element.Element.Description);//添加批注内容
             comment.Author = AcDomain.NodeHost.Nodes.ThisNode.Name;//添加批注作者
             cell.CellComment = comment;//将之前设置的批注给定某个单元格
         }
         cell.CellStyle = helderStyle;
         if (element.Element.Width > 0)
         {
             sheet1.SetColumnWidth(i, element.Element.Width * 256 / 5);
         }
         if (element.IsCodeValue)
         {
             i++;
             ICell nameValue = headRow.CreateCell(i, CellType.String);
             nameValue.SetCellValue(element.Element.Name + "名");
             nameValue.CellStyle = helderStyle;
             if (element.Element.Width > 0)
             {
                 sheet1.SetColumnWidth(i, element.Element.Width * 256 / 5);
             }
         }
         i++;
     }
     foreach (var record in infoValues.Tuples)
     {
         var row = sheet1.CreateRow(rowIndex);
         int j = 0;
         for (int col = 0; col < infoValues.Columns.Count; col++)
         {
             var element = infoValues.Columns[col];
             var item = record[col];
             ICell cell = row.CreateCell(j, CellType.String);
             cell.SetCellValue(item.ToString());
             if (element.IsCodeValue)
             {
                 j++;
                 ICell nameCell = row.CreateCell(j, CellType.String);
                 nameCell.SetCellValue(element.TranslateValue(item.ToString()));
             }
             j++;
         }
         rowIndex++;
     }
     #endregion
     #region orgSheet 目录字典
     ISheet orgSheet = hssfworkbook.CreateSheet("目录字典"); //创建一个sheet
     ICellStyle invalidOrgCodeStyle = hssfworkbook.CreateCellStyle();
     invalidOrgCodeStyle.BorderBottom = BorderStyle.Thin;
     invalidOrgCodeStyle.BorderLeft = BorderStyle.Thin;
     invalidOrgCodeStyle.BorderRight = BorderStyle.Thin;
     invalidOrgCodeStyle.BorderTop = BorderStyle.Thin;
     invalidOrgCodeStyle.FillForegroundColor = HSSFColor.LightOrange.Index;
     invalidOrgCodeStyle.FillPattern = FillPattern.SolidForeground;
     ICellStyle invalidParentOrgStyle = hssfworkbook.CreateCellStyle();
     invalidParentOrgStyle.BorderBottom = BorderStyle.Thin;
     invalidParentOrgStyle.BorderLeft = BorderStyle.Thin;
     invalidParentOrgStyle.BorderRight = BorderStyle.Thin;
     invalidParentOrgStyle.BorderTop = BorderStyle.Thin;
     invalidParentOrgStyle.FillForegroundColor = HSSFColor.LightYellow.Index;
     invalidParentOrgStyle.FillPattern = FillPattern.SolidForeground;
     rowIndex = 0;
     headRow = orgSheet.CreateRow(rowIndex);
     orgSheet.CreateFreezePane(0, 1, 0, 1);
     rowIndex++;
     i = 0;
     var orgCols = new string[] { "父名称", "父编码", "名称", "编码", "创建时间", "最后修改时间", "备注" };
     foreach (var colName in orgCols)
     {
         orgSheet.SetColumnWidth(i, 20 * 256);
         ICell cell = headRow.CreateCell(i, CellType.String);
         cell.SetCellValue(colName);
         cell.CellStyle = helderStyle;
         i++;
     }
     if (AcSession.IsDeveloper())
     {
         foreach (var item in AcDomain.CatalogSet)
         {
             var parentOrg = item.Parent;
             var row = orgSheet.CreateRow(rowIndex);
             row.CreateCell(0, CellType.String).SetCellValue(parentOrg.Name);
             row.CreateCell(1, CellType.String).SetCellValue(parentOrg.Code);
             row.CreateCell(2, CellType.String).SetCellValue(item.Name);
             ICell codeCell = row.CreateCell(3, CellType.String);
             if (item != CatalogState.VirtualRoot)
             {
                 if (parentOrg == CatalogState.Empty)
                 {
                     codeCell.CellStyle = invalidParentOrgStyle;
                     //添加批注
                     IDrawing draw = orgSheet.CreateDrawingPatriarch();
                     IComment comment = draw.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 2, 4, 8));//里面参数应该是指示批注的位置大小吧
                     comment.String = new HSSFRichTextString("警告:该目录的上级目录不存在。");//添加批注内容
                     comment.Author = AcDomain.NodeHost.Nodes.ThisNode.Name;//添加批注作者
                     codeCell.CellComment = comment;//将之前设置的批注给定某个单元格
                 }
                 else if (parentOrg != CatalogState.VirtualRoot && !item.Code.StartsWith(parentOrg.Code))
                 {
                     codeCell.CellStyle = invalidOrgCodeStyle;
                     //添加批注
                     IDrawing draw = orgSheet.CreateDrawingPatriarch();
                     IComment comment = draw.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 2, 4, 8));//里面参数应该是指示批注的位置大小吧
                     comment.String = new HSSFRichTextString("警告:该目录的编码没有以上级目录编码为前缀,这是错误的,后续是要改正的。");//添加批注内容
                     comment.Author = AcDomain.NodeHost.Nodes.ThisNode.Name;//添加批注作者
                     codeCell.CellComment = comment;//将之前设置的批注给定某个单元格
                 }
             }
             codeCell.SetCellValue(item.Code);
             string createOn = string.Empty;
             if (item.CreateOn.HasValue)
             {
                 createOn = item.CreateOn.ToString();
             }
             string modifiedOn = string.Empty;
             if (item.ModifiedOn.HasValue)
             {
                 modifiedOn = item.ModifiedOn.ToString();
             }
             row.CreateCell(4, CellType.String).SetCellValue(createOn);
             row.CreateCell(5, CellType.String).SetCellValue(modifiedOn);
             row.CreateCell(6, CellType.String).SetCellValue(item.Description);
             rowIndex++;
         }
     }
     else
     {
         foreach (var myOrg in AcSession.AccountPrivilege.Catalogs)
         {
             foreach (var item in AcDomain.CatalogSet)
             {
                 if (item.Code.StartsWith(myOrg.Code, StringComparison.OrdinalIgnoreCase))
                 {
                     var row = orgSheet.CreateRow(rowIndex);
                     var parentOrg = item.Parent;
                     row.CreateCell(0, CellType.String).SetCellValue(parentOrg.Name);
                     row.CreateCell(1, CellType.String).SetCellValue(parentOrg.Code);
                     row.CreateCell(2, CellType.String).SetCellValue(item.Name);
                     ICell codeCell = row.CreateCell(3, CellType.String);
                     if (item != CatalogState.VirtualRoot)
                     {
                         if (parentOrg == CatalogState.Empty)
                         {
                             codeCell.CellStyle = invalidParentOrgStyle;
                             //添加批注
                             IDrawing draw = orgSheet.CreateDrawingPatriarch();
                             IComment comment = draw.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 2, 4, 8));//里面参数应该是指示批注的位置大小吧
                             comment.String = new HSSFRichTextString("警告:该目录的上级目录不存在。");//添加批注内容
                             comment.Author = AcDomain.NodeHost.Nodes.ThisNode.Name;//添加批注作者
                             codeCell.CellComment = comment;//将之前设置的批注给定某个单元格
                         }
                         else if (parentOrg != CatalogState.VirtualRoot && !item.Code.StartsWith(parentOrg.Code, StringComparison.OrdinalIgnoreCase))
                         {
                             codeCell.CellStyle = invalidOrgCodeStyle;
                             //添加批注
                             IDrawing draw = orgSheet.CreateDrawingPatriarch();
                             IComment comment = draw.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 2, 4, 8));//里面参数应该是指示批注的位置大小吧
                             comment.String = new HSSFRichTextString("警告:该目录的编码没有以上级目录编码为前缀,这是错误的,后续是要改正的。");//添加批注内容
                             comment.Author = AcDomain.NodeHost.Nodes.ThisNode.Name;//添加批注作者
                             codeCell.CellComment = comment;//将之前设置的批注给定某个单元格
                         }
                     }
                     codeCell.SetCellValue(item.Code);
                     string createOn = string.Empty;
                     if (item.CreateOn.HasValue)
                     {
                         createOn = item.CreateOn.ToString();
                     }
                     string modifiedOn = string.Empty;
                     if (item.ModifiedOn.HasValue)
                     {
                         modifiedOn = item.ModifiedOn.ToString();
                     }
                     row.CreateCell(4, CellType.String).SetCellValue(createOn);
                     row.CreateCell(5, CellType.String).SetCellValue(modifiedOn);
                     row.CreateCell(6, CellType.String).SetCellValue(item.Description);
                     rowIndex++;
                 }
             }
         }
     }
     #endregion
     #region infoDicSheet 信息字典
     ISheet infoDicSheet = hssfworkbook.CreateSheet("信息字典"); //创建一个sheet
     rowIndex = 0;
     headRow = infoDicSheet.CreateRow(rowIndex);
     infoDicSheet.CreateFreezePane(0, 1, 0, 1);
     rowIndex++;
     i = 0;
     var dicCols = new string[] { "字典名", "字典码", "字典项名", "字典项码", "等级", "创建时间", "最后修改时间", "备注" };
     foreach (var colName in dicCols)
     {
         infoDicSheet.SetColumnWidth(i, 20 * 256);
         ICell cell = headRow.CreateCell(i, CellType.String);
         cell.SetCellValue(colName);
         cell.CellStyle = helderStyle;
         i++;
     }
     foreach (var infoDic in AcDomain.NodeHost.InfoDics)
     {
         foreach (var infoDicItem in AcDomain.NodeHost.InfoDics.GetInfoDicItems(infoDic))
         {
             var row = infoDicSheet.CreateRow(rowIndex);
             row.CreateCell(0, CellType.String).SetCellValue(infoDic.Name);
             row.CreateCell(1, CellType.String).SetCellValue(infoDic.Code);
             row.CreateCell(2, CellType.String).SetCellValue(infoDicItem.Name);
             row.CreateCell(3, CellType.String).SetCellValue(infoDicItem.Code);
             row.CreateCell(4, CellType.String).SetCellValue(infoDicItem.Level);
             string createOn = string.Empty;
             if (infoDicItem.CreateOn.HasValue)
             {
                 createOn = infoDicItem.CreateOn.ToString();
             }
             string modifiedOn = string.Empty;
             if (infoDicItem.ModifiedOn.HasValue)
             {
                 modifiedOn = infoDicItem.ModifiedOn.ToString();
             }
             row.CreateCell(5, CellType.String).SetCellValue(createOn);
             row.CreateCell(6, CellType.String).SetCellValue(modifiedOn);
             row.CreateCell(7, CellType.String).SetCellValue(infoDicItem.Description);
             rowIndex++;
         }
     }
     #endregion
     var filestream = new MemoryStream(); //内存文件流(应该可以写成普通的文件流)
     hssfworkbook.Write(filestream); //把文件读到内存流里面
     return new FileContentResult(filestream.GetBuffer(), contentType);
 }
Ejemplo n.º 12
0
        /// <summary>
        /// 根据目录获取给定节点和本体的数据,如果传入的目录为空表示获取本节点的数据
        /// <remarks>本节点通常是中心节点</remarks>
        /// </summary>
        /// <param name="ontology"></param>
        /// <param name="db">模型</param>
        /// <param name="filters"></param>
        /// <param name="selectElements">sql select语句的选择列集合</param>
        /// <param name="pagingData"></param>
        /// <returns>
        /// 数据记录列表,数据记录表现为字典形式,键是数据元素编码值是相应数据元素对应的数据项值
        /// </returns>
        private DataTuple GetPlistInfoItems(
			OntologyDescriptor ontology,
			RdbDescriptor db, OrderedElementSet selectElements, List<FilterData> filters,
			PagingInput pagingData)
        {
            if (string.IsNullOrEmpty(pagingData.SortField))
            {
                pagingData.SortField = "IncrementId";
            }
            if (string.IsNullOrEmpty(pagingData.SortOrder))
            {
                pagingData.SortOrder = "asc";
            }

            var elements = ontology.Elements;
            if (filters != null)
            {
                for (int i = 0; i < filters.Count; i++)
                {
                    var filter = filters[i];
                    if (elements.ContainsKey(filter.field))
                    {
                        // TODO:根据数据属性优化查询,比如对于身份证件号来说如果输入的值长度
                        // 为20或18的话可以将like替换为等于
                        filter.type = "string";
                        var element = elements[filter.field];
                        if (element.Element.IsEnabled != 1)
                        {
                            continue;
                        }
                        if (element.Element.InfoDicId.HasValue)
                        {
                            filter.comparison = "eq";
                        }
                        else
                        {
                            filter.comparison = "like";
                        }
                    }
                    else
                    {
                        filters.RemoveAt(i);
                    }
                }
            }

            var tableName = ontology.Ontology.EntityTableName;
            var sbSqlPredicate = new StringBuilder();
            var l = sbSqlPredicate.Length;

            var pQueryList = new List<DbParameter>();
            List<DbParameter> pFilters;
            var filterString = _filterStringBuilder.FilterString(db, filters, null, out pFilters);
            if (!string.IsNullOrEmpty(filterString))
            {
                foreach (var pFilter in pFilters)
                {
                    object obj = pFilter.Value;
                    if (obj == null)
                    {
                        obj = DBNull.Value;
                    }
                    var p = db.CreateParameter();
                    p.ParameterName = pFilter.ParameterName;
                    p.Value = obj;
                    pQueryList.Add(p);
                }
                if (sbSqlPredicate.Length != l)
                {
                    sbSqlPredicate.Append(" and ");
                }
                sbSqlPredicate.Append(filterString);
            }

            string sqlPredicateString = string.Empty;
            if (sbSqlPredicate.Length > 0)
            {
                sqlPredicateString = sbSqlPredicate.ToString();
            }
            var sqlText = new StringBuilder();
            OrderedElementSet elementList;
            if (selectElements == null || selectElements.Count == 0)
            {
                elementList = new OrderedElementSet { ontology.Elements["id"] };
            }
            else
            {
                elementList = selectElements;
            }
            sqlText.Append("SELECT TOP {0} ");
            int len = sqlText.Length;

            foreach (var element in elementList)
            {
                if (sqlText.Length != len)
                {
                    sqlText.Append(",");
                }
                sqlText.Append("[").Append(element.Element.FieldCode).Append("]");
            }

            sqlText.Append(" FROM (SELECT ROW_NUMBER() OVER(ORDER BY {1} {2}) AS RowNumber,");
            len = sqlText.Length;

            foreach (var element in elementList)
            {
                if (sqlText.Length != len)
                {
                    sqlText.Append(",");
                }
                sqlText.Append("[").Append(element.Element.FieldCode).Append("]");
            }

            sqlText.Append(" FROM {3} where ");
            if (ontology.Ontology.IsLogicalDeletionEntity)
            {
                sqlText.Append("DeletionStateCode = 0");
            }
            else
            {
                sqlText.Append("1 = 1");
            }
            if (!string.IsNullOrEmpty(sqlPredicateString))
            {
                sqlText.Append(" and ").Append(sqlPredicateString);
            }
            sqlText.Append(") a WHERE a.RowNumber > {4}");
            string sqlQuery = string.Format(
                sqlText.ToString(),
                pagingData.PageSize.ToString(CultureInfo.InvariantCulture),
                pagingData.SortField,
                pagingData.SortOrder,
                tableName,
                (pagingData.SkipCount).ToString(CultureInfo.InvariantCulture));

            pagingData.Count(() =>
            {
                string where = ontology.Ontology.IsLogicalDeletionEntity ? "where DeletionStateCode = 0" : "";
                string sqlCount = string.Format("select count(1) from {0} {1}", tableName, where);
                if (!string.IsNullOrEmpty(sqlPredicateString))
                {
                    sqlCount = sqlCount + " and " + sqlPredicateString;
                }
                return (int)db.ExecuteScalar(
                    sqlCount, pQueryList.Select(p => ((ICloneable)p).Clone()).Cast<DbParameter>().ToArray());
            });

            var list = new List<object[]>();
            var reader = db.ExecuteReader(sqlQuery, pQueryList.ToArray());
            while (reader.Read())
            {
                var values = new object[elementList.Count];
                for (int i = 0; i < elementList.Count; i++)
                {
                    values[i] = reader.GetValue(i);
                }
                list.Add(values);
            }
            reader.Close();

            return new DataTuple(elementList, list.ToArray());
        }
Ejemplo n.º 13
0
 private TowInfoTuple GetTop2InfoItemSet(
     ArchiveState archive, IEnumerable <InfoItem> infoIDs, OrderedElementSet selectElements)
 {
     return(GetTop2InfoItemSet(archive.Ontology, this.GetArchiveDb(archive.Ontology, archive), infoIDs, selectElements));
 }
Ejemplo n.º 14
0
        /// <summary>
        /// 获取给定实体标识列表中的标识标识的每一个实体元组
        /// </summary>
        /// <param name="ontology"></param>
        /// <param name="selectElements"></param>
        /// <param name="entityIDs"></param>
        /// <returns></returns>
        public DataTuple GetList(OntologyDescriptor ontology, OrderedElementSet selectElements, List<string> entityIDs)
        {
            if (ontology == null)
            {
                throw new ArgumentNullException("ontology");
            }
            if (selectElements == null)
            {
                throw new ArgumentNullException("selectElements");
            }
            if (entityIDs == null || entityIDs.Count == 0)
            {
                throw new ArgumentException("entityId");
            }
            var ids = new StringBuilder("(");
            int len = ids.Length;
            foreach (var id in entityIDs)
            {
                if (ids.Length != len)
                {
                    ids.Append(",");
                }
                ids.Append("'").Append(id).Append("'");
            }
            ids.Append(")");
            var tableName = ontology.Ontology.EntityTableName;
            if (selectElements.Count == 0)
            {
                selectElements.Add(ontology.Elements[ontology.IdElement.Element.Code]);
            }
            var sqlQuery = new StringBuilder("select ");
            int l = sqlQuery.Length;
            foreach (var item in selectElements)
            {
                if (sqlQuery.Length != l)
                {
                    sqlQuery.Append(",");
                }
                sqlQuery.Append("t.[").Append(item.Element.Code).Append("]");
            }
            sqlQuery.Append(" from [").Append(tableName).Append("] as t where t.[")
                .Append(ontology.IdElement.Element.Code).Append("] in ").Append(ids.ToString());// TODO:参数化EntityIDs
            var list = new List<object[]>();
            var reader = this.GetEntityDb(ontology).ExecuteReader(sqlQuery.ToString());
            while (reader.Read())
            {
                var values = new object[selectElements.Count];
                for (int i = 0; i < selectElements.Count; i++)
                {
                    values[i] = reader.GetValue(i);
                }
                list.Add(values);
            }
            reader.Close();

            return new DataTuple(selectElements, list.ToArray());
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 按照目录分页获取指定节点、本体的数据
        /// <remarks>
        /// 如果传入的目录为空则表示获取全部目录的数据
        /// </remarks>
        /// </summary>
        /// <param name="ontology"></param>
        /// <param name="selectElements"></param>
        /// <param name="filters">过滤器列表</param>
        /// <param name="pagingData"></param>
        /// <returns></returns>
        public DataTuple GetPlist(
			OntologyDescriptor ontology,
			OrderedElementSet selectElements,
			List<FilterData> filters,
			PagingInput pagingData)
        {
            return this.GetPlistInfoItems(
                ontology, this.GetEntityDb(ontology),
                selectElements,
                filters, pagingData);
        }
Ejemplo n.º 16
0
 public ActionResult GetInfo(string nodeId, string ontologyCode, string id, bool? translate, Guid? archiveId)
 {
     if (!archiveId.HasValue)
     {
         OntologyDescriptor ontology;
         if (!AcDomain.NodeHost.Ontologies.TryGetOntology(ontologyCode, out ontology))
         {
             throw new ValidationException("非法的本体码");
         }
         var selectElements = new OrderedElementSet();
         foreach (var item in ontology.Elements.Values.Where(a => a.Element.IsEnabled == 1))
         {
             selectElements.Add(item);
         }
         var infoValues = ontology.EntityProvider.Get(ontology, id, selectElements);
         Dictionary<string, string> infoValueDic;
         if (translate.HasValue && translate.Value == true)
         {
             infoValueDic = infoValues.ToDictionary(k => k.Element.Element.Code, v => v.Element.TranslateValue(v.Value));
         }
         else
         {
             infoValueDic = infoValues.ToDictionary(k => k.Element.Element.Code, v => v.Value);
         }
         return this.JsonResult(infoValueDic);
     }
     else
     {
         ArchiveState archive;
         if (!AcDomain.NodeHost.Ontologies.TryGetArchive(archiveId.Value, out archive))
         {
             throw new ValidationException("意外的归档Id");
         }
         OntologyDescriptor ontology = archive.Ontology;
         var queryInfoIDs = new List<InfoItem>();
         queryInfoIDs.Add(InfoItem.Create(ontology.IdElement, id));
         var selectElements = new OrderedElementSet();
         foreach (var item in ontology.Elements.Values.Where(a => a.Element.IsEnabled == 1))
         {
             selectElements.Add(item);
         }
         var infoValues = ontology.EntityProvider.Get(archive, id, selectElements);
         Dictionary<string, string> infoValueDic;
         if (translate.HasValue && translate.Value == true)
         {
             infoValueDic = infoValues.ToDictionary(k => k.Element.Element.Code, v => v.Element.TranslateValue(v.Value));
         }
         else
         {
             infoValueDic = infoValues.ToDictionary(k => k.Element.Element.Code, v => v.Value);
         }
         return this.JsonResult(infoValueDic);
     }
 }
Ejemplo n.º 17
0
        public DataTuple GetPlist(
			ArchiveState archive,
			OrderedElementSet selectElements,
			List<FilterData> filters,
			PagingInput pagingData)
        {
            return this.GetPlistInfoItems(
                archive.Ontology, this.GetArchiveDb(archive.Ontology, archive),
                selectElements,
                filters, pagingData);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 根据给定的本体码和信息标识获取本节点两条数据
        /// </summary>
        /// <param name="ontology">本体</param>
        /// <param name="db"></param>
        /// <param name="infoIds">多列联合信息标识字典,键必须不区分大小写</param>
        /// <param name="selectElements">选择元素</param>
        /// <returns></returns>
        private TowInfoTuple GetTop2InfoItemSet(OntologyDescriptor ontology,
			RdbDescriptor db, IEnumerable<InfoItem> infoIds, OrderedElementSet selectElements)
        {
            if (infoIds == null || !infoIds.Any())
            {
                return new TowInfoTuple(null, null);
            }

            var sb = new StringBuilder();
            var sqlParameters = new List<DbParameter>();
            var elementList = selectElements.ToList();
            sb.Append("select top 2 ");
            int l = sb.Length;
            foreach (var element in elementList)
            {
                if (sb.Length != l)
                {
                    sb.Append(",");
                }
                sb.Append("t.[").Append(element.Element.FieldCode).Append("]");
            }
            sb.Append(" from [").Append(ontology.Ontology.EntityTableName).Append("] as t where");
            if (ontology.Ontology.IsLogicalDeletionEntity)
            {
                sb.Append(" t.DeletionStateCode=0 ");
            }
            else
            {
                sb.Append(" 1=1 ");
            }
            foreach (var element in infoIds)
            {
                sb.Append(" and t.[").Append(element.Element.Element.FieldCode)
                    .Append("]=").Append("@").Append(element.Element.Element.FieldCode);
                object obj = element.Value;
                if (obj == null)
                {
                    obj = DBNull.Value;
                }
                sqlParameters.Add(CreateParameter(db, element.Element.Element.FieldCode, obj, DbType.String));
            }
            var infoValue1 = new List<InfoItem>();
            var infoValue2 = new List<InfoItem>();
            using (var reader = db.ExecuteReader(sb.ToString(), sqlParameters.ToArray()))
            {
                if (reader.Read())
                {
                    for (int i = 0; i < elementList.Count; i++)
                    {
                        infoValue1.Add(InfoItem.Create(elementList[i], reader.GetValue(i).ToString()));
                    }
                }
                if (reader.Read())
                {
                    for (int i = 0; i < elementList.Count; i++)
                    {
                        infoValue2.Add(InfoItem.Create(elementList[i], reader.GetValue(i).ToString()));
                    }
                }
                reader.Close();
            }

            return new TowInfoTuple(infoValue1.ToArray(), infoValue2.ToArray());
        }
Ejemplo n.º 19
0
        private TowInfoTuple GetTop2InfoItemSet(
			ArchiveState archive, IEnumerable<InfoItem> infoIDs, OrderedElementSet selectElements)
        {
            return GetTop2InfoItemSet(archive.Ontology, this.GetArchiveDb(archive.Ontology, archive), infoIDs, selectElements);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 命令响应。进入此方法标示者进入
        /// </summary>
        /// <returns></returns>
        public void Response(MessageContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            try
            {
                if (!context.Result.IsClosed)
                {
                    var requestType = context.Command.MessageType;
                    if (!context.IsValid)
                    {
                        if (!context.Result.ResultDataItems.Any(a => a.Key.Equals("Id", StringComparison.OrdinalIgnoreCase)))
                        {
                            context.Result.ResultDataItems.Add(new DataItem("Id", context.LocalEntityId));
                        }
                        if (context.Command is IEntity <Guid> )
                        {
                            using (var cmdProviderAct = new WfAct(context.Host, context, context.Ontology.MessageProvider, "保存执行失败的命令"))
                            {
                                if (requestType == MessageType.Action || context.Command.CommandType == MessageTypeKind.Received)
                                {
                                    context.Ontology.MessageProvider.SaveCommand(context.Ontology, context.Command.ToExecuteFailing(context.Result));
                                }
                                else if (requestType == MessageType.Command)
                                {
                                    context.Ontology.MessageProvider.SaveCommand(context.Ontology, context.Command.ToUnaccepted(context.Result));
                                }
                            }
                            context.Ontology.MessageProvider.DeleteCommand(context.Command.CommandType, context.Ontology, context.Command.Id, context.Command.IsDumb);
                        }
                    }
                    else
                    {
                        if (!context.Result.ResultDataItems.Any(a => a.Key.Equals("Id", StringComparison.OrdinalIgnoreCase)))
                        {
                            context.Result.ResultDataItems.Add(new DataItem("Id", context.LocalEntityId));
                        }
                        if (Verb.Get.Equals(context.Command.Verb))
                        {
                            using (var act = new WfAct(context.Host, context, context.Ontology.EntityProvider, "填充get型命令的InfoValue字段"))
                            {
                                var selectElements = new OrderedElementSet();
                                foreach (var element in context.Ontology.Elements.Values.Where(a => a.Element.IsEnabled == 1))
                                {
                                    if (context.ClientAgent.GetElementPermission(element, Verb.Get) != AllowType.NotAllow)
                                    {
                                        selectElements.Add(element);
                                    }
                                }
                                IList <InfoItem> infoValues = context.Ontology.EntityProvider.Get(
                                    context.Ontology, context.LocalEntityId, selectElements);
                                context.Result.ResultDataItems = infoValues.Select(a => new DataItem(a.Key, a.Value)).ToList();
                            }
                        }
                        var nodeHost = context.Host.NodeHost;
                        // ApplyProcessingFilters 应用处理前过滤器
                        ProcessResult result = nodeHost.ApplyEdiMessageHandingFilters(context);
                        if (!result.IsSuccess)
                        {
                            context.Result.UpdateStatus(result.StateCode, result.Description);
                        }
                        if (!context.Result.IsClosed)
                        {
                            switch (requestType)
                            {
                            case MessageType.Action:
                                HandleAction(context);
                                break;

                            case MessageType.Command:
                                HandleCommand(context);
                                break;

                            case MessageType.Event:
                                HandleEvent(context);
                                break;

                            default:
                                throw new GeneralException("意外的请求类型" + context.Command.MessageType);
                            }

                            // ApplyProcessedFilters 应用处理后过滤器
                            result = nodeHost.ApplyEdiMessageHandledFilters(context);
                            if (!result.IsSuccess)
                            {
                                context.Result.UpdateStatus(result.StateCode, result.Description);
                            }
                        }
                    }
                }
                int stateCode = context.Result.Status;
                if (stateCode < 200)
                {
                    IInfoStringConverter converter;
                    if (!context.Host.NodeHost.InfoStringConverters.TryGetInfoStringConverter(context.Command.DataTuple.InfoFormat, out converter))
                    {
                        throw new GeneralException("意外的信息格式" + context.Command.DataTuple.InfoFormat);
                    }
                    var anyLog = new AnyLog(Guid.NewGuid())
                    {
                        Req_Ontology         = context.Ontology.Ontology.Code,
                        Req_Verb             = context.Command.Verb.Code,
                        Req_ClientId         = context.Command.ClientId,
                        Req_ClientType       = context.Command.ClientType.ToName(),
                        CreateOn             = context.Command.CreateOn,
                        Req_Description      = context.Command.Description,
                        Req_EventSourceType  = context.Command.EventSourceType,
                        Req_EventSubjectCode = context.Command.EventSubjectCode,
                        InfoFormat           = context.Command.DataTuple.InfoFormat,
                        Req_InfoId           = context.Command.DataTuple.IdItems.InfoString,
                        Req_InfoValue        = context.Command.DataTuple.ValueItems.InfoString,
                        Req_UserName         = context.Command.UserName,
                        Req_IsDumb           = context.Command.IsDumb,
                        LocalEntityId        = context.Command.LocalEntityId,
                        CatalogCode          = context.Command.CatalogCode,
                        Req_ReasonPhrase     = context.Command.ReasonPhrase,
                        ReceivedOn           = context.Command.ReceivedOn,
                        Req_MessageId        = context.Command.MessageId,
                        Req_MessageType      = context.Command.MessageType.ToName(),
                        Req_QueryList        = context.Command.DataTuple.QueryListString,
                        Req_Status           = context.Command.Status,
                        Req_TimeStamp        = context.Command.TimeStamp,
                        Req_Version          = context.Command.Version,
                        Res_InfoValue        = converter.ToInfoString(context.Result.ResultDataItems),
                        Res_Description      = context.Result.Description,
                        Res_ReasonPhrase     = context.Result.ReasonPhrase,
                        Res_StateCode        = (int)context.Result.Status
                    };
                    context.Ontology.Host.LoggingService.Log(anyLog);
                }
            }
            catch (Exception ex)
            {
                context.Result.UpdateStatus(Status.InternalServerError, "服务器内部逻辑异常");
                context.Result.IsClosed = true;
                context.Exception       = ex;
                throw;
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 根据给定的本体码和信息标识获取本节点两条数据
        /// </summary>
        /// <param name="ontology">本体</param>
        /// <param name="db"></param>
        /// <param name="infoIds">多列联合信息标识字典,键必须不区分大小写</param>
        /// <param name="selectElements">选择元素</param>
        /// <returns></returns>
        private TowInfoTuple GetTop2InfoItemSet(OntologyDescriptor ontology,
                                                RdbDescriptor db, IEnumerable <InfoItem> infoIds, OrderedElementSet selectElements)
        {
            if (infoIds == null || !infoIds.Any())
            {
                return(new TowInfoTuple(null, null));
            }

            var sb            = new StringBuilder();
            var sqlParameters = new List <DbParameter>();
            var elementList   = selectElements.ToList();

            sb.Append("select top 2 ");
            int l = sb.Length;

            foreach (var element in elementList)
            {
                if (sb.Length != l)
                {
                    sb.Append(",");
                }
                sb.Append("t.[").Append(element.Element.FieldCode).Append("]");
            }
            sb.Append(" from [").Append(ontology.Ontology.EntityTableName).Append("] as t where");
            if (ontology.Ontology.IsLogicalDeletionEntity)
            {
                sb.Append(" t.DeletionStateCode=0 ");
            }
            else
            {
                sb.Append(" 1=1 ");
            }
            foreach (var element in infoIds)
            {
                sb.Append(" and t.[").Append(element.Element.Element.FieldCode)
                .Append("]=").Append("@").Append(element.Element.Element.FieldCode);
                object obj = element.Value;
                if (obj == null)
                {
                    obj = DBNull.Value;
                }
                sqlParameters.Add(CreateParameter(db, element.Element.Element.FieldCode, obj, DbType.String));
            }
            var infoValue1 = new List <InfoItem>();
            var infoValue2 = new List <InfoItem>();

            using (var reader = db.ExecuteReader(sb.ToString(), sqlParameters.ToArray()))
            {
                if (reader.Read())
                {
                    for (int i = 0; i < elementList.Count; i++)
                    {
                        infoValue1.Add(InfoItem.Create(elementList[i], reader.GetValue(i).ToString()));
                    }
                }
                if (reader.Read())
                {
                    for (int i = 0; i < elementList.Count; i++)
                    {
                        infoValue2.Add(InfoItem.Create(elementList[i], reader.GetValue(i).ToString()));
                    }
                }
                reader.Close();
            }

            return(new TowInfoTuple(infoValue1.ToArray(), infoValue2.ToArray()));
        }
Ejemplo n.º 22
0
 public TowInfoTuple GetTopTwo(
     OntologyDescriptor ontology, IEnumerable <InfoItem> infoIDs, OrderedElementSet selectElements)
 {
     return(GetTop2InfoItemSet(ontology, this.GetEntityDb(ontology), infoIDs, selectElements));
 }
Ejemplo n.º 23
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="archive"></param>
        /// <param name="localEntityId"></param>
        /// <param name="selectElements"></param>
        /// <returns></returns>
        public InfoItem[] Get(
			ArchiveState archive, string localEntityId, OrderedElementSet selectElements)
        {
            var topTwo = GetTop2InfoItemSet(archive, new InfoItem[] { InfoItem.Create(archive.Ontology.IdElement, localEntityId) }, selectElements);
            if (topTwo.BothHasValue || topTwo.BothNoValue)
            {
                return new InfoItem[0];
            }
            else
            {
                return topTwo.SingleInfoTuple;
            }
        }
Ejemplo n.º 24
0
        public ActionResult GetPlistEntity(GetPlistEntity requestModel)
        {
            if (!ModelState.IsValid)
            {
                return ModelState.ToJsonResult();
            }
            OntologyDescriptor ontology;
            if (!AcDomain.NodeHost.Ontologies.TryGetOntology(requestModel.OntologyCode, out ontology))
            {
                throw new ValidationException("非法的本体码");
            }
            if (ontology.Ontology.IsCataloguedEntity)
            {
                if (string.IsNullOrEmpty(requestModel.CatalogCode))
                {
                    throw new ValidationException("没有选中目录");
                }
                CatalogState org;
                if (!AcDomain.CatalogSet.TryGetCatalog(requestModel.CatalogCode, out org))
                {
                    throw new ValidationException("非法的目录码" + requestModel.CatalogCode);
                }
            }
            var selectElements = new OrderedElementSet();
            foreach (var element in ontology.Elements.Values.Where(a => a.Element.IsEnabled == 1))
            {
                if (element.Element != null && element.Element.IsGridColumn)
                {
                    selectElements.Add(element);
                }
            }
            if (selectElements.Count == 0)
            {
                throw new ValidationException("selectElements为空");
            }
            IDataTuples infoValues = !requestModel.ArchiveId.HasValue ? GetInfoValues(requestModel, selectElements) : GetArchivedInfoValues(requestModel);
            var data = new List<Dictionary<string, string>>();
            foreach (var row in infoValues.Tuples)
            {
                var dic = new Dictionary<string, string>();
                for (int i = 0; i < infoValues.Columns.Count; i++)
                {
                    string value;
                    if (requestModel.Translate.HasValue && requestModel.Translate.Value)
                    {
                        value = infoValues.Columns[i].TranslateValue(row[i].ToString());
                    }
                    else
                    {
                        value = row[i].ToString();
                    }
                    dic.Add(infoValues.Columns[i].Element.Code, value);
                }
                data.Add(dic);
            }

            Debug.Assert(requestModel.Total != null, "requestModel.Total != null");
            return this.JsonResult(new MiniGrid { total = requestModel.Total.Value, data = data });
        }
Ejemplo n.º 25
0
        public TowInfoTuple GetTopTwo(
			OntologyDescriptor ontology, IEnumerable<InfoItem> infoIDs, OrderedElementSet selectElements)
        {
            return GetTop2InfoItemSet(ontology, this.GetEntityDb(ontology), infoIDs, selectElements);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 获取给定实体标识列表中的标识标识的每一个实体元组
        /// </summary>
        /// <param name="ontology"></param>
        /// <param name="selectElements"></param>
        /// <param name="entityIDs"></param>
        /// <returns></returns>
        public DataTuple GetList(OntologyDescriptor ontology, OrderedElementSet selectElements, List <string> entityIDs)
        {
            if (ontology == null)
            {
                throw new ArgumentNullException("ontology");
            }
            if (selectElements == null)
            {
                throw new ArgumentNullException("selectElements");
            }
            if (entityIDs == null || entityIDs.Count == 0)
            {
                throw new ArgumentException("entityId");
            }
            var ids = new StringBuilder("(");
            int len = ids.Length;

            foreach (var id in entityIDs)
            {
                if (ids.Length != len)
                {
                    ids.Append(",");
                }
                ids.Append("'").Append(id).Append("'");
            }
            ids.Append(")");
            var tableName = ontology.Ontology.EntityTableName;

            if (selectElements.Count == 0)
            {
                selectElements.Add(ontology.Elements[ontology.IdElement.Element.Code]);
            }
            var sqlQuery = new StringBuilder("select ");
            int l        = sqlQuery.Length;

            foreach (var item in selectElements)
            {
                if (sqlQuery.Length != l)
                {
                    sqlQuery.Append(",");
                }
                sqlQuery.Append("t.[").Append(item.Element.Code).Append("]");
            }
            sqlQuery.Append(" from [").Append(tableName).Append("] as t where t.[")
            .Append(ontology.IdElement.Element.Code).Append("] in ").Append(ids.ToString());                    // TODO:参数化EntityIDs
            var list   = new List <object[]>();
            var reader = this.GetEntityDb(ontology).ExecuteReader(sqlQuery.ToString());

            while (reader.Read())
            {
                var values = new object[selectElements.Count];
                for (int i = 0; i < selectElements.Count; i++)
                {
                    values[i] = reader.GetValue(i);
                }
                list.Add(values);
            }
            reader.Close();

            return(new DataTuple(selectElements, list.ToArray()));
        }
Ejemplo n.º 27
0
        private IDataTuples GetArchivedInfoValues(GetPlistEntity requestModel)
        {
            ArchiveState archive;
            if (!requestModel.ArchiveId.HasValue || !AcDomain.NodeHost.Ontologies.TryGetArchive(requestModel.ArchiveId.Value, out archive))
            {
                throw new ValidationException("意外的归档Id");
            }
            OntologyDescriptor ontology = archive.Ontology;
            requestModel.Includedescendants = requestModel.Includedescendants ?? false;
            IDataTuples infoValues = null;
            var selectElements = new OrderedElementSet();
            foreach (var element in ontology.Elements.Values.Where(a => a.Element.IsEnabled == 1))
            {
                if (element.Element != null && element.Element.IsGridColumn)
                {
                    selectElements.Add(element);
                }
            }
            if (string.IsNullOrEmpty(requestModel.CatalogCode) && !AcSession.IsDeveloper())
            {
                throw new ValidationException("对不起,您没有查看全部数据的权限");
            }
            else
            {
                if (ontology.Ontology.IsCataloguedEntity && !string.IsNullOrEmpty(requestModel.CatalogCode))
                {
                    if (requestModel.Includedescendants.Value)
                    {
                        requestModel.Filters.Add(FilterData.Like("ZZJGM", requestModel.CatalogCode + "%"));
                    }
                    else
                    {
                        requestModel.Filters.Add(FilterData.EQ("ZZJGM", requestModel.CatalogCode));
                    }
                }
                infoValues = ontology.EntityProvider.GetPlist(
                    archive,
                    selectElements,
                    requestModel.Filters,
                    requestModel);
            }

            return infoValues;
        }
Ejemplo n.º 28
0
        private IDataTuples GetInfoValues(
			GetPlistEntity requestModel, OrderedElementSet selectElements)
        {
            OntologyDescriptor ontology;
            if (!AcDomain.NodeHost.Ontologies.TryGetOntology(requestModel.OntologyCode, out ontology))
            {
                throw new ValidationException("非法的本体码");
            }
            requestModel.Includedescendants = requestModel.Includedescendants ?? false;
            IDataTuples infoValues = null;
            if (string.IsNullOrEmpty(requestModel.CatalogCode) && !AcSession.IsDeveloper())
            {
                throw new ValidationException("对不起,您没有查看全部数据的权限");
            }
            else
            {
                if (ontology.Ontology.IsCataloguedEntity && !string.IsNullOrEmpty(requestModel.CatalogCode))
                {
                    if (requestModel.Includedescendants.Value)
                    {
                        requestModel.Filters.Add(FilterData.Like("ZZJGM", requestModel.CatalogCode + "%"));
                    }
                    else
                    {
                        requestModel.Filters.Add(FilterData.EQ("ZZJGM", requestModel.CatalogCode));
                    }
                }
                infoValues = ontology.EntityProvider.GetPlist(
                    ontology,
                    selectElements,
                    requestModel.Filters,
                    requestModel);
            }

            return infoValues;
        }
Ejemplo n.º 29
0
        public ActionResult DownloadResult(string ontologyCode, string fileName)
        {
            OntologyDescriptor ontology;
            if (!AcDomain.NodeHost.Ontologies.TryGetOntology(ontologyCode, out ontology))
            {
                throw new ValidationException("非法的本体码" + ontologyCode);
            }
            string dirPath = Server.MapPath("~/Content/Import/Excel/" + ontology.Ontology.Code + "/" + AcSession.Account.Id);
            string fullName = Path.Combine(dirPath, fileName);
            if (!System.IO.File.Exists(fullName))
            {
                throw new ValidationException("下载的文件不存在" + fullName);
            }
            // 操作Excel
            FileStream fs = System.IO.File.OpenRead(fullName);
            IWorkbook workbook = new HSSFWorkbook(fs);//从流内容创建Workbook对象
            fs.Close();

            ISheet sheet = workbook.GetSheet(ResultSheetName);
            var sheetIndex = workbook.GetSheetIndex(sheet);
            for (int i = 0; i < workbook.NumberOfSheets; i++)
            {
                if (i != sheetIndex)
                {
                    workbook.RemoveSheetAt(i);
                }
            }
            sheetIndex = workbook.GetSheetIndex("Failed");
            if (sheetIndex >= 0)
            {
                workbook.RemoveSheetAt(sheetIndex);
            }
            ISheet failedSheet = workbook.CreateSheet("Failed");
            if (sheet.LastRowNum == 2)
            {
                throw new ValidationException("没有待导入数据");
            }
            int rowIndex = 0;
            IRow headRow0 = sheet.GetRow(rowIndex);
            var columnWidthDic = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
            for (int i = 0; i < headRow0.Cells.Count; i++)
            {
                var cell = headRow0.Cells[i];
                columnWidthDic.Add(cell.SafeToStringTrim(), sheet.GetColumnWidth(i));
            }
            IRow failedRow0 = failedSheet.CreateRow(rowIndex);
            var cells = headRow0.Cells;
            for (int i = 0; i < cells.Count; i++)
            {
                var cell = failedRow0.CreateCell(i);
                cell.CellStyle = cells[i].CellStyle;
                cell.SetCellValue(cells[i].SafeToStringTrim());
            }
            rowIndex++;
            IRow headRow1 = sheet.GetRow(rowIndex);
            IRow failedRow1 = failedSheet.CreateRow(rowIndex);
            cells = headRow1.Cells;
            for (int i = 0; i < cells.Count; i++)
            {
                var cell = failedRow1.CreateCell(i);
                cell.CellStyle = cells[i].CellStyle;
                cell.SetCellValue(cells[i].SafeToStringTrim());
            }
            rowIndex++;
            IRow headRow2 = sheet.GetRow(rowIndex);
            IRow failedRow2 = failedSheet.CreateRow(rowIndex);
            cells = headRow2.Cells;
            for (int i = 0; i < cells.Count; i++)
            {
                var cell = failedRow2.CreateCell(i);
                cell.CellStyle = cells[i].CellStyle;
                cell.SetCellValue(cells[i].SafeToStringTrim());
            }
            failedSheet.CreateFreezePane(0, 3, 0, 3);
            rowIndex++;
            int resultFailedRowIndex = rowIndex;
            int stateCodeIndex = -1;
            int localEntityIdIndex = -1;
            int infoValueKeysIndex = -1;
            int infoIdKeysIndex = -1;
            for (int i = 0; i < headRow0.Cells.Count; i++)
            {
                var value = headRow0.GetCell(i).SafeToStringTrim();
                if (CommandColHeader.StateCode.Equals(value, StringComparison.OrdinalIgnoreCase))
                {
                    stateCodeIndex = i;
                    break;
                }
            }
            if (stateCodeIndex < 0)
            {
                throw new ValidationException("目标Excel中没有头为$StateCode的列");
            }
            for (int i = 0; i < headRow0.Cells.Count; i++)
            {
                var value = headRow0.GetCell(i).SafeToStringTrim();
                if (CommandColHeader.LocalEntityId.Equals(value, StringComparison.OrdinalIgnoreCase))
                {
                    localEntityIdIndex = i;
                    break;
                }
            }
            if (localEntityIdIndex < 0)
            {
                throw new ValidationException("目标Excel中没有头为$LocalEntityID的列");
            }
            for (int i = 0; i < headRow0.Cells.Count; i++)
            {
                var value = headRow0.GetCell(i).SafeToStringTrim();
                if (CommandColHeader.InfoValueKeys.Equals(value, StringComparison.OrdinalIgnoreCase))
                {
                    infoValueKeysIndex = i;
                    break;
                }
            }
            if (infoValueKeysIndex < 0)
            {
                throw new ValidationException("目标Excel中没有头为$InfoValueKeys的列");
            }
            for (int i = 0; i < headRow0.Cells.Count; i++)
            {
                var value = headRow0.GetCell(i).SafeToStringTrim();
                if (CommandColHeader.InfoIdKeys.Equals(value, StringComparison.OrdinalIgnoreCase))
                {
                    infoIdKeysIndex = i;
                    break;
                }
            }
            if (infoIdKeysIndex < 0)
            {
                throw new ValidationException("目标Excel中没有头为$InfoIDKeys的列");
            }
            string infoValueKeys = headRow1.GetCell(infoValueKeysIndex).SafeToStringTrim();
            if (string.IsNullOrEmpty(infoValueKeys))
            {
                throw new ValidationException("$InfoValueKeys单元格无值");
            }
            string infoIdKeys = headRow1.GetCell(infoIdKeysIndex).SafeToStringTrim();
            if (string.IsNullOrEmpty(infoIdKeys))
            {
                throw new ValidationException("$InfoIDKeys单元格无值");
            }
            var selectKeys = new List<string>();
            string[] keys = infoIdKeys.Split(',');
            if (keys == null || keys.Length == 0)
            {
                throw new ValidationException("$InfoIDKeys单元格内的值格式错误");
            }
            selectKeys.AddRange(keys);
            keys = infoValueKeys.Split(',');
            if (keys == null || keys.Length == 0)
            {
                throw new ValidationException("$InfoValueKeys单元格内的值格式错误");
            }
            selectKeys.AddRange(keys);
            var entityIDs = new List<string>();
            var selectElements = new OrderedElementSet();
            foreach (var key in selectKeys)
            {
                if (!ontology.Elements.ContainsKey(key))
                {
                    throw new ValidationException("Excel文件的$InfoValueKeys单元格内有非法的本体元素码" + key);
                }
                if (ontology.Elements[key].Element.IsEnabled != 1)
                {
                    continue;
                }
                selectElements.Add(ontology.Elements[key]);
            }
            if (ontology.Elements.ContainsKey("LoginName"))
            {
                if (!selectElements.Contains(ontology.Elements["LoginName"]))
                {
                    selectElements.Add(ontology.Elements["LoginName"]);
                }
            }
            for (int i = rowIndex; i <= sheet.LastRowNum; i++)
            {
                var row = sheet.GetRow(i);
                if (row != null)
                {
                    var stateCodeStr = row.GetCell(stateCodeIndex).SafeToStringTrim();
                    if (!string.IsNullOrEmpty(stateCodeStr))
                    {
                        int stateCode;
                        if (!int.TryParse(stateCodeStr, out stateCode))
                        {
                            throw new AnycmdException("文件" + fullName + "行中有意外的状态码");
                        }
                        if (stateCode >= 200 && stateCode < 300)
                        {
                            var cell = row.GetCell(localEntityIdIndex);
                            entityIDs.Add(cell.SafeToStringTrim());
                        }
                        if (stateCode < 200 || stateCode >= 300)
                        {
                            IRow resultRow = failedSheet.CreateRow(resultFailedRowIndex);
                            for (int j = 0; j < headRow0.Cells.Count; j++)
                            {
                                var cell = resultRow.CreateCell(j);
                                var oldCell = row.GetCell(j);
                                if (oldCell != null)
                                {
                                    cell.CellStyle = oldCell.CellStyle;
                                    cell.SetCellValue(oldCell.SafeToStringTrim());
                                }
                            }
                            resultFailedRowIndex++;
                        }
                    }
                    sheet.RemoveRow(row);
                }
                rowIndex++;
            }
            sheet.RemoveRow(headRow0);
            sheet.RemoveRow(headRow1);
            sheet.RemoveRow(headRow2);
            workbook.SetSheetName(workbook.GetSheetIndex(sheet), "Success");
            #region Success 数据
            rowIndex = 0;
            var headRow = sheet.CreateRow(rowIndex);
            sheet.CreateFreezePane(0, 1, 0, 1);
            rowIndex++;
            ICellStyle helderStyle = workbook.CreateCellStyle();
            IFont font = workbook.CreateFont();
            font.FontHeightInPoints = 14;
            helderStyle.SetFont(font);
            helderStyle.BorderBottom = BorderStyle.Thin;
            helderStyle.BorderLeft = BorderStyle.Thin;
            helderStyle.BorderRight = BorderStyle.Thin;
            helderStyle.BorderTop = BorderStyle.Thin;
            helderStyle.FillForegroundColor = HSSFColor.LightGreen.Index;
            helderStyle.FillPattern = FillPattern.SolidForeground;
            int cellIndex = 0;
            foreach (var element in selectElements)
            {
                ICell cell = headRow.CreateCell(cellIndex, CellType.String);
                sheet.SetColumnHidden(cellIndex, hidden: false);
                if (element.IsCodeValue)
                {
                    cell.SetCellValue(element.Element.Name + "码");
                }
                else
                {
                    cell.SetCellValue(element.Element.Name);
                }
                if (!string.IsNullOrEmpty(element.Element.Description))
                {
                    //添加批注
                    IDrawing draw = sheet.CreateDrawingPatriarch();
                    IComment comment = draw.CreateCellComment(new HSSFClientAnchor(0, 0, 0, 0, 1, 2, 4, 8));//里面参数应该是指示批注的位置大小吧
                    comment.String = new HSSFRichTextString(element.Element.Description);//添加批注内容
                    comment.Author = AcDomain.NodeHost.Nodes.ThisNode.Name;//添加批注作者
                    cell.CellComment = comment;//将之前设置的批注给定某个单元格
                }
                cell.CellStyle = helderStyle;
                if (columnWidthDic.ContainsKey(element.Element.Code) && columnWidthDic[element.Element.Code] > 0)
                {
                    sheet.SetColumnWidth(cellIndex, columnWidthDic[element.Element.Code]);
                }
                else if (element.Element.Width > 0)
                {
                    sheet.SetColumnWidth(cellIndex, element.Element.Width * 256 / 5);
                }
                if (element.IsCodeValue)
                {
                    cellIndex++;
                    ICell nameCell = headRow.CreateCell(cellIndex, CellType.String);
                    sheet.SetColumnHidden(cellIndex, hidden: false);
                    nameCell.SetCellValue(element.Element.Name + "名");
                    nameCell.CellStyle = helderStyle;
                    if (columnWidthDic.ContainsKey(element.Element.Code) && columnWidthDic[element.Element.Code] > 0)
                    {
                        sheet.SetColumnWidth(cellIndex, columnWidthDic[element.Element.Code]);
                    }
                    else if (element.Element.Width > 0)
                    {
                        sheet.SetColumnWidth(cellIndex, element.Element.Width * 256 / 5);
                    }
                }
                cellIndex++;
            }
            if (entityIDs.Count > 0)
            {
                DataTuple infoValues = ontology.EntityProvider.GetList(ontology, selectElements, entityIDs);
                foreach (var record in infoValues.Tuples)
                {
                    var row = sheet.CreateRow(rowIndex);
                    int j = 0;
                    for (int col = 0; col < infoValues.Columns.Count; col++)
                    {
                        var element = infoValues.Columns[col];
                        var item = record[col];
                        ICell cell = row.CreateCell(j, CellType.String);
                        cell.SetCellValue(item.ToString());
                        if (element.IsCodeValue)
                        {
                            j++;
                            ICell nameCell = row.CreateCell(j, CellType.String);
                            nameCell.SetCellValue(element.TranslateValue(item.ToString()));
                        }
                        j++;
                    }
                    rowIndex++;
                }
            }
            #endregion
            var filestream = new MemoryStream(); //内存文件流(应该可以写成普通的文件流)
            workbook.Write(filestream); //把文件读到内存流里面
            const string contentType = "application/vnd.ms-excel";
            fileName = fileName.Substring(0, fileName.Length - 36 - ".xls".Length);
            fileName += "_result";
            if (Request.Browser.Type.IndexOf("IE", StringComparison.OrdinalIgnoreCase) > -1)
            {
                fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
            }
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", fileName));
            Response.Clear();

            return new FileContentResult(filestream.GetBuffer(), contentType);
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 根据目录获取给定节点和本体的数据,如果传入的目录为空表示获取本节点的数据
        /// <remarks>本节点通常是中心节点</remarks>
        /// </summary>
        /// <param name="ontology"></param>
        /// <param name="db">模型</param>
        /// <param name="filters"></param>
        /// <param name="selectElements">sql select语句的选择列集合</param>
        /// <param name="pagingData"></param>
        /// <returns>
        /// 数据记录列表,数据记录表现为字典形式,键是数据元素编码值是相应数据元素对应的数据项值
        /// </returns>
        private DataTuple GetPlistInfoItems(
            OntologyDescriptor ontology,
            RdbDescriptor db, OrderedElementSet selectElements, List <FilterData> filters,
            PagingInput pagingData)
        {
            if (string.IsNullOrEmpty(pagingData.SortField))
            {
                pagingData.SortField = "IncrementId";
            }
            if (string.IsNullOrEmpty(pagingData.SortOrder))
            {
                pagingData.SortOrder = "asc";
            }

            var elements = ontology.Elements;

            if (filters != null)
            {
                for (int i = 0; i < filters.Count; i++)
                {
                    var filter = filters[i];
                    if (elements.ContainsKey(filter.field))
                    {
                        // TODO:根据数据属性优化查询,比如对于身份证件号来说如果输入的值长度
                        // 为20或18的话可以将like替换为等于
                        filter.type = "string";
                        var element = elements[filter.field];
                        if (element.Element.IsEnabled != 1)
                        {
                            continue;
                        }
                        if (element.Element.InfoDicId.HasValue)
                        {
                            filter.comparison = "eq";
                        }
                        else
                        {
                            filter.comparison = "like";
                        }
                    }
                    else
                    {
                        filters.RemoveAt(i);
                    }
                }
            }

            var tableName      = ontology.Ontology.EntityTableName;
            var sbSqlPredicate = new StringBuilder();
            var l = sbSqlPredicate.Length;

            var pQueryList = new List <DbParameter>();
            List <DbParameter> pFilters;
            var filterString = _filterStringBuilder.FilterString(db, filters, null, out pFilters);

            if (!string.IsNullOrEmpty(filterString))
            {
                foreach (var pFilter in pFilters)
                {
                    object obj = pFilter.Value;
                    if (obj == null)
                    {
                        obj = DBNull.Value;
                    }
                    var p = db.CreateParameter();
                    p.ParameterName = pFilter.ParameterName;
                    p.Value         = obj;
                    pQueryList.Add(p);
                }
                if (sbSqlPredicate.Length != l)
                {
                    sbSqlPredicate.Append(" and ");
                }
                sbSqlPredicate.Append(filterString);
            }

            string sqlPredicateString = string.Empty;

            if (sbSqlPredicate.Length > 0)
            {
                sqlPredicateString = sbSqlPredicate.ToString();
            }
            var sqlText = new StringBuilder();
            OrderedElementSet elementList;

            if (selectElements == null || selectElements.Count == 0)
            {
                elementList = new OrderedElementSet {
                    ontology.Elements["id"]
                };
            }
            else
            {
                elementList = selectElements;
            }
            sqlText.Append("SELECT TOP {0} ");
            int len = sqlText.Length;

            foreach (var element in elementList)
            {
                if (sqlText.Length != len)
                {
                    sqlText.Append(",");
                }
                sqlText.Append("[").Append(element.Element.FieldCode).Append("]");
            }

            sqlText.Append(" FROM (SELECT ROW_NUMBER() OVER(ORDER BY {1} {2}) AS RowNumber,");
            len = sqlText.Length;

            foreach (var element in elementList)
            {
                if (sqlText.Length != len)
                {
                    sqlText.Append(",");
                }
                sqlText.Append("[").Append(element.Element.FieldCode).Append("]");
            }

            sqlText.Append(" FROM {3} where ");
            if (ontology.Ontology.IsLogicalDeletionEntity)
            {
                sqlText.Append("DeletionStateCode = 0");
            }
            else
            {
                sqlText.Append("1 = 1");
            }
            if (!string.IsNullOrEmpty(sqlPredicateString))
            {
                sqlText.Append(" and ").Append(sqlPredicateString);
            }
            sqlText.Append(") a WHERE a.RowNumber > {4}");
            string sqlQuery = string.Format(
                sqlText.ToString(),
                pagingData.PageSize.ToString(CultureInfo.InvariantCulture),
                pagingData.SortField,
                pagingData.SortOrder,
                tableName,
                (pagingData.SkipCount).ToString(CultureInfo.InvariantCulture));

            pagingData.Count(() =>
            {
                string where    = ontology.Ontology.IsLogicalDeletionEntity ? "where DeletionStateCode = 0" : "";
                string sqlCount = string.Format("select count(1) from {0} {1}", tableName, where);
                if (!string.IsNullOrEmpty(sqlPredicateString))
                {
                    sqlCount = sqlCount + " and " + sqlPredicateString;
                }
                return((int)db.ExecuteScalar(
                           sqlCount, pQueryList.Select(p => ((ICloneable)p).Clone()).Cast <DbParameter>().ToArray()));
            });

            var list   = new List <object[]>();
            var reader = db.ExecuteReader(sqlQuery, pQueryList.ToArray());

            while (reader.Read())
            {
                var values = new object[elementList.Count];
                for (int i = 0; i < elementList.Count; i++)
                {
                    values[i] = reader.GetValue(i);
                }
                list.Add(values);
            }
            reader.Close();

            return(new DataTuple(elementList, list.ToArray()));
        }
Ejemplo n.º 31
0
        /// <summary>
        /// 获取给定本体码和存储标识的本节点的数据
        /// <remarks>本节点通常是中心节点</remarks>
        /// </summary>
        /// <param name="ontology">本体</param>
        /// <param name="localEntityId"></param>
        /// <param name="selectElements"></param>
        /// <returns>数据记录,表现为字典形式,键是数据元素编码值是相应数据元素对应的数据项值</returns>
        public InfoItem[] Get(
			OntologyDescriptor ontology, string localEntityId, OrderedElementSet selectElements)
        {
            var topTwo = GetTopTwo(ontology, new InfoItem[] { InfoItem.Create(ontology.IdElement, localEntityId) }, selectElements);
            if (topTwo.BothHasValue || topTwo.BothNoValue)
            {
                return new InfoItem[0];
            }
            else
            {
                return topTwo.SingleInfoTuple;
            }
        }