コード例 #1
0
        /// <summary>
        /// Gets the resource.
        /// </summary>
        /// <param name="query">The query.</param>
        /// <param name="fullTypeName">Full name of the type.</param>
        /// <returns></returns>
        object IUpdatable.GetResource(System.Linq.IQueryable query, string fullTypeName)
        {
            // Get the first result
            IEnumerable results     = (IEnumerable)query;
            object      returnValue = null;

            foreach (object result in results)
            {
                if (returnValue != null)
                {
                    break;
                }
                returnValue = result;
            }

            // Check the Typename if needed
            if (fullTypeName != null)
            {
                if (fullTypeName != returnValue.GetType().FullName)
                {
                    throw new DataServiceException("Incorrect Type Returned");
                }
            }

            // Return the resource
            return(returnValue);
        }
コード例 #2
0
        /// <summary>
        /// Gets the user dddress id based on the user full name.
        /// </summary>
        /// <param name="userName">The user full name to search on.</param>
        /// <returns>The user id.</returns>
        public virtual Int64 GetUserIDForUserName(string userName)
        {
            Int64 ret = 0;

            // Split the user name.
            char[]   delimeter = new char[] { ' ' };
            string[] splitList = userName.Split(delimeter);

            // Get the name of the user
            // from the split data.
            string firstName = splitList[0].Trim();
            string lastName  = splitList[1].Trim();

            // Get the current user name.
            System.Linq.IQueryable query =
                Select.
                SelectIQueryableItems(u => (u.FirstName == firstName) && (u.LastName == lastName)).
                Select(u => new { UserIdentity = u.UserAddressID });

            // Get the property.
            PropertyInfo property = query.ElementType.GetProperty("UserIdentity");

            // Find the first user id.
            foreach (var item in query)
            {
                ret = (Int64)property.GetValue(item, null);
                break;
            }

            // Return the user id.
            return(ret);
        }
コード例 #3
0
 private void AssertSupportedAndResultNotNullable(
     IQueryable query,
     string expectedEntityName,
     string expectedMemberPath,
     Predicate <IType> expectedMemberType,
     Predicate <IAbstractComponentType> expectedComponentType = null)
 {
     AssertResult(query, true, true, expectedEntityName, expectedMemberPath, expectedMemberType, expectedComponentType, false);
 }
コード例 #4
0
        private void AssertResult(
            IQueryable query,
            bool rewriteQuery,
            bool supported,
            string expectedEntityName,
            string expectedMemberPath,
            Predicate <IType> expectedMemberType,
            Predicate <IAbstractComponentType> expectedComponentType = null,
            bool nullability = true)
        {
            expectedComponentType = expectedComponentType ?? (o => o == null);

            var expression         = query.Expression;
            var preTransformResult = NhRelinqQueryParser.PreTransform(expression, new PreTransformationParameters(QueryMode.Select, Sfi));

            expression = preTransformResult.Expression;
            var constantToParameterMap = ExpressionParameterVisitor.Visit(preTransformResult);
            var queryModel             = NhRelinqQueryParser.Parse(expression);
            var requiredHqlParameters  = new List <NamedParameterDescriptor>();
            var visitorParameters      = new VisitorParameters(
                Sfi,
                constantToParameterMap,
                requiredHqlParameters,
                new QuerySourceNamer(),
                expression.Type,
                QueryMode.Select);

            if (rewriteQuery)
            {
                QueryModelVisitor.GenerateHqlQuery(
                    queryModel,
                    visitorParameters,
                    true,
                    NhLinqExpressionReturnType.Scalar);
            }

            var found = _tryGetMappedType(
                Sfi,
                queryModel.SelectClause.Selector,
                out var memberType,
                out var entityPersister,
                out var componentType,
                out var memberPath);

            Assert.That(found, Is.EqualTo(supported), $"Expression should be {(supported ? "supported" : "unsupported")}");
            Assert.That(entityPersister?.EntityName, Is.EqualTo(expectedEntityName), "Invalid entity name");
            Assert.That(memberPath, Is.EqualTo(expectedMemberPath), "Invalid member path");
            Assert.That(() => expectedMemberType(memberType), $"Invalid member type: {memberType?.Name ?? "null"}");
            Assert.That(() => expectedComponentType(componentType), $"Invalid component type: {componentType?.Name ?? "null"}");

            if (found)
            {
                Assert.That(_tryGetMappedNullability(Sfi, queryModel.SelectClause.Selector, out var isNullable), Is.True, "Expression should be supported");
                Assert.That(nullability, Is.EqualTo(isNullable), "Nullability is not correct");
            }
        }
コード例 #5
0
ファイル: DBContext.cs プロジェクト: simpleway2016/EntityDB
        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="items"></param>
        public void Delete(System.Linq.IQueryable items)
        {
            Type dataType = items.GetType().GetGenericArguments()[0];

            var tableSchema = SchemaManager.GetSchemaTable(dataType);

            if (tableSchema.KeyColumn == null)
            {
                throw new Exception(dataType.Name + "没有定义主键");
            }


            bool needCloseConnection = false;

            if (this.Database.Connection.State != System.Data.ConnectionState.Open)
            {
                needCloseConnection = true;
                this.Database.Connection.Open();
            }

            int pagesize = 100;

            try
            {
                var query = InvokeSelect(items, tableSchema.KeyColumn.PropertyName);
                while (true)
                {
                    var data1     = InvokeTake(query, pagesize);
                    var dataitems = (System.Array)InvokeToArray(data1);

                    foreach (var idvalue in dataitems)
                    {
                        var deldataItem = (DataItem)Activator.CreateInstance(dataType);
                        deldataItem.SetValue(tableSchema.KeyColumn.PropertyName, idvalue);
                        deldataItem.ChangedProperties.Clear();
                        Delete(deldataItem);
                    }

                    if (dataitems.Length < pagesize)
                    {
                        break;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (needCloseConnection)
                {
                    this.Database.Connection.Close();
                }
            }
        }
コード例 #6
0
 private void AssertSupported(
     IQueryable query,
     bool rewriteQuery,
     string expectedEntityName,
     string expectedMemberPath,
     Predicate <IType> expectedMemberType,
     Predicate <IAbstractComponentType> expectedComponentType = null)
 {
     AssertResult(query, rewriteQuery, true, expectedEntityName, expectedMemberPath, expectedMemberType, expectedComponentType);
 }
コード例 #7
0
 private void AssertSupported(
     IQueryable query,
     string expectedEntityName,
     string expectedMemberPath,
     Predicate <IType> expectedMemberType,
     Predicate <IAbstractComponentType> expectedComponentType = null,
     bool?nullability = true)
 {
     AssertResult(query, true, true, expectedEntityName, expectedMemberPath, expectedMemberType, expectedComponentType, nullability);
 }
コード例 #8
0
ファイル: TestService.cs プロジェクト: Vitala/NCore
        public String ToSql(System.Linq.IQueryable queryable)
        {
            var sessionProperty   = typeof(DefaultQueryProvider).GetProperty("Session", BindingFlags.NonPublic | BindingFlags.Instance);
            var session           = sessionProperty.GetValue(queryable.Provider, null) as ISession;
            var sessionImpl       = session.GetSessionImplementation();
            var factory           = sessionImpl.Factory;
            var nhLinqExpression  = new NhLinqExpression(queryable.Expression, factory);
            var translatorFactory = new ASTQueryTranslatorFactory();
            var translator        = translatorFactory.CreateQueryTranslators(nhLinqExpression, null, false, sessionImpl.EnabledFilters, factory).First();

            //in case you want the parameters as well
            //var parameters = nhLinqExpression.ParameterValuesByName.ToDictionary(x => x.Key, x => x.Value.Item1);

            return(translator.SQLString);
        }
コード例 #9
0
        public IActionResult Index(Project.Category category)
        {
            var enumValues = Enum.GetValues(typeof(Project.Category));

            System.Linq.IQueryable result = null;
            if (category == 0)
            {
                result = _context.Project.Include(p => p.ProjectCtratorNavigation)
                         .Include(p => p.ProjectCtratorNavigation.UserDetailsNavigation).OrderBy(p => p.ProjectCtrator);
            }
            else
            {
                result = _context.Project.Include(p => p.ProjectCtratorNavigation).
                         Include(p => p.ProjectCtratorNavigation.UserDetailsNavigation).
                         Where(p => p.ProjectCategory == category).OrderBy(p => p.ProjectCtrator);
            }
            ViewData["ddProjectCategory"] = category;
            return(View(result));
        }
コード例 #10
0
ファイル: DBContext.cs プロジェクト: simpleway2016/EntityDB
        /// <summary>
        /// 开启更新锁
        /// </summary>
        /// <param name="items"></param>
        public void UpdateLock(System.Linq.IQueryable items)
        {
            if (this.Database.Connection.State != System.Data.ConnectionState.Open)
            {
                throw new Exception("没有开启事务");
            }

            Type dataType = items.GetType().GetGenericArguments()[0];

            var tableSchema = SchemaManager.GetSchemaTable(dataType);

            if (tableSchema.KeyColumn == null)
            {
                throw new Exception(dataType.Name + "没有定义主键");
            }

            int pagesize = 100;
            var query    = InvokeSelect(items, tableSchema.KeyColumn.PropertyName);
            int skip     = 0;

            while (true)
            {
                var skipQuery = InvokeSkip(query, skip);
                var data1     = InvokeTake(skipQuery, pagesize);
                var dataitems = (System.Array)InvokeToArray(data1);

                foreach (var idvalue in dataitems)
                {
                    this.Database.UpdateLock(dataType, idvalue);
                }

                if (dataitems.Length < pagesize)
                {
                    break;
                }

                skip += pagesize;
            }
        }
コード例 #11
0
        /// <summary>
        /// 将LINQ的查询结果转换为DataTable最简单的实现方法
        /// </summary>
        /// <param name="queryable">要转换的结果集</param>
        /// <returns>转换后的表</returns>
        public static DataTable ConvertToDataTable(System.Linq.IQueryable queryable)
        {
            DataTable dt = new DataTable();

            var props = queryable.ElementType.GetProperties();

            foreach (PropertyInfo pi in props)
            {
                Type colType = pi.PropertyType;

                if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable <>)))
                {
                    colType = colType.GetGenericArguments()[0];
                }

                dt.Columns.Add(new DataColumn(pi.Name, colType));
            }

            foreach (var item in queryable)
            {
                DataRow dr = dt.NewRow();

                foreach (System.Reflection.PropertyInfo pi in props)
                {
                    if (pi.GetValue(item, null) != null)
                    {
                        if (pi.GetValue(item, null) != null)
                        {
                            dr[pi.Name] = pi.GetValue(item, null);
                        }
                    }
                }

                dt.Rows.Add(dr);
            }

            return(dt);
        }
コード例 #12
0
        /// <summary>
        /// Gets the user full name based on the user id.
        /// </summary>
        /// <param name="userAddressID">The user address id to search on.</param>
        /// <returns>The user full name.</returns>
        public virtual string GetUserNameForUserID(Int64 userAddressID)
        {
            string ret = null;

            // Get the current user id.
            System.Linq.IQueryable query =
                Select.
                SelectIQueryableItems(u => u.UserAddressID == userAddressID).
                Select(u => new { UserName = (u.FirstName + " " + u.LastName) });

            // Get the property.
            PropertyInfo property = query.ElementType.GetProperty("UserName");

            // Find the first user name.
            foreach (var item in query)
            {
                ret = (string)property.GetValue(item, null);
                break;
            }

            // Return the user full name.
            return(ret);
        }
コード例 #13
0
        /// <summary>
        /// Gets the resource of the specified type identified by a query and type name.
        /// </summary>
        /// <param name="query">Language integrated query (LINQ) pointing to a particular resource.</param>
        /// <param name="fullTypeName">The fully qualified type name of resource.</param>
        /// <returns>
        /// An opaque object representing a resource of the specified type, referenced by the specified query.
        /// </returns>
        public virtual object GetResource(System.Linq.IQueryable query, string fullTypeName)
        {
            if (query == null)
            {
                throw new ArgumentException("The specified IQueryable is null.");
            }

            object resource = null;

            foreach (object r in query)
            {
                if (resource != null)
                {
                    throw new ArgumentException(String.Format(System.Globalization.CultureInfo.CurrentCulture, "Invalid Uri specified. The query '{0}' must refer to a single resource", query.ToString()));
                }

                resource = r;
            }

            if (resource != null)
            {
                Type resourceType = resource.GetType();
                if (fullTypeName != null)
                {
                    if (resourceType.FullName != fullTypeName)
                    {
                        throw new ArgumentException("Unknown resource type '" + fullTypeName + "'.");
                    }
                }

                this.session.GetTable(resourceType, this.GetTableId(resourceType)).SetSubmitAction(resource, SubmitAction.PossibleUpdate);

                return(resource);
            }

            return(null);
        }
コード例 #14
0
        /// <summary>
        /// Gets the resource of the given type that the query points to
        /// </summary>
        /// <param name="query">query pointing to a particular resource</param>
        /// <param name="fullTypeName">full type name i.e. Namespace qualified type name of the resource</param>
        /// <returns>object representing a resource of given type and as referenced by the query</returns>
        /// <remarks>This method should obtain a single result from the specified <paramref name="query"/>. It should fail if no or more than one result
        /// can be obtain by evaluating such query.
        /// The result should then be converted to its resource "handle" and that handle should be returned from the method.
        /// The <paramref name="fullTypeName"/> is the expected FullName of the resource type of the resource to be retrieved. If this parameter is null
        /// the method should ignore it. If it's not null, the method should check that the resource returned by the query is of this resource type
        /// and fail if that's not the case.</remarks>
        public object GetResource(System.Linq.IQueryable query, string fullTypeName)
        {
            // Since we're not using resource handles we're going to return the resource itself.
            object resource = null;

            foreach (object r in query)
            {
                if (resource != null)
                {
                    throw new ArgumentException(String.Format("Invalid Uri specified. The query '{0}' must refer to a single resource", query.ToString()));
                }

                resource = r;
            }

            if (resource != null)
            {
                if (fullTypeName != null)
                {
                    ResourceType resourceType;
                    if (!this.metadata.TryResolveResourceType(fullTypeName, out resourceType))
                    {
                        throw new ArgumentException("Unknown resource type '" + fullTypeName + "'.");
                    }

                    if (resource.GetType() != resourceType.InstanceType)
                    {
                        throw new System.ArgumentException(String.Format("Invalid uri specified. ExpectedType: '{0}', ActualType: '{1}'", fullTypeName, resource.GetType().FullName));
                    }
                }

                return(resource);
            }

            return(null);
        }
コード例 #15
0
 protected override System.Linq.IQueryable SortDistinctValues(System.Linq.IQueryable source)
 {
     return(base.SortDistinctValuesByFilteringDisplay(source));
 }
コード例 #16
0
ファイル: DBContext.cs プロジェクト: jangocheng/EntityDB
        /// <summary>
        /// 删除对象
        /// </summary>
        /// <param name="items"></param>
        public void Delete(System.Linq.IQueryable items)
        {
            Type dataType = items.GetType().GetGenericArguments()[0];

            string pkid = null;

            if (dataType != null)
            {
                try
                {
                    var att = dataType.GetTypeInfo().GetCustomAttribute(typeof(Attributes.Table)) as Attributes.Table;
                    if (att != null)
                    {
                        pkid = att.KeyName;
                    }
                }
                catch
                {
                }
            }
            if (pkid == null)
            {
                throw new Exception(dataType.Name + "没有定义主键");
            }


            bool needCloseConnection = false;

            if (this.Database.Connection.State != System.Data.ConnectionState.Open)
            {
                needCloseConnection = true;
                this.Database.Connection.Open();
            }

            try
            {
                var query = InvokeSelect(items, pkid);
                while (true)
                {
                    var data1     = InvokeTake(query, 100);
                    var dataitems = (System.Collections.IList)InvokeToList(data1);
                    if (dataitems.Count == 0)
                    {
                        break;
                    }
                    foreach (var idvalue in dataitems)
                    {
                        var deldataItem = (DataItem)Activator.CreateInstance(dataType);
                        deldataItem.SetValue(pkid, idvalue);
                        Delete(deldataItem);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (needCloseConnection)
                {
                    this.Database.Connection.Close();
                }
            }
        }
コード例 #17
0
 public string GetSQL(System.Linq.IQueryable q)
 {
     return(this.GetCommand(q).CommandText);
 }
コード例 #18
0
    public void Populate()
    {
        #region Types of Keywords

        FieldPublicDynamic = new { PropPublic1 = "A", PropPublic2 = 1, PropPublic3 = "B", PropPublic4 = "B", PropPublic5 = "B", PropPublic6 = "B", PropPublic7 = "B", PropPublic8 = "B", PropPublic9 = "B", PropPublic10 = "B", PropPublic11 = "B", PropPublic12 = new { PropSubPublic1 = 0, PropSubPublic2 = 1, PropSubPublic3 = 2 } };
        FieldPublicObject  = new StringBuilder("Object - StringBuilder");
        FieldPublicInt32   = int.MaxValue;
        FieldPublicInt64   = long.MaxValue;
        FieldPublicULong   = ulong.MaxValue;
        FieldPublicUInt    = uint.MaxValue;
        FieldPublicDecimal = 100000.999999m;
        FieldPublicDouble  = 100000.999999d;
        FieldPublicChar    = 'A';
        FieldPublicByte    = byte.MaxValue;
        FieldPublicBoolean = true;
        FieldPublicSByte   = sbyte.MaxValue;
        FieldPublicShort   = short.MaxValue;
        FieldPublicUShort  = ushort.MaxValue;
        FieldPublicFloat   = 100000.675555f;

        FieldPublicInt32Nullable   = int.MaxValue;
        FieldPublicInt64Nullable   = 2;
        FieldPublicULongNullable   = ulong.MaxValue;
        FieldPublicUIntNullable    = uint.MaxValue;
        FieldPublicDecimalNullable = 100000.999999m;
        FieldPublicDoubleNullable  = 100000.999999d;
        FieldPublicCharNullable    = 'A';
        FieldPublicByteNullable    = byte.MaxValue;
        FieldPublicBooleanNullable = true;
        FieldPublicSByteNullable   = sbyte.MaxValue;
        FieldPublicShortNullable   = short.MaxValue;
        FieldPublicUShortNullable  = ushort.MaxValue;
        FieldPublicFloatNullable   = 100000.675555f;

        #endregion

        #region System

        FieldPublicDateTime         = new DateTime(2000, 1, 1, 1, 1, 1);
        FieldPublicTimeSpan         = new TimeSpan(1, 10, 40);
        FieldPublicEnumDateTimeKind = DateTimeKind.Local;

        // Instantiate date and time using Persian calendar with years,
        // months, days, hours, minutes, seconds, and milliseconds
        FieldPublicDateTimeOffset = new DateTimeOffset(1387, 2, 12, 8, 6, 32, 545,
                                                       new System.Globalization.PersianCalendar(),
                                                       new TimeSpan(1, 0, 0));

        FieldPublicIntPtr         = new IntPtr(100);
        FieldPublicTimeZone       = TimeZone.CurrentTimeZone;
        FieldPublicTimeZoneInfo   = TimeZoneInfo.Utc;
        FieldPublicTuple          = Tuple.Create <string, int, decimal>("T-string\"", 1, 1.1m);
        FieldPublicType           = typeof(object);
        FieldPublicUIntPtr        = new UIntPtr(100);
        FieldPublicUri            = new Uri("http://www.site.com");
        FieldPublicVersion        = new Version(1, 0, 100, 1);
        FieldPublicGuid           = new Guid("d5010f5b-0cd1-44ca-aacb-5678b9947e6c");
        FieldPublicSingle         = Single.MaxValue;
        FieldPublicException      = new Exception("Test error", new Exception("inner exception"));
        FieldPublicEnumNonGeneric = EnumTest.ValueA;
        FieldPublicAction         = () => true.Equals(true);
        FieldPublicAction2        = (a, b) => true.Equals(true);
        FieldPublicFunc           = () => true;
        FieldPublicFunc2          = (a, b) => true;

        #endregion

        #region Arrays and Collections

        FieldPublicArrayUni    = new string[2];
        FieldPublicArrayUni[0] = "[0]";
        FieldPublicArrayUni[1] = "[1]";

        FieldPublicArrayTwo       = new string[2, 2];
        FieldPublicArrayTwo[0, 0] = "[0, 0]";
        FieldPublicArrayTwo[0, 1] = "[0, 1]";
        FieldPublicArrayTwo[1, 0] = "[1, 0]";
        FieldPublicArrayTwo[1, 1] = "[1, 1]";

        FieldPublicArrayThree          = new string[1, 1, 2];
        FieldPublicArrayThree[0, 0, 0] = "[0, 0, 0]";
        FieldPublicArrayThree[0, 0, 1] = "[0, 0, 1]";

        FieldPublicJaggedArrayTwo    = new string[2][];
        FieldPublicJaggedArrayTwo[0] = new string[5] {
            "a", "b", "c", "d", "e"
        };
        FieldPublicJaggedArrayTwo[1] = new string[4] {
            "a1", "b1", "c1", "d1"
        };

        FieldPublicJaggedArrayThree          = new string[1][][];
        FieldPublicJaggedArrayThree[0]       = new string[1][];
        FieldPublicJaggedArrayThree[0][0]    = new string[2];
        FieldPublicJaggedArrayThree[0][0][0] = "[0][0][0]";
        FieldPublicJaggedArrayThree[0][0][1] = "[0][0][1]";

        FieldPublicMixedArrayAndJagged = new int[3][, ]
        {
            new int[, ] {
                { 1, 3 }, { 5, 7 }
            },
            new int[, ] {
                { 0, 2 }, { 4, 6 }, { 8, 10 }
            },
            new int[, ] {
                { 11, 22 }, { 99, 88 }, { 0, 9 }
            }
        };

        FieldPublicDictionary = new System.Collections.Generic.Dictionary <string, string>();
        FieldPublicDictionary.Add("Key1", "Value1");
        FieldPublicDictionary.Add("Key2", "Value2");
        FieldPublicDictionary.Add("Key3", "Value3");
        FieldPublicDictionary.Add("Key4", "Value4");

        FieldPublicList = new System.Collections.Generic.List <int>();
        FieldPublicList.Add(0);
        FieldPublicList.Add(1);
        FieldPublicList.Add(2);

        FieldPublicQueue = new System.Collections.Generic.Queue <int>();
        FieldPublicQueue.Enqueue(10);
        FieldPublicQueue.Enqueue(11);
        FieldPublicQueue.Enqueue(12);

        FieldPublicHashSet = new System.Collections.Generic.HashSet <string>();
        FieldPublicHashSet.Add("HashSet1");
        FieldPublicHashSet.Add("HashSet2");

        FieldPublicSortedSet = new System.Collections.Generic.SortedSet <string>();
        FieldPublicSortedSet.Add("SortedSet1");
        FieldPublicSortedSet.Add("SortedSet2");
        FieldPublicSortedSet.Add("SortedSet3");

        FieldPublicStack = new System.Collections.Generic.Stack <string>();
        FieldPublicStack.Push("Stack1");
        FieldPublicStack.Push("Stack2");
        FieldPublicStack.Push("Stack3");

        FieldPublicLinkedList = new System.Collections.Generic.LinkedList <string>();
        FieldPublicLinkedList.AddFirst("LinkedList1");
        FieldPublicLinkedList.AddLast("LinkedList2");
        FieldPublicLinkedList.AddAfter(FieldPublicLinkedList.Find("LinkedList1"), "LinkedList1.1");

        FieldPublicObservableCollection = new System.Collections.ObjectModel.ObservableCollection <string>();
        FieldPublicObservableCollection.Add("ObservableCollection1");
        FieldPublicObservableCollection.Add("ObservableCollection2");

        FieldPublicKeyedCollection = new MyDataKeyedCollection();
        FieldPublicKeyedCollection.Add(new MyData()
        {
            Data = "data1", Id = 0
        });
        FieldPublicKeyedCollection.Add(new MyData()
        {
            Data = "data2", Id = 1
        });

        var list = new List <string>();
        list.Add("list1");
        list.Add("list2");
        list.Add("list3");

        FieldPublicReadOnlyCollection = new ReadOnlyCollection <string>(list);

        FieldPublicReadOnlyDictionary           = new ReadOnlyDictionary <string, string>(FieldPublicDictionary);
        FieldPublicReadOnlyObservableCollection = new ReadOnlyObservableCollection <string>(FieldPublicObservableCollection);
        FieldPublicCollection = new Collection <string>();
        FieldPublicCollection.Add("collection1");
        FieldPublicCollection.Add("collection2");
        FieldPublicCollection.Add("collection3");

        FieldPublicArrayListNonGeneric = new System.Collections.ArrayList();
        FieldPublicArrayListNonGeneric.Add(1);
        FieldPublicArrayListNonGeneric.Add("a");
        FieldPublicArrayListNonGeneric.Add(10.0m);
        FieldPublicArrayListNonGeneric.Add(new DateTime(2000, 01, 01));

        FieldPublicBitArray    = new System.Collections.BitArray(3);
        FieldPublicBitArray[2] = true;

        FieldPublicSortedList = new System.Collections.SortedList();
        FieldPublicSortedList.Add("key1", 1);
        FieldPublicSortedList.Add("key2", 2);
        FieldPublicSortedList.Add("key3", 3);
        FieldPublicSortedList.Add("key4", 4);

        FieldPublicHashtableNonGeneric = new System.Collections.Hashtable();
        FieldPublicHashtableNonGeneric.Add("key1", 1);
        FieldPublicHashtableNonGeneric.Add("key2", 2);
        FieldPublicHashtableNonGeneric.Add("key3", 3);
        FieldPublicHashtableNonGeneric.Add("key4", 4);

        FieldPublicQueueNonGeneric = new System.Collections.Queue();
        FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric1");
        FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric2");
        FieldPublicQueueNonGeneric.Enqueue("QueueNonGeneric3");

        FieldPublicStackNonGeneric = new System.Collections.Stack();
        FieldPublicStackNonGeneric.Push("StackNonGeneric1");
        FieldPublicStackNonGeneric.Push("StackNonGeneric2");

        FieldPublicIEnumerable = FieldPublicSortedList;

        FieldPublicBlockingCollection = new System.Collections.Concurrent.BlockingCollection <string>();
        FieldPublicBlockingCollection.Add("BlockingCollection1");
        FieldPublicBlockingCollection.Add("BlockingCollection2");

        FieldPublicConcurrentBag = new System.Collections.Concurrent.ConcurrentBag <string>();
        FieldPublicConcurrentBag.Add("ConcurrentBag1");
        FieldPublicConcurrentBag.Add("ConcurrentBag2");
        FieldPublicConcurrentBag.Add("ConcurrentBag3");

        FieldPublicConcurrentDictionary = new System.Collections.Concurrent.ConcurrentDictionary <string, int>();
        FieldPublicConcurrentDictionary.GetOrAdd("ConcurrentDictionary1", 0);
        FieldPublicConcurrentDictionary.GetOrAdd("ConcurrentDictionary2", 0);

        FieldPublicConcurrentQueue = new System.Collections.Concurrent.ConcurrentQueue <string>();
        FieldPublicConcurrentQueue.Enqueue("ConcurrentQueue1");
        FieldPublicConcurrentQueue.Enqueue("ConcurrentQueue2");

        FieldPublicConcurrentStack = new System.Collections.Concurrent.ConcurrentStack <string>();
        FieldPublicConcurrentStack.Push("ConcurrentStack1");
        FieldPublicConcurrentStack.Push("ConcurrentStack2");

        // FieldPublicOrderablePartitioner = new OrderablePartitioner();
        // FieldPublicPartitioner;
        // FieldPublicPartitionerNonGeneric;

        FieldPublicHybridDictionary = new System.Collections.Specialized.HybridDictionary();
        FieldPublicHybridDictionary.Add("HybridDictionaryKey1", "HybridDictionary1");
        FieldPublicHybridDictionary.Add("HybridDictionaryKey2", "HybridDictionary2");

        FieldPublicListDictionary = new System.Collections.Specialized.ListDictionary();
        FieldPublicListDictionary.Add("ListDictionaryKey1", "ListDictionary1");
        FieldPublicListDictionary.Add("ListDictionaryKey2", "ListDictionary2");
        FieldPublicNameValueCollection = new System.Collections.Specialized.NameValueCollection();
        FieldPublicNameValueCollection.Add("Key1", "Value1");
        FieldPublicNameValueCollection.Add("Key2", "Value2");

        FieldPublicOrderedDictionary = new System.Collections.Specialized.OrderedDictionary();
        FieldPublicOrderedDictionary.Add(1, "OrderedDictionary1");
        FieldPublicOrderedDictionary.Add(2, "OrderedDictionary1");
        FieldPublicOrderedDictionary.Add("OrderedDictionaryKey2", "OrderedDictionary2");

        FieldPublicStringCollection = new System.Collections.Specialized.StringCollection();
        FieldPublicStringCollection.Add("StringCollection1");
        FieldPublicStringCollection.Add("StringCollection2");

        #endregion

        #region Several

        PropXmlDocument = new XmlDocument();
        PropXmlDocument.LoadXml("<xml>something</xml>");

        var tr = new StringReader("<Root>Content</Root>");
        PropXDocument         = XDocument.Load(tr);
        PropStream            = GenerateStreamFromString("Stream");
        PropBigInteger        = new System.Numerics.BigInteger(100);
        PropStringBuilder     = new StringBuilder("StringBuilder");
        FieldPublicIQueryable = new List <string>()
        {
            "IQueryable"
        }.AsQueryable();

        #endregion

        #region Custom

        FieldPublicMyCollectionPublicGetEnumerator           = new MyCollectionPublicGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionInheritsPublicGetEnumerator   = new MyCollectionInheritsPublicGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionExplicitGetEnumerator         = new MyCollectionExplicitGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionInheritsExplicitGetEnumerator = new MyCollectionInheritsExplicitGetEnumerator("a b c", new char[] { ' ' });
        FieldPublicMyCollectionInheritsTooIEnumerable        = new MyCollectionInheritsTooIEnumerable("a b c", new char[] { ' ' });

        FieldPublicEnumSpecific = EnumTest.ValueB;
        MyDelegate            = MethodDelegate;
        EmptyClass            = new EmptyClass();
        StructGeneric         = new ThreeTuple <int>(0, 1, 2);
        StructGenericNullable = new ThreeTuple <int>(0, 1, 2);
        FieldPublicNullable   = new Nullable <ThreeTuple <int> >(StructGeneric);

        #endregion
    }
コード例 #19
0
ファイル: DBContext.cs プロジェクト: DebugOfTheRoad/EntityDB
        /// <summary>
        /// 开启更新锁
        /// </summary>
        /// <param name="items"></param>
        public void UpdateLock(System.Linq.IQueryable items)
        {
            if (this.Database.Connection.State != System.Data.ConnectionState.Open)
            {
                throw new Exception("没有开启事务");
            }

            Type dataType = items.GetType().GetGenericArguments()[0];

            string pkid = null;

            Attributes.Table tableAttr = null;
            if (dataType != null)
            {
                try
                {
                    tableAttr = dataType.GetTypeInfo().GetCustomAttribute(typeof(Attributes.Table)) as Attributes.Table;
                    if (tableAttr != null)
                    {
                        pkid = tableAttr.KeyName;
                    }
                }
                catch
                {
                }
            }
            if (pkid == null)
            {
                throw new Exception(dataType.Name + "没有定义主键");
            }

            WayDBColumnAttribute[] columns = null;
            Attributes.Table.DataTypeColumns.TryGetValue(dataType, out columns);
            if (columns == null)
            {
                var properties = dataType.GetProperties();
                List <WayDBColumnAttribute> allcolumns = new List <WayDBColumnAttribute>();
                foreach (var pro in properties)
                {
                    var attr = pro.GetCustomAttribute <WayDBColumnAttribute>();
                    if (attr != null)
                    {
                        allcolumns.Add(attr);
                    }
                }
                Attributes.Table.DataTypeColumns[dataType] = columns = allcolumns.ToArray();
            }

            int pagesize = 100;
            var query    = InvokeSelect(items, pkid);
            int skip     = 0;

            while (true)
            {
                var skipQuery = InvokeSkip(query, skip);
                var data1     = InvokeTake(skipQuery, pagesize);
                var dataitems = (System.Array)InvokeToArray(data1);

                foreach (var idvalue in dataitems)
                {
                    this.Database.UpdateLock(dataType.Name, columns, idvalue);
                }

                if (dataitems.Length < pagesize)
                {
                    break;
                }

                skip += pagesize;
            }
        }
コード例 #20
0
ファイル: page.cs プロジェクト: MrTjming/CSTweb.github.io
 public void DatasourseBind(System.Linq.IQueryable linq, int CurrentPage, int PageSize, Repeater rpt)
 {
 }
コード例 #21
0
        public bool Verify(
            System.Linq.IQueryable queryable,
            string hostIdProp,
            string hostIdValue,
            string clientName,
            string clientIdProp,
            string clientIdValue)
        {
            var expHost = Expression.Parameter(typeof(TEntity), "host");

            var expHostId = Expression.Call(
                // get host id property value as whatever it is
                Expression.Property(
                    expHost,
                    hostIdProp),
                "ToString",
                null);
            var expHostIdValue  = Expression.Constant(hostIdValue);
            var expHostIdentity = Expression.Equal(expHostId, expHostIdValue);

            var expClient        = Expression.Property(expHost, clientName);
            var expClientIdValue = Expression.Constant(clientIdValue);

            if (expClient.Type.Name.StartsWith("ICollection"))
            {
                var clientType = expClient.Type.GenericTypeArguments.First();

                var expClientParameter = Expression.Parameter(clientType, "client");
                var expClientId        = Expression.Call(
                    // get client id property value as whatever it is
                    Expression.Property(
                        expClientParameter,
                        clientIdProp),
                    "ToString",
                    null);

                Expression expression = Expression.Equal(expClientId, expClientIdValue);

                expression = Where <TTarget> (
                    typeof(Enumerable),
                    clientType,
                    expClient,
                    expression,
                    expClientParameter);

                expression = Expression.Call(
                    typeof(Enumerable),
                    "Any",
                    new Type[] { clientType },
                    expression);

                expression = Where <TEntity> (
                    typeof(Queryable),
                    queryable.ElementType,
                    queryable.Expression,
                    Expression.AndAlso(expHostIdentity, expression),
                    expHost);

                var query = queryable.Provider
                            .CreateQuery <TEntity> (expression) as IQueryable <TEntity>;

                return(query.Take(1).Any());
            }
            else
            {
                var expClientId = Expression.Call(
                    Expression.Property(expClient, clientIdProp),
                    "ToString",
                    null);
                var expClientIdentity = Expression.Equal(expClientId, expClientIdValue);

                var predicateBody = Expression.AndAlso(expHostIdentity, expClientIdentity);

                var query = queryable.Provider.CreateQuery <TEntity> (
                    Where <TEntity> (
                        typeof(System.Linq.Queryable),
                        queryable.ElementType,
                        queryable.Expression,
                        predicateBody,
                        expHost)
                    ) as IQueryable <TEntity>;

                return(query.Take(1).Any());
            }
        }
コード例 #22
0
 public override System.Linq.Expressions.Expression BuildLinqExpression(System.Linq.IQueryable query, System.Linq.Expressions.Expression expression, System.Linq.Expressions.Expression item = null)
 {
     throw new NotSupportedException(
               string.Format("{0} is just a placeholder and should be handled differently in Extensions.cs", this.GetType().Name));
 }