コード例 #1
0
ファイル: Tasks.cs プロジェクト: winmissupport/FeatureUpate
        /// <summary>
        /// Perform one or more tasks asyncronously.
        /// </summary>
        /// <param name="actions">The action(s) to perform</param>
        public static void RunAsyncTasks(params Action[] actions)
        {
            var tasks = new List<Task>();

            foreach (var action in actions)
            {
                tasks.Add(Task.Factory.StartNew(action));
            }

            Task.WaitAll(tasks.ToArray());
            tasks.Clear();
        }
コード例 #2
0
ファイル: frmEditor.cs プロジェクト: jango2015/MongoCola
 private void btnImport_Click(object sender, EventArgs e)
 {
     //整体表格
     var multilanFolder = ctlMultiLanFolder.SelectedPathOrFileName;
     //整理出最大列表,防止文件之间出现单词表格不同
     var uuiDs = new List<string>();
     uuiDs.Clear();
     if (!string.IsNullOrEmpty(multilanFolder))
     {
         //便利整个文件夹,获得语言字典
         foreach (var filename in Directory.GetFiles(multilanFolder))
         {
             StringResource.InitLanguage(filename);
             var singleDic = new Dictionary<string, string>();
             foreach (var item in StringResource.StringDic)
             {
                 if (!uuiDs.Contains(item.Key)) uuiDs.Add(item.Key);
                 singleDic.Add(item.Key, item.Value);
             }
             _multiLanguageDictionary.Add(StringResource.LanguageType, singleDic);
         }
     }
     //将数据放入ListView视图
     lstMultiLan.Clear();
     //Header
     lstMultiLan.Columns.Add("统一标示");
     for (var i = 0; i < _multiLanguageDictionary.Keys.Count; i++)
     {
         lstMultiLan.Columns.Add(_multiLanguageDictionary.Keys.ElementAt(i));
     }
     //Details
     for (var i = 0; i < uuiDs.Count; i++)
     {
         var item = new ListViewItem(uuiDs[i]);
         for (var j = 0; j < _multiLanguageDictionary.Keys.Count; j++)
         {
             if (_multiLanguageDictionary[_multiLanguageDictionary.Keys.ElementAt(j)].ContainsKey(uuiDs[i]))
             {
                 item.SubItems.Add(_multiLanguageDictionary[_multiLanguageDictionary.Keys.ElementAt(j)][uuiDs[i]]);
             }
             else
             {
                 item.SubItems.Add("");
             }
         }
         lstMultiLan.Items.Add(item);
     }
     Utility.ListViewColumnResize(lstMultiLan);
 }
コード例 #3
0
        /// <summary>
        /// 投手に要求する投球を取得
        /// </summary>
        /// <returns>要求する投球(コースと球種のみ設定)</returns>
        public PitchingBallData GetRequestPitchBoll()
        {
            // 基本作戦の「常に厳しいコース」を追加
            List<PitchingMission> missions = new List<PitchingMission>();
            missions.Add(new PitchingMission(PitchingMissionKind.Random));

            // 智力依存で投球の作戦を追加
            AddMissions(missions);

            // 検証用の投球作戦が指定されている場合は、他の投球作成をクリアしてそれを設定する
            if (PitchingMissionsForDebug.Count > 0)
            {
                missions.Clear();
                missions.AddRange(PitchingMissionsForDebug);
            }

            // 要求する投球データの初期値
            // (球種はランダム、コースは厳しいコース)
            PitchingBallData requestBall = new PitchingBallData()
            {
                IsFastBall = RandomCreater.GetBool(),
                PitchingCourse = PitchingCourse.Severe
            };

            // 優先順位の低い順にソートした作戦を元にスイングデータを作成する
            // (優先度の高い作戦により、後から上書きする)
            var sortedMissions = missions.OrderBy(m => m.Priority);
            foreach (PitchingMission mission in sortedMissions)
            {
                requestBall = mission.GetRequestBall(GameData, requestBall);
            }

            // ウエストの場合は球種は直球にしておく(アニメーションを直球にするため)
            if (requestBall.PitchingCourse == PitchingCourse.PitchOut)
            {
                requestBall.IsFastBall = true;
            }

            return requestBall;
        }
コード例 #4
0
ファイル: VesselFactory.cs プロジェクト: Bangiev/Battleships
        private List<IPosition> GenerateVesselPositions(int vesselSize, IEnumerable<IVessel> existingVessels)
        {
            Orientation vesselOrientation;
            IPosition startPosition;
            List<IPosition> newVesselPositions = new List<IPosition>();

            // Keep generating random positions until they are valid.
            do
            {
                // Clear the list first (in case any positions have been added during previous iterations).
                newVesselPositions.Clear();

                // Get random orientation and start position which will determine the rest of the positions.
                vesselOrientation = this.GetRandomOrientation();
                startPosition = this.GetRandomStartPosition(vesselSize);
                newVesselPositions.Add(startPosition);

                int currentPositionRow = newVesselPositions[0].Row;
                int currentPositionCol = newVesselPositions[0].Col;

                // Add the remaining positions.
                for (int i = 1; i < vesselSize; i++)
                {
                    if (vesselOrientation == Orientation.Vertical)
                    {
                        currentPositionRow++;
                    }
                    else if (vesselOrientation == Orientation.Horizontal)
                    {
                        currentPositionCol++;
                    }

                    newVesselPositions.Add(new Position(currentPositionRow, currentPositionCol));
                }
            }
            while (!this.ArePositionsEmpty(newVesselPositions, existingVessels));

            return newVesselPositions;
        }
コード例 #5
0
ファイル: AjaxPage.ashx.cs プロジェクト: JoiWilliam/OAProject
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString["type"] != null)
            {
                if (context.Request.QueryString["type"] == "bind")
                {
                    #region 绑定用户列表
                    if (context.Request.QueryString["opera"] == "users")
                    {
                        Dictionary<string, string> userDic = new Dictionary<string, string>();
                        if (context.Request.QueryString["userID"] != null)
                        {
                            userDic["userID"] = context.Request.QueryString["userID"];
                        }
                        if (context.Request.QueryString["userName"] != null)
                        {
                            userDic["userName"] = context.Request.QueryString["userName"];
                        }
                        if (context.Request.QueryString["deptID"] != null)
                        {
                            userDic["deptID"] = context.Request.QueryString["deptID"];
                        }

                        int pageCurrent = Convert.ToInt32(context.Request.QueryString["pageCurrent"]);
                        string order = string.IsNullOrEmpty(context.Request.QueryString["orderField"]) ? "UserID" : context.Request.QueryString["orderField"];
                        int rowCount; UserInfoBLL bll = new UserInfoBLL();
                        DataTable dt = bll.GetUserList(userDic, pageCurrent, order, out rowCount);

                        StringBuilder sb = new StringBuilder();
                        List<string> list = new List<string>();
                        list.Add("<tr><th scope='col'>序号</th><th scope='col'><input id='chkAll' type='checkbox' onclick='selectAll();' /></th><th scope='col'><a href='javascript:void(0);' onclick='order(\"UserID\");'>用户ID</a></th><th scope='col'><a href='javascript:void(0);' onclick='order(\"UserName\");'>用户姓名</a></th><th scope='col'><a href='javascript:void(0);' onclick='order(\"DeptID\");'>所属部门</a></th><th scope='col'>&nbsp;</th></tr>");
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            sb.Append("<tr>");
                            sb.AppendFormat("<td style='width: 10%;'><span>{0}</span></td>", dt.Rows[i][0]);
                            sb.AppendFormat("<td style='width: 10%;'><input type='checkbox' value='{0}' /></td>", dt.Rows[i]["UserID"]);
                            sb.AppendFormat("<td style='width: 15%;'>{0}</td>", dt.Rows[i]["UserID"]);
                            sb.AppendFormat("<td style='width: 20%;'>{0}</td>", dt.Rows[i]["UserName"]);
                            sb.AppendFormat("<td style='width: 15%;'>{0}</td>", dt.Rows[i]["DeptName"]);
                            sb.AppendFormat("<td style='width: 10%;'><img alt='编辑' title='编辑' src='/Image/common/edit.png' class='imgBtn' onclick='editUser(\"{0}\");' /></td>", dt.Rows[i]["UserID"]);
                            sb.Append("</tr>");
                        }
                        if (string.IsNullOrEmpty(sb.ToString()))
                        {
                            list.Clear();
                            list.Add("<td colspan='6' style='text-align:center;line-height:26px;'>没有数据</td>");
                        }
                        else
                        {
                            list.Add(sb.ToString());
                        }
                        list.Add("☭" + rowCount);
                        context.Response.Write(string.Concat(list));
                    }
                    #endregion

                    #region 绑定部门列表
                    else if (context.Request.QueryString["opera"] == "depart")
                    {
                        DepartmentModel dept = new DepartmentModel();
                        if (context.Request.QueryString["deptName"] != null)
                        {
                            dept.DeptName = context.Request.QueryString["deptName"];
                        }
                        if (context.Request.QueryString["manager"] != null)
                        {
                            dept.ManagerID = context.Request.QueryString["manager"];
                        }

                        int pageCurrent = Convert.ToInt32(context.Request.QueryString["pageCurrent"]);
                        int rowCount; DepartmentBLL bll = new DepartmentBLL();
                        DataTable dt = bll.GetDepartList(dept, pageCurrent, out rowCount);

                        StringBuilder sb = new StringBuilder();
                        List<string> list = new List<string>();
                        list.Add("<tr><th scope='col'>序号</th><th scope='col'>部门名称</th><th scope='col'>主管</th><th scope='col'>&nbsp;</th></tr>");
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            string DeptID = dt.Rows[i]["DeptID"].ToString();
                            sb.Append("<tr>");
                            sb.AppendFormat("<td style='width: 10%;'><span>{0}</span></td>", dt.Rows[i][0]);
                            sb.AppendFormat("<td style='width: 30%;'>{0}</td>", dt.Rows[i]["DeptName"]);
                            sb.AppendFormat("<td style='width: 20%;'>{0}</td>", dt.Rows[i]["UserName"]);

                            // 如果部门下没有员工即可删除
                            if (bll.IsEmptyDepart(DeptID))
                                sb.AppendFormat("<td style='width: 20%;'><img alt='编辑' title='编辑' src='/Image/common/edit.png' class='imgBtn' onclick='editDept(\"{0}\");' /> <input type='image' id='btnDelete' title='删除' class='imgBtn' src='/Image/common/delete.png' onclick='return deleteDept(\"{1}\");' style='border-width:0px;'></td>", DeptID, DeptID);
                            else
                                sb.AppendFormat("<td style='width: 20%;'><img alt='编辑' title='编辑' src='/Image/common/edit.png' class='imgBtn' onclick='editDept(\"{0}\");' /></td>", DeptID);
                            sb.Append("</tr>");
                        }
                        if (string.IsNullOrEmpty(sb.ToString()))
                        {
                            list.Clear();
                            list.Add("<td colspan='4' style='text-align:center;line-height:26px;'>没有数据</td>");
                        }
                        else
                        {
                            list.Add(sb.ToString());
                        }
                        list.Add("☭" + rowCount);
                        context.Response.Write(string.Concat(list));
                    }
                    #endregion

                    #region 显示考勤列表
                    else if (context.Request.QueryString["opera"] == "setting")
                    {
                        int year = Convert.ToInt32(context.Request.QueryString["year"]);
                        int month = Convert.ToInt32(context.Request.QueryString["month"]);
                        int days = DateTime.DaysInMonth(year, month);// 获取当前月份的天数

                        StringBuilder sb = new StringBuilder();
                        sb.Append("<tr><th scope='col'>日期</th><th scope='col'>星期</th><th scope='col'>状态</th></tr>");
                        //string[] chsWeek = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
                        AttendanceSettingBLL bll = new AttendanceSettingBLL();
                        DataTable dt = bll.GetAttendanceSetting();
                        for (int i = 1; i <= days; i++)
                        {
                            sb.Append("<tr>");
                            DateTime time = Convert.ToDateTime(year + "-" + month + "-" + i);
                            string date = time.ToString("yyyy-MM-dd");
                            sb.AppendFormat("<td style='width:30%;'>{0}</td>", date);

                            // 判断当前日期是星期几
                            //string week = chsWeek[Convert.ToInt32(time.DayOfWeek)];
                            string week = time.ToString("dddd");
                            sb.AppendFormat("<td style='width:30%;'>{0}</td>", week);

                            // 获取当前的考勤设置
                            DataRow[] rows = dt.Select("Date = '" + date + "'");
                            if (rows.Length > 0)
                            {
                                if (rows[0]["Status"].ToString().Equals("1"))
                                {
                                    sb.AppendFormat("<td style='width:20%;'><select id='ddlStatus' date='{0}'><option value='0' style='color:Black;'>默认</option><option selected='selected' value='1' style='color:Green;'>上班</option><option value='2' style='color:Red;'>休假</option></select></td>", date);
                                }
                                else
                                {
                                    sb.AppendFormat("<td style='width:20%;'><select id='ddlStatus' date='{0}'><option value='0' style='color:Black;'>默认</option><option value='1' style='color:Green;'>上班</option><option selected='selected' value='2' style='color:Red;'>休假</option></select></td>", date);
                                }
                            }
                            else
                            {
                                sb.AppendFormat("<td style='width:20%;'><select id='ddlStatus' date='{0}'><option selected='selected' value='0' style='color:Black;'>默认</option><option value='1' style='color:Green;'>上班</option><option value='2' style='color:Red;'>休假</option></select></td>", date);
                            }
                            sb.Append("</tr>");
                        }
                        context.Response.Write(sb.ToString());
                    }
                    #endregion

                    #region 显示部门员工
                    else if (context.Request.QueryString["opera"] == "deptuser")
                    {
                        if (context.Session["user"] == null)
                        {
                            context.Response.Write("<script>top.location='/View/Default.aspx'</script>");
                            context.Response.End();
                        }
                        string userID = ((UserInfoModel)context.Session["user"]).UserID;
                        int pageCurrent = Convert.ToInt32(context.Request.QueryString["pageCurrent"]);
                        string order = string.IsNullOrEmpty(context.Request.QueryString["orderField"]) ? "UserID" : context.Request.QueryString["orderField"];
                        int rowCount; AttendanceInfoBLL bll = new AttendanceInfoBLL();
                        DataTable dt = bll.GetDeptUser(userID, pageCurrent, order, out rowCount);

                        StringBuilder sb = new StringBuilder();
                        List<string> list = new List<string>();
                        list.Add("<tr><th scope='col'>序号</th><th scope='col'><a href='javascript:void(0);' onclick='order(\"UserID\");'>用户ID</a></th><th scope='col'><a href='javascript:void(0);' onclick='order(\"UserName\");'>用户名</a></th><th scope='col'><a href='javascript:void(0);' onclick='order(\"DeptName\");'>部门</a></th><th scope='col'>考勤信息</th></tr>");
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            sb.Append("<tr>");
                            sb.AppendFormat("<td style='width: 10%;'><span>{0}</span></td>", dt.Rows[i][0]);
                            sb.AppendFormat("<td style='width: 20%;'>{0}</td>", dt.Rows[i]["UserID"]);
                            sb.AppendFormat("<td style='width: 20%;'>{0}</td>", dt.Rows[i]["UserName"]);
                            sb.AppendFormat("<td style='width: 20%;'>{0}</td>", dt.Rows[i]["DeptName"]);
                            sb.AppendFormat("<td style='width: 10%;'><a href='javascript:showAttendance(\"{0}\");'>查看</a></td>", dt.Rows[i]["UserID"]);
                            sb.Append("</tr>");
                        }
                        if (string.IsNullOrEmpty(sb.ToString()))
                        {
                            list.Clear();
                            list.Add("<td colspan='5' style='text-align:center;line-height:26px;'>没有数据</td>");
                        }
                        else
                        {
                            list.Add(sb.ToString());
                        }
                        list.Add("☭" + rowCount);
                        context.Response.Write(string.Concat(list));
                    }
                    #endregion

                    #region 显示请假列表
                    else if (context.Request.QueryString["opera"] == "leave")
                    {
                        if (context.Session["user"] == null)
                        {
                            context.Response.Write("<script>top.location='/View/Default.aspx'</script>");
                            context.Response.End();
                        }

                        string userID = ((UserInfoModel)context.Session["user"]).UserID;
                        string title = null, beginDate = null, endDate = null, statu = null, name = null;
                        if (context.Request.QueryString["title"] != null)
                        {
                            title = context.Request.QueryString["title"];
                        }
                        if (context.Request.QueryString["begin"] != null)
                        {
                            beginDate = context.Request.QueryString["begin"];
                        }
                        if (context.Request.QueryString["end"] != null)
                        {
                            endDate = context.Request.QueryString["end"];
                        }
                        if (context.Request.QueryString["statu"] != null)
                        {
                            statu = context.Request.QueryString["statu"];
                        }
                        if (context.Request.QueryString["name"] != null)
                        {
                            name = context.Request.QueryString["name"];
                        }
                        int pageCurrent = Convert.ToInt32(context.Request.QueryString["pageCurrent"]);
                        string order = string.IsNullOrEmpty(context.Request.QueryString["orderField"]) ? "UserName" : context.Request.QueryString["orderField"];
                        int rowCount; ApproveBLL bll = new ApproveBLL();
                        DataTable dt = bll.GetLeave(userID, title, beginDate, endDate, statu, name, pageCurrent, order, out rowCount);

                        StringBuilder sb = new StringBuilder();
                        List<string> list = new List<string>();
                        list.Add("<tr><th scope='col'>请假单ID</th><th scope='col'><a href='javascript:void(0);' onclick='order(\"UserName\");'>申请人</a></th><th scope='col'>标题</th><th scope='col'><a href='javascript:void(0);' onclick='order(\"BeginDate\");'>起始时间</a></th><th scope='col'><a href='javascript:void(0);' onclick='order(\"EndDate\");'>结束时间</a></th><th scope='col'><a href='javascript:void(0);' onclick='order(\"ApplyDate\");'>申请时间</a></th><th scope='col'>请假单状态</th><th scope='col'>&nbsp;</th></tr>");
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            sb.Append("<tr>");
                            sb.AppendFormat("<td style='width:8%;'>{0}</td>", dt.Rows[i]["ApproveID"]);
                            sb.AppendFormat("<td style='width:10%;'>{0}</td>", dt.Rows[i]["UserName"]);
                            sb.AppendFormat("<td style='width:15%;'>{0}</td>", dt.Rows[i]["Title"]);
                            sb.AppendFormat("<td style='width:10%;'>{0}</td>", dt.Rows[i]["BeginDate"]);
                            sb.AppendFormat("<td style='width:10%;'>{0}</td>", dt.Rows[i]["EndDate"]);
                            sb.AppendFormat("<td style='width:10%;'>{0}</td>", dt.Rows[i]["ApplyDate"]);
                            string status = dt.Rows[i]["Status"].ToString();
                            sb.AppendFormat("<td style='width:7%;'><span id='lblStatus'>{0}</span></td>", status == "0" ? "待审批" : "归档");
                            string opt = HttpUtility.UrlDecode(context.Request.QueryString["opt"], Encoding.UTF8);
                            if (opt == "请假审批")
                            {
                                string type = status == "0" ? "apprv(\"{0}\")" : "show(\"{0}\")";
                                sb.AppendFormat("<td style='width:10%;'><a href='javascript:{0};'>查看</a></td>", string.Format(type, dt.Rows[i]["ApproveID"]));
                            }
                            else
                            {
                                if (status == "0")
                                {
                                    sb.AppendFormat("<td style='width:10%;'><img alt='编辑' title='编辑' src='/Image/common/edit.png' class='imgBtn' onclick='editLeave(\"{0}\");'><input type='image' id='btnDelete' title='删除' class='imgBtn' src='/Image/common/delete.png' onclick='return deleteApp(\"{1}\");' style='border-width:0px;'></td>'", dt.Rows[i]["ApproveID"], dt.Rows[i]["ApproveID"]);
                                }
                                else
                                {
                                    sb.AppendFormat("<td style='width:10%;'><a href='javascript:show(\"{0}\");'>查看</a></td>", dt.Rows[i]["ApproveID"]);
                                }
                            }
                            sb.Append("</tr>");
                        }
                        if (string.IsNullOrEmpty(sb.ToString()))
                        {
                            list.Clear();
                            list.Add("<td colspan='4' style='text-align:center;line-height:26px;'>没有数据</td>");
                        }
                        else
                        {
                            list.Add(sb.ToString());
                        }
                        list.Add("☭" + rowCount);
                        context.Response.Write(string.Concat(list));
                    }
                    #endregion

                    #region 列表显示员工考勤
                    else if (context.Request.QueryString["opera"] == "userattc")
                    {
                        string userID = string.Empty;
                        if (!string.IsNullOrEmpty(context.Request.QueryString["userID"]))
                        {
                            userID = context.Request.QueryString["userID"];
                        }
                        else if (context.Session["user"] != null)
                        {
                            userID = ((UserInfoModel)context.Session["user"]).UserID;
                        }
                        else
                        {
                            context.Response.Write("<script>top.location='/View/Default.aspx'</script>");
                            context.Response.End();
                        }

                        int year = Convert.ToInt32(context.Request.QueryString["year"]);
                        int month = Convert.ToInt32(context.Request.QueryString["month"]);
                        int days = DateTime.DaysInMonth(year, month); // 获取当前月份的天数
                        StringBuilder sb = new StringBuilder();
                        sb.Append("<table class='grid' cellspacing='0' rules='all' border='1' style='border-collapse: collapse;'>");
                        sb.Append("<tr><th scope='col'>日期</th><th scope='col'>星期</th><th scope='col'>首次打卡时间</th><th scope='col'>最后打卡时间</th><th scope='col'>考勤状态</th></tr>");
                        string[] chsWeek = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
                        AttendanceInfoBLL bll = new AttendanceInfoBLL();
                        DataTable dt = bll.GetAskForLeaveTime(userID);
                        for (int i = 1; i <= days; i++)
                        {
                            sb.Append("<tr>");
                            DateTime time = Convert.ToDateTime(year + "-" + month + "-" + i);
                            string date = time.ToString("yyyy-MM-dd");
                            sb.AppendFormat("<td style='width:12%;'>{0}</td>", date);

                            // 判断当前日期是周几
                            string week = chsWeek[Convert.ToInt32(time.DayOfWeek)];
                            sb.AppendFormat("<td style='width:8%;'>{0}</td>", week);

                            // 获取当天的打卡时间
                            string min = bll.GetMinFaceTime(userID, date).ToString();
                            sb.AppendFormat("<td style='width:20%;'>{0}</td>", min);
                            string max = bll.GetMaxFaceTime(userID, date).ToString();
                            sb.AppendFormat("<td style='width:20%;'>{0}</td>", max);

                            DateTime? minTime = null;
                            if (!string.IsNullOrEmpty(min))
                            {
                                minTime = Convert.ToDateTime(min);
                            }
                            DateTime? maxTime = null;
                            if (!string.IsNullOrEmpty(max))
                            {
                                maxTime = Convert.ToDateTime(max);
                            }

                            // 正常的上下班时间
                            DateTime morInTime = Convert.ToDateTime(date + " 08:30:00");
                            DateTime morOutTime = Convert.ToDateTime(date + " 11:50:00");
                            DateTime aftInTime = Convert.ToDateTime(date + " 13:50:00");
                            DateTime aftOutTime = Convert.ToDateTime(date + " 17:00:00");

                            byte statu;
                            try
                            {
                                statu = Convert.ToByte(bll.GetStatus(date));
                            }
                            catch
                            {
                                statu = 0;
                            }

                            if (statu.Equals(0) || statu.Equals(2))
                            {
                                sb.Append("<td style='width:20%;'><span style='color:gray'>休假</span></td>");
                            }
                            else if (statu.Equals(1))
                            {
                                // 如果当天存在请假信息,进行考勤状态的逻辑判断
                                if (bll.IsAskForLeaveTime(userID, date))
                                {
                                    DataRow[] row1 = dt.Select("BeginDate<='" + morInTime + "' and EndDate>='" + morOutTime + "'");
                                    DataRow[] row2 = dt.Select("BeginDate<='" + aftInTime + "' and EndDate>='" + aftOutTime + "'");
                                    if (minTime == null && maxTime == null)
                                    {
                                        if (row1.Length > 0 && row2.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#436EEE'>请假</span></td>");
                                        }
                                        else if (row2.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:red;margin-right:10px;'>缺勤</span><span style='color:#436EEE;margin-left:10px;'>请假</span></td>");
                                        }
                                        else if (row1.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#436EEE;margin-right:10px;'>请假</span><span style='color:red;margin-left:10px;'>缺勤</span></td>");
                                        }
                                        else
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:red'>缺勤</span></td>");
                                        }
                                    }
                                    else
                                    {
                                        // 对比上下班时间判定考勤状态
                                        int r1 = DateTime.Compare((DateTime)minTime, morInTime);
                                        int r2 = DateTime.Compare((DateTime)maxTime, aftOutTime);
                                        int r3 = DateTime.Compare((DateTime)maxTime, morOutTime);
                                        int r4 = DateTime.Compare((DateTime)minTime, aftInTime);
                                        if (row1.Length > 0 && row2.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#436EEE'>请假</span></td>");
                                        }
                                        else if (DateTime.Compare((DateTime)minTime, (DateTime)maxTime) == 0 && row1.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#436EEE;margin-right:10px;'>请假</span><span style='color:pink;margin-left:10px;'>未打卡</span></td>");
                                        }
                                        else if (DateTime.Compare((DateTime)minTime, (DateTime)maxTime) == 0 && row2.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:pink;margin-right:10px;'>未打卡</span><span style='color:#436EEE;margin-left:10px;'>请假</span></td>");
                                        }
                                        else if ((r4 > 0 && r2 < 0) && row1.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#436EEE;margin-right:10px;'>请假</span><span style='color:Aqua;margin-left:10px;'>迟到且早退</span></td>");
                                        }
                                        else if ((r1 > 0 && r3 < 0) && row2.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:Aqua;margin-right:10px;'>迟到且早退</span><span style='color:#436EEE;margin-left:10px;'>请假</span></td>");
                                        }
                                        else if ((r4 <= 0 && r2 >= 0) && row1.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#436EEE;margin-right:10px;'>请假</span><span style='color:#3CB371;margin-left:10px;'>正常</span></td>");
                                        }
                                        else if ((r1 <= 0 && r3 >= 0) && row2.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#3CB371;margin-right:10px;'>正常</span><span style='color:#436EEE;margin-left:10px;'>请假</span></td>");
                                        }
                                        else if (r2 < 0 && row1.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#436EEE;margin-right:10px;'>请假</span><span style='color:Orange;margin-left:10px;'>早退</span></td>");
                                        }
                                        else if (r4 > 0 && row1.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#436EEE;margin-right:10px;'>请假</span><span style='color:#CAFF70;margin-left:10px;'>迟到</span></td>");
                                        }
                                        else if (r1 > 0 && row2.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#CAFF70;margin-right:10px;'>迟到</span><span style='color:#436EEE;margin-left:10px;'>请假</span></td>");
                                        }
                                        else if (r3 < 0 && row2.Length > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:Orange;margin-right:10px;'>早退</span><span style='color:#436EEE;margin-left:10px;'>请假</span></td>");
                                        }
                                        else if (r1 > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#CAFF70;margin-right:10px;'>迟到</span><span style='color:red;margin-left:10px;'>缺勤</span></td>");
                                        }
                                        else if (r2 < 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:red;margin-right:10px;'>缺勤</span><span style='color:Orange;margin-left:10px;'>早退</span></td>");
                                        }
                                        else
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:red'>缺勤</span></td>");
                                        }
                                    }
                                }
                                else
                                {
                                    if (minTime == null && maxTime == null)
                                    {
                                        sb.Append("<td style='width:20%;'><span style='color:red'>缺勤</span></td>");
                                    }
                                    else
                                    {
                                        // 对比上下班时间判定考勤状态
                                        int r1 = DateTime.Compare((DateTime)minTime, morInTime);
                                        int r2 = DateTime.Compare((DateTime)maxTime, aftOutTime);
                                        if (DateTime.Compare((DateTime)minTime, (DateTime)maxTime) == 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:pink'>未打卡</span></td>");
                                        }
                                        else if (r1 <= 0 && r2 >= 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#3CB371'>正常</span></td>");
                                        }
                                        else if (r1 > 0 && r2 < 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:Aqua'>迟到且早退</span></td>");
                                        }
                                        else if (r1 > 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#CAFF70'>迟到</span></td>");
                                        }
                                        else if (r2 < 0)
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:Orange'>早退</span></td>");
                                        }
                                        else
                                        {
                                            sb.Append("<td style='width:20%;'><span style='color:#8B008B'>异常</span></td>");
                                        }
                                    }
                                }
                            }
                            sb.Append("</tr>");
                        }
                        sb.Append("</table>");
                        context.Response.Write(sb.ToString());
                    }
                    #endregion

                    #region 日历显示员工考勤
                    else if (context.Request.QueryString["opera"] == "calendar")
                    {
                        if (context.Session["user"] == null)
                        {
                            context.Response.Write("<script>top.location='/View/Default.aspx'</script>");
                            context.Response.End();
                        }
                        string userID = ((UserInfoModel)context.Session["user"]).UserID;
                        int year = Convert.ToInt32(context.Request.QueryString["year"]);
                        int month = Convert.ToInt32(context.Request.QueryString["month"]);
                        int days = DateTime.DaysInMonth(year, month); // 获取当前月份的天数

                        StringBuilder sb = new StringBuilder();
                        sb.Append("<table class='calendar' cellspacing='0' rules='all' border='1' id='calendar' style='border-collapse:collapse;'>");
                        sb.Append("<tr><th scope='col'>一</th><th scope='col'>二</th><th scope='col'>三</th><th scope='col'>四</th><th scope='col'>五</th><th scope='col'>六</th><th scope='col'>日</th></tr>");
                        int day = 1;
                        DateTime time = Convert.ToDateTime(year + "-" + month + "-" + day);
                        AttendanceInfoBLL bll = new AttendanceInfoBLL();
                        DataTable dt = bll.GetAskForLeaveTime(userID);
                        for (int i = 0; i < 6; i++)
                        {
                            sb.Append("<tr>");
                            // 遍历每个星期的考勤状态
                            for (int j = 0; j < 7; j++)
                            {
                                int week = (Convert.ToInt32(time.DayOfWeek) + 6) % 7;
                                if (j == week && day <= days)
                                {
                                    string date = time.ToString("yyyy-MM-dd");
                                    // 获取当天的打卡时间
                                    string min = bll.GetMinFaceTime(userID, date).ToString();
                                    string max = bll.GetMaxFaceTime(userID, date).ToString();

                                    sb.AppendFormat("<td Day='{0}' FirstTime='{1}' LastTime='{2}'>", time.ToString("yyyy年MM月dd日") + "\t" + time.ToString("dddd"), min, max);
                                    sb.AppendFormat("<div class='left'>{0}</div>", day);

                                    DateTime? minTime = null;
                                    if (!string.IsNullOrEmpty(min))
                                    {
                                        minTime = Convert.ToDateTime(min);
                                    }
                                    DateTime? maxTime = null;
                                    if (!string.IsNullOrEmpty(max))
                                    {
                                        maxTime = Convert.ToDateTime(max);
                                    }

                                    // 正常的上下班时间
                                    DateTime morInTime = Convert.ToDateTime(date + " 08:30:00");
                                    DateTime morOutTime = Convert.ToDateTime(date + " 11:50:00");
                                    DateTime aftInTime = Convert.ToDateTime(date + " 13:50:00");
                                    DateTime aftOutTime = Convert.ToDateTime(date + " 17:00:00");

                                    byte statu;
                                    try
                                    {
                                        statu = Convert.ToByte(bll.GetStatus(date));
                                    }
                                    catch
                                    {
                                        statu = 0;
                                    }

                                    if (statu.Equals(0) || statu.Equals(2))
                                    {
                                        sb.Append("<div class='right'><div class='div1' style='background-color:gray;'>休假</div></div>");
                                    }
                                    else if (statu.Equals(1))
                                    {
                                        // 如果当天存在请假信息,进行考勤状态的逻辑判断
                                        if (bll.IsAskForLeaveTime(userID, date))
                                        {
                                            DataRow[] row1 = dt.Select("BeginDate<='" + morInTime + "' and EndDate>='" + morOutTime + "'");
                                            DataRow[] row2 = dt.Select("BeginDate<='" + aftInTime + "' and EndDate>='" + aftOutTime + "'");
                                            if (minTime == null && maxTime == null)
                                            {
                                                if (row1.Length > 0 && row2.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div1' style='background-color:#436EEE;'>请假</div></div>");
                                                }
                                                else if (row2.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:red;'>缺勤</div><div class='div2' style='background-color:#436EEE;'>请假</div></div>");
                                                }
                                                else if (row1.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:#436EEE;'>请假</div><div class='div2' style='background-color:red;'>缺勤</div></div>");
                                                }
                                                else
                                                {
                                                    sb.Append("<div class='right'><div class='div1' style='background-color:red;'>缺勤</div></div>");
                                                }
                                            }
                                            else
                                            {
                                                // 对比上下班时间判定考勤状态
                                                int r1 = DateTime.Compare((DateTime)minTime, morInTime);
                                                int r2 = DateTime.Compare((DateTime)maxTime, aftOutTime);
                                                int r3 = DateTime.Compare((DateTime)maxTime, morOutTime);
                                                int r4 = DateTime.Compare((DateTime)minTime, aftInTime);
                                                if (row1.Length > 0 && row2.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div1' style='background-color:#436EEE;'>请假</div></div>");
                                                }
                                                else if (DateTime.Compare((DateTime)minTime, (DateTime)maxTime) == 0 && row1.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:#436EEE;'>请假</div><div class='div2' style='background-color:pink;'>未打卡</div></div>");
                                                }
                                                else if (DateTime.Compare((DateTime)minTime, (DateTime)maxTime) == 0 && row2.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:pink;'>未打卡</div><div class='div2' style='background-color:#436EEE;'>请假</div></div>");
                                                }
                                                else if ((r4 > 0 && r2 < 0) && row1.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:#436EEE;'>请假</div><div class='div2' style='background-color:Aqua;'>迟到且早退</div></div>");
                                                }
                                                else if ((r1 > 0 && r3 < 0) && row2.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:Aqua;'>迟到且早退</div><div class='div2' style='background-color:#436EEE;'>请假</div></div>");
                                                }
                                                else if ((r4 <= 0 && r2 >= 0) && row1.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:#436EEE;'>请假</div><div class='div2' style='background-color:#3CB371;'>正常</div></div>");
                                                }
                                                else if ((r1 <= 0 && r3 >= 0) && row2.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:#3CB371;'>正常</div><div class='div2' style='background-color:#436EEE;'>请假</div></div>");
                                                }
                                                else if (r2 < 0 && row1.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:#436EEE;'>请假</div><div class='div2' style='background-color:Orange;'>早退</div></div>");
                                                }
                                                else if (r4 > 0 && row1.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:#436EEE;'>请假</div><div class='div2' style='background-color:#CAFF70;'>迟到</div></div>");
                                                }
                                                else if (r1 > 0 && row2.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:#CAFF70;'>迟到</div><div class='div2' style='background-color:#436EEE;'>请假</div></div>");
                                                }
                                                else if (r3 < 0 && row2.Length > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:Orange;'>早退</div><div class='div2' style='background-color:#436EEE;'>请假</div></div>");
                                                }
                                                else if (r1 > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:#CAFF70;'>迟到</div><div class='div2' style='background-color:red;'>缺勤</div></div>");
                                                }
                                                else if (r2 < 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div2' style='background-color:red;'>缺勤</div><div class='div2' style='background-color:Orange;'>早退</div></div>");
                                                }
                                                else
                                                {
                                                    sb.Append("<div class='right'><div class='div1' style='background-color:red;'>缺勤</div></div>");
                                                }
                                            }
                                        }
                                        else
                                        {
                                            if (minTime == null && maxTime == null)
                                            {
                                                sb.Append("<div class='right'><div class='div1' style='background-color:red;'>缺勤</div></div>");
                                            }
                                            else
                                            {
                                                // 对比上下班时间判定考勤状态
                                                int r1 = DateTime.Compare((DateTime)minTime, morInTime);
                                                int r2 = DateTime.Compare((DateTime)maxTime, aftOutTime);
                                                if (DateTime.Compare((DateTime)minTime, (DateTime)maxTime) == 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div1' style='background-color:pink;'>未打卡</div></div>");
                                                }
                                                else if (r1 <= 0 && r2 >= 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div1' style='background-color:#3CB371;'>正常</div></div>");
                                                }
                                                else if (r1 > 0 && r2 < 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div1' style='background-color:Aqua;'>迟到且早退</div></div>");
                                                }
                                                else if (r1 > 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div1' style='background-color:#CAFF70;'>迟到</div></div>");
                                                }
                                                else if (r2 < 0)
                                                {
                                                    sb.Append("<div class='right'><div class='div1' style='background-color:Orange;'>早退</div></div>");
                                                }
                                                else
                                                {
                                                    sb.Append("<div class='right'><div class='div1' style='background-color:#8B008B;'>异常</div></div>");
                                                }
                                            }
                                        }
                                    }
                                    sb.Append("</td>");
                                    time = time.AddDays(1);
                                    day++;
                                }
                                else
                                {
                                    sb.Append("<td><div class='left'></div><div class='right'></div></td>");
                                }
                            }
                            sb.Append("</tr>");
                            if (day > days) break;
                        }
                        sb.Append("</table>");
                        context.Response.Write(sb.ToString());
                    }

                    #endregion
                }
                else if (context.Request.QueryString["type"] == "delete")
                {
                    #region 删除指定用户
                    if (context.Request.QueryString["opera"] == "users")
                    {
                        if (context.Request.QueryString["userID"] != null)
                        {
                            UserInfoBLL bll = new UserInfoBLL();
                            int res = bll.DeleteUsers(context.Request.QueryString["userID"]);
                            int total = Convert.ToInt32(context.Request.QueryString["total"]);

                            string msg = res > 0 ? "删除成功:" + res + "条,删除失败:" + (res - total) + "条。" : "删除失败!";
                            context.Response.Write(msg);
                        }
                    }
                    #endregion

                    #region 删除指定部门
                    else if (context.Request.QueryString["opera"] == "depart")
                    {
                        if (context.Request.QueryString["deptID"] != null)
                        {
                            DepartmentBLL bll = new DepartmentBLL();
                            try
                            {
                                bll.DeleteDepart(context.Request.QueryString["deptID"]);
                                context.Response.Write("{'Result':'OK','Message':'删除成功!'}");
                            }
                            catch
                            {
                                context.Response.Write("{'Result':'NO','Message':'删除失败!'}");
                            }
                        }
                    }
                    #endregion

                    #region 删除请假单
                    else if (context.Request.QueryString["opera"] == "leave")
                    {
                        if (context.Request.QueryString["appID"] != null)
                        {
                            ApproveBLL bll = new ApproveBLL();
                            try
                            {
                                bll.DeleteLeave(context.Request.QueryString["appID"]);
                                context.Response.Write("{'Result':'OK','Message':'删除成功!'}");
                            }
                            catch
                            {
                                context.Response.Write("{'Result':'NO','Message':'删除失败!'}");
                            }
                        }
                    }
                    #endregion
                }
                else if (context.Request.QueryString["type"] == "append")
                {
                    #region 添加请假单
                    if (context.Request.QueryString["opera"] == "leave")
                    {
                        if (context.Session["user"] == null)
                        {
                            context.Response.Write("<script>top.location='/View/Default.aspx'</script>");
                            context.Response.End();
                        }

                        ApproveModel apprv = new ApproveModel
                        {
                            ApplyUser = ((UserInfoModel)context.Session["user"]).UserID,
                            Title = context.Request.QueryString["title"],
                            BeginDate = Convert.ToDateTime(context.Request.QueryString["beginDate"]),
                            EndDate = Convert.ToDateTime(context.Request.QueryString["endDate"]),
                            Reason = context.Request.QueryString["reason"]
                        };

                        ApproveBLL bll = new ApproveBLL();
                        try
                        {
                            bll.AppendLeave(apprv);
                            context.Response.Write("{'Result':'OK','Message':'保存成功!'}");
                        }
                        catch
                        {
                            context.Response.Write("{'Result':'NO','Message':'保存失败!'}");
                        }
                    }
                    #endregion
                }
                else if (context.Request.QueryString["type"] == "edit")
                {
                    #region 编辑个人资料
                    if (context.Request.QueryString["opera"] == "private")
                    {
                        if (context.Session["user"] == null)
                        {
                            context.Response.Write("<script>top.location='/View/Default.aspx'</script>");
                            context.Response.End();
                        }

                        UserInfoModel user = new UserInfoModel
                        {
                            UserID = ((UserInfoModel)context.Session["user"]).UserID,
                            Cellphone = context.Request.QueryString["phone"]
                        };
                        // 检验用户是否修改密码
                        if (context.Request.QueryString["pwd"] != null)
                        {
                            user.Password = MD5Maker.GetMD5(context.Request.QueryString["pwd"]);
                        }

                        UserInfoBLL bll = new UserInfoBLL();
                        try
                        {
                            bll.EditPrivate(user);
                            context.Response.Write("{'Result':'OK','Message':'保存成功!'}");
                        }
                        catch
                        {
                            context.Response.Write("{'Result':'NO','Message':'保存失败!'}");
                        }
                    }
                    #endregion

                    #region 设置日常考勤
                    else if (context.Request.QueryString["opera"] == "setting")
                    {
                        string date = context.Request.QueryString["date"];
                        string statu = context.Request.QueryString["statu"];

                        AttendanceSettingBLL bll = new AttendanceSettingBLL();
                        try
                        {
                            bll.SetAttendanceSetting(date, statu);
                            context.Response.Write("{'Result':'OK','Message':'保存成功!'}");
                        }
                        catch
                        {
                            context.Response.Write("{'Result':'NO','Message':'保存失败!'}");
                        }
                    }
                    #endregion

                    #region 编辑请假单
                    else if (context.Request.QueryString["opera"] == "leave")
                    {
                        ApproveModel apprv = new ApproveModel
                        {
                            ApproveID = Convert.ToInt32(context.Request.QueryString["appID"]),
                            Title = context.Request.QueryString["title"],
                            BeginDate = Convert.ToDateTime(context.Request.QueryString["beginDate"]),
                            EndDate = Convert.ToDateTime(context.Request.QueryString["endDate"]),
                            Reason = context.Request.QueryString["reason"]
                        };

                        ApproveBLL bll = new ApproveBLL();
                        try
                        {
                            bll.EditLeave(apprv);
                            context.Response.Write("{'Result':'OK','Message':'保存成功!'}");
                        }
                        catch
                        {
                            context.Response.Write("{'Result':'NO','Message':'保存失败!'}");
                        }
                    }
                    #endregion

                    #region 审批请假单
                    else if (context.Request.QueryString["opera"] == "apprv")
                    {
                        if (context.Session["user"] == null)
                        {
                            context.Response.Write("<script>top.location='/View/Default.aspx'</script>");
                            context.Response.End();
                        }

                        ApproveModel apprv = new ApproveModel
                        {
                            ApproveID = Convert.ToInt32(context.Request.QueryString["appID"]),
                            ApproveUser = ((UserInfoModel)context.Session["user"]).UserID,
                            Result = Convert.ToByte(context.Request.QueryString["result"]),
                            Remark = context.Request.QueryString["remark"]
                        };
                        ApproveBLL bll = new ApproveBLL();
                        try
                        {
                            bll.ApprvLeave(apprv);
                            context.Response.Write("{'Result':'OK','Message':'保存成功!'}");
                        }
                        catch
                        {
                            context.Response.Write("{'Result':'NO','Message':'保存失败!'}");
                        }
                    }
                    #endregion
                }
                else if (context.Request.QueryString["type"] == "validate")
                {
                    #region 验证用户ID
                    if (context.Request.QueryString["opera"] == "users")
                    {
                        string userID = context.Request.QueryString["userID"];
                        UserInfoBLL bll = new UserInfoBLL();
                        if (bll.IsExistsID(userID)) context.Response.Write("{'Result':'NO'}");
                        else context.Response.Write("{'Result':'OK'}");
                    }
                    #endregion

                    #region 验证部门名称
                    else if (context.Request.QueryString["opera"] == "depart")
                    {
                        string dept = context.Request.QueryString["dept"];
                        DepartmentBLL bll = new DepartmentBLL();
                        if (bll.IsExistsDept(dept)) context.Response.Write("{'Result':'NO'}");
                        else context.Response.Write("{'Result':'OK'}");
                    }
                    #endregion
                }
                else if (context.Request.QueryString["type"] == "logout")
                {
                    #region 清除Session
                    context.Session["user"] = null;
                    context.Response.Write("<script>location='/View/Default.aspx'</script>");
                    #endregion
                }
            }
        }
コード例 #6
0
ファイル: Ticket.cs プロジェクト: davelondon/dontstayin
        public bool VerifyTicketPurchase()
        {
			List<IBobAsHTML> bobsAsHTML = new List<IBobAsHTML>();

			if ((this.Enabled || this.Cancelled) && (this.Invoice == null || this.CardNumberEnd.Length == 0 || this.FirstName.Length == 0 || this.LastName.Length == 0))
			{
				string oldTicketHTML = this.AsHTML();
				string ticketFromDataBaseHTML = "Unable to retrieve ticket from database.";
				try
				{
					// Get fresh data from database and compare to MemCached Ticket
					TicketSet ticketsFromDatabase = new TicketSet(new Query(new Q(Ticket.Columns.K, this.K)));
					
					if (ticketsFromDatabase.Count == 1)
					{
						ticketFromDataBaseHTML = ticketsFromDatabase[0].AsHTML();
						this.InvoiceItemK = ticketsFromDatabase[0].InvoiceItemK;
						this.FirstName = ticketsFromDatabase[0].FirstName;
						this.LastName = ticketsFromDatabase[0].LastName;
						this.CardNumberEnd = ticketsFromDatabase[0].CardNumberEnd;
						this.CardCV2 = ticketsFromDatabase[0].CardCV2;
						this.Update();
						//if (this.InvoiceItemK != ticketsFromDatabase[0].InvoiceItemK || this.Enabled != ticketsFromDatabase[0].Enabled || this.Cancelled != ticketsFromDatabase[0].Cancelled || Math.Round(this.Price, 2) != Math.Round(ticketsFromDatabase[0].Price, 2))
						//{	
						//    bobsAsHTML.Add(this);
						//    bobsAsHTML.Add(ticketsFromDatabase[0]);
						//    Utilities.AdminEmailAlert("<p>MemCache and database do not match for ticket.</p><p>TicketK= " + this.K.ToString() + ", InvoiceItemK= " + this.InvoiceItemK.ToString() + "</p>", "Error with MemCache", new DSIUserFriendlyException("Error with MemCache"), bobsAsHTML);
						//}
					}

					if (this.InvoiceItemK == 0 || this.CardNumberEnd.Length == 0 || this.FirstName.Length == 0 || this.LastName.Length == 0)
					{
						bobsAsHTML.Clear();
						Query ticketInvoiceQuery = new Query(new And(new Q(Invoice.Columns.UsrK, this.BuyerUsrK),
																	 //new Q(InvoiceItem.Columns.Total, this.Price),
																	 new Q(InvoiceItem.Columns.BuyableObjectType, Convert.ToInt32(Model.Entities.ObjectType.Ticket)),
																	 new Q(InvoiceItem.Columns.BuyableObjectK, this.K),
																	 new Q(Invoice.Columns.Paid, 1),
																	 new Q(Invoice.Columns.PaidDateTime, QueryOperator.GreaterThanOrEqualTo, this.BuyDateTime.AddMinutes(-8)),
																	 new Q(Invoice.Columns.PaidDateTime, QueryOperator.LessThanOrEqualTo, this.BuyDateTime.AddMinutes(8))));
						ticketInvoiceQuery.TableElement = new Join(Invoice.Columns.K, InvoiceItem.Columns.InvoiceK);
						InvoiceSet ticketInvoice = new InvoiceSet(ticketInvoiceQuery);

						if (ticketInvoice.Count == 1 && ticketInvoice[0].Items.Count > 0)
						{
							if (this.InvoiceItemK == 0)
							{
								foreach (InvoiceItem ii in ticketInvoice[0].Items)
								{
									if (ii.Type == InvoiceItem.Types.EventTickets && ii.KeyData == this.K && ii.BuyableObjectType == Model.Entities.ObjectType.Ticket && ii.BuyableObjectK == this.K && Math.Round(ii.Total, 2) == Math.Round(this.Price))
										this.InvoiceItemK = ii.K;
								}
							}
							bobsAsHTML.Add(this);
							bobsAsHTML.Add(ticketInvoice[0]);

							if (ticketInvoice[0].SuccessfulAppliedTransfers.Count == 1)
							{
								bobsAsHTML.Add(ticketInvoice[0].SuccessfulAppliedTransfers[0]);

								if (this.CardNumberEnd.Length == 0)
								{
									this.CardNumberEnd = ticketInvoice[0].SuccessfulAppliedTransfers[0].CardNumberEnd;
									this.CardNumberDigits = ticketInvoice[0].SuccessfulAppliedTransfers[0].CardDigits;
									this.CardCV2 = ticketInvoice[0].SuccessfulAppliedTransfers[0].CardCV2;
								}
								if (this.AddressPostcode.Length == 0)
								{
									this.AddressPostcode = ticketInvoice[0].SuccessfulAppliedTransfers[0].CardPostcode;
								}
								if (this.AddressStreet.Length == 0)
								{
									this.AddressStreet = ticketInvoice[0].SuccessfulAppliedTransfers[0].CardAddress1;
								}
								if (this.FirstName != Cambro.Misc.Utility.Snip(Utilities.GetFirstName(ticketInvoice[0].SuccessfulAppliedTransfers[0].CardName), 100))
								{
									this.FirstName = Cambro.Misc.Utility.Snip(Utilities.GetFirstName(ticketInvoice[0].SuccessfulAppliedTransfers[0].CardName), 100);
								}
								if (this.LastName != Cambro.Misc.Utility.Snip(Utilities.GetLastName(ticketInvoice[0].SuccessfulAppliedTransfers[0].CardName), 100))
								{
									this.LastName = Cambro.Misc.Utility.Snip(Utilities.GetLastName(ticketInvoice[0].SuccessfulAppliedTransfers[0].CardName), 100);
								}
								this.Update();
							}

							Utilities.AdminEmailAlert("<p>Ticket and invoice did not match, but have been auto fixed.</p><p>Please verify manually.</p><p>TicketK= " + this.K.ToString() + ", InvoiceItemK= " + this.InvoiceItemK.ToString() + "</p>" + oldTicketHTML + ticketFromDataBaseHTML,
													  "Ticket auto fixed #" + this.K.ToString(), new DsiUserFriendlyException("Ticket auto fixed"), bobsAsHTML, new string[] { Vars.EMAIL_ADDRESS_TIMI });
						}
						else
						{
							Utilities.AdminEmailAlert("<p>Ticket and invoice did not match, and have not been fixed. Unable to find invoice from database</p><p>Please verify manually.</p><p>TicketK= " + this.K.ToString() + ", InvoiceItemK= " + this.InvoiceItemK.ToString() + "</p>" + oldTicketHTML + ticketFromDataBaseHTML,
													  "Error not fixed with ticket #" + this.K.ToString(), new DsiUserFriendlyException("Ticket not fixed"), bobsAsHTML, new string[] { Vars.EMAIL_ADDRESS_TIMI });
						}
					}
				}
				catch { }
				if (this.InvoiceItemK == 0 || this.CardNumberEnd.Length == 0 || this.FirstName.Length == 0 || this.LastName.Length == 0)
				{
					Utilities.AdminEmailAlert("<p>Ticket information missing.</p><p>Please verify manually.</p><p>TicketK= " + this.K.ToString() + ", InvoiceItemK= " + this.InvoiceItemK.ToString() + "</p>",
											  "Error with Ticket #" + this.K.ToString(), new DsiUserFriendlyException("Error with ticket"), new List<IBobAsHTML>(){this}, new string[] { Vars.EMAIL_ADDRESS_TIMI });
				}
			}
			if ((this.Enabled || this.Cancelled) && this.Invoice != null && !this.Invoice.Paid)
			{
				bobsAsHTML.Clear();
				bobsAsHTML.Add(this);
				bobsAsHTML.Add(this.Invoice);

				Utilities.AdminEmailAlert("<p>Error occurred in VerifyTicketPurchase. Invoice was not fully paid for Ticket #" + this.K.ToString() + "</p>", 
										  "Error occurred in VerifyTicketPurchase. Invoice was not fully paid for Ticket #" + this.K.ToString(), new Exception(), bobsAsHTML);
			}

            if (!this.Enabled)
                throw new DsiUserFriendlyException("Ticket not valid.");

            if (this.Cancelled)
                throw new DsiUserFriendlyException("Ticket has been cancelled.");

            return true;
        }
コード例 #7
0
ファイル: TargetRenderingManager.cs プロジェクト: Zeludon/FEZ
 private void RecreateTargets()
 {
   List<Action<RenderTarget2D>> list = new List<Action<RenderTarget2D>>();
   foreach (RenderTargetHandle renderTargetHandle in this.fullscreenRTs)
   {
     list.Clear();
     foreach (TargetRenderingManager.RtHook rtHook in this.renderTargetsToHook)
     {
       if (renderTargetHandle.Target == rtHook.Target)
       {
         TargetRenderingManager.RtHook _ = rtHook;
         list.Add((Action<RenderTarget2D>) (t => _.Target = t));
       }
     }
     renderTargetHandle.Target.Dispose();
     renderTargetHandle.Target = this.CreateFullscreenTarget();
     foreach (Action<RenderTarget2D> action in list)
       action(renderTargetHandle.Target);
   }
 }
コード例 #8
0
ファイル: DavAStar.cs プロジェクト: muntac/unitytool
        public List<Node> Compute(int startX, int startY, int endX, int endY, Cell[][][] matrix, int time, bool prob)
        {
            try{
            Priority_Queue.IPriorityQueue<Node> heap2 = new Priority_Queue.HeapPriorityQueue<Node>(600);

            // Initialize our version of the matrix (can we skip this?)
            Node[][] newMatrix = new Node[matrix[0].Length][];
            for (int x = 0; x < matrix [0].Length; x++) {
                newMatrix [x] = new Node[matrix [0] [x].Length];
                for (int y = 0; y < matrix [0] [x].Length; y++) {
                    newMatrix [x] [y] = new Node ();
                    newMatrix [x] [y].parent = null;
                    newMatrix [x] [y].cell = matrix [0] [x] [y];
                    newMatrix [x] [y].x = x;
                    newMatrix [x] [y].y = y;
                }
            }
            enemyPathProb(newMatrix);
            // Do the work for the first cell before firing the algorithm
            start = newMatrix [startX] [startY];
            end = newMatrix [endX] [endY];
            start.parent=null;
            start.visited=true;

            foreach (Node n in getAdjacent(start, newMatrix)) {
                n.t=time;
                n.parent = start;
                float fVal = f (n);
                n.Priority = fVal;
                heap2.Enqueue(n,fVal);
            }
            while(heap2.Count != 0){

                Node first = heap2.Dequeue();
                if(first == end)
                    break;
                first.visited=true;
                double temprt = 1;
                List<Node> adjs = getAdjacent(first,newMatrix);

                foreach(Node m in adjs){
                    float currentG = (float)(g (first) + h (first,m, ref temprt));
                    if(m.visited){
                            if(g (m)>currentG){
                                m.parent=first;
                                m.t = first.t+time;
                            }
                        }
                    else{
                        if( !heap2.Contains(m)){
                            m.parent = first;
                            m.t= first.t +time;
                            m.Priority = (float)temprt*f(m);
                            heap2.Enqueue(m, m.Priority);
                        }
                        else
                        {
                            float gVal = g (m);
                            if(gVal>currentG){
                                m.parent= first;
                                m.t = first.t+time;
                                m.Priority= (float)temprt *f (m);
                                heap2.UpdatePriority(m, m.Priority);
                            }
                        }
                    }
                }
            }
                // Creates the result list
                Node l = end;
                List<Node> points = new List<Node> ();
                while (l != null) {
                    points.Add (l);
                    l = l.parent;
                }
                points.Reverse ();

                // If we didn't find a path
                if (points.Count == 1)
                points.Clear ();
                return points;
            }catch(System.Exception e){
                                Debug.Log (e.Message);
                                Debug.Log (e.StackTrace);
                                Debug.Log ("ERROR 2");
                                return null;
                        }
        }
コード例 #9
0
ファイル: DatabaseHelper.cs プロジェクト: saeednazari/Rubezh
		public static OperationResult<List<JournalRecord>> OnGetFilteredArchive(ArchiveFilter archiveFilter, bool isReport)
		{
			var operationResult = new OperationResult<List<JournalRecord>>();
			operationResult.Result = new List<JournalRecord>();
			try
			{
				string dateInQuery = "DeviceTime";
				if (archiveFilter.UseSystemDate)
					dateInQuery = "SystemTime";

				var query =
					"SELECT * FROM Journal WHERE " +
					"\n " + dateInQuery + " > '" + archiveFilter.StartDate.ToString("yyyy-MM-dd HH:mm:ss") + "'" +
					"\n AND " + dateInQuery + " < '" + archiveFilter.EndDate.ToString("yyyy-MM-dd HH:mm:ss") + "'";

				if (archiveFilter.Descriptions.Count > 0)
				{
					query += "\n AND (";
					for (int i = 0; i < archiveFilter.Descriptions.Count; i++)
					{
						if (i > 0)
							query += "\n OR ";
						var description = archiveFilter.Descriptions[i];
						description = description.Replace("'", "''");
						query += " Description = '" + description + "'";
					}
					query += ")";
				}

				if (archiveFilter.Subsystems.Count > 0)
				{
					query += "\n AND (";
					for (int i = 0; i < archiveFilter.Subsystems.Count; i++)
					{
						if (i > 0)
							query += "\n OR ";
						var subsystem = archiveFilter.Subsystems[i];
						query += " SubSystemType = '" + ((int)subsystem).ToString() + "'";
					}
					query += ")";
				}

				if (archiveFilter.PanelUIDs.Count > 0)
				{
					query += "\n AND (";
					for (int i = 0; i < archiveFilter.PanelUIDs.Count; i++)
					{
						var deviceName = archiveFilter.PanelUIDs[i];
						if (deviceName != null)
						{
							if (i > 0)
								query += "\n OR ";
							query += " PanelDatabaseId = '" + deviceName + "'";
						}
					}
					query += ")";
				}

				query += "\n ORDER BY " + dateInQuery + " DESC";

				using (var DataBaseContext = new SqlCeConnection(ConnectionString))
				{
					DataBaseContext.ConnectionString = ConnectionString;
					var journalRecords = new List<JournalRecord>();
					var result = new SqlCeCommand(query, DataBaseContext);
					DataBaseContext.Open();
					var reader = result.ExecuteReader();
					while (reader.Read())
					{
						if (IsAbort && !isReport)
							break;
						try
						{
							var journalRecord = ReadOneJournalRecord(reader);
							operationResult.Result.Add(journalRecord);
							if (!isReport)
							{
								journalRecords.Add(journalRecord);
								if (journalRecords.Count > 100)
								{
									if (ArchivePortionReady != null)
										ArchivePortionReady(journalRecords.ToList());

									journalRecords.Clear();
								}
							}
						}
						catch (Exception e)
						{
							Logger.Error(e, "DatabaseHelper.OnGetFilteredArchive");
						}
					}
					if (!isReport)
					{
						if (ArchivePortionReady != null)
							ArchivePortionReady(journalRecords.ToList());
					}

					DataBaseContext.Close();
				}
			}
			catch (Exception e)
			{
				Logger.Error(e, "Исключение при вызове FiresecService.GetFilteredArchive");
				operationResult.HasError = true;
				operationResult.Error = e.Message.ToString();
			}
			return operationResult;
		}
コード例 #10
0
ファイル: DavAStar3d.cs プロジェクト: muntac/unitytool
        public List<Node> Compute(int startX, int startY, int endX, int endY, Cell[][][] matrix, float playerSpeed)
        {
            this.speed = 1.0d / playerSpeed;
            try {
                Priority_Queue.IPriorityQueue<Node> heap2 = new Priority_Queue.HeapPriorityQueue<Node> (1000000);
                List<Node> closed = new List<Node> ();

                // Initialize our version of the matrix (can we skip this?)
                Node[][][] newMatrix = new Node[matrix.Length][][];
                for (int t=0; t<matrix.Length; t++) {
                    newMatrix [t] = new Node[matrix [t].Length][];
                    for (int x = 0; x < matrix [t].Length; x++) {
                        newMatrix [t] [x] = new Node[matrix [t] [x].Length];
                        for (int y = 0; y < matrix [t] [x].Length; y++) {
                            newMatrix [t] [x] [y] = new Node ();
                            newMatrix [t] [x] [y].parent = null;
                            newMatrix [t] [x] [y].cell = matrix [t] [x] [y];
                            newMatrix [t] [x] [y].x = x;
                            newMatrix [t] [x] [y].y = y;
                            newMatrix [t] [x] [y].t = t;
                        }
                    }
                }
                // Do the work for the first cell before firing the algorithm
                start = newMatrix [0] [startX] [startY];
                end = newMatrix [0] [endX] [endY];
                start.parent = null;
                start.visited = true;
                start.accSpeed = speed - Math.Floor(speed);
                foreach (Node n in getAdjacent(start, newMatrix)) {
                    n.parent = start;
                    float fVal = f (n);
                    n.Priority = fVal;
                    heap2.Enqueue (n, fVal);
                }
                while (heap2.Count != 0) {
                    Node first = heap2.Dequeue ();
                    if (first.x == end.x && first.y == end.y) {
                        end = newMatrix [first.t] [end.x] [end.y];
                        break;
                    }
                    first.visited = true;
                    foreach (Node m in getAdjacent(first, newMatrix)) {
                        float currentG = g (first) + h (m, first);
                        float gVal = g (m);
                        if (m.visited) {
                            if (gVal > currentG) {
                                m.parent = first;
                                acc(m);
                            }
                        } else {
                            if (!heap2.Contains (m)) {
                                m.parent = first;
                                m.Priority = f (m);
                                heap2.Enqueue (m, m.Priority);
                                acc(m);
                            } else {
                                if (gVal > currentG) {
                                    m.parent = first;
                                    m.Priority = f (m);
                                    heap2.UpdatePriority (m, m.Priority);
                                    acc(m);
                                }
                            }
                        }
                    }
                }
                // Creates the result list
                Node e = end;
                List<Node> points = new List<Node> ();
                while (e != null) {
                    points.Add (e);
                    e = e.parent;
                }
                points.Reverse ();

                // If we didn't find a path
                if (points.Count == 1)
                    points.Clear ();
                return points;
            } catch (System.Exception e) {
                Debug.Log (e.Message);
                Debug.Log (e.StackTrace);
                Debug.Log ("ERROR 2");
                return null;
            }
        }
コード例 #11
0
		public static List<FS2JournalItem> OnGetFilteredArchive(ArchiveFilter archiveFilter, bool isReport)
		{
			var result = new List<FS2JournalItem>();
			try
			{
				string dateInQuery = "DeviceTime";
				if (archiveFilter.UseSystemDate)
					dateInQuery = "SystemTime";

				var query =
					"SELECT * FROM Journal WHERE " +
					"\n " + dateInQuery + " > '" + archiveFilter.StartDate.ToString("yyyy-MM-dd HH:mm:ss") + "'" +
					"\n AND " + dateInQuery + " < '" + archiveFilter.EndDate.ToString("yyyy-MM-dd HH:mm:ss") + "'";

				if (archiveFilter.Descriptions.Count > 0)
				{
					query += "\n AND (";
					for (int i = 0; i < archiveFilter.Descriptions.Count; i++)
					{
						if (i > 0)
							query += "\n OR ";
						var description = archiveFilter.Descriptions[i];
						description = description.Replace("'", "''");
						query += " Description = '" + description + "'";
					}
					query += ")";
				}

				if (archiveFilter.Subsystems.Count > 0)
				{
					query += "\n AND (";
					for (int i = 0; i < archiveFilter.Subsystems.Count; i++)
					{
						if (i > 0)
							query += "\n OR ";
						var subsystem = archiveFilter.Subsystems[i];
						query += " SubSystemType = '" + ((int)subsystem).ToString() + "'";
					}
					query += ")";
				}

				if (archiveFilter.PanelUIDs.Count > 0)
				{
					query += "\n AND (";
					for (int i = 0; i < archiveFilter.PanelUIDs.Count; i++)
					{
						var panelUID = archiveFilter.PanelUIDs[i];
						if (panelUID != null)
						{
							if (i > 0)
								query += "\n OR ";
							query += " PanelUID = '" + panelUID + "'";
						}
					}
					query += ")";
				}

				query += "\n ORDER BY " + dateInQuery + " DESC";

				using (var sqlCeConnection = new SqlCeConnection(ConnectionString))
				{
					sqlCeConnection.ConnectionString = ConnectionString;
					var journalItems = new List<FS2JournalItem>();
					var sqlCeCommand = new SqlCeCommand(query, sqlCeConnection);
					sqlCeConnection.Open();
					var reader = sqlCeCommand.ExecuteReader();
					while (reader.Read())
					{
						if (IsAbort && !isReport)
							break;
						try
						{
							var journalItem = ReadOneJournalItem(reader);
							result.Add(journalItem);
							if (!isReport)
							{
								journalItems.Add(journalItem);
								if (journalItems.Count > 100)
								{
									if (ArchivePortionReady != null)
										ArchivePortionReady(journalItems.ToList());

									journalItems.Clear();
								}
							}
						}
						catch (Exception e)
						{
							Logger.Error(e, "DatabaseHelper.OnGetFilteredArchive");
						}
					}
					if (!isReport)
					{
						if (ArchivePortionReady != null)
							ArchivePortionReady(journalItems.ToList());
					}

					sqlCeConnection.Close();
				}
			}
			catch (Exception e)
			{
				Logger.Error(e, "Исключение при вызове FiresecService.GetFilteredArchive");
				throw new FS2Exception(e.Message);
			}
			return result;
		}
コード例 #12
0
ファイル: AStar.cs プロジェクト: muntac/unitytool
        public List<Node> Compute(int startX, int startY, int endX, int endY, Cell[][] matrix, bool improve)
        {
            List<Node> opened = new List<Node> ();
            Priority_Queue.IPriorityQueue<Node> heap2 = new Priority_Queue.HeapPriorityQueue<Node> (600);

            List<Node> closed = new List<Node> ();

            // Initialize our version of the matrix (can we skip this?)
            Node[][] newMatrix = new Node[matrix.Length][];
            for (int x = 0; x < matrix.Length; x++) {
                newMatrix [x] = new Node[matrix [x].Length];
                for (int y = 0; y < matrix[x].Length; y++) {
                    newMatrix [x] [y] = new Node ();
                    newMatrix [x] [y].parent = null;
                    newMatrix [x] [y].cell = matrix [x] [y];
                    newMatrix [x] [y].x = x;
                    newMatrix [x] [y].y = y;
                }
            }

            // Do the work for the first cell before firing the algorithm
            start = newMatrix [startX] [startY];
            end = newMatrix [endX] [endY];

            closed.Add (start);

            foreach (Node c in getAdjacent(start, newMatrix)) {
                c.parent = start;
                if (improve)
                    heap2.Enqueue (c, f (c));
                else
                    opened.Add (c);
            }

            while ((improve && heap2.Count > 0) || (!improve && opened.Count > 0)) {

                // Pick the closest to the goal
                Node minF = null;
                if (improve) {
                    minF = heap2.Dequeue ();
                } else {
                    for (int i = 0; i < opened.Count; i++) {
                        if (minF == null || f (minF) > f (opened [i]))
                            minF = opened [i];
                    }
                    opened.Remove (minF);
                }

                closed.Add (minF);

                // Found it
                if (minF == end)
                    break;

                foreach (Node adj in getAdjacent(minF, newMatrix)) {

                    float soFar = g (minF) + h (adj, minF);

                    // Create the links between cells (picks the best path)
                    if (closed.Contains (adj)) {
                        if (g (adj) > soFar) {
                            adj.parent = minF;
                        }
                    } else {
                        if ((improve && heap2.Contains (adj)) || (!improve && opened.Contains (adj))) {
                            if (g (adj) > soFar) {
                                adj.parent = minF;
                            }
                        } else {
                            adj.parent = minF;
                            if (improve)
                                heap2.Enqueue (adj, f (adj));
                            else
                                opened.Add (adj);
                        }
                    }
                }
            }

            // Creates the result list
            Node n = end;
            List<Node> points = new List<Node> ();
            while (n != null) {
                points.Add (n);
                n = n.parent;
            }
            points.Reverse ();

            // If we didn't find a path
            if (points.Count == 1)
                points.Clear ();
            return points;
        }
コード例 #13
0
ファイル: AIManager.cs プロジェクト: tommai78101/Multiplier
        //Actual update tick
        public void Tick()
        {
            if (this.unitCount <= 0) {
                //Defeat. No more AI units on the map.
                Debug.Log("AI Player is defeated.");
                this.hasLostTheGame = true;
                this.startAIFlag = false;
                return;
            }
            switch (this.currentFiniteState) {
                case FSMState.Wait:
                    if (this.selectedUnits.Count > 0) {
                        this.selectedUnits.Clear();
                    }

                    if (this.unitCount == 1) {
                        //Usually at the start of the game, or when the AI player is on the brink of defeat.
                        Transform child = this.unitContainer.transform.GetChild(this.unitContainer.transform.childCount - 1);
                        AIUnit unit = child.GetComponent<AIUnit>();
                        AILineOfSight lineOfSight = child.GetComponentInChildren<AILineOfSight>();
                        AIAttackRange attackRange = child.GetComponentInChildren<AIAttackRange>();

                        //TODO: Refer to an attribute manager for AI units on what attributes are required.
                        unit.teamFaction = this.teamFaction;
                        lineOfSight.teamFaction = this.teamFaction;
                        attackRange.teamFaction = this.teamFaction;

                        //Always select the unit before doing other AI state machines.
                        this.spawnList.Add(unit);
                        this.currentFiniteState = FSMState.Split;
                        break;
                    }

                    int scoutUnitCount = 0;
                    int splitUnitCount = 0;
                    int mergeUnitCount = 0;

                    foreach (Transform child in this.unitContainer.transform) {
                        if (splitUnitCount > 0) {
                            splitPercentage = splitRatio / splitUnitCount;
                        }
                        else {
                            splitPercentage = splitRatio / 1f;
                        }

                        if (mergeUnitCount > 0) {
                            mergePercentage = mergeRatio / mergeUnitCount;
                        }
                        else {
                            mergePercentage = mergeRatio / 1f;
                        }

                        if (scoutUnitCount > 0) {
                            scoutPercentage = scoutRatio / scoutUnitCount;
                        }
                        else {
                            scoutPercentage = scoutRatio / 1f;
                        }

                        if (this.splitPercentage > this.mergePercentage && this.splitPercentage > this.scoutPercentage) {
                            this.spawnList.Add(child.GetComponent<AIUnit>());
                            splitUnitCount++;
                        }
                        else if (this.splitPercentage > this.mergePercentage && this.splitPercentage < this.scoutPercentage) {
                            this.selectedUnits.Add(child.GetComponent<AIUnit>());
                            scoutUnitCount++;
                        }
                        else if (this.splitPercentage < this.mergePercentage && this.splitPercentage > this.scoutPercentage) {
                            this.mergeList.Add(child.GetComponent<AIUnit>());
                            mergeUnitCount++;
                        }
                        else if (this.splitPercentage < this.mergePercentage && this.splitPercentage < this.scoutPercentage) {
                            if (this.mergePercentage > this.scoutPercentage) {
                                this.mergeList.Add(child.GetComponent<AIUnit>());
                                mergeUnitCount++;
                            }
                            else {
                                this.selectedUnits.Add(child.GetComponent<AIUnit>());
                                scoutUnitCount++;
                            }
                        }
                    }
                    this.currentFiniteState = FSMState.Merge;
                    break;
                case FSMState.Split:
                    if (this.spawnList.Count > 0) {
                        foreach (AIUnit unit in this.spawnList) {
                            if (unit != null && unit.currentState != State.Split) {
                                if (this.unitCount < this.maxUnitCount) {
                                    GameObject splitObject = SplitUnit(unit);
                                    if (splitObject != null) {
                                        this.splitGroupList.Add(new SplitGroup(unit.gameObject, splitObject));
                                    }
                                }
                                else {
                                    break;
                                }
                            }
                        }
                        this.spawnList.Clear();
                    }
                    this.currentFiniteState = FSMState.Wait;
                    break;
                case FSMState.Scout:
                    Debug.Log("AI player is ready to scout.");
                    if (this.selectedUnits.Count > 0) {
                        for (int i = 0; i < this.selectedUnits.Count; i++) {
                            if (this.selectedUnits[i] != null) {
                                this.selectedUnits[i].SetScoutFlag();
                            }
                            else {
                                this.selectedUnits.RemoveAt(i);
                            }
                        }
                        this.selectedUnits.Clear();
                    }
                    if (this.spawnList.Count > 0) {
                        this.currentFiniteState = FSMState.Split;
                    }
                    else {
                        this.currentFiniteState = FSMState.Wait;
                    }
                    break;
                case FSMState.Merge:
                    if (this.mergeList.Count > 0) {
                        if (this.mergeList.Count > 1) {
                            AIUnit owner = null;
                            AIUnit merge = null;
                            List<AIUnit> removeList = new List<AIUnit>();
                            for (int i = 0; i < this.mergeList.Count - 1; i++) {
                                if (this.mergeList[i] != null && !removeList.Contains(this.mergeList[i])) {
                                    owner = this.mergeList[i];
                                    if (owner.CheckMergeFlag()) {
                                        for (int j = i + 1; j < this.mergeList.Count; j++) {
                                            merge = this.mergeList[j];
                                            if (merge != null && !removeList.Contains(merge) && !owner.Equals(merge) && owner.level == merge.level) {
                                                //TODO: Once unit attribute manager is implemented for the AI player, change the 2f to the actual scaling factor.
                                                if (merge.CheckMergeFlag()) {
                                                    owner.SetMergeFlag();
                                                    merge.SetMergeFlag();
                                                    this.mergeGroupList.Add(new MergeGroup(owner.gameObject, merge.gameObject, 1.5f));  //ScaleFactor is done here.
                                                    removeList.Add(owner);
                                                    removeList.Add(merge);
                                                    break;
                                                }
                                                else {
                                                    continue;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            removeList.Clear();
                        }
                        this.mergeList.Clear();
                    }
                    this.currentFiniteState = FSMState.Scout;
                    break;
            }

            foreach (Transform child in this.unitContainer.transform) {
                if (child != null) {
                    AIUnit unit = child.GetComponent<AIUnit>();
                    if (unit != null) {
                        unit.Tick();
                    }
                }
            }
        }
コード例 #14
0
        public override void Run()
        {
            #region Create renderers

            // Note: the renderers take care of creating their own
            // device resources and listen for DeviceManager.OnInitialize

            #region Initialize MeshRenderer instances

            // Create and initialize the mesh renderer
            var loadedMesh = Common.Mesh.LoadFromFile("Scene.cmo");
            List<MeshRenderer> meshes = new List<MeshRenderer>();
            meshes.AddRange((from mesh in loadedMesh
                             select ToDispose(new MeshRenderer(mesh))));

            // We will support a cubemap for each mesh that contains "reflector" in its name
            List<DynamicCubeMap> envMaps = new List<DynamicCubeMap>();

            // We will rotate any meshes that contains "rotate" in its name
            List<MeshRenderer> rotateMeshes = new List<MeshRenderer>();

            // We will generate meshRows * meshColumns of any mesh that contains "replicate" in its name
            int meshRows = 10;
            int meshColumns = 10;

            // Define an action to initialize our meshes so that we can
            // dynamically change the number of reflective surfaces and
            // replicated meshes
            Action createMeshes = () =>
            {
                // Clear context states, ensures we don't have
                // any of the resources we are going to release
                // assigned to the pipeline.
                DeviceManager.Direct3DContext.ClearState();
                if (contextList != null)
                {
                    foreach (var context in contextList)
                        context.ClearState();
                }

                // Remove meshes
                foreach (var mesh in meshes)
                    mesh.Dispose();
                meshes.Clear();

                // Remove environment maps
                foreach (var envMap in envMaps)
                    envMap.Dispose();
                envMaps.Clear();

                // Create non-replicated MeshRenderer instances
                meshes.AddRange(from mesh in loadedMesh
                                where !((mesh.Name ?? "").ToLower().Contains("replicate"))
                                 select ToDispose(new MeshRenderer(mesh)));

                #region Create replicated meshes
                // Add the same mesh multiple times, separate by the combined extent
                var replicatedMeshes = (from mesh in loadedMesh
                                        where (mesh.Name ?? "").ToLower().Contains("replicate")
                                        select mesh).ToArray();
                if (replicatedMeshes.Length > 0)
                {
                    var minExtent = (from mesh in replicatedMeshes
                                     orderby new { mesh.Extent.Min.X, mesh.Extent.Min.Z }
                                     select mesh.Extent).First();
                    var maxExtent = (from mesh in replicatedMeshes
                                     orderby new { mesh.Extent.Max.X, mesh.Extent.Max.Z } descending
                                     select mesh.Extent).First();
                    var extentDiff = (maxExtent.Max - minExtent.Min);

                    for (int x = -(meshColumns / 2); x < (meshColumns / 2); x++)
                    {
                        for (int z = -(meshRows / 2); z < (meshRows / 2); z++)
                        {
                            var meshGroup = (from mesh in replicatedMeshes
                                             where (mesh.Name ?? "").ToLower().Contains("replicate")
                                             select ToDispose(new MeshRenderer(mesh))).ToList();

                            // Reposition based on width/depth of combined extent
                            foreach (var m in meshGroup)
                            {
                                m.World.TranslationVector = new Vector3(m.Mesh.Extent.Center.X + extentDiff.X * x, m.Mesh.Extent.Min.Y, m.Mesh.Extent.Center.Z + extentDiff.Z * z);
                            }

                            meshes.AddRange(meshGroup);
                        }
                    }
                }
                #endregion

                #region Create reflective meshes
                // Create reflections where necessary and add rotation meshes
                int reflectorCount = 0;
                meshes.ForEach(m =>
                {
                    var name = (m.Mesh.Name ?? "").ToLower();
                    if (name.Contains("reflector") && reflectorCount < maxReflectors)
                    {
                        reflectorCount++;
                        var envMap = ToDispose(new DynamicCubeMap(512));
                        envMap.Reflector = m;
                        envMap.Initialize(this);
                        m.EnvironmentMap = envMap;
                        envMaps.Add(envMap);
                    }
                    if (name.Contains("rotate"))
                    {
                        rotateMeshes.Add(m);
                    }

                    m.Initialize(this);
                });
                #endregion

                // Initialize each mesh
                meshes.ForEach(m => m.Initialize(this));
            };
            createMeshes();

            // Set the first animation as the current animation and start clock
            meshes.ForEach(m =>
            {
                if (m.Mesh.Animations != null && m.Mesh.Animations.Any())
                    m.CurrentAnimation = m.Mesh.Animations.First().Value;
                m.Clock.Start();
            });

            // Create the overall mesh World matrix
            var meshWorld = Matrix.Identity;

            #endregion

            // Create an axis-grid renderer
            var axisGrid = ToDispose(new AxisGridRenderer());
            axisGrid.Initialize(this);

            // Create and initialize a Direct2D FPS text renderer
            var fps = ToDispose(new Common.FpsRenderer("Calibri", Color.CornflowerBlue, new Point(8, 8), 16));
            fps.Initialize(this);

            // Create and initialize a general purpose Direct2D text renderer
            // This will display some instructions and the current view and rotation offsets
            var textRenderer = ToDispose(new Common.TextRenderer("Calibri", Color.CornflowerBlue, new Point(8, 40), 12));
            textRenderer.Initialize(this);

            #endregion

            // Initialize the world matrix
            var worldMatrix = Matrix.Identity;

            // Set the camera position
            var cameraPosition = new Vector3(0, 1, 2);
            var cameraTarget = Vector3.Zero; // Looking at the origin 0,0,0
            var cameraUp = Vector3.UnitY; // Y+ is Up

            // Prepare matrices
            // Create the view matrix from our camera position, look target and up direction
            var viewMatrix = Matrix.LookAtRH(cameraPosition, cameraTarget, cameraUp);
            viewMatrix.TranslationVector += new Vector3(0, -0.98f, 0);

            // Create the projection matrix
            /* FoV 60degrees = Pi/3 radians */
            // Aspect ratio (based on window size), Near clip, Far clip
            var projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f);

            // Maintain the correct aspect ratio on resize
            Window.Resize += (s, e) =>
            {
                projectionMatrix = Matrix.PerspectiveFovRH((float)Math.PI / 3f, Width / (float)Height, 0.1f, 100f);
            };

            #region Rotation and window event handlers

            // Create a rotation vector to keep track of the rotation
            // around each of the axes
            var rotation = new Vector3(0.0f, 0.0f, 0.0f);

            // We will call this action to update text
            // for the text renderer
            Action updateText = () =>
            {
                textRenderer.Text =
                    String.Format(
                    "\nPause rotation: P"
                    + "\nThreads: {0} (+/-)"
                    + "\nReflectors: {1} (Shift-Up/Down)"
                    + "\nCPU load: {2} matrix ops (Shift +/-)"
                    + "\nRotating meshes: {3} (Up/Down, Left/Right)"
                    + "\n(G) Build in GS (single pass): {4}"
                    ,
                        threadCount,
                        maxReflectors,
                        additionalCPULoad,
                        meshRows * meshColumns,
                        buildCubeMapGeometryInstancing);
            };

            Dictionary<Keys, bool> keyToggles = new Dictionary<Keys, bool>();
            keyToggles[Keys.Z] = false;
            keyToggles[Keys.F] = false;

            // Support keyboard/mouse input to rotate or move camera view
            var moveFactor = 0.02f; // how much to change on each keypress
            var shiftKey = false;
            var ctrlKey = false;
            var background = Color.White;
            Window.KeyDown += (s, e) =>
            {
                var context = DeviceManager.Direct3DContext;

                shiftKey = e.Shift;
                ctrlKey = e.Control;

                switch (e.KeyCode)
                {
                    // WASD -> pans view
                    case Keys.A:
                        viewMatrix.TranslationVector += new Vector3(moveFactor * 2, 0f, 0f);
                        break;
                    case Keys.D:
                        viewMatrix.TranslationVector -= new Vector3(moveFactor * 2, 0f, 0f);
                        break;
                    case Keys.S:
                        if (shiftKey)
                            viewMatrix.TranslationVector += new Vector3(0f, moveFactor * 2, 0f);
                        else
                            viewMatrix.TranslationVector -= new Vector3(0f, 0f, 1) * moveFactor * 2;
                        break;
                    case Keys.W:
                        if (shiftKey)
                            viewMatrix.TranslationVector -= new Vector3(0f, moveFactor * 2, 0f);
                        else
                            viewMatrix.TranslationVector += new Vector3(0f, 0f, 1) * moveFactor * 2;
                        break;
                    // Up/Down and Left/Right - rotates around X / Y respectively
                    // (Mouse wheel rotates around Z)
                    //case Keys.Down:
                    //    worldMatrix *= Matrix.RotationX(moveFactor);
                    //    rotation += new Vector3(moveFactor, 0f, 0f);
                    //    break;
                    //case Keys.Up:
                    //    worldMatrix *= Matrix.RotationX(-moveFactor);
                    //    rotation -= new Vector3(moveFactor, 0f, 0f);
                    //    break;
                    //case Keys.Left:
                    //    worldMatrix *= Matrix.RotationY(moveFactor);
                    //    rotation += new Vector3(0f, moveFactor, 0f);
                    //    break;
                    //case Keys.Right:
                    //    worldMatrix *= Matrix.RotationY(-moveFactor);
                    //    rotation -= new Vector3(0f, moveFactor, 0f);
                    //    break;
                    case Keys.T:
                        fps.Show = !fps.Show;
                        textRenderer.Show = !textRenderer.Show;
                        break;
                    case Keys.B:
                        if (background == Color.White)
                        {
                            background = new Color(30, 30, 34);
                        }
                        else
                        {
                            background = Color.White;
                        }
                        break;
                    case Keys.G:
                        axisGrid.Show = !axisGrid.Show;
                        break;
                    case Keys.P:
                        // Pause or resume mesh animation
                        meshes.ForEach(m => {
                            if (m.Clock.IsRunning)
                                m.Clock.Stop();
                            else
                                m.Clock.Start();
                        });
                        break;
                    case Keys.X:
                        // To test for correct resource recreation
                        // Simulate device reset or lost.
                        System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                        DeviceManager.Initialize(DeviceManager.Dpi);
                        System.Diagnostics.Debug.WriteLine(SharpDX.Diagnostics.ObjectTracker.ReportActiveObjects());
                        break;
                    //case Keys.Z:
                    //    keyToggles[Keys.Z] = !keyToggles[Keys.Z];
                    //    if (keyToggles[Keys.Z])
                    //    {
                    //        context.PixelShader.Set(depthPixelShader);
                    //    }
                    //    else
                    //    {
                    //        context.PixelShader.Set(pixelShader);
                    //    }
                    //    break;
                    case Keys.F:
                        keyToggles[Keys.F] = !keyToggles[Keys.F];
                        RasterizerStateDescription rasterDesc;
                        if (context.Rasterizer.State != null)
                            rasterDesc = context.Rasterizer.State.Description;
                        else
                            rasterDesc = new RasterizerStateDescription()
                            {
                                CullMode = CullMode.Back,
                                FillMode = FillMode.Solid
                            };
                        if (keyToggles[Keys.F])
                        {
                            rasterDesc.FillMode = FillMode.Wireframe;
                            rasterizerState = ToDispose(new RasterizerState(context.Device, rasterDesc));
                        }
                        else
                        {
                            rasterDesc.FillMode = FillMode.Solid;
                            rasterizerState = ToDispose(new RasterizerState(context.Device, rasterDesc));
                        }
                        break;
                    //case Keys.D1:
                    //    context.PixelShader.Set(pixelShader);
                    //    break;
                    //case Keys.D2:
                    //    context.PixelShader.Set(lambertShader);
                    //    break;
                    //case Keys.D3:
                    //    context.PixelShader.Set(phongShader);
                    //    break;
                    //case Keys.D4:
                    //    context.PixelShader.Set(blinnPhongShader);
                    //    break;
                    //case Keys.D5:
                    //    context.PixelShader.Set(simpleUVShader);
                    //    break;
                    //case Keys.D6:
                    //    context.PixelShader.Set(lambertUVShader);
                    //    break;
                    //case Keys.D7:
                    //    context.PixelShader.Set(phongUVShader);
                    //    break;
                    //case Keys.D8:
                    //    context.PixelShader.Set(blinnPhongUVShader);
                    //    break;
                }

                updateText();
            };
            Window.KeyUp += (s, e) =>
            {
                // Clear the shift/ctrl keys so they aren't sticky
                if (e.KeyCode == Keys.ShiftKey)
                    shiftKey = false;
                if (e.KeyCode == Keys.ControlKey)
                    ctrlKey = false;
            };
            Window.MouseWheel += (s, e) =>
            {
                if (shiftKey)
                {
                    // Zoom in/out
                    viewMatrix.TranslationVector += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor * 2);
                }
                else
                {
                    // rotate around Z-axis
                    viewMatrix *= Matrix.RotationZ((e.Delta / 120f) * moveFactor);
                    rotation += new Vector3(0f, 0f, (e.Delta / 120f) * moveFactor);
                }
                updateText();
            };

            var lastX = 0;
            var lastY = 0;

            Window.MouseDown += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    lastX = e.X;
                    lastY = e.Y;
                }
            };

            Window.MouseMove += (s, e) =>
            {
                if (e.Button == MouseButtons.Left)
                {
                    var yRotate = lastX - e.X;
                    var xRotate = lastY - e.Y;
                    lastY = e.Y;
                    lastX = e.X;

                    // Mouse move changes
                    viewMatrix *= Matrix.RotationX(-xRotate * moveFactor);
                    viewMatrix *= Matrix.RotationY(-yRotate * moveFactor);

                    updateText();
                }
            };

            // Display instructions with initial values
            updateText();

            #endregion

            var clock = new System.Diagnostics.Stopwatch();
            clock.Start();

            // Setup the deferred contexts
            SetupContextList();

            #region Render loop

            // Whether or not to reinitialize meshes
            bool initializeMesh = false;

            // Define additional key handlers for controlling the
            // number of threads, reflectors, and replicated meshes
            #region Dynamic Cube map and threading KeyDown handlers
            Window.KeyDown += (s, e) =>
            {
                switch (e.KeyCode)
                {
                    case Keys.Up:
                        if (shiftKey)
                        {
                            maxReflectors++;
                        }
                        else
                        {
                            meshRows += 2;
                        }
                        initializeMesh = true;
                        break;
                    case Keys.Down:
                        if (shiftKey)
                        {
                            maxReflectors = Math.Max(0, maxReflectors-1);
                        }
                        else
                        {
                            meshRows = Math.Max(2, meshRows - 2);
                        }
                        initializeMesh = true;
                        break;
                    case Keys.Right:
                        meshColumns += 2;
                        initializeMesh = true;
                        break;
                    case Keys.Left:
                        meshColumns = Math.Max(2, meshColumns - 2);
                        initializeMesh = true;
                        break;
                    case Keys.Add:
                        if (shiftKey)
                        {
                            additionalCPULoad += 100;
                        }
                        else
                        {
                            threadCount++;
                        }
                        break;
                    case Keys.Subtract:
                        if (shiftKey)
                        {
                            additionalCPULoad = Math.Max(0, additionalCPULoad - 100);
                        }
                        else
                        {
                            threadCount = Math.Max(1, threadCount - 1);
                        }
                        break;
                    case Keys.G:
                        buildCubeMapGeometryInstancing = !buildCubeMapGeometryInstancing;
                        break;
                    default:
                        break;
                }
                updateText();
            };
            #endregion

            #region Render mesh group
            // Action for rendering a group of meshes for a
            // context (based on number of available contexts)
            Action<int, DeviceContext, Matrix, Matrix> renderMeshGroup = (contextIndex, renderContext, view, projection) =>
            {
                var viewProjection = view * projection;

                // Determine the meshes to render for this context
                int batchSize = (int)Math.Floor((double)meshes.Count / contextList.Length);
                int startIndex = batchSize * contextIndex;
                int endIndex = Math.Min(startIndex + batchSize, meshes.Count - 1);
                // If this is the last context include whatever remains to be
                // rendered due to the rounding above.
                if (contextIndex == contextList.Length - 1)
                    endIndex = meshes.Count - 1;

                // Loop over the meshes for this context and render them
                var perObject = new ConstantBuffers.PerObject();
                for (var i = startIndex; i <= endIndex; i++)
                {
                    // Simulate additional CPU load
                    for (var j = 0; j < additionalCPULoad; j++)
                    {
                        viewProjection = Matrix.Multiply(view, projection);
                    }

                    // Retrieve current mesh
                    var m = meshes[i];

                    // Check if this is a rotating mesh
                    if (rotateMeshes.Contains(m))
                    {
                        var rotate = Matrix.RotationAxis(Vector3.UnitY, m.Clock.ElapsedMilliseconds / 1000.0f);
                        perObject.World = m.World * rotate * worldMatrix;
                    }
                    else
                    {
                        perObject.World = m.World * worldMatrix;
                    }

                    // Update perObject constant buffer
                    perObject.WorldInverseTranspose = Matrix.Transpose(Matrix.Invert(perObject.World));
                    perObject.WorldViewProjection = perObject.World * viewProjection;
                    perObject.Transpose();
                    renderContext.UpdateSubresource(ref perObject, perObjectBuffer);

                    // Provide the material and armature constant buffer to the mesh renderer
                    m.PerArmatureBuffer = perArmatureBuffer;
                    m.PerMaterialBuffer = perMaterialBuffer;

                    // Render the mesh using the provided DeviceContext
                    m.Render(renderContext);
                }
            };

            #endregion

            #region Render scene

            // Action for rendering the entire scene
            Action<DeviceContext, Matrix, Matrix, RenderTargetView, DepthStencilView, DynamicCubeMap> renderScene = (context, view, projection, rtv, dsv, envMap) =>
            {
                // We must initialize the context every time we render
                // the scene as we are changing the state depending on
                // whether we are rendering the envmaps or final scene
                InitializeContext(context, false);

                // We always need the immediate context
                // Note: the passed in context will normally be the immediate context
                // however it is possible to run this method threaded also.
                var immediateContext = this.DeviceManager.Direct3DDevice.ImmediateContext;

                // Clear depth stencil view
                context.ClearDepthStencilView(dsv, DepthStencilClearFlags.Depth | DepthStencilClearFlags.Stencil, 1.0f, 0);
                // Clear render target view
                context.ClearRenderTargetView(rtv, background);

                // Create viewProjection matrix
                var viewProjection = Matrix.Multiply(view, projection);

                // Extract camera position from view
                var camPosition = Matrix.Transpose(Matrix.Invert(view)).Column4;
                cameraPosition = new Vector3(camPosition.X, camPosition.Y, camPosition.Z);

                // Setup the per frame constant buffer
                var perFrame = new ConstantBuffers.PerFrame();
                perFrame.Light.Color = new Color(0.9f, 0.9f, 0.9f, 1.0f);
                var lightDir = Vector3.Transform(new Vector3(-1f, -1f, -1f), worldMatrix);
                perFrame.Light.Direction = new Vector3(lightDir.X, lightDir.Y, lightDir.Z);
                perFrame.CameraPosition = cameraPosition;
                context.UpdateSubresource(ref perFrame, perFrameBuffer);

                // Render each object

                // Prepare the default per material constant buffer
                var perMaterial = new ConstantBuffers.PerMaterial();
                perMaterial.Ambient = new Color4(0.2f);
                perMaterial.Diffuse = Color.White;
                perMaterial.Emissive = new Color4(0);
                perMaterial.Specular = Color.White;
                perMaterial.SpecularPower = 20f;
                context.UpdateSubresource(ref perMaterial, perMaterialBuffer);

                // ----------Render meshes------------

                if (contextList.Length == 1)
                {
                    // If there is only one context available there is no need to
                    // generate command lists and execute them so just render the
                    // mesh directly on the current context (which may or may
                    // not be an immediate context depending on the caller).
                    renderMeshGroup(0, context, view, projection);
                }
                else
                {
                    // There are multiple contexts therefore
                    // we are using deferred contexts. Prepare a
                    // separate thread for each available context
                    // and render a group of meshes on each.
                    Task[] renderTasks = new Task[contextList.Length];
                    CommandList[] commands = new CommandList[contextList.Length];
                    var viewports = context.Rasterizer.GetViewports();

                    for (var i = 0; i < contextList.Length; i++)
                    {
                        // Must store the iteration value in another variable
                        // or each task action will use the last iteration value.
                        var contextIndex = i;

                        // Create task to run on new thread from ThreadPool
                        renderTasks[i] = Task.Run(() =>
                        {
                            // Retrieve context for this thread
                            var renderContext = contextList[contextIndex];
                            // Initialize the context state
                            InitializeContext(renderContext, false);

                            // Set the render targets and viewport
                            renderContext.OutputMerger.SetRenderTargets(dsv, rtv);
                            renderContext.Rasterizer.SetViewports(viewports);

                            // If we are rendering for a cubemap we must set the
                            // per environment map buffer.
                            if (envMap != null)
                                renderContext.GeometryShader.SetConstantBuffer(4, envMap.PerEnvMapBuffer);

                            // Render logic
                            renderMeshGroup(contextIndex, renderContext, view, projection);

                            // Create the command list
                            if (renderContext.TypeInfo == DeviceContextType.Deferred)
                                commands[contextIndex] = renderContext.FinishCommandList(false);
                        });
                    }
                    // Wait for all the tasks to complete
                    Task.WaitAll(renderTasks);

                    // Replay the command lists on the immediate context
                    for (var i = 0; i < contextList.Length; i++)
                    {
                        if (contextList[i].TypeInfo == DeviceContextType.Deferred && commands[i] != null)
                        {
                            immediateContext.ExecuteCommandList(commands[i], false);
                            // Clean up command list
                            commands[i].Dispose();
                            commands[i] = null;
                        }
                    }
                }
            };

            #endregion

            long frameCount = 0;
            int lastThreadCount = threadCount;

            // Create and run the render loop
            RenderLoop.Run(Window, () =>
            {
                // Allow dynamic changes to number of reflectors and replications
                if (initializeMesh)
                {
                    initializeMesh = false;
                    createMeshes();
                }

                // Allow dynamic chnages to the number of threads to use
                if (lastThreadCount != threadCount)
                {
                    SetupContextList();
                    lastThreadCount = threadCount;
                }

                // Start of frame:
                frameCount++;

                // Retrieve immediate context
                var context = DeviceManager.Direct3DContext;

                //if (frameCount % 3 == 1) // to update cubemap once every third frame
                //{
                #region Update environment maps

                // Update each of the cubemaps
                if (buildCubeMapGeometryInstancing)
                {
                    activeVertexShader = envMapVSShader;
                    activeGeometryShader = envMapGSShader;
                    activePixelShader = envMapPSShader;
                }
                else
                {
                    activeVertexShader = vertexShader;
                    activeGeometryShader = null;
                    activePixelShader = blinnPhongShader;
                }

                // Render the scene from the perspective of each of the environment maps
                foreach (var envMap in envMaps)
                {
                    var mesh = envMap.Reflector as MeshRenderer;
                    if (mesh != null)
                    {
                        // Calculate view point for reflector
                        var meshCenter = Vector3.Transform(mesh.Mesh.Extent.Center, mesh.World * worldMatrix);
                        envMap.SetViewPoint(new Vector3(meshCenter.X, meshCenter.Y, meshCenter.Z));
                        if (buildCubeMapGeometryInstancing)
                        {
                            // Render cubemap in single full render pass using
                            // geometry shader instancing.
                            envMap.UpdateSinglePass(context, renderScene);
                        }
                        else
                        {
                            // Render cubemap in 6 full render passes
                            envMap.Update(context, renderScene);
                        }
                    }
                }

                #endregion
                //}

                #region Render final scene
                // Reset the vertex, geometry and pixel shader
                activeVertexShader = vertexShader;
                activeGeometryShader = null;
                activePixelShader = blinnPhongShader;
                // Initialize context (also resetting the render targets)
                InitializeContext(context, true);

                // Render the final scene
                renderScene(context, viewMatrix, projectionMatrix, RenderTargetView, DepthStencilView, null);
                #endregion

                // Render FPS
                fps.Render();

                // Render instructions + position changes
                textRenderer.Render();

                // Present the frame
                Present();
            });
            #endregion
        }
コード例 #15
0
        string ResumeUploadInChunks(string path, Ticket t, int chunk_size, int max_chunks, bool firstTime)
        {
            const int maxFailedAttempts = 5;

            if (!firstTime)
            {
                // Check the ticket
                Debug.WriteLine("ResumeUploadInChunks(" + path + ") Checking ticket...", "VimeoClient");
                var ticket = vimeo_videos_upload_checkTicket(t.id);
                if (ticket == null || ticket.id != t.id)
                {
                    Debug.WriteLine("Error in checking ticket. aborting.", "VimeoClient");
                    return null;
                }
                t = ticket;
            }

            //Load the file, calculate the number of chunks
            var file = new FileInfo(path);
            int chunksCount = GetChunksCount(file.Length, chunk_size);
            Debug.WriteLine("Will upload in " + chunksCount + " chunks", "VimeoClient");

            //Queue chunks for upload
            List<int> missingChunks = new List<int>(chunksCount);
            for (int i = 0; i < chunksCount; i++) missingChunks.Add(i);
            
            int failedAttempts = 0;
            int counter = 0;
            while (failedAttempts <= maxFailedAttempts)
            {
                if (firstTime)
                {
                    firstTime = false;
                }
                else
                {
                    //Verify and remove the successfully uploaded chunks
                    Debug.WriteLine("Verifying chunks...", "VimeoClient");
                    var verify = vimeo_videos_upload_verifyChunks(t.id);
                    Debug.WriteLine(verify.Items.Count.ToString() + "/" + chunksCount + " chunks uploaded successfully.", "VimeoClient");

                    missingChunks.Clear();
                    for (int i = 0; i < chunksCount; i++) missingChunks.Add(i);
                    foreach (var item in verify.Items)
                    {
                        if (missingChunks.Contains(item.id) && item.size == GetChunkSize(file.Length, item.id, chunk_size))
                            missingChunks.Remove(item.id);
                    }
                }

                //If there are no chunks left or the limit is reached stop.
                if (missingChunks.Count == 0 || (max_chunks > 0 && counter >= max_chunks)) 
                    break;

                //Post chunks
                while (missingChunks.Count > 0)
                {
                    //If there are no chunks left or the limit is reached stop.
                    if (missingChunks.Count == 0 || (max_chunks > 0 && counter >= max_chunks)) 
                        break;

                    if (failedAttempts > maxFailedAttempts) break;

                    int chunkId = missingChunks[0];
                    missingChunks.RemoveAt(0);

                    Debug.WriteLine("Posting chunk " + chunkId + ". " + missingChunks.Count + " chunks left.", "VimeoClient");
                    try
                    {
                        counter++;
                        PostVideo(t, chunkId, path, chunk_size);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e, "VimeoClient");
                        failedAttempts++;
                    }
                }
            }

            if (missingChunks.Count == 0)
            {
                //All chunks are uploaded
                return vimeo_videos_upload_complete(file.Name, t.id);
            }

            if ((max_chunks > 0 && counter >= max_chunks))
            {
                //Max limit is reached
                return string.Empty;
            }

            //Error
            return null;
        }
コード例 #16
0
ファイル: Arcadia.cs プロジェクト: KirieZ/Tartarus
        internal static void LoadAuctionCategory()
        {
            AuctionCategoryResource = new Dictionary<int, DB_AuctionCategory[]>();

            using (DBManager dbManager = new DBManager(Databases.Game))
            {
                using (DbCommand dbCmd = dbManager.CreateCommand(0))
                {
                    try
                    {
                        dbManager.CreateInParameter(dbCmd, "localflag", System.Data.DbType.Int32, Settings.LocalFlag);
                        dbCmd.Connection.Open();

                        using (DbDataReader dbReader = dbCmd.ExecuteReader())
                        {
                            int category_id = -1;
                            List<DB_AuctionCategory> subItems = new List<DB_AuctionCategory>();

                            while (dbReader.Read())
                            {
                                if ((int)dbReader[0] != category_id && category_id != -1)
                                {
                                    if (!AuctionCategoryResource.ContainsKey(category_id))
                                        AuctionCategoryResource.Add(category_id, subItems.ToArray());
                                    else
                                        ConsoleUtils.ShowError("Duplicated Auction Category Resource with ID {0}. Skipping duplicated entry.", category_id);

                                    subItems.Clear();
                                }
                                category_id = (int)dbReader[0];
                                DB_AuctionCategory subCat = new DB_AuctionCategory
                                {
                                    sub_category_id = (int)dbReader[1],
                                    name_id = (int)dbReader[2],
                                    local_flag = (int)dbReader[3],
                                    item_group = (int)dbReader[4],
                                    item_class = (int)dbReader[5]
                                };
                                subItems.Add(subCat);
                            }

                            if (category_id != -1)
                            {
                                AuctionCategoryResource.Add(category_id, subItems.ToArray());
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ConsoleUtils.ShowSQL(ex.Message);
                        return;
                    }
                    finally { dbCmd.Connection.Close(); }
                }
            }

            ConsoleUtils.ShowNotice("{0} entries loaded from AuctionCategoryResource", AuctionCategoryResource.Count);
        }
コード例 #17
0
ファイル: Arcadia.cs プロジェクト: KirieZ/Tartarus
        internal static void LoadMarket()
        {
            MarketResource = new Dictionary<String, DB_Market[]>();

            using (DBManager dbManager = new DBManager(Databases.Game))
            {
                using (DbCommand dbCmd = dbManager.CreateCommand(10))
                {
                    try
                    {
                        dbCmd.Connection.Open();

                        using (DbDataReader dbReader = dbCmd.ExecuteReader())
                        {
                            string name = "";
                            List<DB_Market> market = new List<DB_Market>();

                            while (dbReader.Read())
                            {
                                if (name != (string)dbReader[1] && name != "")
                                {
                                    if (!MarketResource.ContainsKey(name))
                                        MarketResource.Add(name, market.ToArray());
                                    else
                                        ConsoleUtils.ShowError("Duplicated Market Name {0}. Skipping duplicated entry.", name);
                                    market.Clear();
                                }
                                name = (string)dbReader[1];

                                market.Add(
                                        new DB_Market
                                        {
                                            code = (int)dbReader[2],
                                            price_ratio = (decimal)dbReader[3],
                                            huntaholic_ratio = (decimal)dbReader[4]
                                        });
                            }

                            if (!MarketResource.ContainsKey(name))
                                MarketResource.Add(name, market.ToArray());
                            else
                                ConsoleUtils.ShowError("Duplicated Market Name {0}. Skipping duplicated entry.", name);

                        }
                    }
                    catch (Exception ex)
                    {
                        ConsoleUtils.ShowSQL(ex.Message);
                        return;
                    }
                    finally { dbCmd.Connection.Close(); }
                }
            }

            ConsoleUtils.ShowNotice("{0} entries loaded from MarketResource", MarketResource.Count);
        }
コード例 #18
0
ファイル: Arcadia.cs プロジェクト: KirieZ/Tartarus
        internal static void LoadItemEffect()
        {
            ItemEffectResource = new Dictionary<int, DB_ItemEffect[]>();

            using (DBManager dbManager = new DBManager(Databases.Game))
            {
                using (DbCommand dbCmd = dbManager.CreateCommand(6))
                {
                    try
                    {
                        dbCmd.Connection.Open();

                        using (DbDataReader dbReader = dbCmd.ExecuteReader())
                        {
                            int id = -1;
                            List<DB_ItemEffect> effects = new List<DB_ItemEffect>();

                            while (dbReader.Read())
                            {
                                int off = 0;

                                if (id != (int)dbReader[off] && id != -1)
                                {
                                    if (!ItemEffectResource.ContainsKey(id))
                                        ItemEffectResource.Add(id, effects.ToArray());
                                    else
                                        ConsoleUtils.ShowError("Duplicated Item Effect with ID {0}. Skipping duplicated entry.", id);

                                    effects.Clear();
                                }
                                id = (int)dbReader[off++];

                                effects.Add(new DB_ItemEffect()
                                {
                                     ordinal_id = (int)dbReader[off++],
                                     tooltip_id = (int)dbReader[off++],
                                     effect_type = (byte)dbReader[off++],
                                     effect_id = (short)dbReader[off++],
                                     effect_level = (short)dbReader[off++],
                                     value_0 = (decimal)dbReader[off++],
                                     value_1 = (decimal)dbReader[off++],
                                     value_2 = (decimal)dbReader[off++],
                                     value_3 = (decimal)dbReader[off++],
                                     value_4 = (decimal)dbReader[off++],
                                     value_5 = (decimal)dbReader[off++],
                                     value_6 = (decimal)dbReader[off++],
                                     value_7 = (decimal)dbReader[off++],
                                     value_8 = (decimal)dbReader[off++],
                                     value_9 = (decimal)dbReader[off++],
                                     value_10 = (decimal)dbReader[off++],
                                     value_11 = (decimal)dbReader[off++],
                                     value_12 = (decimal)dbReader[off++],
                                     value_13 = (decimal)dbReader[off++],
                                     value_14 = (decimal)dbReader[off++],
                                     value_15 = (decimal)dbReader[off++],
                                     value_16 = (decimal)dbReader[off++],
                                     value_17 = (decimal)dbReader[off++],
                                     value_18 = (decimal)dbReader[off++],
                                     value_19 = (decimal)dbReader[off++],
                                });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ConsoleUtils.ShowSQL(ex.Message);
                        return;
                    }
                    finally { dbCmd.Connection.Close(); }
                }
            }

            ConsoleUtils.ShowNotice("{0} entries loaded from ItemEffectResource", ItemEffectResource.Count);
        }
コード例 #19
0
ファイル: DataConnection.cs プロジェクト: r0t0r-r0t0r/linq2db
        internal void InitCommand(CommandType commandType, string sql, DataParameter[] parameters, List<string> queryHints)
        {
            if (queryHints != null && queryHints.Count > 0)
            {
                var sqlProvider = DataProvider.CreateSqlBuilder();
                sql = sqlProvider.ApplyQueryHints(sql, queryHints);
                queryHints.Clear();
            }

            DataProvider.InitCommand(this, commandType, sql, parameters);
            LastQuery = Command.CommandText;
        }
コード例 #20
0
ファイル: GetDataFromHospital.cs プロジェクト: aj-hc/ZSSY
        //根据日期和调用webservice查询数据
        /// <summary>
        /// 根据日期和调用webservice查询数据
        /// </summary>
        /// <param name="dateBegin">开始时间</param>
        /// <param name="dateEnd">结束时间</param>
        /// <returns>OPInfoListForSpecimen数据字典集合</returns>
        private List<Dictionary<string, string>> GetOPInfoListForSpecimenByTimeRangeAndToDicList(string dateBegin, string dateEnd)
        {
            //创建病人字典集合。
            List<Dictionary<string, string>> oPListForSpecimensDicList = new List<Dictionary<string, string>>();

            RuRo.BLL.WebService.ForCenterLabService centerLabServiceSoapClient = new RuRo.BLL.WebService.ForCenterLabService();

            try
            {
                string oPInfoListForSpecimenStr = centerLabServiceSoapClient.GetOPInfoListForSpecimen(dateBegin, dateEnd);
                if (oPInfoListForSpecimenStr != null && oPInfoListForSpecimenStr != "")//有数据并且不为null
                {
                    //02.将数据转换成xml数据
                    XmlDocument getDataFromHospitalXml = HospitalXmlStrHelper.HospitalXmlStrToXmlDoc(oPInfoListForSpecimenStr);
                    if (getDataFromHospitalXml != null)//有数据并且能转换成xml文档
                    {
                        if (getDataFromHospitalXml.HasChildNodes)
                        {
                            XmlNode xmlNode = getDataFromHospitalXml.SelectSingleNode("/OPListForSpecimenRt/ResultCode");
                            //创建临时集合保存多个人的数据
                            Dictionary<string, string> oPListForSpecimenTempDic = new Dictionary<string, string>();
                            if (xmlNode.InnerText == "0") //获取数据成功
                            {
                                //OPListForSpecimens/OPListForSpecimen
                                XmlNodeList xmlNodeList = getDataFromHospitalXml.SelectNodes("//OPListForSpecimens/*");
                                foreach (XmlNode item in xmlNodeList)
                                {
                                    string tempOPListForSpecimenXml = item.OuterXml;
                                    oPListForSpecimenTempDic = ConvertOPListForSpecimenStrToDic(tempOPListForSpecimenXml);
                                    oPListForSpecimensDicList.Add(oPListForSpecimenTempDic);
                                }
                            }
                            else if (xmlNode.InnerText == "-1")
                            //获取数据失败
                            {
                                oPListForSpecimenTempDic.Clear();
                                oPListForSpecimenTempDic.Add("OPListForSpecimenRt", FpJsonHelper.SerializationStr(getDataFromHospitalXml.SelectSingleNode("/OPListForSpecimenRt/ResultContent").InnerText));
                                oPListForSpecimensDicList.Add(oPListForSpecimenTempDic);
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                oPListForSpecimensDicList.Clear();
            }
            return oPListForSpecimensDicList;
        }
コード例 #21
0
ファイル: CacheAspect.cs プロジェクト: calterras/bltoolkit
			private static void Cleanup(object state)
			{
				if (!Monitor.TryEnter(RegisteredAspects.SyncRoot, 10))
				{
					// The Cache is busy, skip this turn.
					//
					return;
				}

				var start          = DateTime.Now;
				var objectsInCache = 0;

				try
				{
					_workTimes++;

					var list = new List<DictionaryEntry>();

					foreach (CacheAspect aspect in RegisteredAspects)
					{
						var cache = aspect.Cache;

						lock (cache.SyncRoot)
						{
							foreach (DictionaryEntry de in cache)
							{
								var wr = de.Value as WeakReference;

								bool isExpired;

								if (wr != null)
								{
									var ca = wr.Target as CacheAspectItem;

									isExpired = ca == null || ca.IsExpired;
								}
								else
								{
									isExpired = ((CacheAspectItem)de.Value).IsExpired;
								}

								if (isExpired)
									list.Add(de);
							}

							foreach (var de in list)
							{
								cache.Remove(de.Key);
								_objectsExpired++;
							}

							list.Clear();

							objectsInCache += cache.Count;
						}
					}

					_objectsInCache = objectsInCache;
				}
				finally
				{
					_workTime += DateTime.Now - start;

					Monitor.Exit(RegisteredAspects.SyncRoot);
				}
			}
コード例 #22
0
ファイル: RRTKDTreeCombat.cs プロジェクト: muntac/unitytool
        // Returns the computed path by the RRT, and smooth it if that's the case
        private List<Node> ReturnPath(Node endNode, bool smooth)
        {
            Node n = endNode;
            List<Node> points = new List<Node> ();

            while (n != null) {
                points.Add (n);
                n = n.parent;
            }
            points.Reverse ();

            // If we didn't find a path
            if (points.Count == 1)
                points.Clear ();
            else if (smooth) {
                // Smooth out the path
                Node final = null;
                foreach (Node each in points) {
                    final = each;
                    while (Extra.Collision.SmoothNode(final, this, SpaceState.Editor, true)) {
                    }
                }

                points.Clear ();

                while (final != null) {
                    points.Add (final);
                    final = final.parent;
                }
                points.Reverse ();
            }

            return points;
        }
コード例 #23
0
ファイル: StringReplacer.cs プロジェクト: orichisonic/Program
 /// <summary>  
 /// 二进制替换,如果没有替换则返回原数组对像的复本. 内部使用List,比直接用数组替换效率低25%  
 /// </summary>  
 /// <param name="sourceByteArray">源数据</param>  
 ///   
 /// </summary>  
 /// <param name="oldValue">需要替换的数据</param>  
 /// <param name="newValue">将要替换成为的数据</param>  
 public static byte[] ReplaceA( byte[] sourceByteArray, byte[] oldValue, byte[] newValue)
 {
     //创建新数据多出1字节
     int newArrayLen = (int)((newValue.Length / (double)oldValue.Length) * sourceByteArray.Length) + 1;
     //得到数组长度
     newArrayLen = Math.Max(newArrayLen, sourceByteArray.Length);
     int oldCurindex = 0;
     List<byte> result = new List<byte>(newArrayLen);
     //替换数据替换
     for (int x = 0; x < sourceByteArray.Length; x++)
     {
         var b = sourceByteArray[x];
         result.Add(b);
         if (b == oldValue[oldCurindex])
         {
             if (oldCurindex == oldValue.Length - 1)
             {
                 oldCurindex = 0;
                 //称除现有数据
                 for (int k = 0; k < oldValue.Length; k++)
                 {
                     result.RemoveAt(result.Count - 1);
                 }
                 //添加新数据
                 result.AddRange(newValue);
             }
             else
             {
                 oldCurindex++;
             }
         }
     }
     byte[] resultarr = result.ToArray();
     result.Clear();
     result = null;
     return resultarr;
 }
コード例 #24
0
        public bool UpdateMachineSignalGroupSetting(List<string> machineIDs, Guid groupID)
        {
            if (machineIDs == null || machineIDs.Count==0 || groupID == null)
            {
                return false;
            }
            SqlConnection cn = null;
            SqlCommand cmd = null;
            SqlTransaction trans = null;
            try
            {
                string strSQL;
                int count;
                List<SqlParameter> sqlparams = new List<SqlParameter>();
                // check if group record exist
                if (groupID != null && groupID != Guid.Empty)
                {
                    strSQL = "SELECT COUNT(1) FROM SignalStatusGroup_ssg a WHERE ssg_cGroupID=@GroupId";
                    sqlparams.Add(SQLHelper.MakeInParam("@GroupId", SqlDbType.UniqueIdentifier, 0, groupID));
                    count = (int)(SQLHelper.ExecuteScalar(strSQL, sqlparams.ToArray()));
                    if (count == 0) return false;
                }

                cn = new SqlConnection(SQLHelper.ConnectionString);
                if (cn.State == ConnectionState.Closed) cn.Open();
                trans = cn.BeginTransaction();

                //delete old machine record
                sqlparams.Clear();
                strSQL = "DELETE FROM MachineSignalStatusGroup_msg WHERE msg_cMachineID in (";
                for (int i = 0; i < machineIDs.Count; i++)
                {
                    if (i > 0) strSQL += ",";
                    strSQL += "@Mid"+i;
                    sqlparams.Add(SQLHelper.MakeInParam("@Mid" + i, SqlDbType.NVarChar, 20, machineIDs[i]));
                }
                strSQL += ");";
                int rowsAffected = SQLHelper.ExecuteNonQuery(strSQL, sqlparams.ToArray());

                if (rowsAffected >= 0 && groupID!= Guid.Empty)
                {
                    //insert new record
                    sqlparams.Clear();
                    strSQL = "";
                    for (int i = 0; i < machineIDs.Count; i++)
                    {
                        strSQL += "INSERT INTO MachineSignalStatusGroup_msg(msg_cMachineID,msg_cGroupID) values (@Mid" + i + ",@Gid);";
                        sqlparams.Add(SQLHelper.MakeInParam("@Mid" + i, SqlDbType.NVarChar, 20, machineIDs[i]));
                    }
                    sqlparams.Add(SQLHelper.MakeInParam("@Gid", SqlDbType.UniqueIdentifier, 0, groupID));
                    rowsAffected = SQLHelper.ExecuteNonQuery(strSQL, sqlparams.ToArray());
                }
                if (rowsAffected >= 0)//当变更的行数小于0时,更新失败
                {
                    trans.Commit();
                    return true;
                }
                trans.Rollback();
                return false;
            }
            catch (Exception e)
            {
                if (trans != null) trans.Rollback();
                return false;
            }
            finally
            {
                if (trans != null) trans.Dispose();
                if (cmd != null) cmd.Dispose();
                if (cn.State == ConnectionState.Open) cn.Close();
                if (cn != null) cn.Dispose();
            }
        }
コード例 #25
0
ファイル: View.cs プロジェクト: apravdivy/MagistrSolution
        public void SendSolvingResultType1(RKResults res, IFunctionExecuter fe)
        {
            var dz = new double[res.Count - 1];
            for (int i = 1; i < res.Count; i++)
            {
                dz[i - 1] = (res[i].Y[0] - res[i - 1].Y[0])/(res[i].X - res[i - 1].X);
            }
            var lambda = new int[res.Count - 1];

            //v[0] = t <= 0 ? -1 : 1
            var valInPoint = new List<double>();
            for (int i = 0; i < res.Count - 1; i++)
            {
                valInPoint.Clear();
                for (int j = 0; j < fe.SetCount; j++)
                {
                    valInPoint.Add(Math.Abs(dz[i] - fe.FunctionSet(res[i].X, res[i].Y, j)));
                }

                lambda[i] = valInPoint.IndexOf(valInPoint.Min()) + 1;
            }
            //int g = 0;

            int mn = lambda[0];
            var divZ = new List<double>(); // res[0].Y[0];
            var divT = new List<double>(); // res[0].X;

            var checkedSet = new List<int>();

            for (int i = 1; i < lambda.Length; i++)
            {
                if (lambda[i] != mn && (checkedSet.Count == 0 || !checkedSet.Contains(lambda[i])))
                {
                    divT.Add((res[i].X + res[i - 1].X)/2f);
                    divZ.Add((res[i].Y[0] + res[i - 1].Y[0])/2f);
                    checkedSet.Add(mn);
                    mn = lambda[i];
                    continue;
                }
            }

            //fill DataSouce
            var list = new List<ResPointViewType1>();
            for (int i = 0; i < lambda.Length; i++)
            {
                list.Add(new ResPointViewType1(res[i].X, res[i].Y[0], lambda[i], -1));
            }

            ShowResultType1(divT, divZ, list, res[0].X, res[res.Count - 1].X);
        }
コード例 #26
0
ファイル: bee_method.cs プロジェクト: elimonova/ExtremSearch
        public double[] search()
        {
            List<Bee> bee = new List<Bee>();
            Bee best = new Bee(argCnt);
            List<Bee> workBee = new List<Bee>();
            List<Bee> newWorkBee = new List<Bee>();
            Bee tmp;

            //Step 2
            for (int i = 0; i < B; i++)
            {
                tmp = getRandBee();
                bee.Add(tmp);
            }
            iter = 1;
            //Step 3
            best.Copy(bee.First());
            while (T != TFinal && iter != iterMax)
            {
                newWorkBee.Clear();
                workBee.Clear();
                for (int i = 0; i < bee.Count; i++)
                {
                    if (best.profit < bee[i].profit)
                    {
                        best.Copy(bee[i]);
                    }
                }
                for (int i = 0; i < bee.Count; i++)
                {
                    if (Math.Exp(-Math.Abs(bee[i].profit - best.profit) / T) > rand.NextDouble())
                    {
                        workBee.Add(bee[i]);
                    }
                }
                workBee.Add(best);
                //Step 4
                foreach (Bee currBee in workBee)
                {
                    tmp = new Bee(argCnt);
                    for (int i = 0; i < argCnt; i++)
                    {
                        tmp.point[i] = currBee.point[i] - getRandSign() * rand.NextDouble() * (currBee.point[i] - best.point[i]);
                    }
                    checkRange(ref tmp);
                    tmp.profit = getProfit(tmp);
                    newWorkBee.Add(tmp);
                }
                foreach (Bee currBee in workBee)
                {
                    tmp = new Bee(argCnt);
                    for (int i = 0; i < argCnt; i++)
                    {
                        tmp.point[i] = best.point[i] - getRandSign() * rand.NextDouble() * (currBee.point[i] - best.point[i]);
                    }
                    checkRange(ref tmp);
                    tmp.profit = getProfit(tmp);
                    newWorkBee.Add(tmp);
                }
                newWorkBee.AddRange(workBee);
                foreach (Bee currBee in newWorkBee)
                {
                    if (best.profit < currBee.profit)
                    {
                        best.Copy(currBee);
                    }
                }
                //Step 5
                double fullProfit = 0;
                foreach (Bee currBee in newWorkBee)
                {
                    fullProfit += currBee.profit;
                }
                double d;
                double L;
                bee.Clear();
                for (int i = 0; i < newWorkBee.Count; i++)
                {
                    d = newWorkBee[i].profit / fullProfit;
                    d += getRandSign() * rand.NextDouble() * wMax;
                    d = d > 1 ? 1 : d;
                    d = d < eMax ? 0 : d;
                    L = (d - eta * fullProfit / newWorkBee.Count) < 0 ? 0 : (d - eta * fullProfit / newWorkBee.Count);
                    if (L / beta > (gamma * fullProfit / newWorkBee.Count))
                    {
                        bee.Add(newWorkBee[i]); //danced bee are added

                        tmp = new Bee(argCnt);
                        for (int j = 0; j < argCnt; j++)
                        {
                            tmp.point[j] = newWorkBee[i].point[j] + range * rand.NextDouble() - range / 2;
                        }
                        checkRange(ref tmp);
                        tmp.profit = getProfit(tmp);
                        bee.Add(tmp);
                    }
                    else
                    {
                        tmp = getRandBee();
                        bee.Add(tmp);
                    }

                }
                iter++;
                T *= alpha;
                range *= (1 - (double)iter / iterMax);
            }
            return (best.point.x);
        }
コード例 #27
0
ファイル: FileTarget.cs プロジェクト: daniefer/NLog
        private void FlushCurrentFileWrites(string currentFileName, LogEventInfo firstLogEvent, MemoryStream ms,
            List<AsyncContinuation> pendingContinuations)
        {
            Exception lastException = null;

            try
            {
                if (currentFileName != null)
                    ProcessLogEvent(firstLogEvent, currentFileName, ms.ToArray());
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                lastException = exception;
            }

            foreach (AsyncContinuation cont in pendingContinuations)
            {
                cont(lastException);
            }

            pendingContinuations.Clear();
        }
コード例 #28
0
ファイル: View.cs プロジェクト: apravdivy/MagistrSolution
        private void ResolveType2(RKResults res, IFunctionExecuter fe, out List<double> divT, out List<double> divZ,
                                  out List<double> divZ2, out List<ResPointViewType2> list)
        {
            var dz1 = new double[res.Count - 1];
            for (int i = 1; i < res.Count; i++)
            {
                dz1[i - 1] = (res[i].Y[0] - res[i - 1].Y[0])/(res[i].X - res[i - 1].X);
            }
            var dz2 = new double[res.Count - 2];
            for (int i = 1; i < dz1.Length; i++)
            {
                dz2[i - 1] = (dz1[i] - dz1[i - 1])/(res[i].X - res[i - 1].X);
            }

            var lambda = new int[res.Count - 2];

            var valInPoint = new List<double>();
            for (int i = 0; i < res.Count - 2; i++)
            {
                valInPoint.Clear();
                for (int j = 0; j < fe.SetCount; j++)
                {
                    valInPoint.Add(Math.Abs(dz2[i] - fe.FunctionSet(res[i].X, res[i].Y, j)));
                }

                lambda[i] = valInPoint.IndexOf(valInPoint.Min()) + 1;
            }
            //int g = 0;

            int mn = lambda[0];
            divZ = new List<double>(); // res[0].Y[0];
            divT = new List<double>(); // res[0].X;
            divZ2 = new List<double>();

            var checkedSet = new List<int>();

            for (int i = 1; i < lambda.Length; i++)
            {
                if (lambda[i] != mn && (checkedSet.Count == 0 || !checkedSet.Contains(lambda[i])))
                {
                    divT.Add((res[i].X + res[i - 1].X)/2f);
                    divZ.Add((res[i].Y[0] + res[i - 1].Y[0])/2f);
                    divZ2.Add((res[i].Y[1] + res[i - 1].Y[1])/2f);
                    checkedSet.Add(mn);
                    mn = lambda[i];
                }
            }

            //fill DataSouce
            list = new List<ResPointViewType2>();
            for (int i = 0; i < lambda.Length; i++)
            {
                list.Add(new ResPointViewType2(res[i].X, res[i].Y[0], res[i].Y[1], lambda[i], -1));
            }
        }
コード例 #29
0
ファイル: FileTarget.cs プロジェクト: koson/NLog
        private void FlushCurrentFileWrites(string currentFileName, LogEventInfo firstLogEvent, MemoryStream ms, List<AsyncContinuation> pendingContinuations)
        {
            Exception lastException = null;

            try
            {
                if (currentFileName != null)
                {
                    if (this.ShouldAutoArchive(currentFileName, firstLogEvent, (int)ms.Length))
                    {
                        this.WriteFooterAndUninitialize(currentFileName);
                        this.InvalidateCacheItem(currentFileName);
                        this.DoAutoArchive(currentFileName, firstLogEvent);
                    }

                    this.WriteToFile(currentFileName, ms.ToArray(), false);
                }
            }
            catch (Exception exception)
            {
                if (exception.MustBeRethrown())
                {
                    throw;
                }

                lastException = exception;
            }

            foreach (AsyncContinuation cont in pendingContinuations)
            {
                cont(lastException);
            }

            pendingContinuations.Clear();
        }
コード例 #30
0
ファイル: ActiveNodes.cs プロジェクト: chrimc62/EntityMatch
        public void DistanceSort(List<int> outNodes, int l, Dictionary<int, int[]> descendants)
        {
            outNodes.Clear();
            m_dist2count.Clear();
            //int mindist = infty, maxdist = 0;
            //Dictionary<int, int>.Enumerator aEnum = m_ht.GetEnumerator();
            //while (aEnum.MoveNext())
            //{
            //    int nodeid = aEnum.Current.Key;
            //    int dist = aEnum.Current.Value;
            //    if (dist < mindist)
            //        mindist = dist;
            //    if (dist > maxdist)
            //        maxdist = dist;
            //    if (!m_dist2count.ContainsKey(dist))
            //        m_dist2count.Add(dist, 0);
            //    m_dist2count[dist]++;
            //    outNodes.Add(aEnum.Current.Key);
            //}

            //return;

            int cumCnt = 0;
            for (int d = m_minDist; d <= m_maxDist; d++)
            {
                List<int> nodeList;
                if (m_dist2nodes.TryGetValue(d, out nodeList))
                {
                    foreach (int nodeid in nodeList)
                    {
                        int[] desc;
                        if (descendants.TryGetValue(nodeid, out desc))
                            cumCnt += desc.Length;
                        outNodes.Add(nodeid);
                        if (cumCnt >= l)
                            return;
                    }
                }
            }

            //Dictionary<int, int>.Enumerator aEnum2 = m_ht.GetEnumerator();
            //while (aEnum2.MoveNext())
            //{
            //    int nodeid = aEnum2.Current.Key;
            //    int dist = aEnum.Current.Value;
            //    int idx = m_dist2count[dist];
            //    outNodes[idx] = nodeid;
            //    m_dist2count[dist]++;
            //}

            //m_dist2count.Clear();
            //SortByDistance(outNodes, 0, outNodes.Count - 1);
        }