示例#1
0
		override protected string Select(string selectClause, ObjectQuery objectQuery) {
			string where = null;
			if (this.entity.BaseEntity == null) {
				where = (objectQuery.WhereClause.Length == 0
					? String.Empty : " WHERE " + objectQuery.WhereClause);
			}
			else {
				string filter = " WHERE " + this.GetExpression(this.entity.Table, this.entity.TypeField, this.entity.TypeValue);
				where = filter + (objectQuery.WhereClause.Length == 0
					? string.Empty : " AND " + objectQuery.WhereClause);
			}
			string sort = (objectQuery.SortClause.Length == 0
				? String.Empty : " ORDER BY " + objectQuery.SortClause);
			if (objectQuery.PageSize <= 0) {
				return selectClause + where + sort + ";";
			}
			else if (objectQuery.PageIndex <= 1) {
				string top = selectClause.Insert(6, " TOP " + objectQuery.PageSize.ToString());
				return top + where + sort + ";";
			}
			else {
				int prevCount = objectQuery.PageSize * (objectQuery.PageIndex - 1);
				string keyField = this.entity.KeyFields[0].Field;
				if (this.entity.KeyFields.Length > 1)
					throw new ORMapperException("ObjectSpace: Composite Key Paging is Not Supported");
				string query = (objectQuery.WhereClause.Length == 0
					? String.Empty : objectQuery.WhereClause + " AND ");
				string format = "{0} WHERE {1} IN (SELECT TOP {2} {1} FROM {3} WHERE {4}{1}"
					+ " NOT IN (SELECT TOP {5} {1} FROM {3}{6}{7}){7}){7};";
				return String.Format(format, selectClause, this.GetDelimited(keyField), objectQuery.PageSize.ToString(),
					this.fromTables, query, prevCount.ToString(), where, sort);
			}
		}
示例#2
0
 protected override string Select(string selectClause, ObjectQuery objectQuery)
 {
     string where = null;
     if (this.entity.BaseEntity == null) {
         where = (objectQuery.WhereClause.Length == 0
             ? String.Empty : " WHERE " + objectQuery.WhereClause);
     }
     else {
         string filter = " WHERE " + this.GetExpression(this.entity.Table, this.entity.TypeField, this.entity.TypeValue);
         where = filter + (objectQuery.WhereClause.Length == 0
             ? string.Empty : " AND " + objectQuery.WhereClause);
     }
     string sort = (objectQuery.SortClause.Length == 0
         ? String.Empty : " ORDER BY " + objectQuery.SortClause);
     if (objectQuery.PageSize <= 0) {
         return selectClause + where + sort + ";";
     }
     else if (objectQuery.PageIndex <= 1) {
         string top = selectClause.Insert(6, " TOP " + objectQuery.PageSize.ToString());
         return top + where + sort + ";";
     }
     else {
         if (sort.Length == 0)
             throw new ORMapperException("ObjectSpace: Paging requires a Sort Clause");
         int totalCount = objectQuery.PageSize * objectQuery.PageIndex;
         int prevCount = objectQuery.PageSize * (objectQuery.PageIndex - 1);
         string format = "SELECT * FROM (SELECT TOP {0} {1}, Row_Number()"
                 + " OVER ({2}) AS {3} FROM {4}{5}) AS {6} WHERE {3} > {7};";
         return string.Format(format, totalCount, this.selectFields, sort, "RowIndex",
             this.fromTables, where, this.GetDelimited(this.entity.Table), prevCount);
     }
 }
示例#3
0
 public static List<COMPortInfo> GetCOMPortsInfo()
 {
     List<COMPortInfo> comPortInfoList = new List<COMPortInfo>();
     ConnectionOptions options = ProcessConnection.ProcessConnectionOptions();
     ManagementScope connectionScope = ProcessConnection.ConnectionScope(Environment.MachineName, options, @"\root\CIMV2");
     ObjectQuery objectQuery = new ObjectQuery("SELECT * FROM Win32_PnPEntity WHERE ConfigManagerErrorCode = 0");
     ManagementObjectSearcher comPortSearcher = new ManagementObjectSearcher(connectionScope, objectQuery);
     using (comPortSearcher) {
         string caption = null;
         foreach (ManagementObject obj in comPortSearcher.Get()) {
             if (obj != null) {
                 object captionObj = obj["Caption"];
                 if (captionObj != null) {
                     caption = captionObj.ToString();
                     if (caption.Contains("(COM")) {
                         COMPortInfo comPortInfo = new COMPortInfo();
                         comPortInfo.Name = caption.Substring(caption.LastIndexOf("(COM")).Replace("(", string.Empty).Replace(")",
                                                              string.Empty);
                         comPortInfo.Description = caption;
                         comPortInfoList.Add(comPortInfo);
                     }
                 }
             }
         }
     }
     return comPortInfoList;
 }
示例#4
0
		override protected string Select(string selectClause, ObjectQuery objectQuery) {
			string where = null;
			if (this.entity.BaseEntity == null) {
				where = (objectQuery.WhereClause.Length == 0
					? String.Empty : " WHERE " + objectQuery.WhereClause);
			}
			else {
				string filter = " WHERE " + this.GetExpression(this.entity.Table, this.entity.TypeField, this.entity.TypeValue);
				where = filter + (objectQuery.WhereClause.Length == 0
					? string.Empty : " AND " + objectQuery.WhereClause);
			}
			string sort = (objectQuery.SortClause.Length == 0
				? String.Empty : " ORDER BY " + objectQuery.SortClause);
			if (objectQuery.PageSize <= 0) {
				return selectClause + where + sort;
			}
			else if (objectQuery.PageIndex <= 1) {
				string format = "SELECT * FROM (SELECT {0} FROM {1}{2}{3}) {4} WHERE RowNum <= {5}"; //NPF modified for oracle
				return String.Format(format, this.selectFields, this.fromTables,
					where, sort, this.GetDelimited(this.entity.Table), objectQuery.PageSize);
			}
			else {
				int totalCount = objectQuery.PageSize * objectQuery.PageIndex;
				int prevCount = objectQuery.PageSize * (objectQuery.PageIndex - 1);
				string format = "SELECT * FROM (SELECT *, RowNum AS {0} FROM ("	//NPF modified for oracle
					+ "SELECT {1} FROM {2}{3}{4}) {5} WHERE RowNum <= {6}) {5} WHERE {0} > {7}";
				return String.Format(format, "RowIndex", this.selectFields, this.fromTables,
					where, sort, this.GetDelimited(this.entity.Table), totalCount, prevCount);
			}
		}
示例#5
0
    protected void AllComboBoxBind()
    {
        RadComboBoxItem Status;//Telerik��״̬�ؼ�

        vUTPCompany vUTPCompanyObj;

        this.OrderBy = " it.CompName desc ";
        string whereStr;

        whereStr = "";
        BLL_vUTPCustomer = new vUTPCustomerBLL();
        vUTPCompanyObjs = BLL_vUTPCustomer.GetUTPCompanys(whereStr, this.OrderBy);

        if (vUTPCompanyObjs.Count() > 0)
        {
            rctxtCompany.DataSource = vUTPCompanyObjs;
            rctxtCompany.DataValueField = "CompanyID";
            rctxtCompany.DataTextField = "Comp";
            rctxtCompany.DataBind();
        }
        vUTPCompanyObj = vUTPCompanyObjs.ToList().First();

        CycleComboBoxBind(vUTPCompanyObj.CompanyID);

        whereStr = " and it.Billable=true";
        this.OrderBy = " it.StatType desc ";
        vUTPCustomerStateObjs = BLL_vUTPCustomer.GetUTPCustomerStates(whereStr, this.OrderBy);

        if (vUTPCustomerStateObjs.Count() > 0)
        {
            try
            {
                rctxtStatusCode.DataSource = vUTPCustomerStateObjs;
                rctxtStatusCode.DataValueField = "CustomerStateID";
                rctxtStatusCode.DataTextField = "StatCode";
                rctxtStatusCode.DataBind();

                Status = new RadComboBoxItem("All", "All");
                rctxtStatusCode.Items.Add(Status);
                rctxtStatusCode.SelectedValue = "All";
            }
            catch (Exception)
            {
                rctxtStatusCode.Items.Clear();

                Status = new RadComboBoxItem("All", "All");
                rctxtStatusCode.Items.Add(Status);
                rctxtStatusCode.SelectedValue = "All";
            }
        }
    }
    /// <summary>
    /// Changes installed SonarQube service's log on user to current logged on user
    /// if windows authentication is chosen.
    /// </summary>
    public static bool ChangeUserAccountOfServiceForWindowsAuthentication(Session session)
    {
        string authType = session.Property("SQLAUTHTYPE");
        string setupType = session.Property("SETUPTYPE");
        string currentLoggedInUser = session.Property("CURRENTLOGGEDINUSER");

        bool success = true;

        // If authentication type is Windows, we need to change the service log on to current user.
        // For SQL auth, it works with System log on which is the default one.
        if (AuthenticationType.Windows.Equals(authType, StringComparison.InvariantCultureIgnoreCase) &&
            SetupType.Express.Equals(setupType, StringComparison.InvariantCultureIgnoreCase))
        {
            try
            {
                string queryString = "SELECT * FROM WIN32_SERVICE WHERE DISPLAYNAME='SonarQube'";

                ObjectQuery oQuery = new ObjectQuery(queryString);
                ManagementObjectSearcher objectSearcher = new ManagementObjectSearcher(oQuery);
                ManagementObjectCollection objectCollection = objectSearcher.Get();

                foreach (ManagementObject mObject in objectCollection)
                {
                    string serviceName = mObject.GetPropertyValue("Name") as string;
                    string fullServiceName = "Win32_Service.Name='" + serviceName + "'";
                    ManagementObject mo = new ManagementObject(fullServiceName);

                    string username = currentLoggedInUser;
                    string password = string.Empty;

                    // Ask current logged on user's password
                    if (!WindowsAuthenticationHelper.PromptForPassword(session, username, out password))
                    {
                        // [TODO] Localization
                        SendMessageBoxMessageToBA(session, "Authentication failed. Service may not run as expected.");
                        success = false;
                    }
                    else
                    {
                        mo.InvokeMethod("Change", new object[] { null, null, null, null, null, null, username, password, null, null, null });
                    }
                }
            }
            catch (Exception e)
            {
                session.Log("[ChangeUserAccountForService] {0}", e.Message);
            }
        }
        return success;
    }
        private int InternalUpdate <TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery <TEntity> query, Expression <Func <TEntity, TEntity> > updateExpression, bool async = false)
            where TEntity : class
#endif
        {
            DbConnection  updateConnection  = null;
            DbTransaction updateTransaction = null;
            DbCommand     updateCommand     = null;
            bool          ownConnection     = false;
            bool          ownTransaction    = false;

            try
            {
                // get store connection and transaction
                var store = GetStore(objectContext);
                updateConnection  = store.Item1;
                updateTransaction = store.Item2;

                if (updateConnection.State != ConnectionState.Open)
                {
                    updateConnection.Open();
                    ownConnection = true;
                }

                // use existing transaction or create new
                if (updateTransaction == null)
                {
                    updateTransaction = updateConnection.BeginTransaction();
                    ownTransaction    = true;
                }

                updateCommand             = updateConnection.CreateCommand();
                updateCommand.Transaction = updateTransaction;
                if (objectContext.CommandTimeout.HasValue)
                {
                    updateCommand.CommandTimeout = objectContext.CommandTimeout.Value;
                }

                var innerSelect = GetSelectSql(query, entityMap, updateCommand);
                var sqlBuilder  = new StringBuilder(innerSelect.Length * 2);

                sqlBuilder.Append("UPDATE ");
                sqlBuilder.Append(entityMap.TableName);
                sqlBuilder.AppendLine(" SET ");

                var memberInitExpression = updateExpression.Body as MemberInitExpression;
                if (memberInitExpression == null)
                {
                    throw new ArgumentException("The update expression must be of type MemberInitExpression.", "updateExpression");
                }

                int  nameCount = 0;
                bool wroteSet  = false;
                foreach (MemberBinding binding in memberInitExpression.Bindings)
                {
                    if (wroteSet)
                    {
                        sqlBuilder.AppendLine(", ");
                    }

                    string propertyName = binding.Member.Name;
                    string columnName   = entityMap.PropertyMaps
                                          .Where(p => p.PropertyName == propertyName)
                                          .Select(p => p.ColumnName)
                                          .FirstOrDefault();


                    var memberAssignment = binding as MemberAssignment;
                    if (memberAssignment == null)
                    {
                        throw new ArgumentException("The update expression MemberBinding must only by type MemberAssignment.", "updateExpression");
                    }

                    Expression memberExpression = memberAssignment.Expression;

                    ParameterExpression parameterExpression = null;
                    memberExpression.Visit((ParameterExpression p) =>
                    {
                        if (p.Type == entityMap.EntityType)
                        {
                            parameterExpression = p;
                        }

                        return(p);
                    });


                    if (parameterExpression == null)
                    {
                        object value;

                        if (memberExpression.NodeType == ExpressionType.Constant)
                        {
                            var constantExpression = memberExpression as ConstantExpression;
                            if (constantExpression == null)
                            {
                                throw new ArgumentException(
                                          "The MemberAssignment expression is not a ConstantExpression.", "updateExpression");
                            }

                            value = constantExpression.Value;
                        }
                        else
                        {
                            LambdaExpression lambda = Expression.Lambda(memberExpression, null);
                            value = lambda.Compile().DynamicInvoke();
                        }

                        if (value != null)
                        {
                            string parameterName = "p__update__" + nameCount++;
                            var    parameter     = updateCommand.CreateParameter();
                            parameter.ParameterName = parameterName;
                            parameter.Value         = value;
                            updateCommand.Parameters.Add(parameter);

                            sqlBuilder.AppendFormat("[{0}] = @{1}", columnName, parameterName);
                        }
                        else
                        {
                            sqlBuilder.AppendFormat("[{0}] = NULL", columnName);
                        }
                    }
                    else
                    {
                        // create clean objectset to build query from
                        var objectSet = objectContext.CreateObjectSet <TEntity>();

                        Type[] typeArguments = new[] { entityMap.EntityType, memberExpression.Type };

                        ConstantExpression constantExpression = Expression.Constant(objectSet);
                        LambdaExpression   lambdaExpression   = Expression.Lambda(memberExpression, parameterExpression);

                        MethodCallExpression selectExpression = Expression.Call(
                            typeof(Queryable),
                            "Select",
                            typeArguments,
                            constantExpression,
                            lambdaExpression);

                        // create query from expression
                        var    selectQuery = objectSet.CreateQuery(selectExpression, entityMap.EntityType);
                        string sql         = selectQuery.ToTraceString();

                        // parse select part of sql to use as update
                        string regex = @"SELECT\s*\r\n\s*(?<ColumnValue>.+)?\s*AS\s*(?<ColumnAlias>\[\w+\])\r\n\s*FROM\s*(?<TableName>\[\w+\]\.\[\w+\]|\[\w+\])\s*AS\s*(?<TableAlias>\[\w+\])";
                        Match  match = Regex.Match(sql, regex);
                        if (!match.Success)
                        {
                            throw new ArgumentException("The MemberAssignment expression could not be processed.", "updateExpression");
                        }

                        string value = match.Groups["ColumnValue"].Value;
                        string alias = match.Groups["TableAlias"].Value;

                        value = value.Replace(alias + ".", "");

                        foreach (ObjectParameter objectParameter in selectQuery.Parameters)
                        {
                            string parameterName = "p__update__" + nameCount++;

                            var parameter = updateCommand.CreateParameter();
                            parameter.ParameterName = parameterName;
                            parameter.Value         = objectParameter.Value ?? DBNull.Value;
                            updateCommand.Parameters.Add(parameter);

                            value = value.Replace(objectParameter.Name, parameterName);
                        }
                        sqlBuilder.AppendFormat("[{0}] = {1}", columnName, value);
                    }
                    wroteSet = true;
                }

                sqlBuilder.AppendLine(" ");
                sqlBuilder.AppendFormat("FROM {0} AS j0 INNER JOIN (", entityMap.TableName);
                sqlBuilder.AppendLine();
                sqlBuilder.AppendLine(innerSelect);
                sqlBuilder.Append(") AS j1 ON (");

                bool wroteKey = false;
                foreach (var keyMap in entityMap.KeyMaps)
                {
                    if (wroteKey)
                    {
                        sqlBuilder.Append(" AND ");
                    }

                    sqlBuilder.AppendFormat("j0.[{0}] = j1.[{0}]", keyMap.ColumnName);
                    wroteKey = true;
                }
                sqlBuilder.Append(")");

                updateCommand.CommandText = sqlBuilder.ToString();

#if net45
                int result = async
                    ? await updateCommand.ExecuteNonQueryAsync()
                    : updateCommand.ExecuteNonQuery();
#else
                int result = updateCommand.ExecuteNonQuery();
#endif
                // only commit if created transaction
                if (ownTransaction)
                {
                    updateTransaction.Commit();
                }

                return(result);
            }
            finally
            {
                if (updateCommand != null)
                {
                    updateCommand.Dispose();
                }
                if (updateTransaction != null && ownTransaction)
                {
                    updateTransaction.Dispose();
                }
                if (updateConnection != null && ownConnection)
                {
                    updateConnection.Close();
                }
            }
        }
示例#8
0
 /// <summary>
 ///删除数据
 /// </summary>
 /// <typeparam name="T">泛型</typeparam>
 /// <param name="objObjectQuery">查询对象</param>
 /// <param name="condition">条件</param>
 public static void DeleteData <T>(this ObjectQuery <T> objObjectQuery, string condition) where T : System.Data.Objects.DataClasses.EntityObject
 {
     objObjectQuery.Where(condition).DeleteData();
 }
	public ManagementObjectSearcher(ManagementScope scope, ObjectQuery query) {}
    /// <summary>
    /// Finds dataset of stored binding objects and joins target object IDs from this dataset using ; separator.
    /// </summary>
    private string GetOriginalSelectorData()
    {
        var bindingObjectQuery = new ObjectQuery(BindingObjectType);
        var bindedItemsIDs = bindingObjectQuery.Column(TargetObjectIDColumn)
                                               .WhereEquals(CurrentObjectIDColumn, CurrentObjectInfo.ObjectID);

        string originalValues = string.Empty;
        if (!DataHelper.DataSourceIsEmpty(bindedItemsIDs))
        {
            originalValues = TextHelper.Join(";", DataHelper.GetStringValues(bindedItemsIDs.Tables[0], TargetObjectIDColumn));
        }

        return originalValues;
    }
示例#11
0
 protected virtual string Select(string selectClause, ObjectQuery objectQuery)
 {
     string where = null;
     if (this.entity.BaseEntity == null) {
         where = (objectQuery.WhereClause.Length == 0
             ? String.Empty : " WHERE " + objectQuery.WhereClause);
     }
     else {
         string filter = " WHERE " + this.GetExpression(this.entity.Table, this.entity.TypeField, this.entity.TypeValue);
         where = filter + (objectQuery.WhereClause.Length == 0
             ? string.Empty : " AND " + objectQuery.WhereClause);
     }
     string sort = (objectQuery.SortClause.Length == 0
         ? String.Empty : " ORDER BY " + objectQuery.SortClause);
     if (objectQuery.PageSize <= 0) {
         return selectClause + where + sort + TS;
     }
     else if (this.provider.SelectPageQuery != null && this.provider.SelectPageQuery.Length > 0) {
         int prevCount = objectQuery.PageSize * (objectQuery.PageIndex - 1);
         string query = this.provider.SelectPageQuery.Replace("*",
             selectClause.Remove(0, 6) + where + sort);
         return string.Format(query, objectQuery.PageSize, prevCount, prevCount + 1);
     }
     else {
         throw new ORMapperException("ObjectSpace: Generic Paging is Not Supported");
     }
 }
    /// <summary>
    /// Gets the query for testing objects of the given type
    /// </summary>
    /// <param name="objectType">Object type</param>
    private static ObjectQuery GetNonTestingObjects(string objectType)
    {
        var results = new ObjectQuery(objectType);

        var typeInfo = results.TypeInfo;
        var where = new WhereCondition();

        // Add condition for testing names
        if (typeInfo.CodeNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN)
        {
            where.WhereNotStartsWith(typeInfo.CodeNameColumn, TEST_PREFIX);
        }
        if (typeInfo.DisplayNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN)
        {
            where.WhereNotStartsWith(typeInfo.DisplayNameColumn, TEST_PREFIX);
        }

        results.Where(where);

        return results;
    }
    private IEnumerable<ManagementObject> GetWmiObject(string query, string machineName, string rootPath)
    {
        try
        {
            var conn = new ConnectionOptions();
            var path = string.Format(@"\\{0}\{1}", machineName, rootPath);
            if (!string.IsNullOrEmpty(this.Username))
            {
                conn.Username = this.Username;
            }

            var pwd = this.Decrypt(this.Password);
            if (!string.IsNullOrEmpty(pwd))
            {
                conn.Password = pwd;
            }

            path = string.Format(@"\\{0}\{1}", this.Hostname, rootPath);
            var scope = new ManagementScope(path, conn);
            this.Log.Debug(string.Format("{0} {1}", path, query));
            var queryObject = new ObjectQuery(query);
            var searcher = new ManagementObjectSearcher(scope, queryObject);
            return searcher.Get().Cast<ManagementObject>().ToList();
        }
        catch (Exception e)
        {
            this.Log.Debug(e);
            throw;
        }
    }
    protected void GetData()
    {
        string whereStr;
        string orderBy;

        whereStr = "";
        orderBy = "it.EmailFrom desc";
        BLL_ScheduleTasks = new ScheduleTasksBLL();
        vBackupAndEmailSettingObj = BLL_ScheduleTasks.GetBackupAndEmailSetting(whereStr, orderBy);
        if (vBackupAndEmailSettingObj.Count()>0)
        {
            foreach (var item in vBackupAndEmailSettingObj)
            {
                this.TempKeyId = item.BackupID.ToString();
            }
        }
    }
 private async Task <int> InternalUpdate <TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery <TEntity> query, Expression <Func <TEntity, TEntity> > updateExpression, bool async = false)
     where TEntity : class
 /// <summary>
 /// Create and run a batch update statement asynchronously.
 /// </summary>
 /// <typeparam name="TEntity">The type of the entity.</typeparam>
 /// <param name="objectContext">The <see cref="ObjectContext"/> to get connection and metadata information from.</param>
 /// <param name="entityMap">The <see cref="EntityMap"/> for <typeparamref name="TEntity"/>.</param>
 /// <param name="query">The query to create the where clause from.</param>
 /// <param name="updateExpression">The update expression.</param>
 /// <returns>
 /// The number of rows updated.
 /// </returns>
 public Task <int> UpdateAsync <TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery <TEntity> query, Expression <Func <TEntity, TEntity> > updateExpression) where TEntity : class
 {
     return(InternalUpdate(objectContext, entityMap, query, updateExpression, true));
 }
        /// <summary>
        /// Create and run a batch update statement.
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <param name="objectContext">The <see cref="ObjectContext"/> to get connection and metadata information from.</param>
        /// <param name="entityMap">The <see cref="EntityMap"/> for <typeparamref name="TEntity"/>.</param>
        /// <param name="query">The query to create the where clause from.</param>
        /// <param name="updateExpression">The update expression.</param>
        /// <returns>
        /// The number of rows updated.
        /// </returns>
        public int Update <TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery <TEntity> query, Expression <Func <TEntity, TEntity> > updateExpression) where TEntity : class
        {
#if net45
            return(InternalUpdate(objectContext, entityMap, query, updateExpression, false).Result);
#else
            return(InternalUpdate(objectContext, entityMap, query, updateExpression));
#endif
        }
示例#18
0
        private static int OldTests()
        {
            using (northwindEFEntities db = new northwindEFEntities())
            {
                {
                    string entitySQL           = "SELECT VALUE o FROM Orders AS o WHERE SQLite.DatePart('yyyy', o.OrderDate) = 1997 ORDER BY o.OrderID;";
                    ObjectQuery <Orders> query = db.CreateQuery <Orders>(entitySQL);

                    foreach (Orders o in query)
                    {
                        Console.WriteLine(o.ShipPostalCode);
                    }
                }

                {
                    var query = from c in db.Customers
                                where c.City == "London"
                                orderby c.CompanyName
                                select c;

                    int cc = query.Count();

                    foreach (Customers c in query)
                    {
                        Console.WriteLine(c.CompanyName);
                    }
                }

                {
                    string    scity = "London";
                    Customers c     = db.Customers.FirstOrDefault(cd => cd.City == scity);
                    Console.WriteLine(c.CompanyName);
                }

                {
                    DateTime dt    = new DateTime(1997, 1, 1);
                    var      query = from order in db.Orders
                                     where order.OrderDate < dt
                                     orderby order.OrderID
                                     select order;

                    foreach (Orders o in query)
                    {
                        Console.WriteLine(o.OrderDate.ToString());
                    }
                }

                {
                    Categories c = new Categories();
                    c.CategoryName = "Test Category";
                    c.Description  = "My Description";
                    db.AddToCategories(c);
                    db.SaveChanges();

                    Console.WriteLine(c.CategoryID);

                    c.Description = "My modified description";
                    db.SaveChanges();

                    db.DeleteObject(c);
                    db.SaveChanges();
                }

                {
                    Customers cust = new Customers();
                    cust.CustomerID  = "MTMTM";
                    cust.ContactName = "My Name";
                    cust.CompanyName = "SQLite Company";
                    cust.Country     = "Netherlands";
                    cust.City        = "Amsterdam";
                    cust.Phone       = "012345677";
                    db.AddToCustomers(cust);
                    db.SaveChanges();

                    db.DeleteObject(cust);
                    db.SaveChanges();
                }

                {
                    var query = db.Customers.Where(cust => cust.Country == "Denmark")
                                .SelectMany(cust => cust.Orders.Where(o => o.Freight > 5))
                                .OrderBy(o => o.Customers.CustomerID);

                    foreach (Orders c in query)
                    {
                        Console.WriteLine(c.Freight);
                    }
                }

                {
                    var query = from c in db.Customers
                                where c.Orders.Any(o => o.OrderDate.HasValue == true && o.OrderDate.Value.Year == 1997)
                                orderby c.CustomerID
                                select c;

                    foreach (Customers c in query)
                    {
                        Console.WriteLine(c.CompanyName);
                    }
                }

                {
                    string entitySQL           = "SELECT VALUE o FROM Orders AS o WHERE o.Customers.Country <> 'UK' AND o.Customers.Country <> 'Mexico' AND Year(o.OrderDate) = 1997 ORDER BY o.OrderID;";
                    ObjectQuery <Orders> query = db.CreateQuery <Orders>(entitySQL);

                    foreach (Orders o in query)
                    {
                        Console.WriteLine(o.ShipPostalCode);
                    }
                }

                {
                    string entitySQL           = "SELECT VALUE o FROM Orders AS o WHERE NewGuid() <> NewGuid() ORDER BY o.OrderID;";
                    ObjectQuery <Orders> query = db.CreateQuery <Orders>(entitySQL);

                    foreach (Orders o in query)
                    {
                        Console.WriteLine(o.ShipPostalCode);
                    }
                }

                // This query requires SQLite 3.6.2 to function correctly
                {
                    var query = from p in db.Products
                                where p.OrderDetails.Count(od => od.Orders.Customers.Country == p.Suppliers.Country) > 2
                                orderby p.ProductID
                                select p;

                    foreach (Products p in query)
                    {
                        Console.WriteLine(p.ProductName);
                    }
                }
            }

            //
            // NOTE: (JJM) Removed on 2011/07/06, makes it harder to run this EXE via
            //       the new unit test suite.
            //
            // Console.ReadKey();

            return(0);
        }
示例#19
0
        /// <summary>
        /// Perform collection task specific processing.
        /// </summary>
        ///
        /// <param name="taskId">Database assigned task Id.</param>
        /// <param name="cleId">Database Id of owning Collection Engine.</param>
        /// <param name="elementId">Database Id of element being collected.</param>
        /// <param name="databaseTimestamp">Database relatvie task dispatch timestamp.</param>
        /// <param name="localTimestamp">Local task dispatch timestamp.</param>
        /// <param name="attributes">Map of attribute names to Id for attributes being collected.</param>
        /// <param name="scriptParameters">Collection script specific parameters (name/value pairs).</param>
        /// <param name="connection">Connection script results (null if this script does not
        ///     require a remote host connection).</param>
        /// <param name="tftpDispatcher">Dispatcher for TFTP transfer requests.</param>
        /// <returns>Collection results.</returns>
        public CollectionScriptResults ExecuteTask(long taskId, long cleId, long elementId, long databaseTimestamp,
                                                   long localTimestamp, IDictionary <string, string> attributes, IDictionary <string, string> scriptParameters,
                                                   IDictionary <string, object> connection, string tftpPath, string tftpPath_login, string tftpPath_password,
                                                   ITftpDispatcher tftpDispatcher)
        {
            m_taskId            = taskId.ToString();
            m_cleId             = cleId;
            m_elementId         = elementId;
            m_databaseTimestamp = databaseTimestamp;
            m_localTimestamp    = localTimestamp;
            m_attributes        = attributes;
            m_scriptParameters  = scriptParameters;
            m_tftpDispatcher    = tftpDispatcher;
            m_connection        = connection;
            m_executionTimer    = Stopwatch.StartNew();

            ResultCodes resultCode = ResultCodes.RC_SUCCESS;

            Lib.Logger.TraceEvent(TraceEventType.Start,
                                  0,
                                  "Task Id {0}: Collection script HyperV_BiosInfoScript.",
                                  m_taskId);
            try
            {
                // Check ManagementScope virtualization
                if (connection == null)
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Connection object passed to HyperV_BiosInfoScript is null.",
                                          m_taskId);
                }
                else if (!connection.ContainsKey("virtualization"))
                {
                    resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Management scope for virtualization namespace is not present in connection object.",
                                          m_taskId);
                }
                else
                {
                    m_virtualizeScope = connection[@"virtualization"] as ManagementScope;
                    if (!m_virtualizeScope.IsConnected)
                    {
                        resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Connection to virtualization namespace failed",
                                              m_taskId);
                    }
                    if (!connection.ContainsKey("v2"))
                    {
                        //resultCode = ResultCodes.RC_NULL_CONNECTION_OBJECT;
                        Lib.Logger.TraceEvent(TraceEventType.Error,
                                              0,
                                              "Task Id {0}: Management scope for virtualization v2 namespace is not present in connection object.",
                                              m_taskId);
                    }
                    else
                    {
                        m_virtualizev2Scope = connection[@"v2"] as ManagementScope;
                        if (!m_virtualizev2Scope.IsConnected)
                        {
                            resultCode = ResultCodes.RC_WMI_CONNECTION_FAILED;
                            Lib.Logger.TraceEvent(TraceEventType.Error,
                                                  0,
                                                  "Task Id {0}: Connection to virtualization v2 namespace failed",
                                                  m_taskId);
                        }
                    }
                }

                //Check VM_Guid attribute
                if (scriptParameters.ContainsKey("VM_Guid"))
                {
                    m_VM_Guid = scriptParameters[@"VM_Guid"];
                }
                else
                {
                    resultCode = ResultCodes.RC_SCRIPT_PARAMETER_MISSING;
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Missing parameter VM_Guid attribute.",
                                          m_taskId);
                }
                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    /*                         ConnectionOptions connectionOptions = new ConnectionOptions();
                     *
                     *                       connectionOptions.Username = "******";
                     *
                     *                       connectionOptions.Password = @"Simple.0";
                     *                       ManagementScope m_virtualizeScope = new ManagementScope(@"\\Hyper-v9140\root\virtualization", connectionOptions);
                     *                       m_virtualizeScope.Connect();     */
                    String      queryString             = @"SELECT * FROM Msvm_VirtualSystemSettingData WHERE InstanceID like '%" + m_VM_Guid + "%'";
                    ObjectQuery query                   = new ObjectQuery(queryString);
                    ManagementObjectSearcher   searcher = null;
                    ManagementObjectCollection moc      = null;
                    if (m_virtualizeScope != null)
                    {
                        searcher = new ManagementObjectSearcher(m_virtualizeScope, query);
                        moc      = searcher.Get();
                        using (searcher)
                        {
                            resultCode = Lib.ExecuteWqlQuery(m_taskId, searcher, out moc);
                        }
                    }
                    if (m_virtualizev2Scope != null && ResultCodes.RC_SUCCESS != resultCode && ResultCodes.RC_WMI_QUERY_TIMEOUT != resultCode)
                    {
                        searcher = new ManagementObjectSearcher(m_virtualizev2Scope, query);
                        moc      = searcher.Get();
                        using (searcher)
                        {
                            resultCode = Lib.ExecuteWqlQuery(m_taskId, searcher, out moc);
                        }
                    }
                    StringBuilder sbVmInfo = new StringBuilder();
                    String        base_board_serial_number = "";
                    String        bios_guid          = "";
                    String        bios_serial_number = "";
                    String        guid = "";
                    sbVmInfo.Append("<BDNA,A>");
                    if (ResultCodes.RC_SUCCESS == resultCode && null != moc)
                    {
                        using (moc)
                        {
                            foreach (ManagementObject mo in moc)
                            {
                                base_board_serial_number = (String)mo["BaseBoardSerialNumber"];
                                bios_guid          = (String)mo["BIOSGUID"];
                                bios_serial_number = (String)mo["BIOSSerialNumber"];
                                guid = (String)mo["InstanceID"];
                                guid = guid.Replace("Microsoft:", "");
                                guid = guid.Substring(0, 36);
                                sbVmInfo.Append(@"<BDNA,>Guid=""" + guid + @"""<BDNA,1>base_board_serial_number =""" + base_board_serial_number + @"""<BDNA,1>bios_guid=""" + bios_guid + @"""<BDNA,1>bios_serial_number=""" + bios_serial_number + @"""");
                            }

                            //
                            // Package data into CLE format to be returned.
                            if (sbVmInfo.Length > 0)
                            {
                                //       BuildDataRow(s_attributeName, sbVmInfo.ToString());
                                BuildDataRow(s_attributeName, sbVmInfo.ToString());
                            }
                        }
                    }
                }
            }
            catch (ManagementException mex)
            {
                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: ManagementException in HyperV_BiosInfoScript.  Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                          m_taskId,
                                          m_executionTimer.Elapsed.ToString(),
                                          mex.ToString());
                    resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
                }
            }
            catch (Exception ex)
            {
                if (resultCode == ResultCodes.RC_SUCCESS)
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in HyperV_BiosInfoScript.  Elapsed time {1}.\n{2}\nResult code changed to RC_PROCESSING_EXCEPTION.",
                                          m_taskId,
                                          m_executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                    resultCode = ResultCodes.RC_PROCESSING_EXCEPTION;
                }
                else
                {
                    Lib.Logger.TraceEvent(TraceEventType.Error,
                                          0,
                                          "Task Id {0}: Unhandled exception in HyperV_BiosInfoScript.  Elapsed time {1}.\n{2}",
                                          m_taskId,
                                          m_executionTimer.Elapsed.ToString(),
                                          ex.ToString());
                }
            }

            Lib.Logger.TraceEvent(TraceEventType.Stop,
                                  0,
                                  "Task Id {0}: Collection script HyperV_BiosInfoScript.  Elapsed time {1}.  Result code {2}.",
                                  m_taskId,
                                  m_executionTimer.Elapsed.ToString(),
                                  resultCode.ToString());
            return(new CollectionScriptResults(resultCode, 0, null, null, null, false, m_dataRow.ToString()));
        }
示例#20
0
        public static IEnumerable <Win32DiskDrive> Retrieve(ManagementScope managementScope)
        {
            var objectQuery      = new ObjectQuery("SELECT * FROM Win32_DiskDrive");
            var objectSearcher   = new ManagementObjectSearcher(managementScope, objectQuery);
            var objectCollection = objectSearcher.Get();

            foreach (ManagementObject managementObject in objectCollection)
            {
                yield return new Win32DiskDrive
                       {
                           Availability           = (ushort)(managementObject.Properties["Availability"]?.Value ?? default(ushort)),
                           BytesPerSector         = (uint)(managementObject.Properties["BytesPerSector"]?.Value ?? default(uint)),
                           Capabilities           = (ushort[])(managementObject.Properties["Capabilities"]?.Value ?? new ushort[0]),
                           CapabilityDescriptions = (string[])(managementObject.Properties["CapabilityDescriptions"]?.Value ?? new string[0]),
                           Caption                 = (string)(managementObject.Properties["Caption"]?.Value),
                           CompressionMethod       = (string)(managementObject.Properties["CompressionMethod"]?.Value),
                           ConfigManagerErrorCode  = (uint)(managementObject.Properties["ConfigManagerErrorCode"]?.Value ?? default(uint)),
                           ConfigManagerUserConfig = (bool)(managementObject.Properties["ConfigManagerUserConfig"]?.Value ?? default(bool)),
                           CreationClassName       = (string)(managementObject.Properties["CreationClassName"]?.Value),
                           DefaultBlockSize        = (ulong)(managementObject.Properties["DefaultBlockSize"]?.Value ?? default(ulong)),
                           Description             = (string)(managementObject.Properties["Description"]?.Value),
                           DeviceId                = (string)(managementObject.Properties["DeviceID"]?.Value),
                           ErrorCleared            = (bool)(managementObject.Properties["ErrorCleared"]?.Value ?? default(bool)),
                           ErrorDescription        = (string)(managementObject.Properties["ErrorDescription"]?.Value),
                           ErrorMethodology        = (string)(managementObject.Properties["ErrorMethodology"]?.Value),
                           FirmwareRevision        = (string)(managementObject.Properties["FirmwareRevision"]?.Value),
                           Index                       = (uint)(managementObject.Properties["Index"]?.Value ?? default(uint)),
                           InstallDate                 = ManagementDateTimeConverter.ToDateTime(managementObject.Properties["InstallDate"]?.Value as string ?? "00010102000000.000000+060"),
                           InterfaceType               = (string)(managementObject.Properties["InterfaceType"]?.Value),
                           LastErrorCode               = (uint)(managementObject.Properties["LastErrorCode"]?.Value ?? default(uint)),
                           Manufacturer                = (string)(managementObject.Properties["Manufacturer"]?.Value),
                           MaxBlockSize                = (ulong)(managementObject.Properties["MaxBlockSize"]?.Value ?? default(ulong)),
                           MaxMediaSize                = (ulong)(managementObject.Properties["MaxMediaSize"]?.Value ?? default(ulong)),
                           MediaLoaded                 = (bool)(managementObject.Properties["MediaLoaded"]?.Value ?? default(bool)),
                           MediaType                   = (string)(managementObject.Properties["MediaType"]?.Value),
                           MinBlockSize                = (ulong)(managementObject.Properties["MinBlockSize"]?.Value ?? default(ulong)),
                           Model                       = (string)(managementObject.Properties["Model"]?.Value),
                           Name                        = (string)(managementObject.Properties["Name"]?.Value),
                           NeedsCleaning               = (bool)(managementObject.Properties["NeedsCleaning"]?.Value ?? default(bool)),
                           NumberOfMediaSupported      = (uint)(managementObject.Properties["NumberOfMediaSupported"]?.Value ?? default(uint)),
                           Partitions                  = (uint)(managementObject.Properties["Partitions"]?.Value ?? default(uint)),
                           PnpDeviceId                 = (string)(managementObject.Properties["PNPDeviceID"]?.Value),
                           PowerManagementCapabilities = (ushort[])(managementObject.Properties["PowerManagementCapabilities"]?.Value ?? new ushort[0]),
                           PowerManagementSupported    = (bool)(managementObject.Properties["PowerManagementSupported"]?.Value ?? default(bool)),
                           RelativePath                = managementObject.Path.RelativePath,
                           ScsiBus                     = (uint)(managementObject.Properties["SCSIBus"]?.Value ?? default(uint)),
                           ScsiLogicalUnit             = (ushort)(managementObject.Properties["SCSILogicalUnit"]?.Value ?? default(ushort)),
                           ScsiPort                    = (ushort)(managementObject.Properties["SCSIPort"]?.Value ?? default(ushort)),
                           ScsiTargetId                = (ushort)(managementObject.Properties["SCSITargetId"]?.Value ?? default(ushort)),
                           SectorsPerTrack             = (uint)(managementObject.Properties["SectorsPerTrack"]?.Value ?? default(uint)),
                           SerialNumber                = (string)(managementObject.Properties["SerialNumber"]?.Value),
                           Signature                   = (uint)(managementObject.Properties["Signature"]?.Value ?? default(uint)),
                           Size                        = (ulong)(managementObject.Properties["Size"]?.Value ?? default(ulong)),
                           Status                      = (string)(managementObject.Properties["Status"]?.Value),
                           StatusInfo                  = (ushort)(managementObject.Properties["StatusInfo"]?.Value ?? default(ushort)),
                           SystemCreationClassName     = (string)(managementObject.Properties["SystemCreationClassName"]?.Value),
                           SystemName                  = (string)(managementObject.Properties["SystemName"]?.Value),
                           TotalCylinders              = (ulong)(managementObject.Properties["TotalCylinders"]?.Value ?? default(ulong)),
                           TotalHeads                  = (uint)(managementObject.Properties["TotalHeads"]?.Value ?? default(uint)),
                           TotalSectors                = (ulong)(managementObject.Properties["TotalSectors"]?.Value ?? default(ulong)),
                           TotalTracks                 = (ulong)(managementObject.Properties["TotalTracks"]?.Value ?? default(ulong)),
                           TracksPerCylinder           = (uint)(managementObject.Properties["TracksPerCylinder"]?.Value ?? default(uint))
                       }
            }
            ;
        }
    public static void ExtractNewsletterUnsubscriptionsFromActivities()
    {
        if (!ModuleEntryManager.IsModuleLoaded(ModuleName.NEWSLETTER))
        {
            return;
        }

        var activitiesQuery = new ObjectQuery(PredefinedObjectType.ACTIVITY)
            .Source(s => s.Join("OM_Contact", "ActivityActiveContactID", "ContactID"))
            .WhereEquals("ActivityType", PredefinedActivityType.NEWSLETTER_UNSUBSCRIBING)
            .WhereNotEmpty("ContactEmail")
            .Columns("ContactEmail", "ActivitySiteID", "ActivityCreated", "ActivityItemID")
            .Distinct();

        var activities = activitiesQuery.Select(row => new
        {
            SiteID = DataHelper.GetIntValue(row, "ActivitySiteID"),
            ContactEmail = DataHelper.GetStringValue(row, "ContactEmail"),
            ActivityCreated = DataHelper.GetDateTimeValue(row, "ActivityCreated"),
            NewsletterID = DataHelper.GetIntValue(row, "ActivityItemID"),
        });

        var existingUnsubscriptionsByNewsletterID = new ObjectQuery(PredefinedObjectType.NEWSLETTERUNSUBSCRIPTION)
            .WhereNotNull("UnsubscriptionNewsletterID")
            .Select(row => new
            {
                Email = DataHelper.GetStringValue(row, "UnsubscriptionEmail"),
                NewsletterID = DataHelper.GetIntValue(row, "UnsubscriptionNewsletterID"),
            })
            .GroupBy(unsubscription => unsubscription.NewsletterID)
            .ToDictionary(group => group.Key, group => group.Select(u => u.Email).ToHashSet(StringComparer.InvariantCultureIgnoreCase));

        foreach (var activity in activities)
        {
            if (existingUnsubscriptionsByNewsletterID.ContainsKey(activity.NewsletterID) && existingUnsubscriptionsByNewsletterID[activity.NewsletterID].Contains(activity.ContactEmail))
            {
                continue;
            }

            if (!ValidationHelper.IsEmail(activity.ContactEmail))
            {
                continue;
            }

            var unsubscriptionInfo = ModuleManager.GetObject(PredefinedObjectType.NEWSLETTERUNSUBSCRIPTION);

            unsubscriptionInfo.SetValue("UnsubscriptionEmail", activity.ContactEmail.ToLowerInvariant());
            unsubscriptionInfo.SetValue("UnsubscriptionNewsletterID", activity.NewsletterID);
            unsubscriptionInfo.SetValue("UnsubscriptionSiteID", activity.SiteID);
            unsubscriptionInfo.SetValue("UnsubscriptionCreated", activity.ActivityCreated);
            unsubscriptionInfo.SetValue("UnsubscriptionGUID", Guid.NewGuid());

            unsubscriptionInfo.Insert();

            if (existingUnsubscriptionsByNewsletterID.ContainsKey(activity.NewsletterID))
            {
                existingUnsubscriptionsByNewsletterID[activity.NewsletterID].Add(activity.ContactEmail);
            }
            else
            {
                existingUnsubscriptionsByNewsletterID[activity.NewsletterID] = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase) { activity.ContactEmail };
            }
        }
    }
        /// <summary>
        /// Create and run a batch delete statement.
        /// </summary>
        /// <typeparam name="TEntity">The type of the entity.</typeparam>
        /// <param name="objectContext">The <see cref="ObjectContext"/> to get connection and metadata information from.</param>
        /// <param name="entityMap">The <see cref="EntityMap"/> for <typeparamref name="TEntity"/>.</param>
        /// <param name="query">The query to create the where clause from.</param>
        /// <returns>
        /// The number of rows deleted.
        /// </returns>
        public int Delete <TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery <TEntity> query) where TEntity : class
        {
#if net45
            return(InternalDelete(objectContext, entityMap, query, false).Result);
#else
            return(InternalDelete(objectContext, entityMap, query));
#endif
        }
    /// <summary>
    /// Mass action 'ok' button clicked.
    /// </summary>
    protected void btnOk_Click(object sender, EventArgs e)
    {
        CheckModifyPermissions();

        Action action = (Action)ValidationHelper.GetInteger(drpAction.SelectedItem.Value, 0);
        What what = (What)ValidationHelper.GetInteger(drpWhat.SelectedItem.Value, 0);

        var where = new WhereCondition()
            .WhereEquals("ContactGroupMemberContactGroupID", cgi.ContactGroupID)
            // Set constraint for account relations only
            .WhereEquals("ContactGroupMemberType", 1);

        switch (what)
        {
            // All items
            case What.All:
                var accountIds = new ObjectQuery("om.contactgroupaccountlist")
                    .Column("AccountID")
                    .Where(gridElem.WhereCondition)
                    .Where(gridElem.WhereClause);

                where.WhereIn("ContactGroupMemberRelatedID", accountIds);
                break;
            // Selected items
            case What.Selected:
                // Convert array to integer values to make sure no sql injection is possible (via string values)
                where.WhereIn("ContactGroupMemberRelatedID", gridElem.SelectedItems);
                break;
            default:
                return;
        }

        switch (action)
        {
            // Action 'Remove'
            case Action.Remove:
                // Delete the relations between contact group and accounts
                ContactGroupMemberInfoProvider.DeleteContactGroupMembers(where.ToString(true), cgi.ContactGroupID, true, true);
                // Show result message
                if (what == What.Selected)
                {
                    ShowConfirmation(GetString("om.account.massaction.removed"));
                }
                else
                {
                    ShowConfirmation(GetString("om.account.massaction.removedall"));
                }
                break;
            default:
                return;
        }

        // Reload unigrid
        gridElem.ResetSelection();
        gridElem.ReloadData();
        pnlUpdate.Update();
    }
 /// <summary>
 /// Create and run a batch delete statement asynchronously.
 /// </summary>
 /// <typeparam name="TEntity">The type of the entity.</typeparam>
 /// <param name="objectContext">The <see cref="ObjectContext"/> to get connection and metadata information from.</param>
 /// <param name="entityMap">The <see cref="EntityMap"/> for <typeparamref name="TEntity"/>.</param>
 /// <param name="query">The query to create the where clause from.</param>
 /// <returns>
 /// The number of rows deleted.
 /// </returns>
 public Task <int> DeleteAsync <TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery <TEntity> query) where TEntity : class
 {
     return(InternalDelete(objectContext, entityMap, query, true));
 }
示例#25
0
 public string Select(ObjectQuery objectQuery)
 {
     string selectClause = this.select;
     if (objectQuery.manyTable != null && objectQuery.manyTable.Length > 0) {
         selectClause += ", " + this.GetDelimited(objectQuery.manyTable);
     }
     return this.Select(selectClause, objectQuery);
 }
 private async Task <int> InternalDelete <TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery <TEntity> query, bool async = false)
     where TEntity : class
示例#27
0
 //Optional - to allow static collection:
 public static IQueryable <TEntity> WhereIn <TEntity, TValue>(this ObjectQuery <TEntity> query, Expression <Func <TEntity, TValue> > selector, params TValue[] collection)
 {
     return(WhereIn(query, selector, (IEnumerable <TValue>)collection));
 }
        private int InternalDelete <TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery <TEntity> query)
            where TEntity : class
#endif
        {
            DbConnection  deleteConnection  = null;
            DbTransaction deleteTransaction = null;
            DbCommand     deleteCommand     = null;
            bool          ownConnection     = false;
            bool          ownTransaction    = false;

            try
            {
                // get store connection and transaction
                var store = GetStore(objectContext);
                deleteConnection  = store.Item1;
                deleteTransaction = store.Item2;

                if (deleteConnection.State != ConnectionState.Open)
                {
                    deleteConnection.Open();
                    ownConnection = true;
                }

                if (deleteTransaction == null)
                {
                    deleteTransaction = deleteConnection.BeginTransaction();
                    ownTransaction    = true;
                }


                deleteCommand             = deleteConnection.CreateCommand();
                deleteCommand.Transaction = deleteTransaction;
                if (objectContext.CommandTimeout.HasValue)
                {
                    deleteCommand.CommandTimeout = objectContext.CommandTimeout.Value;
                }

                var innerSelect = GetSelectSql(query, entityMap, deleteCommand);

                var sqlBuilder = new StringBuilder(innerSelect.Length * 2);

                sqlBuilder.Append("DELETE ");
                sqlBuilder.Append(entityMap.TableName);
                sqlBuilder.AppendLine();

                sqlBuilder.AppendFormat("FROM {0} AS j0 INNER JOIN (", entityMap.TableName);
                sqlBuilder.AppendLine();
                sqlBuilder.AppendLine(innerSelect);
                sqlBuilder.Append(") AS j1 ON (");

                bool wroteKey = false;
                foreach (var keyMap in entityMap.KeyMaps)
                {
                    if (wroteKey)
                    {
                        sqlBuilder.Append(" AND ");
                    }

                    sqlBuilder.AppendFormat("j0.[{0}] = j1.[{0}]", keyMap.ColumnName);
                    wroteKey = true;
                }
                sqlBuilder.Append(")");

                deleteCommand.CommandText = sqlBuilder.ToString();

#if net45
                int result = async
                    ? await deleteCommand.ExecuteNonQueryAsync()
                    : deleteCommand.ExecuteNonQuery();
#else
                int result = deleteCommand.ExecuteNonQuery();
#endif
                // only commit if created transaction
                if (ownTransaction)
                {
                    deleteTransaction.Commit();
                }

                return(result);
            }
            finally
            {
                if (deleteCommand != null)
                {
                    deleteCommand.Dispose();
                }

                if (deleteTransaction != null && ownTransaction)
                {
                    deleteTransaction.Dispose();
                }

                if (deleteConnection != null && ownConnection)
                {
                    deleteConnection.Close();
                }
            }
        }
示例#29
0
            /// <summary>
            /// Gets the appropriate LINQ expression for an inline ObjectQuery instance.
            /// </summary>
            private Expression InlineObjectQuery(ObjectQuery inlineQuery, Type expressionType)
            {
                EntityUtil.CheckArgumentNull(inlineQuery, "inlineQuery");

                Expression queryExpression;
                if (_funcletizer._mode == Mode.CompiledQueryLockdown)
                {
                    // In the lockdown phase, we don't chase down inline object queries because
                    // we don't yet know what the object context is supposed to be.
                    queryExpression = Expression.Constant(inlineQuery, expressionType);
                }
                else
                {
                    if (!object.ReferenceEquals(_funcletizer._rootContext, inlineQuery.QueryState.ObjectContext))
                    {
                        throw EntityUtil.NotSupported(System.Data.Entity.Strings.ELinq_UnsupportedDifferentContexts);
                    }

                    queryExpression = inlineQuery.GetExpression();

                    // If it's not an entity-sql (terminal) query, recursively process
                    if (!(inlineQuery.QueryState is EntitySqlQueryState))
                    {
                        queryExpression = InlineExpression(queryExpression);
                    }

                    queryExpression = TypeSystem.EnsureType(queryExpression, expressionType);
                }

                return queryExpression;
            }
示例#30
0
        public static ObjectQuery <T> Include <T>(this ObjectQuery <T> query, Expression <Func <T, object> > selector)
        {
            string path = new PropertyPathVisitor().GetPropertyPath(selector);

            return(query.Include(path));
        }
	public ManagementObjectSearcher(ObjectQuery query) {}
示例#32
0
        public static ObjectQuery <TEntity> FetchMany <TEntity, TReleated>(this ObjectQuery <TEntity> query, Expression <Func <TEntity, IEnumerable <TReleated> > > selector) where TEntity : class
        {
            string path = new PropertyPathVisitor().GetPropertyPath(selector);

            return(query.Include(path));
        }
示例#33
0
        public static IEnumerable <SqlExpressBrokerStatistics> Retrieve(ManagementScope managementScope)
        {
            var objectQuery      = new ObjectQuery("SELECT * FROM Win32_PerfRawData_MSSQLSQLEXPRESS_MSSQLSQLEXPRESSBrokerStatistics");
            var objectSearcher   = new ManagementObjectSearcher(managementScope, objectQuery);
            var objectCollection = objectSearcher.Get();

            foreach (ManagementObject managementObject in objectCollection)
            {
                yield return new SqlExpressBrokerStatistics
                       {
                           ActivationErrorsTotal      = (ulong)(managementObject.Properties["ActivationErrorsTotal"]?.Value ?? default(ulong)),
                           BrokerTransactionRollbacks = (ulong)(managementObject.Properties["BrokerTransactionRollbacks"]?.Value ?? default(ulong)),
                           Caption = (string)(managementObject.Properties["Caption"]?.Value),
                           CorruptedMessagesTotal          = (ulong)(managementObject.Properties["CorruptedMessagesTotal"]?.Value ?? default(ulong)),
                           DequeuedTransmissionQMsgsPersec = (ulong)(managementObject.Properties["DequeuedTransmissionQMsgsPersec"]?.Value ?? default(ulong)),
                           Description                     = (string)(managementObject.Properties["Description"]?.Value),
                           DialogTimerEventCount           = (ulong)(managementObject.Properties["DialogTimerEventCount"]?.Value ?? default(ulong)),
                           DroppedMessagesTotal            = (ulong)(managementObject.Properties["DroppedMessagesTotal"]?.Value ?? default(ulong)),
                           EnqueuedLocalMessagesPersec     = (ulong)(managementObject.Properties["EnqueuedLocalMessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedLocalMessagesTotal      = (ulong)(managementObject.Properties["EnqueuedLocalMessagesTotal"]?.Value ?? default(ulong)),
                           EnqueuedMessagesPersec          = (ulong)(managementObject.Properties["EnqueuedMessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedMessagesTotal           = (ulong)(managementObject.Properties["EnqueuedMessagesTotal"]?.Value ?? default(ulong)),
                           EnqueuedP10MessagesPersec       = (ulong)(managementObject.Properties["EnqueuedP10MessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedP1MessagesPersec        = (ulong)(managementObject.Properties["EnqueuedP1MessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedP2MessagesPersec        = (ulong)(managementObject.Properties["EnqueuedP2MessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedP3MessagesPersec        = (ulong)(managementObject.Properties["EnqueuedP3MessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedP4MessagesPersec        = (ulong)(managementObject.Properties["EnqueuedP4MessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedP5MessagesPersec        = (ulong)(managementObject.Properties["EnqueuedP5MessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedP6MessagesPersec        = (ulong)(managementObject.Properties["EnqueuedP6MessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedP7MessagesPersec        = (ulong)(managementObject.Properties["EnqueuedP7MessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedP8MessagesPersec        = (ulong)(managementObject.Properties["EnqueuedP8MessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedP9MessagesPersec        = (ulong)(managementObject.Properties["EnqueuedP9MessagesPersec"]?.Value ?? default(ulong)),
                           EnqueuedTransmissionQMsgsPersec = (ulong)(managementObject.Properties["EnqueuedTransmissionQMsgsPersec"]?.Value ?? default(ulong)),
                           EnqueuedTransportMsgFragsPersec = (ulong)(managementObject.Properties["EnqueuedTransportMsgFragsPersec"]?.Value ?? default(ulong)),
                           EnqueuedTransportMsgFragTot     = (ulong)(managementObject.Properties["EnqueuedTransportMsgFragTot"]?.Value ?? default(ulong)),
                           EnqueuedTransportMsgsPersec     = (ulong)(managementObject.Properties["EnqueuedTransportMsgsPersec"]?.Value ?? default(ulong)),
                           EnqueuedTransportMsgsTotal      = (ulong)(managementObject.Properties["EnqueuedTransportMsgsTotal"]?.Value ?? default(ulong)),
                           ForwardedMessagesPersec         = (ulong)(managementObject.Properties["ForwardedMessagesPersec"]?.Value ?? default(ulong)),
                           ForwardedMessagesTotal          = (ulong)(managementObject.Properties["ForwardedMessagesTotal"]?.Value ?? default(ulong)),
                           ForwardedMsgBytesPersec         = (ulong)(managementObject.Properties["ForwardedMsgBytesPersec"]?.Value ?? default(ulong)),
                           ForwardedMsgByteTotal           = (ulong)(managementObject.Properties["ForwardedMsgByteTotal"]?.Value ?? default(ulong)),
                           ForwardedMsgDiscardedTotal      = (ulong)(managementObject.Properties["ForwardedMsgDiscardedTotal"]?.Value ?? default(ulong)),
                           ForwardedMsgsDiscardedPersec    = (ulong)(managementObject.Properties["ForwardedMsgsDiscardedPersec"]?.Value ?? default(ulong)),
                           ForwardedPendingMsgBytes        = (ulong)(managementObject.Properties["ForwardedPendingMsgBytes"]?.Value ?? default(ulong)),
                           ForwardedPendingMsgCount        = (ulong)(managementObject.Properties["ForwardedPendingMsgCount"]?.Value ?? default(ulong)),
                           FrequencyObject                 = (ulong)(managementObject.Properties["Frequency_Object"]?.Value ?? default(ulong)),
                           FrequencyPerfTime               = (ulong)(managementObject.Properties["Frequency_PerfTime"]?.Value ?? default(ulong)),
                           FrequencySys100Ns               = (ulong)(managementObject.Properties["Frequency_Sys100NS"]?.Value ?? default(ulong)),
                           Name = (string)(managementObject.Properties["Name"]?.Value),
                           SqlreceivEsPersec = (ulong)(managementObject.Properties["SQLRECEIVEsPersec"]?.Value ?? default(ulong)),
                           SqlreceiveTotal   = (ulong)(managementObject.Properties["SQLRECEIVETotal"]?.Value ?? default(ulong)),
                           SqlsenDsPersec    = (ulong)(managementObject.Properties["SQLSENDsPersec"]?.Value ?? default(ulong)),
                           SqlsendTotal      = (ulong)(managementObject.Properties["SQLSENDTotal"]?.Value ?? default(ulong)),
                           TimestampObject   = (ulong)(managementObject.Properties["Timestamp_Object"]?.Value ?? default(ulong)),
                           TimestampPerfTime = (ulong)(managementObject.Properties["Timestamp_PerfTime"]?.Value ?? default(ulong)),
                           TimestampSys100Ns = (ulong)(managementObject.Properties["Timestamp_Sys100NS"]?.Value ?? default(ulong))
                       }
            }
            ;
        }
    }
        /// <summary>Creates a command to execute the batch operation.</summary>
        /// <exception cref="Exception">Thrown when an exception error condition occurs.</exception>
        /// <typeparam name="T">Generic type parameter.</typeparam>
        /// <param name="query">The query.</param>
        /// <param name="entity">The schema entity.</param>
        /// <param name="visitor">The visitor.</param>
        /// <returns>The new command to execute the batch operation.</returns>
        internal DbCommand CreateCommand <T>(ObjectQuery query, SchemaEntityType <T> entity)
        {
            // GET command
            var command = query.Context.CreateStoreCommand();

            bool isMySql  = command.GetType().FullName.Contains("MySql");
            var  isSqlCe  = command.GetType().Name == "SqlCeCommand";
            var  isOracle = command.GetType().Namespace.Contains("Oracle");

            // Oracle BindByName
            if (isOracle)
            {
                var bindByNameProperty = command.GetType().GetProperty("BindByName") ?? command.GetType().GetProperty("PassParametersByName");
                if (bindByNameProperty != null)
                {
                    bindByNameProperty.SetValue(command, true, null);
                }
            }

            // GET mapping
            var mapping = entity.Info.EntityTypeMapping.MappingFragment;
            var store   = mapping.StoreEntitySet;

            string tableName;

            if (isMySql)
            {
                tableName = string.Concat("`", store.Table, "`");
            }
            else if (isSqlCe)
            {
                tableName = string.Concat("[", store.Table, "]");
            }
            else if (isOracle)
            {
                tableName = string.IsNullOrEmpty(store.Schema) || store.Schema == "dbo" ?
                            string.Concat("\"", store.Table, "\"") :
                            string.Concat("\"", store.Schema, "\".\"", store.Table, "\"");
            }
            else
            {
                tableName = string.IsNullOrEmpty(store.Schema) ?
                            string.Concat("[", store.Table, "]") :
                            string.Concat("[", store.Schema, "].[", store.Table, "]");
            }

            // GET keys mappings
            var columnKeys = new List <string>();

            foreach (var propertyKey in entity.Info.Key.PropertyRefs)
            {
                var mappingProperty = mapping.ScalarProperties.Find(x => x.Name == propertyKey.Name);

                if (mappingProperty == null)
                {
                    throw new Exception(string.Format(ExceptionMessage.BatchOperations_PropertyNotFound, propertyKey.Name));
                }

                columnKeys.Add(mappingProperty.ColumnName);
            }

            // GET command text template
            var commandTextTemplate = command.GetType().Name == "NpgsqlCommand" ?
                                      CommandTextPostgreSQLTemplate :
                                      isOracle ?
                                      CommandTextOracleTemplate :
                                      isMySql ?
                                      CommandTextTemplate_MySql :
                                      isSqlCe ?
                                      CommandTextSqlCeTemplate :
                                      BatchSize > 0 ?
                                      BatchDelayInterval > 0 ?
                                      CommandTextWhileDelayTemplate :
                                      CommandTextWhileTemplate :
                                      CommandTextTemplate;

            // GET inner query
            var customQuery = query.GetCommandTextAndParameters();

            if (customQuery.Item1.EndsWith("WHERE 1 = 0", StringComparison.InvariantCultureIgnoreCase))
            {
                return(null);
            }

            var querySelect = customQuery.Item1;

            // GET primary key join
            string primaryKeys;

            if (isSqlCe || isOracle)
            {
                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat(tableName + ".", EscapeName(x, isMySql, isOracle), " = B.", EscapeName(x, isMySql, isOracle), "")));
            }
            else
            {
                primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.", EscapeName(x, isMySql, isOracle), " = B.", EscapeName(x, isMySql, isOracle), "")));
            }

            // REPLACE template
            commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                  .Replace("{Select}", querySelect)
                                  .Replace("{PrimaryKeys}", primaryKeys)
                                  .Replace("{Top}", BatchSize.ToString())
                                  .Replace("{Delay}", TimeSpan.FromMilliseconds(BatchDelayInterval).ToString(@"hh\:mm\:ss\:fff"))
                                  .Replace("{Hint}", UseTableLock ? "WITH ( TABLOCK )" : "");

            // CREATE command
            command.CommandText = commandTextTemplate;

            // ADD Parameter
            var parameterCollection = customQuery.Item2;

#if EF5
            foreach (ObjectParameter parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.CopyFrom(parameter);

                command.Parameters.Add(param);
            }
#elif EF6
            foreach (DbParameter parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.CopyFrom(parameter);

                command.Parameters.Add(param);
            }
#endif

            return(command);
        }
示例#35
0
        public static Dictionary <string, string[]> EnumManagementServices()
        {
            string sHostname = System.Environment.MachineName;

            string QueryString = "SELECT * FROM Win32_Service";

            string[] serviceInfo = null;
            Dictionary <string, string[]> services = new Dictionary <string, string[]>();
            ManagementScope managementScope        = null;

            Logger.Log(string.Format("ServiceManagerWindowsWrapper.EnumManagementServices(sHostname={0})", sHostname), Logger.ServiceManagerLoglevel);

            try
            {
                //Point to machine
                managementScope = new ManagementScope("\\\\" + sHostname + "\\root\\cimv2", new ConnectionOptions());

                //Query remote computer across the connection
                ObjectQuery objectQuery = new ObjectQuery(QueryString);
                ManagementObjectSearcher mgtQueryCollection = new ManagementObjectSearcher(managementScope, objectQuery);

                foreach (ManagementObject MObj in mgtQueryCollection.Get())
                {
                    serviceInfo = new string[5];
                    try
                    {
                        serviceInfo[0] = MObj["Caption"].ToString();
                        serviceInfo[1] = MObj["Description"].ToString();

                        if (MObj["State"].Equals("Paused"))
                        {
                            serviceInfo[2] = "Paused";
                        }
                        else if (MObj["Started"].Equals(true))
                        {
                            serviceInfo[2] = "Started";
                        }
                        else
                        {
                            serviceInfo[2] = string.Empty;
                        }

                        if (MObj["StartMode"].ToString().Equals("Auto"))
                        {
                            serviceInfo[3] = "Automatic";
                        }
                        else
                        {
                            serviceInfo[3] = MObj["StartMode"].ToString();
                        }

                        string startName = MObj["StartName"].ToString();
                        serviceInfo[4] = startName.IndexOf("\\") >= 0 ?
                                         startName.Substring(startName.IndexOf("\\") + 1) : startName;

                        services.Add(MObj["Name"].ToString(), serviceInfo);
                    }
                    catch { }
                }
            }
            catch (Exception ex)
            {
                services = null;
                Logger.LogException("ServiceManagerWindowsWrapper.EnumManagementServices()", ex);
            }

            return(services);
        }
示例#36
0
        protected void CheckBoxList1_DataBound(object sender, EventArgs e)
        {
            MetaTable childTable = ChildrenColumn.ChildTable;

            // Comments assume employee/territory for illustration, but the code is generic

            IList         entityList    = null;
            ObjectContext objectContext = null;

            if (Mode == DataBoundControlMode.Edit)
            {
                object entity;
                ICustomTypeDescriptor rowDescriptor = Row as ICustomTypeDescriptor;
                if (rowDescriptor != null)
                {
                    // Get the real entity from the wrapper
                    entity = rowDescriptor.GetPropertyOwner(null);
                }
                else
                {
                    entity = Row;
                }

                // Get the collection of territories for this employee and make sure it's loaded
                RelatedEnd entityCollection = Column.EntityTypeProperty.GetValue(entity, null) as RelatedEnd;
                if (entityCollection == null)
                {
                    throw new InvalidOperationException(String.Format("The ManyToMany template does not support the collection type of the '{0}' column on the '{1}' table.", Column.Name, Table.Name));
                }
                if (!entityCollection.IsLoaded)
                {
                    entityCollection.Load();
                }

                // Get an IList from it (i.e. the list of territories for the current employee)
                // REVIEW: we should be using EntityCollection directly, but EF doesn't have a
                // non generic type for it. They will add this in vnext
                entityList = ((IListSource)entityCollection).GetList();

                // Get the current ObjectContext
                // REVIEW: this is quite a dirty way of doing this. Look for better alternative
                ObjectQuery objectQuery = (ObjectQuery)entityCollection.GetType().GetMethod(
                    "CreateSourceQuery").Invoke(entityCollection, null);
                objectContext = objectQuery.Context;
            }

            // Go through all the territories (not just those for this employee)
            foreach (object childEntity in childTable.GetQuery(objectContext))
            {
                MetaTable actualTable = MetaTable.GetTable(childEntity.GetType());
                // Create a checkbox for it
                ListItem listItem = new ListItem(
                    actualTable.GetDisplayString(childEntity),
                    actualTable.GetPrimaryKeyString(childEntity));

                // Make it selected if the current employee has that territory
                if (Mode == DataBoundControlMode.Edit)
                {
                    listItem.Selected = entityList.Contains(childEntity);
                }

                CheckBoxList1.Items.Add(listItem);
            }
        }
    /// <summary>
    /// Returns binding info objects for each changed item.
    /// </summary>
    /// <param name="changedItems">Comma separated list of changed IDs</param>
    /// <param name="parentColumn">Parent ID column in the binding object</param>
    /// <param name="targetColumn">Other related object ID column in the binding object</param>
    /// <param name="create">If true, bindings will not be retrieved from database. Otherwise only if the binding has own ID column.</param>
    private IEnumerable<BaseInfo> GetBindings(string changedItems, string parentColumn, string targetColumn, bool create)
    {
        var bindingsToProcess = Enumerable.Empty<BaseInfo>();

        if (!String.IsNullOrEmpty(changedItems))
        {
            var items = changedItems.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            if (items.Any())
            {
                var bindingTypeInfo = ObjectTypeManager.GetTypeInfo(BindingObjectType);

                if (create || bindingTypeInfo.IDColumn == ObjectTypeInfo.COLUMN_NAME_UNKNOWN)
                {
                    bindingsToProcess = CreateBindings(items, parentColumn, targetColumn);
                }
                else
                {
                    // If binding has object ID column, retrieve all changed objects by single query
                    bindingsToProcess = new ObjectQuery(BindingObjectType, false)
                        .WhereEquals(parentColumn, ObjectID)
                        .WhereIn(targetColumn, items);
                }
            }
        }

        return bindingsToProcess;
    }
示例#38
0
        public BindingData GetBindingData(string interfaceId)
        {
            BindingData bindings_data = new BindingData()
            {
                CfMN    = BindingStatus.NotInstalled,
                FaPSfMN = BindingStatus.NotInstalled,
                LLDP    = BindingStatus.NotInstalled,
            };

            var scope = new ManagementScope("\\\\.\\ROOT\\StandardCimv2");
            var query = new ObjectQuery("SELECT * FROM MSFT_NetAdapterBindingSettingData");

            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
            {
                using (ManagementObjectCollection bindings = searcher.Get())
                {
                    foreach (ManagementObject item in bindings)
                    {
                        string InstanceID  = (string)item["InstanceID"];
                        string ComponentID = (string)item["ComponentID"];

                        // Client for Microsoft Networks
                        if (InstanceID.ToLower().Contains(interfaceId.ToLower()) && InstanceID.ToLower() == "ms_msclient")
                        {
                            bool Enabled = (bool)item["Enabled"];

                            if (Enabled)
                            {
                                bindings_data.CfMN = BindingStatus.InstalledEnabled;
                            }
                            else
                            {
                                bindings_data.CfMN = BindingStatus.NotInstalled;
                            }
                        }

                        // File and Print Sharing for Microsoft Networks
                        if (InstanceID.ToLower().Contains(interfaceId.ToLower()) && InstanceID.ToLower() == "ms_server")
                        {
                            bool Enabled = (bool)item["Enabled"];

                            if (Enabled)
                            {
                                bindings_data.FaPSfMN = BindingStatus.InstalledEnabled;
                            }
                            else
                            {
                                bindings_data.FaPSfMN = BindingStatus.NotInstalled;
                            }
                        }

                        // Microsoft LLDP Protocol Driver
                        if (InstanceID.ToLower().Contains(interfaceId.ToLower()) && InstanceID.ToLower() == "ms_lldp")
                        {
                            bool Enabled = (bool)item["Enabled"];

                            if (Enabled)
                            {
                                bindings_data.LLDP = BindingStatus.InstalledEnabled;
                            }
                            else
                            {
                                bindings_data.LLDP = BindingStatus.NotInstalled;
                            }
                        }
                    }
                }
            }

            return(bindings_data);
        }
    /// <summary>
    /// Checks if current user has subscribed given post.
    /// </summary>
    /// <param name="postId">ID of forum post</param>
    /// <returns>true if user has subscriptions for given post, false if not</returns>
    private bool CheckSubscription()
    {
        if (UserID != MembershipContext.AuthenticatedUser.UserID)
        {
            // Check permissions
            if (!CheckPermissions("cms.forums", PERMISSION_MODIFY))
            {
                return false;
            }
        }
        var query = new ObjectQuery<ForumSubscriptionInfo>().Where(new WhereCondition().WhereNull("SubscriptionApproved").Or().WhereEquals("SubscriptionApproved", 1)).And().WhereEquals("SubscriptionUserID", UserID).And().WhereEquals("SubscriptionPostID", PostID).Column("SubscriptionID").TopN(1);

        return query.Any();
    }
示例#40
0
 public static ObjectQuery <T> IncludeToQuery <T>(this ObjectQuery <T> query, IEnumerable <Expression <Func <T, object> > > includePaths)
 {
     return(includePaths.Aggregate(query, (current, path) => (ObjectQuery <T>)current.Include(path)));
 }
    /// <summary>
    /// Post-processing of the clicked link/opened email records generated via subscriber link. Ensure valid emails from subscriber table.
    /// </summary>
    private static void ProcessClickedLinkAndOpenedEmailGeneratedViaSubscriberLink()
    {
        bool isSeparated = !String.IsNullOrEmpty(DatabaseSeparationHelper.ConnStringSeparate);

        // If the database is separated, create temporary table with subscribers' ID and email
        if (isSeparated)
        {
            // Get the subscribers with email from the default database
            var subscribersQuery = new ObjectQuery("newsletter.subscriber")
            .Columns("SubscriberID", "SubscriberEmail")
            .WhereNull("SubscriberType").Or()
            .WhereEquals("SubscriberType", "om.contact");

            // Get the subscribers of user type from the default database
            var subscribersFromUsersQuery = new ObjectQuery("newsletter.subscriber")
            .Source(s => s.LeftJoin<UserInfo>("SubscriberRelatedID", "UserID"))
            .Columns(new QueryColumn("SubscriberID"), new QueryColumn("Email").As("SubscriberEmail"))
            .WhereEquals("SubscriberType", "cms.user")
            .WhereNotNull("Email");

            DataSet subscribers = subscribersQuery.Union(subscribersFromUsersQuery);

            const string createTempTableScript =
        @"
        CREATE TABLE [Temp_Newsletter_Subscriber]
        (
        [SubscriberEmail] [nvarchar] (400),
        [SubscriberID] [int] NOT NULL
        ) ON [PRIMARY];
        ";
            // Create temporary table with subscribers on the separated db
            using (new CMSConnectionScope(DatabaseSeparationHelper.OM_CONNECTION_STRING, false, true))
            {
                ConnectionHelper.ExecuteQuery(createTempTableScript, null, QueryTypeEnum.SQLQuery);
            }

            // Fill the table with subscribers' data
            using (var bulkCopy = new SqlBulkCopy(DatabaseSeparationHelper.ConnStringSeparate, SqlBulkCopyOptions.KeepIdentity))
            {
                bulkCopy.ColumnMappings.Add("SubscriberEmail", "SubscriberEmail");
                bulkCopy.ColumnMappings.Add("SubscriberID", "SubscriberID");
                bulkCopy.BulkCopyTimeout = 6000;
                bulkCopy.DestinationTableName = "Temp_Newsletter_Subscriber";
                bulkCopy.WriteToServer(subscribers.Tables[0]);
            }

            const string updateClicksScript =
        @"
        UPDATE Newsletter_ClickedLink
        SET ClickedLinkEmail = SubscriberEmail
        FROM Newsletter_ClickedLink
        LEFT JOIN Temp_Newsletter_Subscriber
        ON REPLACE(ClickedLinkEmail,'subscriberid_','') = Temp_Newsletter_Subscriber.SubscriberID
        WHERE ClickedLinkEmail NOT LIKE '%@%' AND SubscriberEmail IS NOT NULL;
        ";
            const string updateOpensScript =
        @"
        UPDATE Newsletter_OpenedEmail
        SET OpenedEmailEmail = SubscriberEmail
        FROM Newsletter_OpenedEmail
        LEFT JOIN Temp_Newsletter_Subscriber
        ON REPLACE(OpenedEmailEmail,'subscriberid_','') = SubscriberID
        WHERE OpenedEmailEmail NOT LIKE '%@%' AND SubscriberEmail IS NOT NULL;
        ";
            var existingIssueIDs = new ObjectQuery("newsletter.issue")
                .Column("IssueID")
                .GetListResult<int>();

            string deleteOpensWithNonExistingIssues =
        string.Format(@"
        DELETE FROM [Newsletter_OpenedEmail]
        WHERE [OpenedEmailIssueID] NOT IN ({0})
        ", string.Join(",", existingIssueIDs));

            // Update the data in ClickedLink/OpenedEmail table using OM connection string (or default)
            using (new CMSConnectionScope(DatabaseSeparationHelper.OM_CONNECTION_STRING, false, true))
            {
                ConnectionHelper.ExecuteQuery(updateClicksScript, null, QueryTypeEnum.SQLQuery);
                ConnectionHelper.ExecuteQuery(updateOpensScript, null, QueryTypeEnum.SQLQuery);
                ConnectionHelper.ExecuteQuery(deleteOpensWithNonExistingIssues, null, QueryTypeEnum.SQLQuery);
            }

            const string dropTempTableScript =
        @"
        DROP TABLE Temp_Newsletter_Subscriber;
        ";
            const string deleteUnresolvedClicksScript =
        @"
        DELETE FROM Newsletter_ClickedLink WHERE ClickedLinkEmail LIKE 'subscriberid_%' OR ClickedLinkEmail = '';
        ";
            const string deleteUnresolvedOpensScript =
        @"
        DELETE FROM Newsletter_OpenedEmail WHERE OpenedEmailEmail LIKE 'subscriberid_%' OR OpenedEmailEmail = '';
        ";
            const string deleteDuplicatesScript =
        @"
        WITH NOE AS(
           SELECT OpenedEmailID, OpenedEmailEmail, OpenedEmailIssueID, OpenedEmailTime,
           RN = ROW_NUMBER() OVER (PARTITION BY OpenedEmailEmail, OpenedEmailIssueID ORDER BY OpenedEmailTime ASC)
           FROM Newsletter_OpenedEmail
        )
        DELETE FROM NOE
        WHERE RN > 1;";

            // Delete the temporary table on the separated database and ClickedLinks/OpenedEmails with unresolved emails
            using (new CMSConnectionScope(DatabaseSeparationHelper.OM_CONNECTION_STRING, false, false))
            {
                ConnectionHelper.ExecuteQuery(dropTempTableScript, null, QueryTypeEnum.SQLQuery);
                ConnectionHelper.ExecuteQuery(deleteUnresolvedClicksScript, null, QueryTypeEnum.SQLQuery);
                ConnectionHelper.ExecuteQuery(deleteUnresolvedOpensScript, null, QueryTypeEnum.SQLQuery);
                ConnectionHelper.ExecuteQuery(deleteDuplicatesScript, null, QueryTypeEnum.SQLQuery);
            }

            // Update Issues with opened email count
            var openedEmailsSummary = new ObjectQuery("newsletter.openedemail")
                .Columns(new QueryColumn("OpenedEmailIssueID"), new AggregatedColumn(AggregationType.Count, "OpenedEmailIssueID").As("Count"))
                .GroupBy("OpenedEmailIssueID");

            const string createOpenedEmailsSummaryTempTableScript =
        @"
        CREATE TABLE [Temp_Opened_Summary]
        (
        [OpenedEmailIssueID] [int],
        [Count] [int]
        ) ON [PRIMARY];
        ";
            ConnectionHelper.ExecuteQuery(createOpenedEmailsSummaryTempTableScript, null, QueryTypeEnum.SQLQuery);

            using (var bulkCopy = new SqlBulkCopy(ConnectionHelper.ConnectionString, SqlBulkCopyOptions.KeepIdentity))
            {
                bulkCopy.ColumnMappings.Add("OpenedEmailIssueID", "OpenedEmailIssueID");
                bulkCopy.ColumnMappings.Add("Count", "Count");
                bulkCopy.BulkCopyTimeout = 6000;
                bulkCopy.DestinationTableName = "Temp_Opened_Summary";
                bulkCopy.WriteToServer(openedEmailsSummary.Tables[0]);
            }

            const string updateIssueOpenedEmailsScript =
        @"
        UPDATE Newsletter_NewsletterIssue
        SET IssueOpenedEmails = (
        SELECT Count FROM Temp_Opened_Summary
        WHERE OpenedEmailIssueID = IssueID);
        ";
            ConnectionHelper.ExecuteQuery(updateIssueOpenedEmailsScript, null, QueryTypeEnum.SQLQuery);

            const string dropOpenedEmailsSummaryTempTableScript =
        @"
        DROP TABLE Temp_Opened_Summary;
        ";
            ConnectionHelper.ExecuteQuery(dropOpenedEmailsSummaryTempTableScript, null, QueryTypeEnum.SQLQuery);
        }
        else
        {
            const string updateClicksScript =
        @"
        UPDATE Newsletter_ClickedLink
        SET ClickedLinkEmail = ISNULL(SubscriberEmail, Email)
        FROM Newsletter_ClickedLink
        LEFT JOIN Newsletter_Subscriber
        ON REPLACE(ClickedLinkEmail,'subscriberid_','') = Newsletter_Subscriber.SubscriberID
        LEFT JOIN CMS_User
        ON (UserID = SubscriberRelatedID AND SubscriberType = 'cms.user')
        WHERE ClickedLinkEmail NOT LIKE '%@%' AND (SubscriberEmail IS NOT NULL OR Email IS NOT NULL);
        ";
            const string deleteUnresolvedClicksScript =
        @"
        DELETE FROM Newsletter_ClickedLink WHERE ClickedLinkEmail LIKE 'subscriberid_%' OR ClickedLinkEmail = '';
        ";
            const string updateOpensScript =
        @"
        UPDATE Newsletter_OpenedEmail
        SET OpenedEmailEmail = SubscriberEmail
        FROM Newsletter_OpenedEmail
        LEFT JOIN Newsletter_Subscriber
        ON REPLACE(OpenedEmailEmail,'subscriberid_','') = SubscriberID
        WHERE OpenedEmailEmail NOT LIKE '%@%' AND SubscriberEmail IS NOT NULL;
        ";
            const string deleteUnresolvedOpensScript =
        @"
        DELETE FROM Newsletter_OpenedEmail WHERE OpenedEmailEmail LIKE 'subscriberid_%' OR OpenedEmailEmail = '';
        ";
            const string deleteDuplicatesScript =
        @"
        WITH NOE AS(
           SELECT OpenedEmailID, OpenedEmailEmail, OpenedEmailIssueID, OpenedEmailTime,
           RN = ROW_NUMBER() OVER (PARTITION BY OpenedEmailEmail, OpenedEmailIssueID ORDER BY OpenedEmailTime ASC)
           FROM Newsletter_OpenedEmail
        )
        DELETE FROM NOE
        WHERE RN > 1;
        ";
            const string updateIssueOpenedEmailsScript =
        @"
        UPDATE Newsletter_NewsletterIssue
        SET IssueOpenedEmails = (
        SELECT COUNT(OpenedEmailIssueID) FROM Newsletter_OpenedEmail
        WHERE OpenedEmailIssueID = IssueID
        GROUP BY OpenedEmailIssueID);
        ";

            // Update the data in ClickedLink/OpenEmail and delete unresolved emails
            using (new CMSConnectionScope())
            {
                ConnectionHelper.ExecuteQuery(updateClicksScript, null, QueryTypeEnum.SQLQuery);
                ConnectionHelper.ExecuteQuery(deleteUnresolvedClicksScript, null, QueryTypeEnum.SQLQuery);
                ConnectionHelper.ExecuteQuery(updateOpensScript, null, QueryTypeEnum.SQLQuery);
                ConnectionHelper.ExecuteQuery(deleteUnresolvedOpensScript, null, QueryTypeEnum.SQLQuery);
                ConnectionHelper.ExecuteQuery(deleteDuplicatesScript, null, QueryTypeEnum.SQLQuery);
                ConnectionHelper.ExecuteQuery(updateIssueOpenedEmailsScript, null, QueryTypeEnum.SQLQuery);
            }
        }
    }
            public static void QueryAndLog()
            {
                var winQuery = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");

                var searcher = new ManagementObjectSearcher(winQuery);

                foreach (ManagementObject item in searcher.Get())
                {
                    if (item["FreePhysicalMemory"] != null)
                    {
                        ulong.TryParse(item["FreePhysicalMemory"].ToString(), out FreePhysicalMemory);
                    }
                    if (item["FreeSpaceInPagingFiles"] != null)
                    {
                        ulong.TryParse(item["FreeSpaceInPagingFiles"].ToString(), out FreeSpaceInPagingFiles);
                    }
                    if (item["FreeVirtualMemory"] != null)
                    {
                        ulong.TryParse(item["FreeVirtualMemory"].ToString(), out FreeVirtualMemory);
                    }
                    if (item["LargeSystemCache"] != null)
                    {
                        uint.TryParse(item["LargeSystemCache"].ToString(), out LargeSystemCache);
                    }
                    if (item["MaxNumberOfProcesses"] != null)
                    {
                        uint.TryParse(item["MaxNumberOfProcesses"].ToString(), out MaxNumberOfProcesses);
                    }
                    if (item["MaxProcessMemorySize"] != null)
                    {
                        ulong.TryParse(item["MaxProcessMemorySize"].ToString(), out MaxProcessMemorySize);
                    }
                    if (item["NumberOfLicensedUsers"] != null)
                    {
                        uint.TryParse(item["NumberOfLicensedUsers"].ToString(), out NumberOfLicensedUsers);
                    }
                    if (item["NumberOfProcesses"] != null)
                    {
                        uint.TryParse(item["NumberOfProcesses"].ToString(), out NumberOfProcesses);
                    }
                    if (item["NumberOfUsers"] != null)
                    {
                        uint.TryParse(item["NumberOfUsers"].ToString(), out NumberOfUsers);
                    }
                    if (item["OperatingSystemSKU"] != null)
                    {
                        uint.TryParse(item["OperatingSystemSKU"].ToString(), out OperatingSystemSKU);
                    }
                    if (item["SizeStoredInPagingFiles"] != null)
                    {
                        ulong.TryParse(item["SizeStoredInPagingFiles"].ToString(), out SizeStoredInPagingFiles);
                    }
                    if (item["SuiteMask"] != null)
                    {
                        uint.TryParse(item["SuiteMask"].ToString(), out SuiteMask);
                    }
                    if (item["TotalSwapSpaceSize"] != null)
                    {
                        ulong.TryParse(item["TotalSwapSpaceSize"].ToString(), out TotalSwapSpaceSize);
                    }
                    if (item["TotalVirtualMemorySize"] != null)
                    {
                        ulong.TryParse(item["TotalVirtualMemorySize"].ToString(), out TotalVirtualMemorySize);
                    }
                    if (item["TotalVisibleMemorySize"] != null)
                    {
                        ulong.TryParse(item["TotalVisibleMemorySize"].ToString(), out TotalVisibleMemorySize);
                    }
                    // log
                    Helpers.ConsolePrint("SystemSpecs", $"FreePhysicalMemory = {FreePhysicalMemory}");
                    Helpers.ConsolePrint("SystemSpecs", $"FreeSpaceInPagingFiles = {FreeSpaceInPagingFiles}");
                    Helpers.ConsolePrint("SystemSpecs", $"FreeVirtualMemory = {FreeVirtualMemory}");
                    Helpers.ConsolePrint("SystemSpecs", $"LargeSystemCache = {LargeSystemCache}");
                    Helpers.ConsolePrint("SystemSpecs", $"MaxNumberOfProcesses = {MaxNumberOfProcesses}");
                    Helpers.ConsolePrint("SystemSpecs", $"MaxProcessMemorySize = {MaxProcessMemorySize}");
                    Helpers.ConsolePrint("SystemSpecs", $"NumberOfLicensedUsers = {NumberOfLicensedUsers}");
                    Helpers.ConsolePrint("SystemSpecs", $"NumberOfProcesses = {NumberOfProcesses}");
                    Helpers.ConsolePrint("SystemSpecs", $"NumberOfUsers = {NumberOfUsers}");
                    Helpers.ConsolePrint("SystemSpecs", $"OperatingSystemSKU = {OperatingSystemSKU}");
                    Helpers.ConsolePrint("SystemSpecs", $"SizeStoredInPagingFiles = {SizeStoredInPagingFiles}");
                    Helpers.ConsolePrint("SystemSpecs", $"SuiteMask = {SuiteMask}");
                    Helpers.ConsolePrint("SystemSpecs", $"TotalSwapSpaceSize = {TotalSwapSpaceSize}");
                    Helpers.ConsolePrint("SystemSpecs", $"TotalVirtualMemorySize = {TotalVirtualMemorySize}");
                    Helpers.ConsolePrint("SystemSpecs", $"TotalVisibleMemorySize = {TotalVisibleMemorySize}");
                }
            }
示例#43
0
        static void Main(string[] args)
        {
            try
            {
                FileStream fileStream = new FileStream(inventFile, FileMode.Append);

                if (File.Exists(inventFile))
                {
                    using (StreamWriter sw = new StreamWriter(fileStream))
                    {
                        sw.Write("Added: " + DateTime.Now.ToString());

                        ManagementScope scope = new ManagementScope(@"\\" + computerName + @"\root\cimv2");
                        scope.Connect();

                        ObjectQuery query = new ObjectQuery("Select * From Win32_SystemEnclosure");
                        ManagementObjectSearcher   searcher = new ManagementObjectSearcher(scope, query);
                        ManagementObjectCollection objColl  = searcher.Get();

                        foreach (ManagementObject o in objColl)
                        {
                            Console.WriteLine("ServiceTag=" + o["SerialNumber"].ToString());
                            sw.Write(",  ServiceTag=" + o["SerialNumber"].ToString());
                        }

                        query    = new ObjectQuery("Select * from Win32_ComputerSystem");
                        searcher = new ManagementObjectSearcher(scope, query);

                        objColl = searcher.Get();

                        foreach (ManagementObject oReturn in objColl)
                        {
                            string Manufacturer = (string)oReturn["Manufacturer"];
                            sw.Write(", Manufacturer=" + (string)oReturn["Manufacturer"]);

                            string Model = (string)oReturn["Model"];
                            sw.Write(", Model=" + (string)oReturn["Model"]);

                            string name = (string)oReturn["Name"];
                            sw.Write(", name=" + (string)oReturn["name"]);

                            string userName = (string)oReturn["UserName"];
                            sw.Write(", userName="******"userName"]);

                            Console.WriteLine((string)oReturn["Manufacturer"]);
                            Console.WriteLine((string)oReturn["Model"]);
                            Console.WriteLine((string)oReturn["Name"]);
                            Console.WriteLine((string)oReturn["UserName"]);
                        }
                        sw.WriteLine();
                        sw.Close();
                    }
                }
                // else
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error :" + ex.Message);
                Console.WriteLine("Prova att köra programmet en gång till..");
            }

            Console.WriteLine("");
            Console.Write("<Enter> to quit :");
            Console.ReadLine();
        }
    protected void RadGrid_DeleteCommand(object sender, GridCommandEventArgs e)
    {
        string strWhere;
        string getScheduleID;//获取的绑定MasterTableView的Guid值

        getScheduleID = (e.Item as GridDataItem).GetDataKeyValue("ScheduleID").ToString();

        BLL_ScheduleTasks = new ScheduleTasksBLL();
        SchedulerObj      = BLL_ScheduleTasks.FindSchedulerById(getScheduleID);

        this.OrderBy = " it.name desc ";
        strWhere     = " and it.name='" + SchedulerObj.TaskName + "'";
        BLL_vSysJobs = new vSysJobsBLL();
        vSysJobsObjs = BLL_vSysJobs.GetVSysJobs(strWhere, this.OrderBy);

        if (vSysJobsObjs.Count() > 0)
        {
            BLL_JOB = new JOB();
            count   = BLL_JOB.DeleteJob(SchedulerObj.JobID.ToString()); //删除job

            if (count == 1)                                             //删除作业成功
            {
                successFlag = BLL_ScheduleTasks.LogicDelete(getScheduleID);
                if (!successFlag.Equals("InsertError"))//删除ScheduleTasks内的数据成功
                {
                    GridViewDataBinding();

                    //删除ScheduleTask数据成功
                    MessageBox(true, false, false,
                               GetGlobalResourceObject("WebResource", "ScheduleTasksForm_DeleteTasksMessage_RightMessage").ToString());
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "reload", "<script>window.location=window.self.location;</script>");//强制刷页
                }
                else
                {
                    //删除ScheduleTask数据失败
                    MessageBox(false, false, true,
                               GetGlobalResourceObject("WebResource", "ScheduleTasksForm_DeleteTasksMessage_ErrorMessage").ToString());
                }
            }
            else
            {
                //删除job失败
                MessageBox(false, false, true,
                           GetGlobalResourceObject("WebResource", "ScheduleTasksForm_DeleteJobMessage_ErrorMessage").ToString());
            }
        }
        else
        {
            successFlag = BLL_ScheduleTasks.LogicDelete(getScheduleID);
            if (!successFlag.Equals("InsertError"))//删除ScheduleTasks内的数据成功
            {
                GridViewDataBinding();

                //删除ScheduleTask数据成功
                MessageBox(true, false, false,
                           GetGlobalResourceObject("WebResource", "ScheduleTasksForm_DeleteTasksMessage_RightMessage").ToString());
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "reload", "<script>window.location=window.self.location;</script>");//强制刷页
            }
            else
            {
                //删除ScheduleTask数据失败
                MessageBox(false, false, true,
                           GetGlobalResourceObject("WebResource", "ScheduleTasksForm_DeleteTasksMessage_ErrorMessage").ToString());
            }
        }
    }
    /// <summary>
    /// Excludes the testing objects from the given infos query
    /// </summary>
    /// <param name="infos">Query</param>
    private static void ExcludeTestingObjects(ObjectQuery infos)
    {
        var typeInfo = infos.TypeInfo;

        // Add condition for testing names
        if (typeInfo.CodeNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN)
        {
            infos.WhereNotStartsWith(typeInfo.CodeNameColumn, TEST_PREFIX);
        }
        if (typeInfo.DisplayNameColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN)
        {
            infos.WhereNotStartsWith(typeInfo.DisplayNameColumn, TEST_PREFIX);
        }

        var sites = GetNonTestingObjects(SiteInfo.OBJECT_TYPE);

        // Add site condition (exclude testing site)
        if (typeInfo.SiteIDColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN)
        {
            infos.WhereIn(typeInfo.SiteIDColumn, sites);
        }

        // Add condition for testing parent (exclude testing parents)
        var parentObjectType = typeInfo.ParentObjectType;
        if (!String.IsNullOrEmpty(parentObjectType))
        {
            var parents = GetNonTestingObjects(parentObjectType);
            var parentTypeInfo = parents.TypeInfo;

            // Add site condition for parent (exclude parents from testing site)
            if (parentTypeInfo.SiteIDColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN)
            {
                parents.WhereIn(parentTypeInfo.SiteIDColumn, sites);
            }

            infos.WhereIn(typeInfo.ParentIDColumn, parents);
        }
    }
    public void GridViewDataBinding()
    {
        Boolean       isExtit;
        StringBuilder jobExpetion;

        this.OrderBy = " it.StartTime desc ";
        string whereStr;

        whereStr          = "";
        BLL_ScheduleTasks = new ScheduleTasksBLL();
        SchedulerObjList  = BLL_ScheduleTasks.GetSchedulers(whereStr, OrderBy);//查询SD的job信息

        BLL_vSysJobs = new vSysJobsBLL();
        if (SchedulerObjList.Count() > 0)
        {
            BLL_ScheduleLog = new vScheduleLogBLL();
            TasksTempList   = new List <TasksTemp>();

            foreach (tblScheduler item in SchedulerObjList)
            {
                this.OrderBy = " it.name desc";
                whereStr     = " and it.name='" + item.TaskName + "'";

                vSysJobsObjs = BLL_vSysJobs.GetVSysJobs(whereStr, this.OrderBy);

                if (vSysJobsObjs.Count() > 0)
                {//job存在
                    foreach (vSchedulerTasks Temp in vSysJobsObjs)
                    {
                        TasksTempObj              = new TasksTemp();
                        TasksTempObj.ScheduleID   = item.ScheduleID;
                        TasksTempObj.TaskName     = item.TaskName.Substring(0, item.TaskName.LastIndexOf("-"));//截取-CreateSD;
                        TasksTempObj.ScheduleType = item.ScheduleType;
                        TasksTempObj.Enable       = Temp.enabled;
                        if (TasksTempObj.Enable.Equals(1))
                        {//job运行
                            TasksTempObj.StatusImageURL = GetGlobalResourceObject("WebResource", "ScheduleTasksForm_CustomerMessage_Message").ToString();
                            TasksTempObj.Status         = "Enable";
                        }
                        else
                        {//job停止运行
                            TasksTempObj.StatusImageURL = GetGlobalResourceObject("WebResource", "ScheduleTasksForm_CustomerMessage_Message").ToString();
                            TasksTempObj.Status         = "Disable";
                        }
                        TasksTempObj.Next_run_date = Temp.RunOnlyEnd.ToString();
                        TasksTempObj.Last_run_date = Temp.RunOnlyStart.ToString();

                        TasksTempObj.LogResult = BLL_ScheduleLog.FindJobResultByScheduleId(
                            item.ScheduleID.ToString(),
                            item.RunOnlyStart.ToString(),
                            item.RunOnlyEnd.ToString());
                    }
                    TasksTempList.Add(TasksTempObj);
                }
                else
                {//job不存在
                    TasksTempObj                = new TasksTemp();
                    TasksTempObj.ScheduleID     = item.ScheduleID;
                    TasksTempObj.TaskName       = item.TaskName.Substring(0, item.TaskName.LastIndexOf("-"));//截取-CreateSD;;
                    TasksTempObj.ScheduleType   = item.ScheduleType;
                    TasksTempObj.StatusImageURL = GetGlobalResourceObject("WebResource", "ScheduleTasksForm_CustomerMessage_Message").ToString();
                    TasksTempObj.Status         = "Disable";
                    TasksTempList.Add(TasksTempObj);
                }
            }
        }

        this.OrderBy  = " it.name desc";
        whereStr      = "";
        vOnlyJobsObjs = BLL_vSysJobs.GetVOnlyJobs(whereStr, this.OrderBy);//查询job的系统信息

        jobExpetion = new StringBuilder();
        foreach (vOnlySysJobs job in vOnlyJobsObjs)
        {
            isExtit = SchedulerObjList.Any(it => it.TaskName == job.name); //在SD中是否存在相应的Taskname
            if (!isExtit)                                                  //不存在
            {
                if (job.name.IndexOf("-CreateSD") > 0)                     //是否SD创建
                {
                    pnlMessage.Visible = true;                             //显示提示信息
                    //在系统中存在为-CreateSD结尾的job但是在SD数据库中不存在
                    if (jobExpetion.ToString() == string.Empty)
                    {
                        jobExpetion.Append("Job Excepetion:" + " ");
                        jobExpetion.Append("\"" + job.name + "\"");
                    }
                    else
                    {
                        jobExpetion.Append(",\"" + job.name + "\"");
                    }
                }
            }
        }
        if (pnlMessage.Visible == true && SuccessFlag == null)//显示异常job信息
        {
            jobExpetion.Append(" ");
            jobExpetion.Append(GetGlobalResourceObject("WebResource", "ScheduleTasksForm_JobExcepeciton_Message").ToString());
            MessageBox(false, true, false,
                       jobExpetion.ToString());
        }
        else
        {
            pnlMessage.Visible = false;
        }

        RadGrid.DataSource = TasksTempList;
    }
    /// <summary>
    /// Gets the macros from the system
    /// </summary>
    /// <param name="startIndex">Start index</param>
    /// <param name="endIndex">End index</param>
    /// <param name="maxTotalRecords">Maximum number of total records to process</param>
    /// <param name="totalRecords">Returns the total number of records found</param>
    private IEnumerable<MacroExpr> GetMacros(int startIndex, int endIndex, int maxTotalRecords, ref int totalRecords)
    {
        var index = 0;
        IEnumerable<string> objectTypes = null;

        // Get object types to search
        var selectedType = ValidationHelper.GetString(selObjectType.Value, "");
        if (!String.IsNullOrEmpty(selectedType))
        {
            if (ObjectTypeManager.GetRegisteredTypeInfo(selectedType) != null)
            {
                objectTypes = new List<string> { selectedType };
            }
        }

        if (objectTypes == null)
        {
            objectTypes = ObjectTypeManager.ObjectTypesWithMacros;
        }

        var result = new List<MacroExpr>();
        var search = txtFilter.Text;

        var invalid = chkInvalid.Checked;
        var skipTesting = SystemContext.DevelopmentMode && chkSkipTesting.Checked;

        var type = drpType.Text;

        foreach (var objectType in objectTypes)
        {
            // Skip certain object types
            switch (objectType)
            {
                case ObjectVersionHistoryInfo.OBJECT_TYPE:
                case VersionHistoryInfo.OBJECT_TYPE:
                case StagingTaskInfo.OBJECT_TYPE:
                case IntegrationTaskInfo.OBJECT_TYPE:
                    continue;
            }

            // Process all objects of the given type
            var infos = new ObjectQuery(objectType)
                .TopN(maxTotalRecords)
                .BinaryData(false);

            var typeInfo = infos.TypeInfo;

            if (skipTesting)
            {
                ExcludeTestingObjects(infos);
            }

            if (!String.IsNullOrEmpty(search))
            {
                // Search particular expression
                infos.WhereAnyColumnContains(search);
            }
            else
            {
                // Search just type
                infos.WhereAnyColumnContains("{" + type);
            }

            Action<DataRow> collectMacros = dr =>
            {
                var drc = new DataRowContainer(dr);

                // Process all expressions
                MacroProcessor.ProcessMacros(drc, (expression, colName) =>
                    {
                        var originalExpression = expression;

                        // Decode macro from XML
                        if (MacroProcessor.IsXMLColumn(colName))
                        {
                            expression = HTMLHelper.HTMLDecode(expression);
                        }

                        MacroExpr e = null;
                        bool add = false;

                        if (String.IsNullOrEmpty(search) || (expression.IndexOfCSafe(search, true) >= 0))
                        {
                            // If not tracking errors, count immediately
                            if (!invalid)
                            {
                                // Apply paging. Endindex is -1 when paging is off
                                if ((endIndex < 0) || ((index >= startIndex) && (index <= endIndex)))
                                {
                                    e = GetMacroExpr(expression);
                                    add = true;
                                }

                                index++;
                            }
                            else
                            {
                                e = GetMacroExpr(expression);

                                // Filter invalid signature / syntax
                                var pass = !e.SignatureValid || e.Error;
                                if (pass)
                                {
                                    // Apply paging. Endindex is -1 when paging is off
                                    if ((endIndex < 0) || ((index >= startIndex) && (index <= endIndex)))
                                    {
                                        add = true;
                                    }

                                    index++;
                                }
                            }
                        }

                        if (add)
                        {
                            // Fill in the object information
                            e.ObjectType = objectType;
                            e.ObjectID = (typeInfo.IDColumn == ObjectTypeInfo.COLUMN_NAME_UNKNOWN) ? 0 : ValidationHelper.GetInteger(dr[typeInfo.IDColumn], 0);
                            e.Field = colName;

                            result.Add(e);
                        }

                        return originalExpression;
                    },
                    new List<string> { type }
                );

                if ((maxTotalRecords != -1) && (index >= maxTotalRecords))
                {
                    // Enough data - cancel enumeration
                    throw new ActionCancelledException();
                }
            };

            using (var scope = new CMSConnectionScope())
            {
                scope.Connection.CommandTimeout = ConnectionHelper.LongRunningCommandTimeout;

                infos.ForEachRow(collectMacros);
            }

            if (((maxTotalRecords != -1) && (index >= maxTotalRecords)) || !CMSHttpContext.Current.Response.IsClientConnected)
            {
                break;
            }
        }

        totalRecords = index;
        return result;
    }
示例#48
0
    public static string GetPhysicalMemory()
    {
        ManagementScope oMs = new ManagementScope();
        ObjectQuery oQuery = new ObjectQuery("SELECT Capacity FROM Win32_PhysicalMemory");
        ManagementObjectSearcher oSearcher = new ManagementObjectSearcher(oMs, oQuery);
        ManagementObjectCollection oCollection = oSearcher.Get();

        long MemSize = 0;
        long mCap = 0;

        // In case more than one Memory sticks are installed
        foreach (ManagementObject obj in oCollection)
        {
            mCap = Convert.ToInt64(obj["Capacity"]);
            MemSize += mCap;
        }
        MemSize = (MemSize / 1024) / 1024;
        return MemSize.ToString() + "MB";
    }
示例#49
0
 public string Select(ObjectQuery objectQuery, string[] selectFields)
 {
     return this.Select(this.CreateSelect(selectFields), objectQuery);
 }
        private int GenerateContactRelationships(ObjectQuery<ContactInfo> contacts)
        {
            var contactsList = contacts.ToList();

            foreach (var contact in contactsList)
            {
                ContactMembershipInfoProvider.SetRelationship(MemberTypeEnum.CmsUser, StaticRandomUsers.NextUser(), contact, false);
            }

            return contactsList.Count;
        }
        /// <summary>Creates a command to execute the batch operation.</summary>
        /// <param name="query">The query.</param>
        /// <param name="entity">The schema entity.</param>
        /// <returns>The new command to execute the batch operation.</returns>
        internal DbCommand CreateCommand <T>(ObjectQuery query, SchemaEntityType <T> entity, List <Tuple <string, object> > values)
        {
            var  command = query.Context.CreateStoreCommand();
            bool isMySql = command.GetType().FullName.Contains("MySql");

            // GET mapping
            var mapping = entity.Info.EntityTypeMapping.MappingFragment;
            var store   = mapping.StoreEntitySet;

            string tableName;

            if (isMySql)
            {
                tableName = string.Concat("`", store.Table, "`");
            }
            else
            {
                tableName = string.IsNullOrEmpty(store.Schema) ?
                            string.Concat("[", store.Table, "]") :
                            string.Concat("[", store.Schema, "].[", store.Table, "]");
            }


            // GET keys mappings
            var columnKeys = new List <string>();

            foreach (var propertyKey in entity.Info.Key.PropertyRefs)
            {
                var mappingProperty = mapping.ScalarProperties.Find(x => x.Name == propertyKey.Name);

                if (mappingProperty == null)
                {
                    throw new Exception(string.Format(ExceptionMessage.BatchOperations_PropertyNotFound, propertyKey.Name));
                }

                columnKeys.Add(mappingProperty.ColumnName);
            }


            // GET command text template
            var commandTextTemplate =
#if TODO
                BatchSize > 0 ?
                BatchDelayInterval > 0 ?
                CommandTextWhileDelayTemplate :
                CommandTextWhileTemplate :
#endif
                isMySql ? CommandTextTemplate_MySQL : CommandTextTemplate;

            // GET inner query
            var querySelect = query.ToTraceString();

            // GET primary key join
            var primaryKeys = string.Join(Environment.NewLine + "AND ", columnKeys.Select(x => string.Concat("A.", EscapeName(x, isMySql), " = B.", EscapeName(x, isMySql), "")));

            // GET updateSetValues
            var setValues = string.Join("," + Environment.NewLine, values.Select((x, i) => x.Item2 is ConstantExpression ?
                                                                                 string.Concat("A.", EscapeName(x.Item1, isMySql), " = ", ((ConstantExpression)x.Item2).Value) :
                                                                                 string.Concat("A.", EscapeName(x.Item1, isMySql), " = @zzz_BatchUpdate_", i)));

            // REPLACE template
            commandTextTemplate = commandTextTemplate.Replace("{TableName}", tableName)
                                  .Replace("{Select}", querySelect)
                                  .Replace("{PrimaryKeys}", primaryKeys)
                                  .Replace("{SetValue}", setValues);

            // CREATE command
            command.CommandText = commandTextTemplate;

            // ADD Parameter
            var parameterCollection = query.Parameters;

            foreach (var parameter in parameterCollection)
            {
                var param = command.CreateParameter();
                param.ParameterName = parameter.Name;
                param.Value         = parameter.Value;

                command.Parameters.Add(param);
            }

            for (var i = 0; i < values.Count; i++)
            {
                var value = values[i];

                if (value.Item2 is ConstantExpression)
                {
                    continue;
                }

                var parameter = command.CreateParameter();
                parameter.ParameterName = "@zzz_BatchUpdate_" + i;
                parameter.Value         = values[i].Item2 ?? DBNull.Value;
                command.Parameters.Add(parameter);
            }

            return(command);
        }
示例#52
0
 /// <summary>
 ///     Constructs a new <see cref="ObjectQueryState" /> copying the state information from the specified
 ///     <see cref="ObjectQuery" />.
 /// </summary>
 /// <param name="elementType"> The element type of the implemented ObjectQuery, as a CLR type. </param>
 /// <param name="query"> The ObjectQuery from which the state should be copied. </param>
 protected ObjectQueryState(Type elementType, ObjectQuery query)
     : this(elementType, query.Context, null, null)
 {
     _cachingEnabled = query.EnablePlanCaching;
     UserSpecifiedStreamingBehaviour = query.QueryState.UserSpecifiedStreamingBehaviour;
 }
示例#53
0
        private void Form1_Load(object sender, EventArgs ee)
        {
            if (File.Exists(@"LogFile.xml")) File.Delete(@"LogFile.xml");

            //string serverconnstring = ConfigurationManager.ConnectionStrings["GuangZhou_GnEntities"].ToString();

            servercontext = new GuangZhou_GnEntities();
            servercontext1 = new GuangZhou_GnEntities1();
            servercontext2 = new GuangZhou_GnEntities2();
            servercontext3 = new GuangZhou_GnEntities3();

            servercontext4 = new GuangZhou_GnEntities4();

            servercontext.CommandTimeout = 0;
            servercontext1.CommandTimeout = 0;
            servercontext2.CommandTimeout = 0;
            servercontext3.CommandTimeout = 0;
            servercontext4.CommandTimeout = 0;

            sqlserver_objectquery = servercontext.mpos_gn_common;
            sqlerver_segment = servercontext1.Gn_IP_Fragment;

            gb_ip_fragment = servercontext4.Gb_IP_Fragment;

            //修改成远端??
            gb_xid = servercontext2.Gb_XID;
            gb_pdp_xid = servercontext2.Gb_PDP_XID;
            gb_auth_imei = servercontext2.Gb_auth_imeisv;
            gb_imeitypes = servercontext2.imeitype;

            url_list = new HashSet<string>();

            var url_lists = servercontext3.url_result.Select(e => e.url);
            foreach (string url in url_lists) url_list.Add(url);

            string mysqlconnstring = ConfigurationManager.ConnectionStrings["guangzhou_0410Entities"].ToString();
            mysqlcontext = new guangzhou_0410Entities(mysqlconnstring);
        }
示例#54
0
        private void Get()
        {
            if (string.IsNullOrEmpty(this.ProcessName))
            {
                this.Log.LogError("ProcessName is required");
                return;
            }

            this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Getting Processes matching: {0}", this.ProcessName));

            ObjectQuery query         = new ObjectQuery("SELECT * FROM Win32_Process");
            Regex       userFilter    = new Regex(this.User, RegexOptions.Compiled);
            Regex       processFilter = new Regex(this.ProcessName, RegexOptions.Compiled);

            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(this.Scope, query, null))
            {
                this.Processes = new ITaskItem[searcher.Get().Count];
                int i = 0;
                foreach (ManagementObject ret in searcher.Get())
                {
                    if (processFilter.IsMatch(ret["Name"].ToString()))
                    {
                        ITaskItem processItem = new TaskItem(ret["Name"].ToString());
                        processItem.SetMetadata("Caption", ret["Caption"].ToString());
                        processItem.SetMetadata("Description", ret["Description"].ToString());
                        processItem.SetMetadata("Handle", ret["Handle"].ToString());
                        processItem.SetMetadata("HandleCount", ret["HandleCount"].ToString());
                        processItem.SetMetadata("KernelModeTime", ret["KernelModeTime"].ToString());
                        processItem.SetMetadata("PageFaults", ret["PageFaults"].ToString());
                        processItem.SetMetadata("PageFileUsage", ret["PageFileUsage"].ToString());
                        processItem.SetMetadata("ParentProcessId", ret["ParentProcessId"].ToString());
                        processItem.SetMetadata("PeakPageFileUsage", ret["PeakPageFileUsage"].ToString());
                        processItem.SetMetadata("PeakVirtualSize", ret["PeakVirtualSize"].ToString());
                        processItem.SetMetadata("PeakWorkingSetSize", ret["PeakWorkingSetSize"].ToString());
                        processItem.SetMetadata("Priority", ret["Priority"].ToString());
                        processItem.SetMetadata("PrivatePageCount", ret["PrivatePageCount"].ToString());
                        processItem.SetMetadata("ProcessId", ret["ProcessId"].ToString());
                        processItem.SetMetadata("QuotaNonPagedPoolUsage", ret["QuotaNonPagedPoolUsage"].ToString());
                        processItem.SetMetadata("QuotaPagedPoolUsage", ret["QuotaPagedPoolUsage"].ToString());
                        processItem.SetMetadata("QuotaPeakNonPagedPoolUsage", ret["QuotaPeakNonPagedPoolUsage"].ToString());
                        processItem.SetMetadata("QuotaPeakPagedPoolUsage", ret["QuotaPeakPagedPoolUsage"].ToString());
                        processItem.SetMetadata("ReadOperationCount", ret["ReadOperationCount"].ToString());
                        processItem.SetMetadata("ReadTransferCount", ret["ReadTransferCount"].ToString());
                        processItem.SetMetadata("SessionId", ret["SessionId"].ToString());
                        processItem.SetMetadata("ThreadCount", ret["ThreadCount"].ToString());
                        processItem.SetMetadata("UserModeTime", ret["UserModeTime"].ToString());
                        processItem.SetMetadata("VirtualSize", ret["VirtualSize"].ToString());
                        processItem.SetMetadata("WindowsVersion", ret["WindowsVersion"].ToString());
                        processItem.SetMetadata("WorkingSetSize", ret["WorkingSetSize"].ToString());
                        processItem.SetMetadata("WriteOperationCount", ret["WriteOperationCount"].ToString());
                        processItem.SetMetadata("WriteTransferCount", ret["WriteTransferCount"].ToString());
                        if (this.IncludeUserInfo)
                        {
                            string[] o = new string[2];
                            ret.InvokeMethod("GetOwner", o);

                            if (o[0] == null)
                            {
                                continue;
                            }

                            if (!userFilter.IsMatch(o[0]))
                            {
                                continue;
                            }

                            processItem.SetMetadata("User", o[0]);

                            if (o[1] != null)
                            {
                                processItem.SetMetadata("Domain", o[1]);
                            }

                            string[] sid = new string[1];
                            ret.InvokeMethod("GetOwnerSid", sid);
                            if (sid[0] != null)
                            {
                                processItem.SetMetadata("OwnerSID", sid[0]);
                            }
                        }

                        this.Processes[i] = processItem;
                        i++;
                    }
                }
            }
        }
示例#55
0
        // requires: inlineQuery is not null and inlineQuery is Entity-SQL query
        // effects: interprets the given query as an inline query in the current expression and unites
        // the current query context with the context for the inline query. If the given query specifies
        // span information, then an entry is added to the span mapping dictionary from the CQT expression
        // that is the root of the inline query, to the span information that was present in the inline
        // query's Span property.
        private DbExpression TranslateInlineQueryOfT(ObjectQuery inlineQuery)
        {
            if (!ReferenceEquals(_funcletizer.RootContext, inlineQuery.QueryState.ObjectContext))
            {
                throw new NotSupportedException(Strings.ELinq_UnsupportedDifferentContexts);
            }

            // Check if the inline query has been encountered so far. If so, we don't need to
            // include its parameters again. We do however need to translate it to a new
            // DbExpression instance since the expressions may be tagged with span information
            // and we don't want to mistakenly apply the directive to the wrong part of the query.
            if (null == _inlineEntitySqlQueries)
            {
                _inlineEntitySqlQueries = new HashSet<ObjectQuery>();
            }
            var isNewInlineQuery = _inlineEntitySqlQueries.Add(inlineQuery);

            // The ObjectQuery should be Entity-SQL-based at this point. All other query types are currently
            // inlined.
            var esqlState = (EntitySqlQueryState)inlineQuery.QueryState;

            // We will produce the translated expression by parsing the Entity-SQL query text.
            DbExpression resultExpression = null;

            // If we are not converting a compiled query, or the referenced Entity-SQL ObjectQuery
            // does not have parameters (and so no parameter references can be in the parsed tree)
            // then the Entity-SQL can be parsed directly using the conversion command tree.
            var objectParameters = inlineQuery.QueryState.Parameters;
            if (!_funcletizer.IsCompiledQuery
                || objectParameters == null
                || objectParameters.Count == 0)
            {
                // Add parameters if they exist and we haven't yet encountered this inline query.
                if (isNewInlineQuery && objectParameters != null)
                {
                    // Copy the parameters into the aggregated parameter collection - this will result
                    // in an exception if any duplicate parameter names are encountered.
                    if (_parameters == null)
                    {
                        _parameters = new List<Tuple<ObjectParameter, QueryParameterExpression>>();
                    }
                    foreach (var prm in inlineQuery.QueryState.Parameters)
                    {
                        _parameters.Add(new Tuple<ObjectParameter, QueryParameterExpression>(prm.ShallowCopy(), null));
                    }
                }

                resultExpression = esqlState.Parse();
            }
            else
            {
                // We are converting a compiled query and parameters are present on the referenced ObjectQuery.
                // The set of parameters available to a compiled query is fixed (so that adding/removing parameters
                // to/from a referenced ObjectQuery does not invalidate the compiled query's execution plan), so the
                // referenced ObjectQuery will be fully inlined by replacing each parameter reference with a
                // DbConstantExpression containing the value of the referenced parameter.
                resultExpression = esqlState.Parse();
                resultExpression = ParameterReferenceRemover.RemoveParameterReferences(resultExpression, objectParameters);
            }

            return resultExpression;
        }
示例#56
0
        public static IEnumerable <Synchronization> Retrieve(ManagementScope managementScope)
        {
            var objectQuery      = new ObjectQuery("SELECT * FROM Win32_PerfFormattedData_Counters_Synchronization");
            var objectSearcher   = new ManagementObjectSearcher(managementScope, objectQuery);
            var objectCollection = objectSearcher.Get();

            foreach (ManagementObject managementObject in objectCollection)
            {
                yield return new Synchronization
                       {
                           Caption     = (string)(managementObject.Properties["Caption"]?.Value),
                           Description = (string)(managementObject.Properties["Description"]?.Value),
                           ExecResourceAcquiresAcqExclLitePersec                     = (uint)(managementObject.Properties["ExecResourceAcquiresAcqExclLitePersec"]?.Value ?? default(uint)),
                           ExecResourceAcquiresAcqShrdLitePersec                     = (uint)(managementObject.Properties["ExecResourceAcquiresAcqShrdLitePersec"]?.Value ?? default(uint)),
                           ExecResourceAcquiresAcqShrdStarveExclPersec               = (uint)(managementObject.Properties["ExecResourceAcquiresAcqShrdStarveExclPersec"]?.Value ?? default(uint)),
                           ExecResourceAcquiresAcqShrdWaitForExclPersec              = (uint)(managementObject.Properties["ExecResourceAcquiresAcqShrdWaitForExclPersec"]?.Value ?? default(uint)),
                           ExecResourceAttemptsAcqExclLitePersec                     = (uint)(managementObject.Properties["ExecResourceAttemptsAcqExclLitePersec"]?.Value ?? default(uint)),
                           ExecResourceAttemptsAcqShrdLitePersec                     = (uint)(managementObject.Properties["ExecResourceAttemptsAcqShrdLitePersec"]?.Value ?? default(uint)),
                           ExecResourceAttemptsAcqShrdStarveExclPersec               = (uint)(managementObject.Properties["ExecResourceAttemptsAcqShrdStarveExclPersec"]?.Value ?? default(uint)),
                           ExecResourceAttemptsAcqShrdWaitForExclPersec              = (uint)(managementObject.Properties["ExecResourceAttemptsAcqShrdWaitForExclPersec"]?.Value ?? default(uint)),
                           ExecResourceBoostExclOwnerPersec                          = (uint)(managementObject.Properties["ExecResourceBoostExclOwnerPersec"]?.Value ?? default(uint)),
                           ExecResourceBoostSharedOwnersPersec                       = (uint)(managementObject.Properties["ExecResourceBoostSharedOwnersPersec"]?.Value ?? default(uint)),
                           ExecResourceContentionAcqExclLitePersec                   = (uint)(managementObject.Properties["ExecResourceContentionAcqExclLitePersec"]?.Value ?? default(uint)),
                           ExecResourceContentionAcqShrdLitePersec                   = (uint)(managementObject.Properties["ExecResourceContentionAcqShrdLitePersec"]?.Value ?? default(uint)),
                           ExecResourceContentionAcqShrdStarveExclPersec             = (uint)(managementObject.Properties["ExecResourceContentionAcqShrdStarveExclPersec"]?.Value ?? default(uint)),
                           ExecResourceContentionAcqShrdWaitForExclPersec            = (uint)(managementObject.Properties["ExecResourceContentionAcqShrdWaitForExclPersec"]?.Value ?? default(uint)),
                           ExecResourcenoWaitsAcqExclLitePersec                      = (uint)(managementObject.Properties["ExecResourcenoWaitsAcqExclLitePersec"]?.Value ?? default(uint)),
                           ExecResourcenoWaitsAcqShrdLitePersec                      = (uint)(managementObject.Properties["ExecResourcenoWaitsAcqShrdLitePersec"]?.Value ?? default(uint)),
                           ExecResourcenoWaitsAcqShrdStarveExclPersec                = (uint)(managementObject.Properties["ExecResourcenoWaitsAcqShrdStarveExclPersec"]?.Value ?? default(uint)),
                           ExecResourcenoWaitsAcqShrdWaitForExclPersec               = (uint)(managementObject.Properties["ExecResourcenoWaitsAcqShrdWaitForExclPersec"]?.Value ?? default(uint)),
                           ExecResourceRecursiveExclAcquiresAcqExclLitePersec        = (uint)(managementObject.Properties["ExecResourceRecursiveExclAcquiresAcqExclLitePersec"]?.Value ?? default(uint)),
                           ExecResourceRecursiveExclAcquiresAcqShrdLitePersec        = (uint)(managementObject.Properties["ExecResourceRecursiveExclAcquiresAcqShrdLitePersec"]?.Value ?? default(uint)),
                           ExecResourceRecursiveExclAcquiresAcqShrdStarveExclPersec  = (uint)(managementObject.Properties["ExecResourceRecursiveExclAcquiresAcqShrdStarveExclPersec"]?.Value ?? default(uint)),
                           ExecResourceRecursiveExclAcquiresAcqShrdWaitForExclPersec = (uint)(managementObject.Properties["ExecResourceRecursiveExclAcquiresAcqShrdWaitForExclPersec"]?.Value ?? default(uint)),
                           ExecResourceRecursiveShAcquiresAcqShrdLitePersec          = (uint)(managementObject.Properties["ExecResourceRecursiveShAcquiresAcqShrdLitePersec"]?.Value ?? default(uint)),
                           ExecResourceRecursiveShAcquiresAcqShrdStarveExclPersec    = (uint)(managementObject.Properties["ExecResourceRecursiveShAcquiresAcqShrdStarveExclPersec"]?.Value ?? default(uint)),
                           ExecResourceRecursiveShAcquiresAcqShrdWaitForExclPersec   = (uint)(managementObject.Properties["ExecResourceRecursiveShAcquiresAcqShrdWaitForExclPersec"]?.Value ?? default(uint)),
                           ExecResourceSetOwnerPointerExclusivePersec                = (uint)(managementObject.Properties["ExecResourceSetOwnerPointerExclusivePersec"]?.Value ?? default(uint)),
                           ExecResourceSetOwnerPointerSharedExistingOwnerPersec      = (uint)(managementObject.Properties["ExecResourceSetOwnerPointerSharedExistingOwnerPersec"]?.Value ?? default(uint)),
                           ExecResourceSetOwnerPointerSharedNewOwnerPersec           = (uint)(managementObject.Properties["ExecResourceSetOwnerPointerSharedNewOwnerPersec"]?.Value ?? default(uint)),
                           ExecResourceTotalAcquiresPersec              = (uint)(managementObject.Properties["ExecResourceTotalAcquiresPersec"]?.Value ?? default(uint)),
                           ExecResourceTotalContentionsPersec           = (uint)(managementObject.Properties["ExecResourceTotalContentionsPersec"]?.Value ?? default(uint)),
                           ExecResourceTotalConvExclusiveToSharedPersec = (uint)(managementObject.Properties["ExecResourceTotalConvExclusiveToSharedPersec"]?.Value ?? default(uint)),
                           ExecResourceTotalDeletePersec            = (uint)(managementObject.Properties["ExecResourceTotalDeletePersec"]?.Value ?? default(uint)),
                           ExecResourceTotalExclusiveReleasesPersec = (uint)(managementObject.Properties["ExecResourceTotalExclusiveReleasesPersec"]?.Value ?? default(uint)),
                           ExecResourceTotalInitializePersec        = (uint)(managementObject.Properties["ExecResourceTotalInitializePersec"]?.Value ?? default(uint)),
                           ExecResourceTotalReInitializePersec      = (uint)(managementObject.Properties["ExecResourceTotalReInitializePersec"]?.Value ?? default(uint)),
                           ExecResourceTotalSharedReleasesPersec    = (uint)(managementObject.Properties["ExecResourceTotalSharedReleasesPersec"]?.Value ?? default(uint)),
                           FrequencyObject   = (ulong)(managementObject.Properties["Frequency_Object"]?.Value ?? default(ulong)),
                           FrequencyPerfTime = (ulong)(managementObject.Properties["Frequency_PerfTime"]?.Value ?? default(ulong)),
                           FrequencySys100Ns = (ulong)(managementObject.Properties["Frequency_Sys100NS"]?.Value ?? default(ulong)),
                           IpiSendBroadcastRequestsPersec  = (uint)(managementObject.Properties["IPISendBroadcastRequestsPersec"]?.Value ?? default(uint)),
                           IpiSendRoutineRequestsPersec    = (uint)(managementObject.Properties["IPISendRoutineRequestsPersec"]?.Value ?? default(uint)),
                           IpiSendSoftwareInterruptsPersec = (uint)(managementObject.Properties["IPISendSoftwareInterruptsPersec"]?.Value ?? default(uint)),
                           Name = (string)(managementObject.Properties["Name"]?.Value),
                           SpinlockAcquiresPersec    = (uint)(managementObject.Properties["SpinlockAcquiresPersec"]?.Value ?? default(uint)),
                           SpinlockContentionsPersec = (uint)(managementObject.Properties["SpinlockContentionsPersec"]?.Value ?? default(uint)),
                           SpinlockSpinsPersec       = (uint)(managementObject.Properties["SpinlockSpinsPersec"]?.Value ?? default(uint)),
                           TimestampObject           = (ulong)(managementObject.Properties["Timestamp_Object"]?.Value ?? default(ulong)),
                           TimestampPerfTime         = (ulong)(managementObject.Properties["Timestamp_PerfTime"]?.Value ?? default(ulong)),
                           TimestampSys100Ns         = (ulong)(managementObject.Properties["Timestamp_Sys100NS"]?.Value ?? default(ulong))
                       }
            }
            ;
        }
    }
示例#57
0
 internal static MethodInfo GetIncludeMethod <TElementType>(ObjectQuery <TElementType> sourceQuery)
 {
     return(sourceQuery.GetType().GetOnlyDeclaredMethod("Include"));
 }
	public ManagementObjectSearcher(ManagementScope scope, ObjectQuery query, EnumerationOptions options) {}
    /// <summary>
    /// Handles the Click event of the btnApprove control.
    /// </summary>
    protected void btnUnsubscribe_Click(object sender, EventArgs e)
    {
        if (UserID != MembershipContext.AuthenticatedUser.UserID)
        {
            // Check permissions
            if (!CheckPermissions("cms.forums", PERMISSION_MODIFY))
            {
                return;
            }
        }

        var query = new ObjectQuery<ForumSubscriptionInfo>().Where(new WhereCondition().WhereNull("SubscriptionApproved").Or().WhereEquals("SubscriptionApproved", 1)).And().WhereEquals("SubscriptionUserID", UserID).And().WhereEquals("SubscriptionPostID", PostID).Column("SubscriptionID").TopN(1);

        ForumSubscriptionInfo fsi = query.FirstOrDefault();
        if (fsi != null)
        {
            ForumSubscriptionInfoProvider.DeleteForumSubscriptionInfo(fsi);
            RefreshParentWindow();
        }
    }
示例#60
0
    protected void rctxtStartingCycle_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        string whereStr;

        vUTPCycle endingCycle;//��ֹ����

        if (rctxtCompany.SelectedValue != "N/A")
        {
            whereStr = "  and it.CompanyID='" + rctxtCompany.SelectedValue + "'";
            this.OrderBy = " it.Cycle asc ";

            BLL_vUTPCustomer = new vUTPCustomerBLL();
            endingCycle = BLL_vUTPCustomer.FindLastCycleByCompanyId(rctxtCompany.SelectedValue, this.OrderBy);

            whereStr = " and it.CompanyID='" + rctxtCompany.SelectedValue + "' and it.Cycle >= " +
                                                    rctxtStartingCycle.SelectedValue + " and it.Cycle <= " + endingCycle.Cycle + "";

            vUTPCycleObjs = BLL_vUTPCustomer.GetUTPCycles(whereStr, this.OrderBy);

            if (vUTPCycleObjs.Count()>0)
            {
                rctxtEndingCycle.DataSource = vUTPCycleObjs;
                rctxtEndingCycle.DataValueField = "Cycle";
                rctxtEndingCycle.DataTextField = "Cycle";
                rctxtEndingCycle.DataBind();
            }
        }
    }