internal static T ExecuteGetCookie <T>(HttpRequestBase httpRequest, string cookieName, Dictionary <string, object> propertyDict, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            HttpCookie httpCookie = GetHttpCookie(httpRequest, cookieName);

            if (httpCookie == null)
            {
                return(null);
            }

            Dictionary <PropertyInfo, string> mapperDict = CommonHelper.InitPropertyReadMapper <T, CookieTAttribute>(propertyDict, (name) => httpCookie.Values[name] != null);

            dynamic propertySetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertySetDict = ReflectionExtendHelper.PropertySetCallDict <T>(reflectionType);
            }

            T t = ReflectionGenericHelper.New <T>();

            foreach (var keyValueItem in mapperDict)
            {
                if (propertySetDict != null && propertySetDict.ContainsKey(keyValueItem.Key.Name))
                {
                    ReflectionGenericHelper.SetPropertyValue(propertySetDict[keyValueItem.Key.Name], t, HttpUtility.UrlDecode(httpCookie[keyValueItem.Value]), keyValueItem.Key);
                }
                else
                {
                    ReflectionHelper.SetPropertyValue(t, HttpUtility.UrlDecode(httpCookie[keyValueItem.Value]), keyValueItem.Key);
                }
            }
            return(t);
        }
        private static void SetPropertyValueByElementList(object t, PropertyInfo propertyInfo, XmlNodeList xmlNodeList, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression)
        {
            Type itemType = ReflectionHelper.GetListGenericType(propertyInfo);

            Dictionary <PropertyInfo, XmlTAttribute> propertyNameDict = InitXmlToEntityMapper(itemType);

            dynamic propertySetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertySetDict = ReflectionExtendHelper.PropertySetCallDict(itemType, reflectionType);
            }

            var objectDataList = ReflectionHelper.NewList(itemType) as IList;

            foreach (XmlNode xmlNode in xmlNodeList)
            {
                objectDataList.Add(XmlNodeToObject(itemType, xmlNode, propertySetDict, propertyNameDict, reflectionType));
            }
            if (propertySetDict != null && propertySetDict.ContainsKey(propertyInfo.Name))
            {
                propertySetDict[propertyInfo.Name](t, objectDataList);
            }
            else
            {
                ReflectionHelper.SetPropertyValue(t, objectDataList, propertyInfo);
            }
        }
        internal static void ToSheet <T>(Workbook workbook, List <T> dataList, string sheetName, List <string> filterNameList = null, bool propertyContain = true, Dictionary <string, object> propertyDict = null, Dictionary <string, object> valueFormatDict = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            Worksheet iSheet = workbook.Worksheets[0];

            iSheet.Name = sheetName;
            // 获得表头数据
            Dictionary <string, PropertyInfo> headerColumnNameDict = CommonHelper.InitPropertyWriteMapperFormat <T, ExcelTAttribute>(propertyDict, filterNameList, propertyContain);
            Cells cellList = iSheet.Cells;

            int columnIndex = 0;

            // 遍历设置表头
            foreach (KeyValuePair <string, PropertyInfo> keyValuePair in headerColumnNameDict)
            {
                cellList[0, columnIndex].PutValue(keyValuePair.Key);
                columnIndex++;
            }

            dynamic propertyGetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertyGetDict = ReflectionExtendHelper.PropertyGetCallDict <T>(reflectionType);
            }

            if (dataList != null)
            {
                // 遍历设置数据
                for (int rowIndex = 1; rowIndex <= dataList.Count; rowIndex++)
                {
                    SetRowDataValue(cellList, rowIndex, dataList[rowIndex - 1], propertyGetDict, headerColumnNameDict, valueFormatDict);
                }
            }
        }
        /// <summary>
        /// 返回实体数据列表
        /// </summary>
        /// <typeparam name="T">泛型实体对象</typeparam>
        /// <param name="xmlDocument">XmlDocument</param>
        /// <param name="xPath">XPath 查询语句</param>
        /// <param name="reflectionType">反射类型</param>
        /// <returns></returns>
        public static List <T> ToEntityList <T>(XmlDocument xmlDocument, string xPath, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            List <T> dataList = new List <T>();

            Type type = typeof(T);

            Dictionary <PropertyInfo, XmlTAttribute> propertyNameDict = InitXmlToEntityMapper(type);

            dynamic propertySetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertySetDict = ReflectionExtendHelper.PropertySetCallDict <T>(reflectionType);
            }

            // 根据 XPath 查询 XmlNodeList 数据
            XmlNodeList xmlNodeList = xmlDocument.SelectNodes(xPath);

            foreach (XmlNode xmlNode in xmlNodeList)
            {
                dataList.Add(XmlNodeToEntity <T>(xmlNode, propertySetDict, propertyNameDict, reflectionType));
            }

            return(dataList);
        }
        internal static DataTable ExecuteToDataTable <T>(List <T> dataList, Dictionary <string, object> propertyDict, List <string> propertyList = null, bool propertyContain = true, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class
        {
            Dictionary <string, string> columnNameList = CommonHelper.InitPropertyWriteMapper <T, DataTableTAttribute>(propertyDict, propertyList, propertyContain);

            DataTable dataTable = new DataTable();

            // 遍历设置标题
            foreach (KeyValuePair <string, string> keyValuePair in columnNameList)
            {
                dataTable.Columns.Add(keyValuePair.Key);
            }

            dynamic propertyGetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertyGetDict = ReflectionExtendHelper.PropertyGetCallDict <T>(reflectionType);
            }

            DataRow dataRow = null;

            // 遍历数据并设置到 DataTable
            foreach (T t in dataList)
            {
                dataRow = dataTable.NewRow();
                SetRowDataValue(dataRow, t, propertyGetDict, columnNameList);
                dataTable.Rows.Add(dataRow);
            }
            return(dataTable);
        }
Example #6
0
        private static List <T> ToEntityListNormal <T>(HtmlDocument htmlDocument, string xPath, List <XPathMatch> xPathMatchList = null, object propertyMatchList = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            HtmlNode documentNode = htmlDocument.DocumentNode;

            if (documentNode == null)
            {
                return(null);
            }

            List <T> dataList = new List <T>();

            dynamic propertySetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertySetDict = ReflectionExtendHelper.PropertySetCallDict <T>(reflectionType);
            }

            Dictionary <PropertyInfo, HtmlAttributeMapperItem> attributeMapperDict = GetAttributeMapperDict <T>(propertyMatchList);

            HtmlNodeCollection htmlNodeCollection = documentNode.SelectNodes(xPath);

            if (htmlNodeCollection == null || htmlNodeCollection.Count == 0)
            {
                return(null);
            }

            Dictionary <PropertyInfo, XPathMatch> propertyInfoXPathDict = new Dictionary <PropertyInfo, XPathMatch>();

            XPathMatch matchItem = null;

            foreach (HtmlNode htmlNode in htmlNodeCollection)
            {
                T t = new T();
                ReflectionGenericHelper.Foreach <T>((PropertyInfo propertyInfo) =>
                {
                    matchItem = null;
                    if (propertyInfoXPathDict.ContainsKey(propertyInfo))
                    {
                        matchItem = propertyInfoXPathDict[propertyInfo];
                    }
                    else
                    {
                        matchItem = xPathMatchList.Where(p => p.PropertyName == propertyInfo.Name).FirstOrDefault();
                        if (matchItem != null)
                        {
                            propertyInfoXPathDict.Add(propertyInfo, matchItem);
                        }
                    }
                    if (matchItem != null)
                    {
                        HtmlNode childHtmlNode = htmlNode.SelectSingleNode(matchItem.XPath);
                        SetEntityValue <T>(t, childHtmlNode, propertyInfo, attributeMapperDict[propertyInfo], propertySetDict);
                    }
                });
                dataList.Add(t);
            }
            return(dataList);
        }
        /// <summary>
        /// 查询数据
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="queryFieldList">查询字段列表</param>
        /// <param name="search">搜索内容</param>
        /// <param name="filter">Filter</param>
        /// <param name="sortField">排序字段,例:"id desc"</param>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="reflectionType">反射类型</param>
        /// <returns></returns>
        public static List <T> Query <T>(string[] queryFieldList, string search, Filter filter, string sortField, int pageIndex, int pageSize, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            IndexSearcher indexSearcher = null;

            try
            {
                List <T> dataList = new List <T>();

                BooleanQuery booleanQuery = new BooleanQuery();
                if (!string.IsNullOrEmpty(search))
                {
                    QueryParser queryParser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_29, queryFieldList, new PanGuAnalyzer());
                    Query       query       = queryParser.Parse(search);
                    booleanQuery.Add(query, Lucene.Net.Search.BooleanClause.Occur.MUST);
                }

                indexSearcher = new IndexSearcher(IndexDictDirectory, true);

                bool     desc          = false;
                string[] sortFieldList = sortField.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                if (sortFieldList != null && sortFieldList.Length == 2 && sortFieldList[1] == DESC)
                {
                    desc = true;
                }

                Sort sort = new Sort(new SortField(sortField, SortField.DOC, desc));

                dynamic propertySetDict = null;
                if (reflectionType != ReflectionTypeEnum.Original)
                {
                    ReflectionExtendHelper.PropertySetCallDict <T>(reflectionType);
                }

                TopDocs topDocs = indexSearcher.Search(booleanQuery, filter, pageIndex * pageSize, sort);
                if (topDocs != null && topDocs.totalHits > 0)
                {
                    Document document = null;
                    for (int i = 0; i < topDocs.totalHits; i++)
                    {
                        document = indexSearcher.Doc(topDocs.scoreDocs[i].doc);
                        dataList.Add(DocumentToEntity <T>(document, propertySetDict));
                    }
                }
                indexSearcher.Close();
                return(dataList);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (indexSearcher != null)
                {
                    indexSearcher.Close();
                }
            }
        }
Example #8
0
        /// <summary>
        /// 复制数据
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="originalData">原实体数据</param>
        /// <param name="propertyMatchList">属性匹配,例:new { ID = "UserID" }</param>
        /// <param name="propertyIgnore">忽略属性列表,例:new { ID = "" }</param>
        /// <param name="reflectionType">反射类型</param>
        /// <returns></returns>
        public static T Copy <T>(object originalData, object propertyMatchList = null, object propertyIgnore = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            Dictionary <PropertyInfo, string> propertyMatchDict = InitPropertyMatchMapper(originalData.GetType(), typeof(T), propertyMatchList, propertyIgnore);

            dynamic propertyGetDict = ReflectionExtendHelper.PropertyGetCallDict(originalData.GetType(), reflectionType);
            dynamic propertySetDict = ReflectionExtendHelper.PropertySetCallDict <T>(reflectionType);

            return(CopyData(typeof(T), propertySetDict, propertyGetDict, propertyMatchDict, originalData, propertyMatchList, propertyIgnore, reflectionType) as T);
        }
Example #9
0
        /// <summary>
        /// 复制数据
        /// </summary>
        /// <param name="originalData">原实体数据</param>
        /// <param name="targetData">目标实体数据</param>
        /// <param name="propertyMatchList">属性匹配,例:new { ID = "UserID" }</param>
        /// <param name="propertyIgnore">忽略属性列表,例:new { ID = "" }</param>
        /// <param name="reflectionType">反射类型</param>
        /// <returns></returns>
        public static dynamic Copy(object originalData, object targetData, object propertyMatchList = null, object propertyIgnore = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression)
        {
            Dictionary <PropertyInfo, string> propertyMatchDict = InitPropertyMatchMapper(originalData.GetType(), targetData.GetType(), propertyMatchList, propertyIgnore);

            dynamic propertyGetDict = ReflectionExtendHelper.PropertyGetCallDict(originalData.GetType(), reflectionType);
            dynamic propertySetDict = ReflectionExtendHelper.PropertySetCallDict(targetData.GetType(), reflectionType);

            object copyData = CopyData(targetData, propertySetDict, propertyGetDict, propertyMatchDict, originalData, propertyMatchList, propertyIgnore, reflectionType);

            return(Convert.ChangeType(copyData, targetData.GetType()));
        }
        internal static List <T> SheetEntityList <T>(Workbook workbook, string sheetName, Dictionary <string, string> propertyDict = null, int headerIndex = 0, int dataIndex = 1, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            List <T> dataList = new List <T>();

            Worksheet sheet    = workbook.Worksheets[sheetName];
            Cells     cellList = sheet.Cells;

            Dictionary <int, TExcelToEntityColumnMapper> excelToEntityMapperList = InitExcelToEntityMapper <T>(headerIndex, cellList, propertyDict);

            dynamic propertySetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertySetDict = ReflectionExtendHelper.PropertySetCallDict <T>(reflectionType);
            }

            int rowCount  = cellList.MaxDataRow + 1;
            int cellCount = cellList.MaxColumn + 1;

            for (int index = dataIndex; index < rowCount; index++)
            {
                T t = new T();
                for (int cellIndex = 0; cellIndex < cellCount; cellIndex++)
                {
                    if (excelToEntityMapperList.ContainsKey(cellIndex))
                    {
                        TExcelToEntityColumnMapper columnMapper = excelToEntityMapperList[cellIndex];

                        Cell cell = cellList[index, cellIndex];
                        if (cell != null && cell.Value != null)
                        {
                            if (propertySetDict != null && propertySetDict.ContainsKey(columnMapper.ColumnPropertyName))
                            {
                                ReflectionGenericHelper.SetPropertyValue(propertySetDict[columnMapper.ColumnPropertyName], t, cell.StringValue, columnMapper.ColumnPropertyInfo);
                            }
                            else
                            {
                                ReflectionHelper.SetPropertyValue(t, cell.StringValue, columnMapper.ColumnPropertyInfo);
                            }
                        }
                    }
                }
                dataList.Add(t);
            }

            return(dataList);
        }
        internal static List <T> SheetEntityList <T>(IWorkbook workbook, string sheetName, Dictionary <string, object> propertyDict = null, int headerIndex = 0, int dataIndex = 1, string primaryKey = "", ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            List <T> dataList = new List <T>();

            ISheet sheet = workbook.GetSheet(sheetName);

            if (sheet == null)
            {
                throw new Exception(string.Format(ExcelSheetNullException, sheetName));
            }

            bool isHeader  = headerIndex != dataIndex;
            IRow headerRow = sheet.GetRow(headerIndex);

            int primaryIndex = 0;

            Dictionary <PropertyInfo, ExcelToEntityColumnMapper> excelToEntityMapperList = InitExcelToEntityMapper <T>(headerRow, isHeader, primaryKey, ref primaryIndex, propertyDict);

            dynamic propertySetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertySetDict = ReflectionExtendHelper.PropertySetCallDict <T>(reflectionType);
            }

            List <ExcelMergeCell> mergeCellList = SheetMergeCellList(sheet);

            IRow  row   = null;
            ICell iCell = null;

            for (int index = dataIndex; index <= sheet.LastRowNum; index++)
            {
                row = sheet.GetRow(index);
                if (row != null)
                {
                    iCell = row.GetCell(primaryIndex);
                    // 检查主键列是否有数据
                    if (iCell != null && !string.IsNullOrEmpty(iCell.ToString()))
                    {
                        dataList.Add(IRowToEntity <T>(index, row, propertySetDict, excelToEntityMapperList, mergeCellList));
                    }
                }
            }

            return(dataList);
        }
Example #12
0
        private static Dictionary <int, PropertyInfo> InitEntityToTxtMapper <T>(object propertyMatchList = null, TxtTypeEnum typeEnum = TxtTypeEnum.Normal, string[] propertyList = null, bool propertyContain = true) where T : class
        {
            List <string> filterNameList = null;

            if (propertyList != null)
            {
                filterNameList = propertyList.ToList <string>();
            }

            int propertyIndex = 0;

            Dictionary <string, object>    propertyMatchDict = CommonHelper.GetParameterDict(propertyMatchList);
            Dictionary <int, PropertyInfo> propertyNameDict  = new Dictionary <int, PropertyInfo>();

            ReflectionGenericHelper.Foreach <T>((PropertyInfo propertyInfo) =>
            {
                if (filterNameList == null || (propertyContain && filterNameList.IndexOf(propertyInfo.Name) >= 0) || (!propertyContain && filterNameList.IndexOf(propertyInfo.Name) < 0))
                {
                    if (propertyMatchDict != null && propertyMatchDict.ContainsKey(propertyInfo.Name))
                    {
                        propertyNameDict.Add(int.Parse(propertyMatchDict[propertyInfo.Name].ToString()), propertyInfo);
                    }
                    else
                    {
                        if (typeEnum == TxtTypeEnum.Attribute)
                        {
                            TxtTAttribute attribute = propertyInfo.GetCustomAttribute <TxtTAttribute>();
                            if (attribute != null && (attribute.Type == AttributeReadAndWriteTypeEnum.ReadAndWrite || attribute.Type == AttributeReadAndWriteTypeEnum.Write))
                            {
                                object attributeIndex = ReflectionExtendHelper.GetAttributeValue <TxtTAttribute>(typeof(T), propertyInfo, p => p.Index);
                                if (attributeIndex != null)
                                {
                                    propertyNameDict.Add(int.Parse(attributeIndex.ToString()), propertyInfo);
                                }
                            }
                        }
                        else
                        {
                            propertyNameDict.Add(propertyIndex, propertyInfo);
                            propertyIndex++;
                        }
                    }
                }
            });
            return(propertyNameDict);
        }
Example #13
0
        private static Dictionary <PropertyInfo, string> InitDbToEntityMapper <T>(DbDataReader reader, object propertyMatchList = null) where T : class
        {
            Dictionary <PropertyInfo, string> resultDict = new Dictionary <PropertyInfo, string>();

            if (propertyMatchList != null)
            {
                Dictionary <string, object> propertyMatchDict = CommonHelper.GetParameterDict(propertyMatchList);
                ReflectionGenericHelper.Foreach <T>((PropertyInfo propertyInfo) =>
                {
                    string columnName    = propertyInfo.Name;
                    object propertyValue = propertyMatchDict[propertyInfo.Name];
                    if (propertyValue != null)
                    {
                        columnName = propertyValue.ToString();
                    }
                    resultDict.Add(propertyInfo, columnName);
                });
                return(resultDict);
            }

            string key = typeof(T).FullName;

            if (PropertyAttributeDict.ContainsKey(key))
            {
                return(PropertyAttributeDict[key]);
            }

            lock (lockItem)
            {
                ReflectionGenericHelper.Foreach <T>((PropertyInfo propertyInfo) =>
                {
                    string columnName = ReflectionExtendHelper.GetAttributeValue <DataBaseTAttribute>(typeof(T), propertyInfo, p => p.Name);
                    if (string.IsNullOrEmpty(columnName))
                    {
                        columnName = propertyInfo.Name;
                    }
                    resultDict.Add(propertyInfo, columnName);
                });
                if (!PropertyAttributeDict.ContainsKey(key))
                {
                    PropertyAttributeDict.Add(key, resultDict);
                }
                return(resultDict);
            }
        }
Example #14
0
        internal static void ToSheet <T>(IWorkbook workbook, List <T> dataList, string sheetName, Action <ICell, object> cellCallback = null, Action <ISheet, List <string> > sheetCallback = null, bool isHeader = true, List <string> filterNameList = null, bool propertyContain = true, Dictionary <string, object> propertyDict = null, Dictionary <string, object> valueFormatDict = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            ISheet iSheet = workbook.CreateSheet(sheetName);
            // 获得表头数据
            Dictionary <string, PropertyInfo> headerColumnNameDict = CommonHelper.InitPropertyWriteMapperFormat <T, ExcelTAttribute>(propertyDict, filterNameList, propertyContain);

            int dataIndex = 0;

            if (isHeader)
            {
                IRow headerRow   = iSheet.CreateRow(dataIndex);
                int  columnIndex = 0;
                // 遍历设置表头
                foreach (KeyValuePair <string, PropertyInfo> keyValuePair in headerColumnNameDict)
                {
                    headerRow.CreateCell(columnIndex).SetCellValue(keyValuePair.Key);
                    columnIndex++;
                }
                dataIndex = 1;
            }

            dynamic propertyGetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertyGetDict = ReflectionExtendHelper.PropertyGetCallDict <T>(reflectionType);
            }

            IRow row = null;

            if (dataList != null)
            {
                // 遍历设置数据
                for (int rowIndex = 0; rowIndex < dataList.Count; rowIndex++, dataIndex++)
                {
                    row = iSheet.CreateRow(dataIndex);
                    SetRowDataValue(row, cellCallback, dataList[rowIndex], propertyGetDict, headerColumnNameDict, valueFormatDict);
                }
            }
            if (sheetCallback != null)
            {
                sheetCallback(iSheet, headerColumnNameDict.Keys.ToList());
            }
        }
        internal static void ExecuteSetCookie <T>(HttpResponseBase httpResponse, string cookieName, T data, DateTime expires, Dictionary <string, object> propertyDict, List <string> propertyList, bool propertyContain = true, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class
        {
            Dictionary <string, string> cookieNameDict = CommonHelper.InitPropertyWriteMapper <T, CookieTAttribute>(propertyDict, propertyList, propertyContain);

            dynamic propertyGetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertyGetDict = ReflectionExtendHelper.PropertyGetCallDict <T>(reflectionType);
            }

            HttpCookie httpCookie = new HttpCookie(cookieName);

            httpCookie.HttpOnly = true;
            httpCookie.Expires  = expires;

            object cookieValue = null;

            foreach (KeyValuePair <string, string> keyValueItem in cookieNameDict)
            {
                if (propertyGetDict != null && propertyGetDict.ContainsKey(keyValueItem.Value))
                {
                    cookieValue = propertyGetDict[keyValueItem.Value](data);
                }
                else
                {
                    cookieValue = ReflectionHelper.GetPropertyValue(data, keyValueItem.Value);
                }
                if (cookieValue != null)
                {
                    httpCookie.Values.Add(keyValueItem.Key, HttpUtility.UrlEncode(cookieValue.ToString()));
                }
            }

            if (httpResponse != null)
            {
                httpResponse.Cookies.Add(httpCookie);
            }
            else
            {
                HttpContext.Current.Response.Cookies.Add(httpCookie);
            }
        }
        internal static List <T> ExecuteToEntityList <T>(DataTable dataTable, Dictionary <string, object> propertyDict, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            Dictionary <PropertyInfo, string> columnNameDict = CommonHelper.InitPropertyReadMapper <T, DataTableTAttribute>(propertyDict, (name) => dataTable.Columns.Contains(name));

            List <T> dataList = new List <T>();

            dynamic propertySetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertySetDict = ReflectionExtendHelper.PropertySetCallDict <T>(reflectionType);
            }

            // 读取 DataTable 数据到实体对象列表中
            foreach (DataRow dataRow in dataTable.Rows)
            {
                dataList.Add(DataRowToEntity <T>(dataRow, propertySetDict, columnNameDict));
            }
            return(dataList);
        }
        private static void ExecuteSetValue <T>(Action <List <string>, dynamic, XmlNode, string> callback, string xmlPath, string xPath, XmlDocument xmlDocument, string[] propertyList = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class
        {
            List <string> filterNameList = null;

            if (propertyList != null && propertyList.Length > 0)
            {
                filterNameList = propertyList.ToList();
            }

            dynamic propertyGetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertyGetDict = ReflectionExtendHelper.PropertyGetCallDict <T>(reflectionType);
            }

            XmlNode xmlNode = GetNode(xPath, xmlDocument);

            if (xmlNode == null)
            {
                return;
            }

            string elementName = ReflectionExtendHelper.GetAttributeValue <XmlTAttribute>(typeof(T), p => p.Name);

            if (elementName == null)
            {
                elementName = typeof(T).Name;
            }

            if (callback != null)
            {
                callback(filterNameList, propertyGetDict, xmlNode, elementName);
            }

            if (!string.IsNullOrEmpty(xPath))
            {
                xmlDocument.Save(xmlPath);
            }
        }
Example #18
0
        private static List <T> ToEntityListStrict <T>(HtmlDocument htmlDocument, string xPath, List <XPathMatch> xPathMatchList = null, object propertyMatchList = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            HtmlNode documentNode = htmlDocument.DocumentNode;

            if (documentNode == null)
            {
                return(null);
            }

            List <T> dataList = new List <T>();

            HtmlNodeCollection htmlNodeCollection = documentNode.SelectNodes(xPath);

            if (htmlNodeCollection == null || htmlNodeCollection.Count == 0)
            {
                return(null);
            }

            Dictionary <string, List <HtmlNode> > propertyNodeDict = GetXPathNodeDict(documentNode, xPathMatchList, htmlNodeCollection.Count);

            dynamic propertySetDict = null;

            if (reflectionType != ReflectionTypeEnum.Original)
            {
                propertySetDict = ReflectionExtendHelper.PropertySetCallDict <T>(reflectionType);
            }

            Dictionary <PropertyInfo, HtmlAttributeMapperItem> attributeMapperDict = GetAttributeMapperDict <T>(propertyMatchList);

            int index = 0;

            foreach (HtmlNode mathHtmlNode in htmlNodeCollection)
            {
                dataList.Add(HtmlNodeToEntity <T>(mathHtmlNode, index, propertyNodeDict, propertySetDict, attributeMapperDict));
                index++;
            }
            return(dataList);
        }
Example #19
0
        private static List <T> DataReaderToEntityList <T>(DbCommand command, object propertyMatchList = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            List <T> dataList = new List <T>();

            bool          initStatus     = false;
            List <string> columnNameList = null;
            Dictionary <PropertyInfo, string> columnNameDict = null;

            using (DbDataReader dataReader = command.ExecuteReader(CommandBehavior.CloseConnection))
            {
                dynamic propertySetDict = null;
                if (reflectionType != ReflectionTypeEnum.Original)
                {
                    propertySetDict = ReflectionExtendHelper.PropertySetCallDict <T>(reflectionType);
                }

                if (dataReader.Read())
                {
                    if (!initStatus)
                    {
                        columnNameList = new List <string>();
                        for (int index = 0; index < dataReader.FieldCount; index++)
                        {
                            columnNameList.Add(dataReader.GetName(index));
                        }
                        columnNameDict = InitDbToEntityMapper <T>(dataReader, propertyMatchList);
                        initStatus     = true;
                    }
                    dataList.Add(DataReaderToEntity <T>(dataReader, propertySetDict, columnNameList, columnNameDict));
                }
                while (dataReader.Read())
                {
                    dataList.Add(DataReaderToEntity <T>(dataReader, propertySetDict, columnNameList, columnNameDict));
                }
            }
            return(dataList);
        }
Example #20
0
        /// <summary>
        /// 实体对象数据写入 Txt
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="txtPath">Txt 路径</param>
        /// <param name="dataList">实体数据列表</param>
        /// <param name="splitChar">列分隔符,例:|</param>
        /// <param name="typeEnum">TxtTypeEnum 枚举类型</param>
        /// <param name="encoding">编码格式</param>
        /// <param name="propertyMatchList">属性匹配,Dictionary&lt;string, object&gt; 或 new {}</param>
        /// <param name="propertyList">属性列表,如果指定,则按指定属性列表生成文本数据</param>
        /// <param name="lineSplitChar">行分隔符,例:\r\n</param>
        /// <param name="reflectionType">反射类型</param>
        /// <returns></returns>
        public static bool ToTxt <T>(string txtPath, List <T> dataList, string splitChar, System.Text.Encoding encoding, TxtTypeEnum typeEnum, object propertyMatchList = null, string[] propertyList = null, bool propertyContain = true, string lineSplitChar = NewLine, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class
        {
            bool result = ExecuteStreamWriter(txtPath, encoding, false, () =>
            {
                StringBuilder stringBuilder = new StringBuilder();

                Dictionary <int, PropertyInfo> propertyNameDict = InitEntityToTxtMapper <T>(propertyMatchList, typeEnum, propertyList, propertyContain);
                List <int> propertyIndexList = propertyNameDict.Keys.ToList <int>();

                propertyIndexList.Sort((int x, int y) =>
                {
                    if (x > y)
                    {
                        return(1);
                    }
                    if (x < y)
                    {
                        return(-1);
                    }
                    return(0);
                });

                dynamic propertyGetDict = null;
                if (reflectionType != ReflectionTypeEnum.Original)
                {
                    propertyGetDict = ReflectionExtendHelper.PropertyGetCallDict <T>(reflectionType);
                }

                foreach (T t in dataList)
                {
                    stringBuilder.Append(EntityToText <T>(t, splitChar, propertyGetDict, propertyNameDict, propertyIndexList, lineSplitChar));
                }
                return(stringBuilder.ToString());
            });

            return(result);
        }
Example #21
0
        /// <summary>
        /// 返回实体数据列表
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="txtPath">Txt 路径</param>
        /// <param name="splitChar">列分隔符,例:|</param>
        /// <param name="encoding">编码格式</param>
        /// <param name="propertyMatchList">属性匹配,Dictionary&lt;string, object&gt; 或 new {}</param>
        /// <param name="typeEnum">TxtTypeEnum 枚举类型</param>
        /// <param name="lineSplitChar">行分隔符,例:\r\n</param>
        /// <param name="reflectionType">反射类型</param>
        /// <returns></returns>
        public static List <T> ToEntityList <T>(string txtPath, string splitChar, System.Text.Encoding encoding, object propertyMatchList = null, TxtTypeEnum typeEnum = TxtTypeEnum.Normal, string lineSplitChar = NewLine, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class, new()
        {
            List <T> dataList = new List <T>();

            ExecuteStreamReader(txtPath, encoding, (StreamReader streamReader) =>
            {
                Dictionary <string, object> propertyDict        = CommonHelper.GetParameterDict(propertyMatchList);
                Dictionary <PropertyInfo, int> propertyNameDict = InitTxtToEntityMapper <T>(propertyDict, typeEnum);

                dynamic propertySetDict = null;
                if (reflectionType != ReflectionTypeEnum.Original)
                {
                    propertySetDict = ReflectionExtendHelper.PropertySetCallDict <T>(reflectionType);
                }

                string content       = streamReader.ReadToEnd();
                string[] contentList = content.Split(new string[] { lineSplitChar }, StringSplitOptions.None);
                foreach (string contentItem in contentList)
                {
                    dataList.Add(TextToEntity <T>(contentItem, splitChar, propertySetDict, propertyNameDict));
                }
            });
            return(dataList);
        }
        private static object XmlNodeToObject(Type type, XmlNode xmlNode, dynamic propertySetDict, Dictionary <PropertyInfo, XmlTAttribute> propertyNameDict, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression)
        {
            object t = ReflectionHelper.New(type);

            if (propertyNameDict == null)
            {
                propertyNameDict = InitXmlToEntityMapper(type);
            }
            if (propertySetDict == null)
            {
                if (reflectionType != ReflectionTypeEnum.Original)
                {
                    propertySetDict = ReflectionExtendHelper.PropertySetCallDict(type, reflectionType);
                }
            }

            foreach (var keyValueItem in propertyNameDict)
            {
                XmlNodeList childXmlNodeList = null;
                string      propertyValue    = null;

                switch (keyValueItem.Value.NameType)
                {
                case XmlTEnum.Attribute:
                    // 如果是获得 XmlNode 属性值
                    if (xmlNode.Attributes[keyValueItem.Value.Name] != null)
                    {
                        propertyValue = xmlNode.Attributes[keyValueItem.Value.Name].Value;
                    }
                    ; break;

                case XmlTEnum.Text:
                    // 如果是获得 XmlNode 的 Text 数据
                    propertyValue = xmlNode.InnerText;
                    break;

                case XmlTEnum.Xml:
                    // 如果是获得 XmlNode 的子元素数据
                    propertyValue = xmlNode.InnerXml;
                    break;

                case XmlTEnum.Element:
                case XmlTEnum.ElementList:
                    // 如果是元素或者元素列表
                    childXmlNodeList = xmlNode.SelectNodes("descendant::" + keyValueItem.Value.Name);
                    break;
                }

                if (keyValueItem.Value.NameType == XmlTEnum.Element)
                {
                    SetPropertyValueByElement(t, keyValueItem.Key, childXmlNodeList, propertySetDict, reflectionType);
                }
                else if (keyValueItem.Value.NameType == XmlTEnum.ElementList)
                {
                    SetPropertyValueByElementList(t, keyValueItem.Key, childXmlNodeList, reflectionType);
                }
                else
                {
                    if (propertySetDict != null && propertySetDict.ContainsKey(keyValueItem.Key.Name))
                    {
                        ReflectionGenericHelper.SetPropertyValue(propertySetDict[keyValueItem.Key.Name], t, propertyValue, keyValueItem.Key);
                    }
                    else
                    {
                        ReflectionHelper.SetPropertyValue(t, propertyValue, keyValueItem.Key);
                    }
                }
            }

            return(t);
        }
Example #23
0
        private static object CopyData(object targetData, dynamic propertySetDict, dynamic propertyGetDict, Dictionary <PropertyInfo, string> propertyMatchDict, dynamic originalData, object propertyMatch = null, object propertyIgnore = null, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression)
        {
            if (originalData == null)
            {
                return(targetData);
            }

            PropertyInfo propertyInfo  = null;
            dynamic      propertyValue = null;

            foreach (var keyValueItem in propertyMatchDict)
            {
                propertyInfo = keyValueItem.Key;
                if (propertyGetDict != null && propertyGetDict.ContainsKey(keyValueItem.Value))
                {
                    propertyValue = propertyGetDict[keyValueItem.Value](originalData);
                }
                else
                {
                    propertyValue = ReflectionHelper.GetPropertyValue(originalData, keyValueItem.Value);
                }
                if (propertyValue != null)
                {
                    if (ReflectionHelper.IsListType(propertyInfo.PropertyType))
                    {
                        Type originalTType = ReflectionHelper.GetListGenericType(originalData.GetType().GetProperty(keyValueItem.Value));
                        var  originalPropertyMatchValue  = ReflectionHelper.GetPropertyValue(propertyMatch, propertyInfo.Name);
                        var  originalPropertyIgnoreValue = ReflectionHelper.GetPropertyValue(propertyIgnore, propertyInfo.Name);
                        var  originalPropertyValue       = ReflectionHelper.GetPropertyValue(targetData, propertyInfo) as IList;

                        Type listTType      = ReflectionHelper.GetListGenericType(propertyInfo);
                        var  objectDataList = ReflectionHelper.NewList(listTType) as IList;

                        dynamic listPropertySetDict = null;
                        if (reflectionType != ReflectionTypeEnum.Original)
                        {
                            listPropertySetDict = ReflectionExtendHelper.PropertySetCallDict(listTType, reflectionType);
                        }

                        dynamic listPropertyGetDict = null;
                        if (reflectionType != ReflectionTypeEnum.Original)
                        {
                            listPropertyGetDict = ReflectionExtendHelper.PropertyGetCallDict(originalTType, reflectionType);
                        }

                        for (int index = 0; index < propertyValue.Count; index++)
                        {
                            if (originalPropertyValue != null && index < originalPropertyValue.Count)
                            {
                                objectDataList.Add(CopyData(originalPropertyValue[index], listPropertySetDict, listPropertyGetDict, InitPropertyMatchMapper(originalTType, listTType, originalPropertyMatchValue, originalPropertyIgnoreValue), propertyValue[index], originalPropertyMatchValue, originalPropertyIgnoreValue, reflectionType));
                            }
                            else
                            {
                                objectDataList.Add(CopyData(listTType, listPropertySetDict, listPropertyGetDict, InitPropertyMatchMapper(originalTType, listTType, originalPropertyMatchValue, originalPropertyIgnoreValue), propertyValue[index], originalPropertyMatchValue, originalPropertyIgnoreValue, reflectionType));
                            }
                        }
                        targetData.GetType().GetProperty(propertyInfo.Name).SetValue(targetData, objectDataList, null);
                    }
                    else if (ReflectionHelper.IsCustomType(propertyInfo.PropertyType))
                    {
                        var originalPropertyMatchValue  = ReflectionHelper.GetPropertyValue(propertyMatch, propertyInfo.Name);
                        var originalPropertyIgnoreValue = ReflectionHelper.GetPropertyValue(propertyIgnore, propertyInfo.Name);
                        var originalPropertyValue       = ReflectionHelper.GetPropertyValue(targetData, propertyInfo);

                        if (originalPropertyValue == null)
                        {
                            targetData.GetType().GetProperty(propertyInfo.Name).SetValue(targetData, CopyData(propertyInfo.PropertyType, null, null, InitPropertyMatchMapper(propertyValue.GetType(), propertyInfo.PropertyType, originalPropertyMatchValue, originalPropertyIgnoreValue), propertyValue, originalPropertyMatchValue, originalPropertyIgnoreValue, reflectionType), null);
                        }
                        else
                        {
                            targetData.GetType().GetProperty(propertyInfo.Name).SetValue(targetData, CopyData(originalPropertyValue, null, null, InitPropertyMatchMapper(propertyValue.GetType(), propertyInfo.PropertyType, originalPropertyMatchValue, originalPropertyIgnoreValue), propertyValue, originalPropertyMatchValue, originalPropertyIgnoreValue, reflectionType), null);
                        }
                    }
                    else
                    {
                        if (propertySetDict != null && propertySetDict.ContainsKey(propertyInfo.Name))
                        {
                            ReflectionGenericHelper.SetPropertyValue(propertySetDict[propertyInfo.Name], targetData, propertyValue.ToString(), propertyInfo);
                        }
                        else
                        {
                            ReflectionHelper.SetPropertyValue(targetData, propertyValue.ToString(), propertyInfo);
                        }
                    }
                }
            }
            return(targetData);
        }
        private static bool ExecuteSet <T>(List <T> dataList, string primaryKey = "", List <string> propertyList = null, int maxBufferedDocs = 1000, int maxMergeFactory = 1000, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class
        {
            IndexWriter indexWriter = null;
            IndexWriter RAMWriter   = null;

            try
            {
                RAMDirectory = new RAMDirectory();

                bool create = IndexReader.IndexExists(IndexDictDirectory);
                if (create)
                {
                    if (IndexWriter.IsLocked(IndexDictDirectory))
                    {
                        IndexWriter.Unlock(IndexDictDirectory);
                    }
                }

                dynamic propertyGetDict = null;
                if (reflectionType != ReflectionTypeEnum.Original)
                {
                    propertyGetDict = ReflectionExtendHelper.PropertyGetCallDict <T>(reflectionType);
                }

                indexWriter = new IndexWriter(IndexDictDirectory, new PanGuAnalyzer(), !create, IndexWriter.MaxFieldLength.LIMITED);
                RAMWriter   = new IndexWriter(RAMDirectory, new PanGuAnalyzer(), true, IndexWriter.MaxFieldLength.LIMITED);

                RAMWriter.SetMaxBufferedDocs(maxBufferedDocs);
                RAMWriter.SetMergeFactor(maxMergeFactory);

                List <List <LuceneIndexModel> > modelList = EntityListToLuceneIndexModelList(dataList, propertyGetDict, propertyList);

                Document document     = null;
                Term     term         = null;
                string   primaryValue = null;

                foreach (List <LuceneIndexModel> model in modelList)
                {
                    document = new Document();
                    foreach (LuceneIndexModel fieldModel in model)
                    {
                        if (fieldModel.Name == primaryKey)
                        {
                            primaryValue = fieldModel.Value;
                        }
                        document.Add(new Field(fieldModel.Name, fieldModel.Value, fieldModel.StoreEnum, fieldModel.IndexEnum));
                    }
                    if (string.IsNullOrEmpty(primaryKey))
                    {
                        RAMWriter.AddDocument(document);
                    }
                    else
                    {
                        term = new Term(primaryKey, primaryValue);
                        RAMWriter.UpdateDocument(term, document);
                    }
                }
                RAMWriter.Close();

                indexWriter.AddIndexesNoOptimize(new Directory[] { RAMDirectory });
                indexWriter.Optimize();
                indexWriter.Close();
                return(true);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (indexWriter != null)
                {
                    indexWriter.Close();
                }
            }
        }
        /// <summary>
        /// 按模板生成 Excel 文档
        /// </summary>
        /// <typeparam name="T">实体类型</typeparam>
        /// <param name="templatePath">模板路径</param>
        /// <param name="templateSheetName">模板表单名称</param>
        /// <param name="excelPath">Excel 路径</param>
        /// <param name="dataMatchList">数据匹配,Dictionary&lt;string, object&gt; 或 new {}</param>
        /// <param name="dataList">数据列表</param>
        /// <param name="reflectionType">反射类型</param>
        public static void ToExcel <T>(string templatePath, string templateSheetName, string excelPath, object dataMatchList, List <T> dataList, ReflectionTypeEnum reflectionType = ReflectionTypeEnum.Expression) where T : class
        {
            Dictionary <string, object> propertyDict = CommonHelper.GetParameterDict(dataMatchList);

            FileStream fileStream = null;
            IWorkbook  workbook   = null;

            try
            {
                using (fileStream = new FileStream(templatePath, FileMode.Open, FileAccess.ReadWrite))
                {
                    workbook = ExcelHelper.ExecuteIWorkBookGet(templatePath, fileStream);
                    if (workbook == null)
                    {
                        throw new Exception(ExcelHelper.ExcelWorkbookNullException);
                    }
                }

                Dictionary <int, string>        propertyMapperDict = new Dictionary <int, string>();
                List <ExcelTemplateFormulaItem> formulaItemList    = new List <ExcelTemplateFormulaItem>();

                int lastRowIndex   = 0;
                int insertRowIndex = -1;

                ISheet sheet = workbook.GetSheet(templateSheetName);
                if (sheet != null)
                {
                    lastRowIndex = sheet.LastRowNum;
                    for (int rowIndex = 0; rowIndex <= lastRowIndex; rowIndex++)
                    {
                        IRow iRow = sheet.GetRow(rowIndex);
                        if (iRow != null)
                        {
                            for (int colIndex = 0; colIndex <= iRow.LastCellNum; colIndex++)
                            {
                                ICell iCell = iRow.GetCell(colIndex);
                                if (iCell != null && !string.IsNullOrEmpty(iCell.ToString()))
                                {
                                    string cellText = iCell.ToString();
                                    if (cellText.StartsWith("$"))
                                    {
                                        cellText = cellText.TrimStart(new char[] { '$' });
                                        if (propertyDict != null && propertyDict.ContainsKey(cellText))
                                        {
                                            iCell.SetCellValue(propertyDict[cellText].ToString());
                                        }
                                    }
                                    else if (cellText.StartsWith("#"))
                                    {
                                        if (insertRowIndex == -1)
                                        {
                                            insertRowIndex = rowIndex;
                                        }

                                        cellText = cellText.TrimStart(new char[] { '#' });
                                        propertyMapperDict.Add(colIndex, cellText);
                                    }
                                    else if (cellText.StartsWith("&="))
                                    {
                                        if (rowIndex != insertRowIndex)
                                        {
                                            formulaItemList.Add(new ExcelTemplateFormulaItem()
                                            {
                                                Cell = iCell, FormulaText = cellText
                                            });
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (propertyMapperDict != null && propertyMapperDict.Count > 0 && insertRowIndex != -1)
                {
                    if (dataList != null && dataList.Count > 0)
                    {
                        dynamic propertyGetDict = null;
                        if (reflectionType != ReflectionTypeEnum.Original)
                        {
                            propertyGetDict = ReflectionExtendHelper.PropertyGetCallDict <T>(reflectionType);
                        }

                        CopyRow(sheet, insertRowIndex, dataList, propertyMapperDict, propertyGetDict);

                        if (formulaItemList != null && formulaItemList.Count > 0)
                        {
                            foreach (ExcelTemplateFormulaItem formulaItem in formulaItemList)
                            {
                                formulaItem.FormulaText = formulaItem.FormulaText.TrimStart(new char[] { '&', '=' });
                                formulaItem.FormulaText = formulaItem.FormulaText.Replace("_dataBegin", (insertRowIndex + 1).ToString());
                                formulaItem.FormulaText = formulaItem.FormulaText.Replace("_dataEnd", (insertRowIndex + dataList.Count).ToString());

                                formulaItem.Cell.SetCellFormula(formulaItem.FormulaText);
                                formulaItem.Cell.SetCellType(CellType.Formula);
                            }
                        }
                    }
                }

                sheet.ForceFormulaRecalculation = true;

                if (System.IO.File.Exists(excelPath))
                {
                    System.IO.File.Delete(excelPath);
                }
                using (fileStream = new FileStream(excelPath, FileMode.Create, FileAccess.ReadWrite))
                {
                    workbook.Write(fileStream);
                }
                workbook.Close();
            }
            catch
            {
                throw;
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
                if (workbook != null)
                {
                    workbook.Close();
                }
            }
        }