Allocate

We found 10 examples in language CSharp for this search. You will see 53 fragments of code.
       ///----allocateClassRoom----///
       public bool Add(AllocateClassRoom allocateClassRoom)
       {
           if (AllocateClassRoomGetAll().Where(c => !c.IsUnallocate && c.RoomNo == allocateClassRoom.RoomNo && c.Day == allocateClassRoom.Day
               && (c.FromTime>= allocateClassRoom.FromTime && c.FromTime< allocateClassRoom.ToTime || c.ToTime> allocateClassRoom.FromTime && c.ToTime<= allocateClassRoom.FromTime)).Any())
           {

               return false;
           }

           else
           {
               db.AllocateClassRooms.Add(allocateClassRoom);
               return db.SaveChanges() > 0;
           }              

       }

       public List<AllocateClassRoom> AllocateClassRoomGetAll()
       {
           return db.AllocateClassRooms.Where(c => !c.IsUnallocate).Include(c => c.Course).ToList();
       }
        ///----allocateClassRoom end----///
       public int Complete()
       {         
           return db.SaveChanges();
       }

/** AccessLevel
@return 1 - Org 
*/
protected override int Get_AccessLevel()
{
return Convert.ToInt32(accessLevel.ToString());
}
/** Load Meta Data
@param ctx context
@return PO Info
*/
protected override POInfo InitPO (Ctx ctx)
{
POInfo poi = POInfo.GetPOInfo (ctx, Table_ID);
return poi;
}
/** Load Meta Data
@param ctx context
@return PO Info
*/
protected override POInfo InitPO(Context ctx)
{
POInfo poi = POInfo.GetPOInfo (ctx, Table_ID);
return poi;
}
/** Info
@return info
*/
public override String ToString()
{
StringBuilder sb = new StringBuilder ("X_C_PaymentAllocate[").Append(Get_ID()).Append("]");
return sb.ToString();
}
/** Set Amount.
@param Amount Amount in a defined currency */
public void SetAmount (Decimal? Amount)
{
if (Amount == null) throw new ArgumentException ("Amount is mandatory.");
Set_Value ("Amount", (Decimal?)Amount);
}
/** Get Amount.
@return Amount in a defined currency */
public Decimal GetAmount() 
{
Object bd =Get_Value("Amount");
if (bd == null) return Env.ZERO;
return  Convert.ToDecimal(bd);
}


		public TDescriptor Index(IndexName index) => Assign(index, (a, v) => a.Index = v);

		public TDescriptor Index<T>() where T : class => Assign(typeof(T), (a, v) => a.Index = v);

		public TDescriptor Shard(int? shard) => Assign(shard, (a, v) => a.Shard = v);

		public TDescriptor Node(string node) => Assign(node, (a, v) => a.Node = v);

		public AllocateEmptyPrimaryRerouteCommandDescriptor AcceptDataLoss(bool? acceptDataLoss = true) =>
			Assign(acceptDataLoss, (a, v) => a.AcceptDataLoss = v);

		public AllocateStalePrimaryRerouteCommandDescriptor AcceptDataLoss(bool? acceptDataLoss = true) =>
			Assign(acceptDataLoss, (a, v) => a.AcceptDataLoss = v);

        public List<Day> GetAllDay()
        {
            SqlConnection connection = new SqlConnection(connectionString);
            string query = "SELECT * FROM Day";
            SqlCommand command = new SqlCommand(query, connection);
            connection.Open();

            SqlDataReader reader = command.ExecuteReader();
            List<Day> days = new List<Day>();

            while (reader.Read())
            {
                Day aDay = new Day
                {
                    DayId = (int)reader["DayId"],
                    DayName = reader["DayName"].ToString()
                };
                days.Add(aDay);
            }

            reader.Close();
            connection.Close();

            return days;
        }

        public List<RoomNo> GetAllRoom()
        {
            SqlConnection connection = new SqlConnection(connectionString);
            string query = "SELECT * FROM RoomNo";
            SqlCommand command = new SqlCommand(query, connection);
            connection.Open();

            SqlDataReader reader = command.ExecuteReader();
            List<RoomNo> rooms = new List<RoomNo>();

            while (reader.Read())
            {
                RoomNo aRoom = new RoomNo
                {
                    RoomId = (int)reader["RoomId"],
                    RoomName = reader["RoomName"].ToString()
                };
                rooms.Add(aRoom);
            }

            reader.Close();
            connection.Close();

            return rooms;
        }

        public List<Course> GetAllCourse()
        {
            SqlConnection connection = new SqlConnection(connectionString);
            string query = "SELECT * FROM Course";
            SqlCommand command = new SqlCommand(query, connection);
            connection.Open();

            SqlDataReader reader = command.ExecuteReader();
            List<Course> courses = new List<Course>();

            while (reader.Read())
            {
                Course aCourse = new Course
                {
                    Id = (int)reader["Id"],
                    Name = reader["Name"].ToString()
                };
                courses.Add(aCourse);
            }

            reader.Close();
            connection.Close();

            return courses;
        }

        public int Save(AllocateClassRoom allocate)
        {

            allocate.FromTime = allocate.FromTime +" "+allocate.FromRadioButton;
            allocate.EndTime = allocate.EndTime +" "+ allocate.ToRadioButton;

            SqlConnection connection = new SqlConnection(connectionString);

            string query = "INSERT INTO AllocateClassRoom VALUES(@departmentId,@courseId,@roomNo,@day,@from,@to);Update Course set IsAllocated ='YES' where [email protected] ";
            SqlCommand command = new SqlCommand(query, connection);

            command.Parameters.Clear();

            command.Parameters.Add("departmentId", SqlDbType.Int);
            command.Parameters["departmentId"].Value = allocate.DepartmentId;

            command.Parameters.Add("courseId", SqlDbType.Int);
            command.Parameters["courseId"].Value = allocate.CourseId;
            
            command.Parameters.Add("roomNo", SqlDbType.VarChar);
            command.Parameters["roomNo"].Value = allocate.RoomNo;
            
            command.Parameters.Add("day", SqlDbType.VarChar);
            command.Parameters["day"].Value = allocate.Day;

            command.Parameters.Add("from", SqlDbType.VarChar);
            command.Parameters["from"].Value = allocate.FromTime;
            
            command.Parameters.Add("to", SqlDbType.VarChar);
            command.Parameters["to"].Value = allocate.EndTime;

            command.Parameters.Add("id", SqlDbType.Int);
            command.Parameters["id"].Value = allocate.CourseId;

            connection.Open();

            int rowAffected = command.ExecuteNonQuery();

            connection.Close();

            return rowAffected;
        }
       
        public bool CheckRoomAvailablity(AllocateClassRoom allocateClass)
        {
            if (allocateClass.FromRadioButton == "PM" )
            {
                if (double.Parse(allocateClass.FromTime) < 12)
                {
                    allocateClass.FromTime = (Convert.ToInt32(allocateClass.FromTime) + 12).ToString();
 
                }
                
            }

            if (allocateClass.ToRadioButton == "PM")
            {
                if (double.Parse(allocateClass.EndTime) < 12)
                {
                    allocateClass.EndTime = (Convert.ToInt32(allocateClass.EndTime) + 12).ToString();

                }
                
            }
            bool result = false;
            string[] fromAndTime={"0","1"};
            SqlConnection connection = new SqlConnection(connectionString);

            string query = "SELECT FromTime,EndTime from AllocateClassRoom WHERE RoomNo = @roomNo and [email protected]";

            SqlCommand command = new SqlCommand(query, connection);

            command.Parameters.Clear();

            command.Parameters.Add("roomNo", SqlDbType.VarChar);
            command.Parameters["roomNo"].Value = allocateClass.RoomNo;


            command.Parameters.Add("day", SqlDbType.VarChar);
            command.Parameters["day"].Value = allocateClass.Day;

            connection.Open();
            SqlDataReader reader = command.ExecuteReader();


            bool hasRow = false;

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    roomTimes.Add(new RoomTimeCheck
                    {
                        FromTime = double.Parse(reader["FromTime"].ToString().Remove(reader["FromTime"].ToString().Length-2)),
                        ToTime = double.Parse(reader["EndTime"].ToString().Remove(reader["EndTime"].ToString().Length - 2))

                    }); 

                }

                foreach (var item in roomTimes)
                {

                    if (double.Parse(allocateClass.FromTime) > item.FromTime &&
                        double.Parse(allocateClass.FromTime) < item.ToTime ||
                        double.Parse(allocateClass.EndTime) > item.FromTime &&
                        double.Parse(allocateClass.EndTime) <= item.ToTime)
                    {
                        result = true;
                        
                    }
           
                    
                }


            }
            else
            {
                reader.Close();
                connection.Close();

                return result;
            }
            reader.Close();
            connection.Close();

            return result;
        }

        /// <summary>
        /// Allocates the consignments using default allocation rules.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        List<WithMessage<string>> AllocateConsignments(AllocateConsignmentsRequest request);
        /// <summary>
        /// Allocates the consignments using default allocation rules.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        Task<List<WithMessage<string>>> AllocateConsignmentsAsync(AllocateConsignmentsRequest request);
        /// <summary>
        /// Allocates the consignments with the specific carrier service.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        List<WithMessage<string>> AllocateConsignments(AllocateConsignmentsWithCarrierServiceRequest request);
        /// <summary>
        /// Allocates the consignments with the specific carrier service.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        Task<List<WithMessage<string>>> AllocateConsignmentsAsync(AllocateConsignmentsWithCarrierServiceRequest request);
        /// <summary>
        /// Allocates the consignments using the specific carrier service group.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        List<WithMessage<string>> AllocateConsignments(AllocateConsignmentsWithServiceGroupRequest request);
        /// <summary>
        /// Allocates the consignments using the specific carrier service group.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        Task<List<WithMessage<string>>> AllocateConsignmentsAsync(AllocateConsignmentsWithServiceGroupRequest request);

        public CustomJsonResult GetDetails(string operater, string merchantId, string allocaterId, string id)
        {
            var ret = new RetObBatchAllocateTaskGetDetails();

            var obBatchAllocate = CurrentDb.ObBatchAllocate.Where(m => m.MerchantId == merchantId && m.Id == id).FirstOrDefault();

            if (obBatchAllocate != null)
            {
                var obBatch = CurrentDb.ObBatch.Where(m => m.Id == obBatchAllocate.ObBatchId).FirstOrDefault();

                ret.Id = obBatchAllocate.Id ?? ""; ;
                ret.ObBatchId = obBatch.Id;
                ret.ObBatchCode = obBatch.Code ?? ""; ;
                ret.ObBatchName = obBatch.Name ?? ""; ;
                ret.UnAllocatedCount = obBatchAllocate.UnAllocatedCount;


                var organizations = CurrentDb.Organization.Where(m => m.PId == obBatchAllocate.BelongerOrganizationId && m.IsDelete == false).OrderBy(m => m.Priority).ToList();
                if (organizations.Count > 0)
                {
                    foreach (var item in organizations)
                    {
                        var sysUser = CurrentDb.SysUser.Where(m => m.Id == item.HeaderId && m.Id != allocaterId).FirstOrDefault();
                        if (sysUser != null)
                        {
                            ret.BelongUsers.Add(new RetObBatchAllocateTaskGetDetails.BelongUser { UserId = sysUser.Id, UserName = string.Format("{0}:{1}({2})", item.FullName, sysUser.FullName, sysUser.UserName), OrganizationId = item.Id });
                        }
                    }
                }
                else
                {

                    var sysMerchantUsers = CurrentDb.SysMerchantUser.Where(m => m.MerchantId == merchantId && m.OrganizationId == obBatchAllocate.BelongerOrganizationId && m.Id != allocaterId).ToList();

                    foreach (var sysMerchantUser in sysMerchantUsers)
                    {
                        ret.BelongUsers.Add(new RetObBatchAllocateTaskGetDetails.BelongUser { UserId = sysMerchantUser.Id, UserName = string.Format("{0}({1})", sysMerchantUser.FullName, sysMerchantUser.UserName), OrganizationId = sysMerchantUser.OrganizationId });
                    }

                }
            }

            return new CustomJsonResult(ResultType.Success, ResultCode.Success, "获取成功", ret);
        }

        private string GetFilters(RupObCustomerGetList filters)
        {
            StringBuilder sb = new StringBuilder();

            if (filters != null)
            {
                if (!string.IsNullOrEmpty(filters.CsrName))
                {
                    sb.Append("客户名称:" + filters.CsrName + ",");
                }
                if (!string.IsNullOrEmpty(filters.CsrPhoneNumber))
                {
                    sb.Append("电话号码:" + filters.CsrPhoneNumber + ",");
                }
                if (!string.IsNullOrEmpty(filters.CsrIdNumber))
                {
                    sb.Append("身份证号:" + filters.CsrIdNumber + ",");
                }

                if (!string.IsNullOrEmpty(filters.CsrAddress))
                {
                    sb.Append("地址:" + filters.CsrAddress + ",");
                }

                if (!string.IsNullOrEmpty(filters.CarInsLastCompany))
                {
                    sb.Append("保险公司:" + filters.CarInsLastCompany + ",");
                }
                if (!string.IsNullOrEmpty(filters.CarPlateNo))
                {
                    sb.Append("车牌号码:" + filters.CarPlateNo + ",");
                }
                if (!string.IsNullOrEmpty(filters.CarEngineNo))
                {
                    sb.Append("发动号:" + filters.CarEngineNo + ",");
                }

                if (!string.IsNullOrEmpty(filters.CarModel))
                {
                    sb.Append("厂牌:" + filters.CarModel + ",");
                }

                if (filters.CarRegisterDateStart != null)
                {
                    sb.Append("初登日期开始:" + filters.CarRegisterDateStart + ",");
                }
                if (filters.CarRegisterDateEnd != null)
                {
                    sb.Append("初登日期结束:" + filters.CarRegisterDateEnd + ",");
                }

                if (filters.CarInsLastStartTime != null)
                {
                    sb.Append("起保开始:" + filters.CarInsLastStartTime + ",");
                }

                if (filters.CarInsLastEndTime != null)
                {
                    sb.Append("起保结束:" + filters.CarInsLastEndTime + ",");
                }
            }


            return sb.ToString();
        }

        public CustomJsonResult Add(string operater, string merchantId, RopObBatchAllocateAdd rop)
        {
            CustomJsonResult result = new CustomJsonResult();


            using (TransactionScope ts = new TransactionScope())
            {
                var obBatchAllocate = CurrentDb.ObBatchAllocate.Where(m => m.Id == rop.Id).FirstOrDefault();
                if (obBatchAllocate == null)
                {
                    return new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "此任务ID未找到");
                }

                if (rop.BelongUsers == null || rop.BelongUsers.Count <= 0)
                {
                    return new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "分配的对象为空");
                }

                int allocatedCount = rop.BelongUsers.Sum(m => m.AllocatedCount);

                if (allocatedCount == 0)
                {
                    return new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "请输入分配的数量");
                }

                if (allocatedCount > obBatchAllocate.UnAllocatedCount)
                {
                    return new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "分配的总数量大于批次的数量");
                }

                obBatchAllocate.AllocatedCount += allocatedCount;
                obBatchAllocate.UnAllocatedCount -= allocatedCount;
                obBatchAllocate.Mender = operater;
                obBatchAllocate.MendTime = this.DateTime;

                var soureUser = CurrentDb.SysUser.Where(m => m.Id == obBatchAllocate.BelongerId).FirstOrDefault();

                var belongUsers = rop.BelongUsers.Where(m => m.AllocatedCount > 0).ToList();

                foreach (var item in belongUsers)
                {
                    var belongUser = CurrentDb.SysUser.Where(m => m.Id == item.UserId).FirstOrDefault();
                    var belongOrganization = CurrentDb.Organization.Where(m => m.Id == item.OrganizationId).FirstOrDefault();

                    var new_Allocate = new ObBatchAllocate();
                    new_Allocate.Id = GuidUtil.New();
                    new_Allocate.PId = obBatchAllocate.Id;
                    new_Allocate.MerchantId = obBatchAllocate.MerchantId;
                    new_Allocate.ObBatchId = obBatchAllocate.ObBatchId;
                    new_Allocate.DataCount = item.AllocatedCount;
                    new_Allocate.AllocatedCount = 0;
                    new_Allocate.UnAllocatedCount = item.AllocatedCount;
                    new_Allocate.UsedCount = 0;
                    new_Allocate.BelongerId = item.UserId;
                    new_Allocate.BelongerName = string.Format("{0}机构:{1}({2})", belongOrganization.FullName, belongUser.FullName, belongUser.UserName);
                    new_Allocate.BelongerOrganizationId = item.OrganizationId;
                    new_Allocate.AllocaterId = soureUser.Id;
                    new_Allocate.Creator = operater;
                    new_Allocate.CreateTime = this.DateTime;
                    new_Allocate.SoureName = string.Format("上级分配人:{0}({1})", soureUser.FullName, soureUser.UserName);
                    new_Allocate.AllocateMode = rop.Mode;
                    new_Allocate.Description = rop.Description;

                    List<ObCustomer> obCustomers = new List<ObCustomer>();


                    if (rop.Mode == Enumeration.ObBatchAllocateMode.Random)
                    {
                        //随机分配
                        obCustomers = CurrentDb.ObCustomer.Where(x => x.ObBatchId == obBatchAllocate.ObBatchId && x.BelongerId == obBatchAllocate.BelongerId).OrderBy(x => Guid.NewGuid()).Take(item.AllocatedCount).ToList();
                    }
                    else if (rop.Mode == Enumeration.ObBatchAllocateMode.Filter)
                    {
                        new_Allocate.Filters = GetFilters(rop.Filters);
                        //过滤分配
                        obCustomers = CurrentDb.ObCustomer.Where(x =>
                                     x.ObBatchId == obBatchAllocate.ObBatchId &&
                                     x.BelongerId == obBatchAllocate.BelongerId
                                     &&
                                     (rop.Filters.CarPlateNo == null || x.CarPlateNo.Contains(rop.Filters.CarPlateNo)) &&
                                     (rop.Filters.CarModel == null || x.CarModel.Contains(rop.Filters.CarModel)) &&
                                     (rop.Filters.CarEngineNo == null || x.CarEngineNo.Contains(rop.Filters.CarEngineNo)) &&
                                     (rop.Filters.CsrAddress == null || x.CsrAddress.Contains(rop.Filters.CsrAddress)) &&
                                     (rop.Filters.CsrPhoneNumber == null || x.CsrPhoneNumber.Contains(rop.Filters.CsrPhoneNumber)) &&
                                     (rop.Filters.CsrName == null || x.CsrName.Contains(rop.Filters.CsrName)) &&
                                     (rop.Filters.CsrIdNumber == null || x.CsrIdNumber.Contains(rop.Filters.CsrIdNumber)) &&
                                     (rop.Filters.CarInsLastCompany == null || x.CarInsLastCompany.Contains(rop.Filters.CarInsLastCompany)) &&
                                     (rop.Filters.CarRegisterDateStart == null || x.CarRegisterDate >= rop.Filters.CarRegisterDateStart) &&
                                     (rop.Filters.CarRegisterDateEnd == null || x.CarRegisterDate <= rop.Filters.CarRegisterDateEnd) &&
                                     (rop.Filters.CarInsLastStartTime == null || x.CarInsLastStartTime >= rop.Filters.CarInsLastStartTime) &&
                                     (rop.Filters.CarInsLastEndTime == null || x.CarInsLastEndTime <= rop.Filters.CarInsLastEndTime)
                                     ).OrderBy(x => Guid.NewGuid()).Take(item.AllocatedCount).ToList();
                    }

                    if (obCustomers.Count != item.AllocatedCount)
                    {
                        return new CustomJsonResult(ResultType.Failure, ResultCode.Failure, "分配的总数量与库存数据不一致");
                    }

                    foreach (var obCustomer in obCustomers)
                    {
                        obCustomer.BelongerId = item.UserId;
                        obCustomer.BelongerOrganizationId = item.OrganizationId;
                        obCustomer.ObBatchAllocateId = new_Allocate.Id;
                        obCustomer.Mender = operater;
                        obCustomer.MendTime = this.DateTime;
                        CurrentDb.SaveChanges();

                        var obCustomerBelongTrack = new ObCustomerBelongTrack();
                        obCustomerBelongTrack.Id = GuidUtil.New();
                        obCustomerBelongTrack.MerchantId = obCustomer.MerchantId;
                        obCustomerBelongTrack.ObBatchId = obCustomer.ObBatchId;
                        obCustomerBelongTrack.ObBatchDataId = obCustomer.ObBatchId;
                        obCustomerBelongTrack.ObCustomerId = obCustomer.Id;
                        obCustomerBelongTrack.BelongerId = item.UserId;
                        obCustomerBelongTrack.Description = string.Format("分配给用户:{0}({1})", belongUser.FullName, belongUser.UserName);
                        obCustomerBelongTrack.Creator = operater;
                        obCustomerBelongTrack.CreateTime = this.DateTime;
                        CurrentDb.ObCustomerBelongTrack.Add(obCustomerBelongTrack);
                    }

                    CurrentDb.ObBatchAllocate.Add(new_Allocate);
                }


                CurrentDb.SaveChanges();
                ts.Complete();

                result = new CustomJsonResult(ResultType.Success, ResultCode.Success, "新建成功");
            }

            return result;
        }



        public void a(string operater, string obBatchAllocateId, int count)
        {
            var obBatchAllocate = CurrentDb.ObBatchAllocate.Where(m => m.Id == obBatchAllocateId).FirstOrDefault();

            var pObBatchAllocates = CurrentDb.ObBatchAllocate.Where(m => m.PId == obBatchAllocateId).ToList();

            if (pObBatchAllocates.Count > 0)
            {
                foreach (var item in pObBatchAllocates)
                {
                    int unAllocatedCount = item.UnAllocatedCount;

                    if (unAllocatedCount > 0)
                    {

                        item.RestoreCount = unAllocatedCount;
                        item.UnAllocatedCount = unAllocatedCount;

                        var obCustomers = CurrentDb.ObCustomer.Where(m => m.ObBatchAllocateId == item.Id && m.BelongerId == item.BelongerId && m.IsUseCall == false && m.IsTake == false).Take(unAllocatedCount).ToList();
                        if (obCustomers.Count > 0)
                        {

                            var belongUser = CurrentDb.SysMerchantUser.Where(m => m.Id == obBatchAllocate.AllocaterId).FirstOrDefault();
                            var belongOrganization = CurrentDb.Organization.Where(m => m.Id == belongUser.OrganizationId).FirstOrDefault();

                            foreach (var obCustomer in obCustomers)
                            {
                                obCustomer.BelongerId = belongUser.Id;
                                obCustomer.BelongerOrganizationId = belongUser.OrganizationId;
                                obCustomer.ObBatchAllocateId = item.PId;
                                obCustomer.Mender = operater;
                                obCustomer.MendTime = this.DateTime;
                                CurrentDb.SaveChanges();

                                var obCustomerBelongTrack = new ObCustomerBelongTrack();
                                obCustomerBelongTrack.Id = GuidUtil.New();
                                obCustomerBelongTrack.MerchantId = obCustomer.MerchantId;
                                obCustomerBelongTrack.ObBatchId = obCustomer.ObBatchId;
                                obCustomerBelongTrack.ObBatchDataId = obCustomer.ObBatchId;
                                obCustomerBelongTrack.ObCustomerId = obCustomer.Id;
                                obCustomerBelongTrack.BelongerId = belongUser.Id;
                                obCustomerBelongTrack.Description = string.Format("还原给用户:{0}({1})", belongUser.FullName, belongUser.UserName);
                                obCustomerBelongTrack.Creator = operater;
                                obCustomerBelongTrack.CreateTime = this.DateTime;
                                CurrentDb.ObCustomerBelongTrack.Add(obCustomerBelongTrack);
                            }
                            CurrentDb.SaveChanges();
                        }
                    }

                    a(operater, item.Id, count);
                }
            }
            else
            {
                var obCustomers = CurrentDb.ObCustomer.Where(m => m.ObBatchAllocateId == obBatchAllocate.Id && m.BelongerId == obBatchAllocate.BelongerId && m.IsUseCall == false && m.IsTake == false).Take(count).ToList();
                if (obCustomers.Count > 0)
                {

                    var belongUser = CurrentDb.SysMerchantUser.Where(m => m.Id == obBatchAllocate.AllocaterId).FirstOrDefault();
                    var belongOrganization = CurrentDb.Organization.Where(m => m.Id == belongUser.OrganizationId).FirstOrDefault();

                    foreach (var obCustomer in obCustomers)
                    {
                        obCustomer.BelongerId = belongUser.Id;
                        obCustomer.BelongerOrganizationId = belongUser.OrganizationId;
                        obCustomer.ObBatchAllocateId = obBatchAllocate.PId;
                        obCustomer.Mender = operater;
                        obCustomer.MendTime = this.DateTime;
                        CurrentDb.SaveChanges();

                        var obCustomerBelongTrack = new ObCustomerBelongTrack();
                        obCustomerBelongTrack.Id = GuidUtil.New();
                        obCustomerBelongTrack.MerchantId = obCustomer.MerchantId;
                        obCustomerBelongTrack.ObBatchId = obCustomer.ObBatchId;
                        obCustomerBelongTrack.ObBatchDataId = obCustomer.ObBatchId;
                        obCustomerBelongTrack.ObCustomerId = obCustomer.Id;
                        obCustomerBelongTrack.BelongerId = belongUser.Id;
                        obCustomerBelongTrack.Description = string.Format("还原给用户:{0}({1})", belongUser.FullName, belongUser.UserName);
                        obCustomerBelongTrack.Creator = operater;
                        obCustomerBelongTrack.CreateTime = this.DateTime;
                        CurrentDb.ObCustomerBelongTrack.Add(obCustomerBelongTrack);
                    }
                    CurrentDb.SaveChanges();
                }
            }

        }
        public CustomJsonResult Restore(string operater, string merchantId, string obBatchAllocateId)
        {
            CustomJsonResult result = new CustomJsonResult();

            using (TransactionScope ts = new TransactionScope())
            {

                var obBatchAllocate = CurrentDb.ObBatchAllocate.Where(m => m.Id == obBatchAllocateId).FirstOrDefault();

                int unAllocatedCount = obBatchAllocate.UnAllocatedCount - obBatchAllocate.RestoreCount;

                var pObBatchAllocate = CurrentDb.ObBatchAllocate.Where(m => m.Id == obBatchAllocate.PId).FirstOrDefault();


                if (unAllocatedCount > 0)
                {
                    a(operater, obBatchAllocateId, unAllocatedCount);

                    obBatchAllocate.RestoreCount = unAllocatedCount;

                    pObBatchAllocate.UnAllocatedCount += unAllocatedCount;
                    pObBatchAllocate.AllocatedCount -= unAllocatedCount;

                    CurrentDb.SaveChanges();
                    ts.Complete();

                    result = new CustomJsonResult(ResultType.Success, ResultCode.Success, "还原成功");
                }
                else
                {
                    result = new CustomJsonResult(ResultType.Success, ResultCode.Success, "没有可还原的数据");
                }




            }

            return result;
        }


        /// <summary>
        /// Initializes the fixture by creating a MemoryCache object.
        /// </summary>
        [TestInitialize]
        [Description("Setup the MemoryCacheTests fixture")]
        public void Setup()
        {
            this.memoryCache = new MemoryCache(BufferSize, MaxBuffers);           
        }

        /// <summary>
        /// Verify the BufferSize property.
        /// </summary>
        [TestMethod]
        [Priority(0)]
        [Description("Verify the BufferSizeProperty")]
        public void VerifyBufferSizeProperty()
        {
            Assert.AreEqual(BufferSize, this.memoryCache.BufferSize);
        }

        /// <summary>
        /// Test the Duplicate method.
        /// </summary>
        [TestMethod]
        [Priority(0)]
        [Description("Test the Duplicate method")]
        public void TestDuplicate()
        {
            byte[] input = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 };
            byte[] output = MemoryCache.Duplicate(input, input.Length);
            CollectionAssert.AreEqual(input, output);
        }

        /// <summary>
        /// Test the Duplicate method with a zero-length array.
        /// </summary>
        [TestMethod]
        [Priority(0)]
        [Description("Test the Duplicate method with a zero-length array")]
        public void TestDuplicateZeroLength()
        {
            byte[] input = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 };
            byte[] output = MemoryCache.Duplicate(input, 0);
            Assert.AreEqual(0, output.Length);
        }

        /// <summary>
        /// Verify duplicating a zero-length array returns the same array.
        /// </summary>
        [TestMethod]
        [Priority(0)]
        [Description("Verify duplicating a zero-length array returns the same array")]
        public void TestDuplicateZeroLengthReturnsSameArray()
        {
            byte[] input = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6 };
            byte[] output1 = MemoryCache.Duplicate(input, 0);
            byte[] output2 = MemoryCache.Duplicate(input, 0);
            Assert.AreSame(output1, output2);
        }

        /// <summary>
        /// Verify freeing a null buffer throws an exception.
        /// </summary>
        [TestMethod]
        [Priority(0)]
        [Description("Verify freeing a null buffer throws an exception")]
        [ExpectedException(typeof(ArgumentNullException))]
        public void VerifyFreeOfNullThrowsException()
        {
            byte[] buffer = null;
            this.memoryCache.Free(ref buffer);
        }


        // GET: Allocates
        public ActionResult Index()
        {
            var allocate = db.Allocate.Include(a => a.Room).Include(a => a.User);
            return View(allocate.ToList());
        }

        // GET: Allocates/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Allocate allocate = db.Allocate.Find(id);
            if (allocate == null)
            {
                return HttpNotFound();
            }
            return View(allocate);
        }
        // GET: Allocates/Create
        public ActionResult Create()
        {
            /*var rooms = (from a in db.Allocate select a.RoomId).ToList();
            var urooms = (from b in db.Room where !rooms.Contains(b.RoomId) select b).ToList();*/
            //var user = (from a in db.Allocate select a.Uid).ToList();
            //var uuser = (from b in db.User where !user.Contains(b.Uid) select b).ToList();
          
            //var user = (from a in db.Allocate select a.Uid).ToList();

           // var duplicates = (user.GroupBy(txt => txt)
            //.Where(grouping => grouping.Count() > 1)).ToList();
            ViewBag.RoomId = new SelectList(db.Room, "RoomId", "Rid");
            ViewBag.Uid = new SelectList(db.User, "Uid", "MID");
            return View();
        }

        // POST: Allocates/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "Aid,Uid,RoomId")] Allocate allocate)
        {
            if (ModelState.IsValid)
            {
                var q = (from a in db.Allocate select a.Uid).ToList();
                var duplicate = (from a in db.Allocate group a by a.Uid into b where (b.Count() == 2) select b.Key).ToList();
                //var y = (from c in db.User where !u.Contains(c.Uid) select c.Uid).ToList();
                //foreach(var x in duplicate)
                //{
                //    if()
                //}
                if (duplicate.Count > 0)
                {
                    TempData["Message"] = "Only 2 rooms per User is allowed";
                    return RedirectToAction("Create");
                    //return Content("Only 2 rooms per User is allowed");
                }
                else
                {
                    db.Allocate.Add(allocate);
                    await db.SaveChangesAsync();
                    return RedirectToAction("Index");
                }
            }
            ViewBag.RoomId = new SelectList(db.Room, "RoomId", "Rid", allocate.RoomId);
            ViewBag.Uid = new SelectList(db.User, "Uid", "MID", allocate.Uid);
            return View(allocate);
        }

        // GET: Allocates/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Allocate allocate = db.Allocate.Find(id);
            if (allocate == null)
            {
                return HttpNotFound();
            }
            ViewBag.RoomId = new SelectList(db.Room, "RoomId", "BlockName", allocate.RoomId);
            ViewBag.Uid = new SelectList(db.User, "Uid", "MID", allocate.Uid);
            return View(allocate);
        }

        // POST: Allocates/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "Aid,Uid,RoomId")] Allocate allocate)
        {
            if (ModelState.IsValid)
            {
                db.Entry(allocate).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            ViewBag.RoomId = new SelectList(db.Room, "RoomId", "BlockName", allocate.RoomId);
            ViewBag.Uid = new SelectList(db.User, "Uid", "MID", allocate.Uid);
            return View(allocate);
        }

        //
        // GET: /AllocateClassRoom/
        public ActionResult Allocate()
        {
            DepartmentBind();
            ViewBag.Courses = allocateManager.GetAllCourse();
            ViewBag.Days = allocateManager.GetAllDay();
            ViewBag.RoomNo = allocateManager.GetAllRoom();
            //ViewBag.Departments = aDepartmentManager.GetAllDepartments();

            return View();
        }
        [HttpPost]

        public ActionResult Allocate(AllocateClassRoom allocate)
        {
            DepartmentBind();
            ViewBag.Courses = allocateManager.GetAllCourse();
            ViewBag.Days = allocateManager.GetAllDay();
            ViewBag.RoomNo = allocateManager.GetAllRoom();
            //ViewBag.Departments = aDepartmentManager.GetAllDepartments();

            ViewBag.Message = allocateManager.Save(allocate);

            return View();
        }


        public void DepartmentBind()
        {

            DataSet ds = assignGateway.GetDepartment();

            List<SelectListItem> departmentList = new List<SelectListItem>();

            foreach (DataRow dr in ds.Tables[0].Rows)
            {

                departmentList.Add(new SelectListItem { Text = dr["Name"].ToString(), Value = dr["Id"].ToString() });

            }

            ViewBag.DepartmentId = departmentList;

        }

        public JsonResult CourseBind(int departmentId)
        {
            string code;

            DataSet ds = assignGateway.GetAllCourse(departmentId);

            List<SelectListItem> courseList = new List<SelectListItem>();

            foreach (DataRow dr in ds.Tables[0].Rows)
            {

                courseList.Add(new SelectListItem { Text = dr["Name"].ToString(), Value = dr["Id"].ToString() });
                code = dr["Name"].ToString();
                // ViewBag.Course = assignGateway.CourseName(code);
            }

            //            ViewBag.Course = assignGateway.CourseName(code);

            return Json(courseList, JsonRequestBehavior.AllowGet);

        }

    [Fact]
    [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
    public unsafe void AllocateNativeOverlapped_NullAsCallback_ThrowsArgumentNullException()
    {
        using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
        {
            AssertExtensions.Throws<ArgumentNullException>("callback", () =>
            {
                handle.AllocateNativeOverlapped(null, new object(), new byte[256]);
            });
        }
    }

    [Fact]
    [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
    public unsafe void AllocateNativeOverlapped_PreAllocated_ThrowsArgumentNullException()
    {
        using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
        {
            AssertExtensions.Throws<ArgumentNullException>("preAllocated", () =>
            {
                handle.AllocateNativeOverlapped((PreAllocatedOverlapped)null);
            });
        }
    }

    [Fact]
    [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
    public unsafe void AllocateNativeOverlapped_NullAsContext_DoesNotThrow()
    {
        using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
        {
            NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, (object)null, new byte[256]);

            Assert.True(result != null);

            handle.FreeNativeOverlapped(result);
        }
    }

    [Fact]
    [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
    public unsafe void AllocateNativeOverlapped_NullAsPinData_DoesNotThrow()
    {
        using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
        {
            NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), (byte[])null);

            Assert.True(result != null);

            handle.FreeNativeOverlapped(result);
        }
    }

    [Fact]
    [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
    public unsafe void AllocateNativeOverlapped_EmptyArrayAsPinData_DoesNotThrow()
    {
        using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
        {
            NativeOverlapped* result = handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new byte[0]);

            Assert.True(result != null);

            handle.FreeNativeOverlapped(result);
        }
    }

    [Fact]
    [PlatformSpecific(TestPlatforms.Windows)] // ThreadPoolBoundHandle.BindHandle is not supported on Unix
    public unsafe void AllocateNativeOverlapped_NonBlittableTypeAsPinData_Throws()
    {
        using(ThreadPoolBoundHandle handle = CreateThreadPoolBoundHandle())
        {
            AssertExtensions.Throws<ArgumentException>(null, () => handle.AllocateNativeOverlapped((_, __, ___) => { }, new object(), new NonBlittableType() { s = "foo" }));
        }
    }

Microsoft.Quantum.Intrinsic.Allocate : IApplyData

Constructors :

public Allocate(IOperationFactory m = )

Methods :

public abstract Qubit Apply()
public abstract IQArray<Qubit> Apply(Int64 count = )
public Void __Init__()
public IOperationFactory get___Factory__()
public RuntimeMetadata GetRuntimeMetadata(IApplyData args = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()

Other methods