예제 #1
0
        async Task ReadPipeAsync(PipeReader reader, ClientManager clientManager, RequestReader requestReader)
        {
            try
            {
                while (true)
                {
                    ReadResult result = await reader.ReadAsync();

                    ReadOnlySequence <byte> buffer = result.Buffer;
                    clientManager.MarkActivity();
                    requestReader.Read(ref buffer);


                    // Tell the PipeReader how much of the buffer we have consumed
                    reader.AdvanceTo(buffer.Start, buffer.End);

                    // Stop reading if there's no more data coming
                    if (result.IsCompleted)
                    {
                        break;
                    }
                }

                // Mark the PipeReader as complete
                reader.Complete();
                DisposeClient(clientManager);
            }
            catch (SocketException so_ex)
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + so_ex.ToString());
                }

                DisposeClient(clientManager);
            }
            catch (Exception e)
            {
                var clientIsDisposed = clientManager.IsDisposed;
                DisposeClient(clientManager);

                if (!clientIsDisposed)
                {
                    AppUtil.LogEvent(e.ToString(), EventLogEntryType.Error);
                }

                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + e.ToString());
                }
                if (SocketServer.Logger.IsErrorLogsEnabled)
                {
                    SocketServer.Logger.NCacheLog.Error("ConnectionManager.ReceiveCallback", clientManager.ToString() + " Error " + e.ToString());
                }

                try
                {
                    if (Management.APILogging.APILogManager.APILogManger != null && Management.APILogging.APILogManager.EnableLogging)
                    {
                        APILogItemBuilder log = new APILogItemBuilder();
                        log.GenerateConnectionManagerLog(clientManager, e.ToString());
                    }
                }
                catch
                {
                }
            }
            finally
            {
                //  clientManager.StopCommandExecution();
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.StopClientActivity(clientManager.ClientID);
                }
            }
        }
예제 #2
0
        public GpuProfilesPageViewModel(MinerClientsWindowViewModel minerClientsWindowVm)
        {
            _minerClientsWindowVm = minerClientsWindowVm;
            if (minerClientsWindowVm.SelectedMinerClients == null && minerClientsWindowVm.SelectedMinerClients.Length != 1)
            {
                throw new InvalidProgramException();
            }
            _minerClientVm = minerClientsWindowVm.SelectedMinerClients[0];
            if (AppContext.Instance.CoinVms.TryGetCoinVm(_minerClientVm.MainCoinCode, out CoinViewModel outCoinVm))
            {
                this._coinVm = outCoinVm;
            }
            if (this._coinVm == null)
            {
                this._coinVm = CoinVms.MainCoins.FirstOrDefault();
            }
            this.Save = new DelegateCommand(() => {
                if (_data == null)
                {
                    return;
                }
                GpuProfilesJsonDb jsonObj = new GpuProfilesJsonDb()
                {
                    Gpus = _data.Gpus
                };
                foreach (var coinVm in CoinVms.MainCoins)
                {
                    if (coinVm.IsOverClockEnabled)
                    {
                        jsonObj.CoinOverClocks.Add(new CoinOverClockData()
                        {
                            CoinId             = coinVm.Id,
                            IsOverClockEnabled = coinVm.IsOverClockEnabled,
                            IsOverClockGpuAll  = coinVm.IsOverClockGpuAll
                        });
                        if (CoinVm.IsOverClockGpuAll)
                        {
                            jsonObj.GpuProfiles.Add(new GpuProfileData().Update(coinVm.GpuAllProfileVm));
                        }
                        jsonObj.GpuProfiles.AddRange(coinVm.GpuProfileVms.Select(a => new GpuProfileData().Update(a)));
                    }
                }
                string json = VirtualRoot.JsonSerializer.Serialize(jsonObj);
                foreach (var client in minerClientsWindowVm.SelectedMinerClients)
                {
                    RpcRoot.Client.NTMinerDaemonService.SaveGpuProfilesJsonAsync(client.MinerIp, json);
                }
                VirtualRoot.Out.ShowSuccess("应用成功,请观察效果");
                VirtualRoot.Execute(new CloseWindowCommand(this.Id));
            });
            RpcRoot.Client.NTMinerDaemonService.GetGpuProfilesJsonAsync(_minerClientVm.MinerIp, (data, e) => {
                _data = data;
                if (e != null)
                {
                    Write.UserError(e.Message);
                }
                else if (data != null)
                {
                    string iconName;
                    switch (_minerClientVm.GpuType)
                    {
                    case GpuType.NVIDIA:
                    case GpuType.AMD:
                        iconName    = "Icon_Nvidia";
                        GpuIconFill = "Green";
                        RedText     = "超频有风险,操作需谨慎";
                        IsEnabled   = true;
                        break;

                    case GpuType.Empty:
                    default:
                        iconName    = "Icon_GpuEmpty";
                        GpuIconFill = "Gray";
                        RedText     = "没有矿卡或矿卡未驱动";
                        IsEnabled   = false;
                        break;
                    }
                    GpuIcon = AppUtil.GetResource <Geometry>(iconName);
                    foreach (var coinVm in AppContext.Instance.CoinVms.MainCoins)
                    {
                        var coinOverClock = data.CoinOverClocks.FirstOrDefault(a => a.CoinId == coinVm.Id);
                        var gpuProfiles   = data.GpuProfiles.Where(a => a.CoinId == coinVm.Id).ToArray();
                        if (coinOverClock == null)
                        {
                            coinOverClock = new CoinOverClockData()
                            {
                                CoinId             = coinVm.Id,
                                IsOverClockEnabled = false,
                                IsOverClockGpuAll  = true
                            };
                        }
                        coinVm.IsOverClockEnabled = coinOverClock.IsOverClockEnabled;
                        coinVm.IsOverClockGpuAll  = coinOverClock.IsOverClockGpuAll;
                        List <GpuProfileViewModel> gpuProfileVms = new List <GpuProfileViewModel>();
                        GpuProfileViewModel gpuAllProfileVm      = null;
                        #region
                        foreach (var gpu in data.Gpus.OrderBy(a => a.Index))
                        {
                            var gpuProfile = gpuProfiles.FirstOrDefault(a => a.Index == gpu.Index);
                            if (gpuProfile == null)
                            {
                                gpuProfile = new GpuProfileData(coinVm.Id, gpu.Index);
                            }
                            var gpuVm = new GpuViewModel(gpu, data.Gpus);
                            if (gpu.Index == NTMinerRoot.GpuAllId)
                            {
                                gpuAllProfileVm = new GpuProfileViewModel(gpuProfile, gpuVm);
                            }
                            else
                            {
                                gpuProfileVms.Add(new GpuProfileViewModel(gpuProfile, gpuVm));
                            }
                        }
                        if (gpuAllProfileVm == null)
                        {
                            gpuAllProfileVm = new GpuProfileViewModel(
                                new GpuProfileData(coinVm.Id, NTMinerRoot.GpuAllId), new GpuViewModel(new GpuData {
                                Index = NTMinerRoot.GpuAllId,
                                Name  = "All"
                            }, data.Gpus));
                        }
                        #endregion
                        coinVm.GpuAllProfileVm = gpuAllProfileVm;
                        coinVm.GpuProfileVms   = gpuProfileVms;
                    }
                }
            });
        }
예제 #3
0
        //根据word文档生成对应的html文档, 并存储到指定位置
        private bool DeviceBaseGenerateHtmlByWord(string wordFullPath)
        {
            if (File.Exists(wordFullPath))                      //若所选中的文件存在
            {
                //获取文件对应的HTML所在目录----目录名+\\+不带后缀的文件名+"-html"
                string htmlDirPath = Path.GetDirectoryName(wordFullPath).Replace("SrcFiles", "HtmlFiles") + "\\" + Path.GetFileNameWithoutExtension(wordFullPath) + "-html";
                //获取对应的html文件的文件名
                string htmlFilePath = htmlDirPath + "\\" + Path.GetFileNameWithoutExtension(wordFullPath) + ".html";

                if (Directory.Exists(htmlDirPath))                      //若存放HTML文件的目录存在
                {
                    if (File.Exists(htmlFilePath))                      //若Html文件存在, 则显示出来
                    {
                        webBrowserDeviceBase.Navigate(htmlFilePath);    //显示到WebBrowser中
                    }
                    else                                                //若Html文件不存在, 则创建
                    {
                        try
                        {
                            AppUtil.ConvertDocToHtml(wordFullPath, htmlFilePath);                               //创建Html文件
                            return(true);
                        }
                        catch (Exception ex) { Console.WriteLine(ex.Message); log.Info(AppUtil.getExceptionInfo(ex)); }
                    }
                }
                else                                                                            //若存放HTML文件的目录不存在, 则创建目录
                {
                    try
                    {
                        Directory.CreateDirectory(htmlDirPath);
                        AppUtil.ConvertDocToHtml(wordFullPath, htmlFilePath);                                   //创建Html文件
                        return(true);
                    }
                    catch (Exception ex) { Console.WriteLine(ex.Message); log.Info(AppUtil.getExceptionInfo(ex)); }
                }
            }
            return(false);
        }
예제 #4
0
        private void SaveData()
        {
            try
            {
                if (ValidateData())
                {
                    int flag = 0;
                    StaffDataManagement data = new StaffDataManagement();
                    data.Username      = txtUsername.Text.Trim();
                    data.EmpCode       = txtEmpCode.Text.Trim();
                    data.MarketingCode = txtMarketingCode.Text.Trim();
                    data.StaffNameTH   = txtStaffNameTH.Text.Trim();
                    data.TelNo         = txtTellNo.Text.Trim();
                    data.StaffEmail    = txtStaffEmail.Text.Trim();
                    data.PositionId    = cmbPosition.SelectedItem.Value;
                    data.StaffTypeId   = decimal.Parse(cmbStaffType.SelectedItem.Value);
                    data.Team          = txtTeam.Text.Trim();
                    data.BranchCode    = cmbBranchCode.SelectedItem.Value;
                    data.StaffId       = int.Parse(txtStaffId.Text.Trim());
                    if (rdNormal.Checked == true)
                    {
                        data.Is_Deleted = 0;
                    }
                    else if (rdRetire.Checked == true)
                    {
                        data.Is_Deleted = 1;
                    }

                    if (cmbHeadStaffId.Items.Count > 0 && cmbHeadStaffId.SelectedItem.Value != "")
                    {
                        data.HeadStaffId = int.Parse(cmbHeadStaffId.SelectedItem.Value);
                    }
                    else
                    {
                        data.HeadStaffId = null;
                    }

                    if (cmbDepartment.Items.Count > 0)
                    {
                        if (!string.IsNullOrEmpty(cmbDepartment.SelectedItem.Value))
                        {
                            data.DepartmentId = int.Parse(cmbDepartment.SelectedItem.Value);
                        }
                    }
                    if (cmbCocTeam.Items.Count > 0)
                    {
                        data.CocTeam = cmbCocTeam.SelectedItem.Value;
                    }

                    if (txtOldIsDeleted.Text.Trim() != txtNewIsDeleted.Text.Trim())
                    {
                        flag = 1;
                    }

                    string staffId = StaffBiz.UpdateStaff(data, HttpContext.Current.User.Identity.Name, flag);

                    AppUtil.ClientAlert(Page, "บันทึกข้อมูลเจ้าหน้าที่สำเร็จ");
                    txtStaffId.Text = staffId;
                    InitialControl();
                    LoadStaffData();
                    CheckConditionOper();
                    SetDept();
                    upInfo.Update();
                }
                else
                {
                    AppUtil.ClientAlert(Page, "กรุณาระบุข้อมูลให้ครบถ้วน");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #5
0
        public string Initialize(System.Collections.IDictionary properties, string partitionID, string cacheName, bool isStartedAsMirror, bool inproc)
        {
            if (log != null)
            {
                throw new Exception("Multiple Initialize calls for same logger");
            }

            MemoryStream logStream = new MemoryStream(log4netXML);

            log4net.Config.XmlConfigurator.Configure(Log4net.LogRepository, logStream);

            if (_loggerName != null)
            {
                return(_loggerName);
            }
            try
            {
                _loggerName = cacheName;
                if (partitionID != null && partitionID.Length > 0)
                {
                    _loggerName += "-" + partitionID;
                }

                if (isStartedAsMirror)
                {
                    _loggerName += "-" + "replica";
                }

                if (inproc && !isStartedAsMirror)
                {
                    _loggerName += "." + System.Diagnostics.Process.GetCurrentProcess().Id;
                }

                string LogExceptions = "";

                if (_loggerName == "LogExceptions")
                {
                    LogExceptions = "\\LogExceptions";
                }
                bool   defaultPath = true;
                string initialPath = "";

                if (properties.Contains("log-path"))
                {
                    initialPath = Convert.ToString(properties["log-path"]);
                    if (!String.IsNullOrEmpty(initialPath))
                    {
                        defaultPath = !IsValidLocation(initialPath, cacheName);
                    }
                }


                if (defaultPath)
                {
                    initialPath = GetLogPath();
                }

                string fileName = initialPath + LogExceptions + Path.DirectorySeparatorChar + _loggerName + "_" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month + "-" + DateTime.Now.Year + "-" + DateTime.Now.Hour + "-" + DateTime.Now.Minute + "-" + DateTime.Now.Second + "_" + _nodeIP + ".txt";;

                AddAppender(CreateBufferAppender(fileName, false, false));


                if (properties != null)
                {
                    if (properties.Contains("trace-errors"))
                    {
                        if (Convert.ToBoolean(properties["trace-errors"]))
                        {
                            SetLevel(LoggerLevel.Error);
                        }
                    }

                    if (properties.Contains("trace-notices"))
                    {
                        if (Convert.ToBoolean(properties["trace-notices"]))
                        {
                            SetLevel(LoggerLevel.Info);
                        }
                    }

                    if (properties.Contains("trace-warnings"))
                    {
                        if (Convert.ToBoolean(properties["trace-warnings"]))
                        {
                            SetLevel(LoggerLevel.Warn);
                        }
                    }

                    if (properties.Contains("trace-debug"))
                    {
                        if (Convert.ToBoolean(properties["trace-debug"]))
                        {
                            SetLevel(LoggerLevel.All);
                        }
                    }

                    if (properties.Contains("enabled"))
                    {
                        if (!Convert.ToBoolean(properties["trace-errors"]))
                        {
                            SetLevel(LoggerLevel.Off);
                        }
                    }
                }
                else
                {
                    SetLevel(LoggerLevel.Warn);
                }
            }
            catch (Exception e)
            {
                AppUtil.LogEvent(_cacheserver, "Failed to open log. " + e, System.Diagnostics.EventLogEntryType.Error, EventCategories.Error, EventID.GeneralError);
            }

            return(_loggerName);
        }
예제 #6
0
 /// <summary>
 /// レコード件数取得
 /// </summary>
 /// <returns>レコード件数</returns>
 public int Count()
 {
     return(AppUtil.Obj2Int((ExecuteFetchOne(string.Format("SELECT COUNT(*) as TOTAL_COUNT FROM {0}", TblName()))["TOTAL_COUNT"])));
 }
예제 #7
0
 private void RegisterMessage()
 {
     AppUtil.RegisterEvents <InkMode>(this, AppConsts.MSG_SwitchInkMode, SwitchInkMode);
 }
예제 #8
0
        protected void btnPopupSave_Click(object sender, EventArgs e)
        {
            try
            {
                string strErrorMessage = string.Empty;

                if (ValidatePerCent(textCommissionPct.Text))
                {
                    strErrorMessage = "ค่าคอมมิชชั่น(%) ต้องไม่เกิน 100%";
                }
                else if (ValidateDecimal(textCommissionPct.Text))
                {
                    strErrorMessage += (strErrorMessage.Trim() != string.Empty ? Environment.NewLine : string.Empty) + "ค่าคอมมิชชั่น(%) ทศนิยมต้องไม่เกิน 2 ตำแหน่ง";
                }
                else if (ValidateDecimal(textCommissionThb.Text))
                {
                    strErrorMessage += (strErrorMessage.Trim() != string.Empty ? Environment.NewLine : string.Empty) + "ค่าคอมมิชชั่น(บาท) ทศนิยมต้องไม่เกิน 2 ตำแหน่ง";
                }

                if (ValidatePerCent(textOV1Pct.Text))
                {
                    strErrorMessage += (strErrorMessage.Trim() != string.Empty ? Environment.NewLine : string.Empty) + "OV1(%) ต้องไม่เกิน 100%";
                }
                else if (ValidateDecimal(textOV1Pct.Text))
                {
                    strErrorMessage += (strErrorMessage.Trim() != string.Empty ? Environment.NewLine : string.Empty) + "OV1(%) ทศนิยมต้องไม่เกิน 2 ตำแหน่ง";
                }
                else if (ValidateDecimal(textOV1Thb.Text))
                {
                    strErrorMessage += (strErrorMessage.Trim() != string.Empty ? Environment.NewLine : string.Empty) + "OV1(บาท) ทศนิยมต้องไม่เกิน 2 ตำแหน่ง";
                }

                if (ValidatePerCent(textOV2Pct.Text))
                {
                    strErrorMessage += (strErrorMessage.Trim() != string.Empty ? Environment.NewLine : string.Empty) + "OV2(%) ต้องไม่เกิน 100%";
                }
                else if (ValidateDecimal(textOV2Pct.Text))
                {
                    strErrorMessage += (strErrorMessage.Trim() != string.Empty ? Environment.NewLine : string.Empty) + "OV2(%) ทศนิยมต้องไม่เกิน 2 ตำแหน่ง";
                }
                else if (ValidateDecimal(textOV2Thb.Text))
                {
                    strErrorMessage += (strErrorMessage.Trim() != string.Empty ? Environment.NewLine : string.Empty) + "OV2(บาท) ทศนิยมต้องไม่เกิน 2 ตำแหน่ง";
                }

                if (strErrorMessage.Trim() != string.Empty)
                {
                    AppUtil.ClientAlert(Page, strErrorMessage);
                    return;
                }

                // save
                string saveResponse = "";
                bool   saveResult   = SlmScr035Biz.Save(Benefit, out saveResponse);

                if (saveResult)
                {
                    mpePopupReceiveNo.Hide();
                    BindGridview(pcTop, LoadData().ToArray(), 0);
                }
                else
                {
                    mpePopupReceiveNo.Show();
                }
                AppUtil.ClientAlert(Page, saveResponse);
            }
            catch (Exception ex)
            {
                string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                _log.Error(message);
                AppUtil.ClientAlert(Page, message);
            }
        }
예제 #9
0
        /*********************************************************************************************/
        #endregion


        #region  发送部分函数
        /*-----------------------------------------发送部分函数---------------------------------------*/

        //从发送队列中取出消息, 然后发送
        private void SerialSend()
        {
            SerialSendMsg sendMsg;
            int           SendQueueItemCount = 0;

            while (true)
            {
                SendQueueWaitHandle.WaitOne();
                SendQueueItemCount = serialSendQueue.Count;                                     //提取队列中消息的个数
                if (serialPortIsOpen && (SendQueueItemCount > 0))                               //若串口已打开, 且队列中有数据
                {
                    for (int i = 0; i < SendQueueItemCount; i++)
                    {
                        lock (serialSendQueue) { sendMsg = serialSendQueue.Dequeue(); }                         //从发送队列中取出消息
                        bool isSendSuccess = false;
                        //发送出去
                        try
                        {
                            for (int n = 0; n < sendMsg.PackNumPerCmd; n++)
                            {
                                if (sendMsg.PacketData.Cmd == 0xFE)                                             // 先提取修改信道命令
                                {
                                    comDevice.Write(sendMsg.PacketData.DataFiled, 0, 6);
                                }
                                else                                                                            // 直接发送的命令
                                {
                                    comDevice.Write(sendMsg.PacketData.DataBytes, 0, sendMsg.PacketDataLength); //发送数据
                                }
                                                                #if DEBUG                                       //将发送消息投入调试发送队列中
                                if (SerialComDebug.isPauseDebug == false)                                       //若当前不是暂停状态
                                {
                                    sendMsg.SendTime = DateTime.Now;                                            //记录时间
                                    this.DebugQueue_Enqueue(sendMsg);
                                }
                                                                #endif
                                //写入串口发送记录到日志文件中
                                worklog.LogQueue_Enqueue(LogCommand.getSerialRecord(SerialRecordType.SerialSend, sendMsg));

                                Thread.Sleep(55);                                               //底层串口每2个包发送的间隔不能小于50ms
                            }
                            isSendSuccess = true;
                        }
                        catch (Exception ex)
                        {
                            isSendSuccess    = false;
                            serialPortIsOpen = false;                                           //串口未开启
                            Console.WriteLine(ex.Message);
                            log.Info(AppUtil.getExceptionInfo(ex));
                            //写入串口断开记录到日志文件中
                            worklog.LogQueue_Enqueue(LogCommand.getSerialRecord(SerialRecordType.Disconnect, null));
                        }
                        if (isSendSuccess)                                              //若发送成功
                        {
                            if (sendMsg.IsWaitAck)                                      //若需要重发, 则记录本次发送时间, 并投入重发字典中
                            {
                                sendMsg.SendTime = DateTime.Now;                        //记录时间
                                if (sendMsg.SendNumMax > 0)                             //将发送次数减1
                                {
                                    sendMsg.SendNumMax--;
                                }
                                sendMsg.PacketData.generateSendUType();
                                lock (resendDic)
                                {
                                    try
                                    {
                                        resendDic.Add(sendMsg.PacketData.SendUType, sendMsg);                                                   //存入重发字典中
                                    }
                                    catch (Exception ex) { Console.WriteLine(ex.Message); log.Info(AppUtil.getExceptionInfo(ex)); }
                                }
                            }
                        }
                    }
                }
            }
        }
예제 #10
0
        protected void lbAolSummaryReport_Click(object sender, EventArgs e)
        {
            try
            {
                int    index        = int.Parse(((ImageButton)sender).CommandArgument);
                string appNo        = ((Label)gvResult.Rows[index].FindControl("lblAppNo")).Text.Trim(); //"1002363";
                string productId    = ((Label)gvResult.Rows[index].FindControl("lblProductId")).Text.Trim();
                string privilegeNCB = "";

                if (txtStaffTypeId.Text.Trim() != "")
                {
                    privilegeNCB = SlmScr003Biz.GetPrivilegeNCB(productId, Convert.ToDecimal(txtStaffTypeId.Text.Trim()));
                }

                ScriptManager.RegisterClientScriptBlock(Page, GetType(), "callaolsummaryreport", AppUtil.GetCallAolSummaryReportScript(appNo, txtEmpCode.Text.Trim(), txtStaffTypeDesc.Text.Trim(), privilegeNCB), true);
            }
            catch (Exception ex)
            {
                string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                _log.Error(message);
                AppUtil.ClientAlert(Page, message);
            }
        }
예제 #11
0
    void Update()
    {
        int       count = AppUtil.getTouchCount();
        TouchInfo phase = AppUtil.GetTouch();
        Vector3   point = AppUtil.GetTouchPosition();

        if (Input.touchCount == 2)
        {
            Touch touchZero = Input.GetTouch(0);
            Touch touchOne  = Input.GetTouch(1);

            // 各タッチの前フレームでの位置をもとめます
            Vector2 touchZeroPrevPos = touchZero.position - touchZero.deltaPosition;
            Vector2 touchOnePrevPos  = touchOne.position - touchOne.deltaPosition;

            // 各フレームのタッチ間のベクター (距離) の大きさをもとめます
            float prevTouchDelta = (touchZeroPrevPos - touchOnePrevPos).magnitude;
            float touchDelta     = (touchZero.position - touchOne.position).magnitude;

            // 各フレーム間の距離の差をもとめます
            float deltaMagnitudeDiff = prevTouchDelta - touchDelta;
            // 前フレームからのピンチインアウトの距離が十分大きい
            if (Mathf.Abs(deltaMagnitudeDiff) > 6)
            {
                // タッチ間の距離の変化に基づいて有効視野を変更します
                Camera.main.fieldOfView += deltaMagnitudeDiff * perspectiveZoomSpeed;
                Camera.main.fieldOfView  = Mathf.Clamp(Camera.main.fieldOfView, 5f, 100f);
            }
            else
            {
                Vector2 movement = (touchZeroPrevPos - touchZero.position);
                Camera.main.transform.position += new Vector3(movement.x, 0, movement.y);
            }
        }
        else if (Input.GetMouseButtonUp(0) && (Input.touchCount == 1 || Application.isEditor))
        {
            if (!UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject())
            {
                Ray        ray = Camera.main.ScreenPointToRay(point);
                RaycastHit hit = new RaycastHit();

                // Raycastで画面のポイント先の座標取得
                if (Physics.Raycast(ray, out hit, Mathf.Infinity, mask))
                {
                    if (hit.transform.gameObject.layer != 11 && hit.transform.gameObject.layer != 5 && hit.transform.gameObject.layer != 12)
                    {
                        Vector3 center = hit.point + new Vector3(0, 450, 0);
                        // BoxCastで範囲に建物がないか確認
                        if (Physics.BoxCast(center, POINTSIZE, Vector3.down, out hit, Quaternion.identity, 450f, mask, QueryTriggerInteraction.Collide))
                        {
                            if (hit.transform.gameObject.layer != 11 && hit.transform.gameObject.layer != 5 && hit.transform.gameObject.layer != 12)
                            {
                                bool       isMulti        = AppUtil.isMulti == 1;
                                string     instantiteThis = "passingPoint";
                                GameObject g;

                                // マスター→経由地点
                                // クライアント→トラップ
                                if (isMulti)
                                {
                                    if (AppUtil.IsMasterClient)
                                    {
                                        // passingPointはマスターがいなくなっても引き継ぎたいためInstantiateSceneObjectを使う
                                        GameObject obj = AppUtil.InstantiateSceneObject(instantiteThis, hit.point, Quaternion.identity);
                                        AppUtil.RaiseEvent((byte)RaiseEventType.noticeListChanged, hit.point, AppUtil.raiseEventOptionsOthers);
                                        noticeListChanged(obj);
                                    }
                                    else
                                    {
                                        instantiteThis = "trap";
                                        AppUtil.Instantiate(instantiteThis, hit.point, Quaternion.identity);
                                    }
                                }
                                else
                                {
                                    // offline
                                    g = Instantiate(passingPoing, hit.point, Quaternion.identity);
                                    noticeListChanged(g);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
예제 #12
0
 private void SetStaffCombo()
 {
     AppUtil.BuildCombo(cmbTelesaleName, SlmScr032Biz.GetSearchStaffList(cmbTelesale.SelectedValue == "" ? -1 : SLMUtil.SafeInt(cmbTelesale.SelectedValue)), "ทั้งหมด");
 }
예제 #13
0
 protected override void OnInit(EventArgs e)
 {
     base.OnInit(e);
     AppUtil.BuildCombo(cmbTelesale, SlmScr032Biz.GetTeamSalesList(), "ทั้งหมด");
 }
예제 #14
0
        async Task FillPipeAsync(Socket socket, PipeWriter writer, ClientManager clientManager)
        {
            try
            {
                const int minimumBufferSize = 4 * 1024;

                while (true)
                {
                    // Allocate at least 512 bytes from the PipeWriter
                    Memory <byte> memory = writer.GetMemory(minimumBufferSize);

                    if (MemoryMarshal.TryGetArray(memory, out ArraySegment <byte> arraySegment))
                    {
                        if (!socket.Connected)
                        {
                            break;
                        }

                        int bytesRead = await socket.ReceiveAsync(arraySegment, SocketFlags.None);

                        clientManager.AddToClientsBytesRecieved(bytesRead);

                        if (SocketServer.IsServerCounterEnabled)
                        {
                            PerfStatsColl.IncrementBytesReceivedPerSecStats(bytesRead);
                        }

                        if (bytesRead == 0)
                        {
                            DisposeClient(clientManager);
                            break;
                        }
                        // Tell the PipeWriter how much was read from the Socket
                        writer.Advance(bytesRead);
                    }


                    // Make the data available to the PipeReader
                    FlushResult result = await writer.FlushAsync();

                    if (result.IsCompleted)
                    {
                        break;
                    }
                }

                // Tell the PipeReader that there's no more data coming
                writer.Complete();
                DisposeClient(clientManager);
            }
            catch (SocketException so_ex)
            {
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + so_ex.ToString());
                }

                DisposeClient(clientManager);
            }
            catch (Exception e)
            {
                var clientIsDisposed = clientManager.IsDisposed;
                DisposeClient(clientManager);

                if (!clientIsDisposed)
                {
                    AppUtil.LogEvent(e.ToString(), EventLogEntryType.Error);
                }

                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.LogClientActivity("ConMgr.RecvClbk", "Error :" + e.ToString());
                }
                if (SocketServer.Logger.IsErrorLogsEnabled)
                {
                    SocketServer.Logger.NCacheLog.Error("ConnectionManager.ReceiveCallback", clientManager.ToString() + " Error " + e.ToString());
                }

                try
                {
                    if (Management.APILogging.APILogManager.APILogManger != null && Management.APILogging.APILogManager.EnableLogging)
                    {
                        APILogItemBuilder log = new APILogItemBuilder();
                        log.GenerateConnectionManagerLog(clientManager, e.ToString());
                    }
                }
                catch
                {
                }
            }
            finally
            {
                //  clientManager.StopCommandExecution();
                if (ServerMonitor.MonitorActivity)
                {
                    ServerMonitor.StopClientActivity(clientManager.ClientID);
                }
            }
        }
예제 #15
0
        /// <summary>
        /// UploadMDMDealerCreationImage
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public JsonResponse <string> UploadMDMDealerCreationImage(Stream image)
        {
            JsonResponse <string> response = new JsonResponse <string>();

            try
            {
                ExceptionEngine.AppExceptionManager.Process(() =>
                {
                    var parser              = new MultipartFormDataParser(image);
                    string apiKey           = parser.Parameters["APIKey"].Data;
                    string apiToken         = parser.Parameters["APIToken"].Data;
                    string userid           = parser.Parameters["userid"].Data;
                    DealerCreationBO dealer = new DealerCreationBO();
                    int dealerCreationID    = Convert.ToInt32(parser.Parameters["dealerCreationID"].Data);

                    MDMDealerCreationBO dealerMDM = new MDMDealerCreationBO();
                    bool isValid = SystemBusinessInstance.IsValidServiceUser(apiKey, apiToken, userid);
                    if (isValid)
                    {
                        FileStream fileData  = null;
                        MemoryStream ms      = null;
                        int counter          = 0;
                        string fileDirectory = AppUtil.GetUploadDirectory(AspectEnums.ImageFileTypes.DealerCreation);

                        foreach (var file in parser.Files)
                        {
                            string filename = file.FileName;
                            if (Directory.Exists(fileDirectory))
                            {
                                string newFileName      = AppUtil.GetUniqueKey().ToUpper() + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("/", "") + counter.ToString() + ".jpeg";
                                string uploadedFileName = fileDirectory + @"\" + newFileName;
                                #region Step 1: Save Image
                                byte[] arrBite;
                                using (ms = new MemoryStream())
                                {
                                    file.Data.CopyTo(ms);
                                    arrBite = ms.ToArray();
                                    if (MimeType.GetMimeType(arrBite, filename))
                                    {
                                        using (fileData = new FileStream(uploadedFileName, FileMode.Create, FileAccess.Write, FileShare.None))
                                        {
                                            ms.Position = 0;
                                            if (ms.Length != 0)
                                            {
                                                ms.CopyTo(fileData);
                                            }
                                            file.Data.Close();
                                            if (ms != null)
                                            {
                                                ms.Close();
                                                ms.Dispose();
                                            }
                                        }
                                        switch (filename)
                                        {
                                        case "ContactPersonPhoto": dealer.CONTACTPERSONPHOTO = newFileName; dealerMDM.ByteCONTACTPERSONPHOTO = arrBite; break;

                                        case "GSBPhoto": dealer.GSBPHOTO = newFileName; dealerMDM.ByteGSBPHOTO = arrBite; break;

                                        case "OwnerPhoto": dealer.OWNERPHOTO = newFileName; dealerMDM.ByteOWNERPHOTO = arrBite; break;

                                        case "PanPhoto": dealer.PANPHOTO = newFileName; dealerMDM.BytePANPHOTO = arrBite; break;

                                        case "Tinphoto": dealer.TINPHOTO = newFileName; dealerMDM.ByteTINPHOTO = arrBite; break;
                                        }
                                    }
                                    else
                                    {
                                        file.Data.Close();
                                        if (ms != null)
                                        {
                                            ms.Close();
                                            ms.Dispose();
                                        }
                                        response.Message = "Not a valid image type";
                                        return;
                                        //throw new System.Security.SecurityException("Not a valid image type");
                                    }
                                }
                                #endregion
                            }
                        }
                        #region Step 2: Save the Content
                        response.IsSuccess = StoreBusinessInstance.PhotoMDMDealerCreation(dealer, dealerCreationID);
                        //var dealerDBData = StoreBusinessInstance.GetDealerCreationData(dealerCreationID);
                        //dealerDBData.ByteCONTACTPERSONPHOTO = dealerMDM.ByteCONTACTPERSONPHOTO;
                        #region Filldata for dealercreation request in MDM
                        var tempCONTACTPERSONPHOTO = dealerMDM.ByteCONTACTPERSONPHOTO;
                        var tempGSBPHOTO           = dealerMDM.ByteGSBPHOTO;
                        var tempOWNERPHOTO         = dealerMDM.ByteOWNERPHOTO;
                        var tempPANPHOTO           = dealerMDM.BytePANPHOTO;
                        var tempTINPHOTO           = dealerMDM.ByteTINPHOTO;

                        EntityMapper.Map(StoreBusinessInstance.GetDealerCreationData(dealerCreationID), dealerMDM);
                        dealerMDM.ByteCONTACTPERSONPHOTO = tempCONTACTPERSONPHOTO;
                        dealerMDM.ByteGSBPHOTO           = tempGSBPHOTO;
                        dealerMDM.ByteOWNERPHOTO         = tempOWNERPHOTO;
                        dealerMDM.BytePANPHOTO           = tempPANPHOTO;
                        dealerMDM.ByteTINPHOTO           = tempTINPHOTO;
                        MDMServiceInstance.CreateDealer(dealerMDM);
                        #endregion
                        #endregion
                    }
                    else
                    {
                        throw new System.Security.SecurityException(Messages.ApiAccessDenied);
                    }
                }, AspectEnums.ExceptionPolicyName.ServiceExceptionPolicy.ToString());
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }
            return(response);
        }
예제 #16
0
        private void CheckStatus(SLMDBEntities slmdb, kkslm_tr_lead lead, BatchCARInsertStatusData data, string batchCode)
        {
            try
            {
                string newExternalSystem        = "";
                string newExternalStatus        = "";
                string newExternalSubStatus     = "";
                string newExternalSubStatusDesc = "";
                string oldExternalSystem        = "";
                string oldExternalStatus        = "";
                string oldExternalSubStatus     = "";
                string oldExternalSubStatusDesc = "";
                string slmOldStatus             = "";

                slmOldStatus             = lead.slm_Status;
                oldExternalSystem        = lead.slm_ExternalSystem;
                oldExternalStatus        = lead.slm_ExternalStatus;
                oldExternalSubStatus     = string.IsNullOrEmpty(lead.slm_ExternalSubStatus) ? null : lead.slm_ExternalSubStatus;
                oldExternalSubStatusDesc = lead.slm_ExternalSubStatusDesc;

                if (string.IsNullOrEmpty(data.OwnerSystemCode))
                {
                    throw new Exception("System Name in view is null or blank");
                }

                string slmNewStatus = GetSlmStatusCode(slmdb, data.OwnerSystemCode, data.Status, "", lead.slm_Product_Id);
                if (slmNewStatus == "")
                {
                    throw new Exception("Cannot find slmStatusCode from the specified " + data.Status + " mapping statusCode=" + data.Status + ", slmProductId=" + lead.slm_Product_Id);
                }

                newExternalSystem        = data.OwnerSystemCode.Trim().ToUpper();
                newExternalStatus        = data.Status;
                newExternalSubStatus     = data.Status;
                newExternalSubStatusDesc = data.StatusName;

                if (slmNewStatus != slmOldStatus || newExternalStatus != oldExternalStatus || newExternalSubStatus != oldExternalSubStatus || newExternalSystem != oldExternalSystem)
                {
                    DateTime updateDate = DateTime.Now;

                    kkslm_tr_activity activity = new kkslm_tr_activity()
                    {
                        slm_TicketId           = data.RefSystemId,
                        slm_OldStatus          = slmOldStatus,
                        slm_NewStatus          = slmNewStatus,
                        slm_CreatedBy          = "SYSTEM",
                        slm_CreatedBy_Position = null,
                        slm_CreatedDate        = updateDate,
                        slm_Type                      = "09",
                        slm_SystemAction              = data.OwnerSystemCode.Trim().ToUpper(), //System ที่เข้ามาทำ action (18/10/2017)
                        slm_SystemActionBy            = "SLM",                                 //action เกิดขึ้นที่ระบบอะไร (18/10/2017)
                        slm_ExternalSystem_Old        = oldExternalSystem,
                        slm_ExternalStatus_Old        = oldExternalStatus,
                        slm_ExternalSubStatus_Old     = oldExternalSubStatus,
                        slm_ExternalSubStatusDesc_Old = oldExternalSubStatusDesc,
                        slm_ExternalSystem_New        = newExternalSystem,
                        slm_ExternalStatus_New        = newExternalStatus,
                        slm_ExternalSubStatus_New     = newExternalSubStatus,
                        slm_ExternalSubStatusDesc_New = newExternalSubStatusDesc
                    };
                    slmdb.kkslm_tr_activity.AddObject(activity);

                    DateTime StatusDateTime = data.StatusDateTime.ConvertStringToStatusDateTime();

                    AppUtil.CalculateTotalSLA(slmdb, lead, activity, StatusDateTime, logfilename, batchCode);
                    lead.slm_Status           = slmNewStatus;
                    lead.slm_StatusDate       = StatusDateTime;
                    lead.slm_StatusDateSource = StatusDateTime;
                    lead.slm_Counting         = 0;
                    lead.slm_UpdatedBy        = "SYSTEM";
                    lead.slm_UpdatedDate      = updateDate;

                    lead.slm_ExternalSystem = newExternalSystem;
                    lead.slm_ExternalStatus = newExternalStatus;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #17
0
 private void BuildModelCombo(DropDownList cmbB, DropDownList cmbM, string defaulttxt)
 {
     AppUtil.BuildCombo(cmbM, SlmScr039Biz.GetModelDataList(cmbB.SelectedValue), defaulttxt);
 }
예제 #18
0
        public bool UpdateBatchCARInsertStatus(string batchCode)
        {
            Int64 batchMonitorId = 0;
            int   totalRecord    = 0;
            int   totalSuccess   = 0;
            int   totalFail      = 0;
            bool  ret            = false;

            try {
                ErrorStep = "Set start time";
                _logger.Info("I:-- Start Batch --:--UpdateBatchCARInsertStatus--" + batchCode);
                batchMonitorId = BizUtil.SetStartTime(batchCode);

                ErrorStep = "GetFileList";
                _logger.Info(_logMsg.Clear().Add("GetFileList", batchCode).ToInputLogString());
                //1. ดึง List ของไฟล์ที่มีใน FTPs โดยเอาไฟล์ที่สร้างมาตั้งแต่ เมื่อวาน วันนี้ และวันพรุ่งนี้ โดยดูจาก FileName
                IEnumerable <string> files = GetFileList();

                if (files.Count <string>() > 0)
                {
                    ret = true;

                    ErrorStep = "Validate Text History " + files.Count <string>().ToString() + " file(s)";
                    //2. เก็บชื่อไฟล์ลง DB เพื่อเตรียมทำการ Process กรณีมีไฟล์อยู่แล้ว ก็ไม่ต้องทำซ้ำ
                    List <kkslm_ext_sys_status_cbs_file> fileList = new List <kkslm_ext_sys_status_cbs_file>();
                    foreach (string f in files)
                    {
                        FileInfo fInfo = new FileInfo(f);
                        ErrorStep = "Validate Text History " + fInfo.Name;
                        _logger.Info(_logMsg.Clear().Add("Validate Text History", fInfo.Name).ToInputLogString());

                        SLMDBEntities slmdb = AppUtil.GetSlmDbEntities();
                        var           file  = checkFileHistory(fInfo.Name, slmdb);
                        if (file != null)
                        {
                            file.kkslm_filename          = fInfo.Name;
                            file.kkslm_filepath          = f;
                            file.kkslm_file_created_date = fInfo.CreationTime;
                            file.kkslm_file_process_time = DateTime.Now;
                            file.kkslm_process_status    = AppConstant.InProcess;

                            if (file.kkslm_ext_sys_status_cbs_file_id == 0)
                            {
                                slmdb.kkslm_ext_sys_status_cbs_file.AddObject(file);
                                _logger.Info(_logMsg.Clear().Add("Process New File", fInfo.Name).ToInputLogString());
                            }
                            slmdb.SaveChanges();
                            fileList.Add(file);
                        }
                    }

                    foreach (kkslm_ext_sys_status_cbs_file file in fileList)
                    {
                        //3. เช็ค Format TextFile ทุก Record
                        ErrorStep = "Validate Text Format " + file.kkslm_filename;
                        _logger.Info(_logMsg.Clear().Add("Validate Text Format", file.kkslm_filename).ToInputLogString());
                        ValidateTextfileData validTextFormat = ValidateTextFileFormat(file.kkslm_filepath);
                        if (validTextFormat.IsValid == false)
                        {
                            ErrorStep = "Invalid Textfile " + file.kkslm_filename;
                            _logger.Error(_logMsg.Clear().Add("Invalid Textfile", file.kkslm_filename).Add("ErrorMessage", validTextFormat.ErrorMessage).ToInputLogString());
                            UpdateFileStatus(file.kkslm_ext_sys_status_cbs_file_id, AppConstant.Fail, "Invalid Textfile " + file.kkslm_filename + Environment.NewLine + validTextFormat.ErrorMessage);
                            break;
                        }

                        //4. Process Text File ตาม Requirement
                        ErrorStep = "GetEBatchCARInsertStatusList " + file.kkslm_filename;
                        _logger.Info(_logMsg.Clear().Add("GetEBatchCARInsertStatusList", "").Add("FileName", file.kkslm_filename).ToInputLogString());
                        var lists = GetEBatchCARInsertStatusList(file.kkslm_filepath, file.kkslm_ext_sys_status_cbs_file_id);
                        if (lists != null)
                        {
                            bool isSuccess = true;
                            totalRecord = lists.Count;
                            foreach (BatchCARInsertStatusData data in lists)
                            {
                                try
                                {
                                    SLMDBEntities slmdb = new SLMDBEntities();
                                    using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions {
                                        IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted
                                    }))
                                    {
                                        ErrorStep = "Find TicketId = " + data.RefSystemId;
                                        var lead = slmdb.kkslm_tr_lead.Where(p => p.slm_ticketId == data.RefSystemId && p.is_Deleted == 0).FirstOrDefault();
                                        if (lead == null)
                                        {
                                            _logger.ErrorFormat("Ticket Id {0} not found in SLM", data.RefSystemId);
                                            throw new Exception("Ticket Id " + data.RefSystemId + " not found in SLM");
                                        }

                                        ErrorStep = "CheckStatus TicketId = " + data.RefSystemId;
                                        _logger.Info(_logMsg.Clear().Add("Check Ticket Status", " Ticket Id:" + data.RefSystemId));
                                        CheckStatus(slmdb, lead, data, batchCode);

                                        ErrorStep = "CheckPhoneCallHistory TicketId = " + data.RefSystemId;
                                        _logger.Info(_logMsg.Clear().Add("Check Phone Call History", " Ticket Id:" + data.RefSystemId));
                                        CheckPhoneCallHistory(slmdb, lead, data);

                                        slmdb.SaveChanges();

                                        totalSuccess += 1;
                                        _logger.Info(_logMsg.Clear().Add("TicketId", data.RefSystemId + ": SUCCESS").ToInputLogString());

                                        ts.Complete();
                                    }
                                }
                                catch (Exception ex)
                                {
                                    totalFail += 1;
                                    string message     = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                                    string errorDetail = "TicketId=" + data.RefSystemId + ", Error=" + message;

                                    BizUtil.InsertLog(batchMonitorId, data.RefSystemId, "", errorDetail);

                                    _logger.Error(_logMsg.Clear().Add("TicketId", data.ReferenceNo + ": FAIL").ToInputLogString());
                                }
                            }

                            ErrorStep = "Set end time";
                            BizUtil.SetEndTime(batchCode, batchMonitorId, AppConstant.Success, totalRecord, totalSuccess, totalFail);


                            //5. นำข้อมูลใน Text File เก็บลงใน Archives
                            int dataRow = 0;
                            ErrorStep = "InsertArchiveData";
                            _logger.Info(_logMsg.Clear().Add("InsertArchiveData", "TABLE : kkslm_ext_sys_status_cbs_file_data").ToInputLogString());
                            foreach (BatchCARInsertStatusData list in lists)
                            {
                                SLMDBEntities slmdb = new SLMDBEntities();
                                kkslm_ext_sys_status_cbs_file_data data = new kkslm_ext_sys_status_cbs_file_data
                                {
                                    kkslm_ext_sys_status_cbs_file_id = file.kkslm_ext_sys_status_cbs_file_id,
                                    kkslm_reference_code             = list.HeaderData.ReferenceCode,
                                    kkslm_file_name              = list.HeaderData.FileName,
                                    kkslm_create_date            = list.HeaderData.CreateDate,
                                    kkslm_current_sequence       = Convert.ToInt16(list.HeaderData.CurrentSequence),
                                    kkslm_total_sequence         = Convert.ToInt16(list.HeaderData.TotalSequence),
                                    kkslm_total_record           = Convert.ToInt16(list.HeaderData.TotalRecord),
                                    kkslm_system_code            = list.HeaderData.SystemCode,
                                    kkslm_reference_no           = list.ReferenceNo,
                                    kkslm_channel_id             = list.ChannelID,
                                    kkslm_status_date_time       = list.StatusDateTime,
                                    kkslm_subscription_id        = list.SubscriptionID,
                                    kkslm_subscription_cus_type  = list.SubscriptionCusType,
                                    kkslm_subscription_card_type = list.SubscriptionCardType,
                                    kkslm_owner_system_id        = list.OwnerSystemId,
                                    kkslm_owner_system_code      = list.OwnerSystemCode,
                                    kkslm_ref_system_id          = list.RefSystemId,
                                    kkslm_ref_system_code        = list.RefSystemCode,
                                    kkslm_status      = list.Status,
                                    kkslm_status_name = list.StatusName
                                };
                                dataRow += 1;

                                slmdb.kkslm_ext_sys_status_cbs_file_data.AddObject(data);
                                isSuccess = (slmdb.SaveChanges() > 0);
                                if (isSuccess == false)
                                {
                                    ErrorStep = "Error InsertArchiveData at row " + dataRow.ToString();
                                    break;
                                }
                            }

                            if (isSuccess == true)
                            {
                                ErrorStep = "MoveBatchFileToArchive";
                                _logger.Info(_logMsg.Clear().Add("MoveBatchFileToArchive", "Filename:" + file.kkslm_filename));
                                if (MoveBatchFileToArchive(file.kkslm_filepath) == true)
                                {
                                    ErrorStep = "UpdateSuccessStatus Filename:" + file.kkslm_filename;
                                    _logger.Info(_logMsg.Clear().Add("UpdateSuccessStatus", "Filename:" + file.kkslm_filename));
                                    UpdateFileStatus(file.kkslm_ext_sys_status_cbs_file_id, AppConstant.Success, "");
                                }
                            }
                        }
                    }

                    ErrorStep = "Send Mail";
                    SendMail(totalRecord);
                }
                else
                {
                    ret = false;
                }
            }
            catch (Exception ex) {
                _logger.Error("Exception occur:\n", ex);
                ret = false;
            }

            return(ret);
        }
예제 #19
0
        protected void imbEdit_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                txtConfigScriptId.Text = ((ImageButton)sender).CommandArgument;
                BindPopupProductCampaignCombo("edit");

                ConfigScriptBiz         biz  = new ConfigScriptBiz();
                ConfigProductScriptData data = biz.GetConfigScriptData(decimal.Parse(txtConfigScriptId.Text));

                if (data != null)
                {
                    if (!string.IsNullOrEmpty(data.ProductId))
                    {
                        rbProductPopup.Checked        = true;
                        rbProductPopup.Enabled        = false;
                        cmbProductPopup.Enabled       = false;
                        cmbProductPopup.SelectedIndex = cmbProductPopup.Items.IndexOf(cmbProductPopup.Items.FindByValue(data.ProductId));

                        rbCampaignPopup.Checked  = false;
                        rbCampaignPopup.Enabled  = false;
                        cmbCampaignPopup.Enabled = false;
                    }
                    if (!string.IsNullOrEmpty(data.CampaignId))
                    {
                        rbCampaignPopup.Checked        = true;
                        rbCampaignPopup.Enabled        = false;
                        cmbCampaignPopup.Enabled       = false;
                        cmbCampaignPopup.SelectedIndex = cmbCampaignPopup.Items.IndexOf(cmbCampaignPopup.Items.FindByValue(data.CampaignId));

                        rbProductPopup.Checked  = false;
                        rbProductPopup.Enabled  = false;
                        cmbProductPopup.Enabled = false;
                    }
                    if (!string.IsNullOrEmpty(data.DataType))
                    {
                        cmbDataTypePopup.SelectedIndex = cmbDataTypePopup.Items.IndexOf(cmbDataTypePopup.Items.FindByValue(data.DataType));
                    }

                    txtSubjectPopup.Text = data.Subject;
                    txtDetailPopup.Text  = data.Detail;
                    txtSeqPopup.Text     = data.Seq != null?data.Seq.Value.ToString() : "";

                    if (data.IsDeleted != null)
                    {
                        if (data.IsDeleted.Value)
                        {
                            rdActivePopup.Checked   = false;
                            rdNoActivePopup.Checked = true;
                        }
                        else
                        {
                            rdActivePopup.Checked   = true;
                            rdNoActivePopup.Checked = false;
                        }
                    }

                    upPopup.Update();
                    mpePopup.Show();
                }
                else
                {
                    ClearPopupControl();
                    upPopup.Update();
                    AppUtil.ClientAlert(Page, "ไม่พบข้อมูล ConfigScriptId " + txtConfigScriptId.Text + " ในระบบ");
                }
            }
            catch (Exception ex)
            {
                string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                _log.Error(message);
                AppUtil.ClientAlert(Page, message);
            }
        }
예제 #20
0
    public IEnumerator LightUp()
    {
        // 対象オブジェクトにヒットした回数を取得
        int hitCount = 0;

        for (int i = 0; i < hitArray.Length - 1; ++i)
        {
            string hitName    = hitArray[i].collider.name;
            string targetName = moveDataArray[i + 1][0];
            Debug.Log(hitName);
            if (hitName == targetName && hitCount >= i)
            {
                hitCount += 1;
            }
        }

        // 光を伸ばす場所をRayCastから取得
        Vector3[] linePointArray = new Vector3[hitArray.Length + 1];
        var       data           =
            from x in moveDataArray
            select x[0];

        string[] nameArray = data.ToArray();
        for (int i = 0; i < linePointArray.Length; ++i)
        {
            if (i == 0)
            {
                linePointArray[i] = transform.position;
            }
            else
            {
                if (nameArray.Contains(hitArray[i - 1].collider.name) || hitArray[i - 1].collider.name == "HitPlace")
                {
                    linePointArray[i] = hitArray[i - 1].transform.position;
                }
                else
                {
                    linePointArray[i] = hitArray[i - 1].point;
                }
            }
        }

        // 徐々に光を伸ばしていく
        DG.Tweening.Tween[] tweenArray = new DG.Tweening.Tween[hitCount + 1];
        lr.SetPosition(0, linePointArray[0]);   // 初期設定
        lr.positionCount += 1;
        int lineNum = 1;

        lr.SetPosition(lineNum, linePointArray[0]);
        for (int i = 0; i < tweenArray.Length; ++i) // 線を伸ばすためのTweenの配列を作成
        {
            int index = i;                          // なぜかtweenの中ではインクリメントが使用できなかったので新しくint型変数を作成
            tweenArray[i] = AppUtil.DOTO(
                () => linePointArray[index],
                v =>
            {
                linePointArray[index] = v;
                lr.SetPosition(lineNum, linePointArray[index]);
            },
                linePointArray[index + 1],
                0.5f,
                "OutExpo",
                0.5f
                );
            if (i < tweenArray.Length - 1)     // 次のラインのセッティング
            {
                AppUtil.SetOnCompleteCallback(tweenArray[i], () => {
                    lineNum++;
                    lr.positionCount += 1;
                    lr.SetPosition(lineNum, linePointArray[index + 1]);
                    lr.endWidth += 0.3f;
                });
            }
        }

        AppUtil.SetOnCompleteCallback(AppUtil.DOSequence(tweenArray, 0f, 0f, 1), () => {  // 線を伸ばす&ゴール判定
            if (hitCount == nameArray.Length - 1 && hitArray[hitArray.Length - 1].collider.name == "HitPlace")
            {
                Debug.Log("goal");
            }
        });

        yield break;
    }
예제 #21
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string desc;
                if (LeadBiz.CheckHeadStaff(txtStaffId.Text, cmbHeadStaffId.SelectedValue.Trim(), out desc))
                {
                    AppUtil.ClientAlert(Page, "ไม่สามารถเปลี่ยนหัวหน้างานได้เนื่องจาก " + txtStaffNameTH.Text + "เป็นหัวหน้างาน" + cmbHeadStaffId.Text.Trim());
                    return;
                }
                //เช็ก Lead on hand ในส่วนของ slm
                if (cmbBranchCode.SelectedItem.Value != txtOldBranchCode.Text.Trim())
                {
                    if (LeadBiz.CheckExistLeadOnHand(txtUsername.Text.Trim(), txtEmpCode.Text.Trim()) == false)
                    {
                        SaveData();
                    }
                    else
                    {
                        AppUtil.ClientAlert(Page, "ไม่สามารถเปลี่ยนข้อมูลสาขาได้ เนื่องจากยังมีงานค้างอยู่");
                        return;
                    }
                }
                else if (txtOldIsDeleted.Text.Trim() != txtNewIsDeleted.Text.Trim())
                {
                    if (LeadBiz.CheckExistLeadOnHand(txtUsername.Text.Trim(), txtEmpCode.Text.Trim()) == false)
                    {
                        SaveData();
                    }
                    else
                    {
                        AppUtil.ClientAlert(Page, "ไม่สามารถเปลี่ยนสถานะพนักงานได้ เนื่องจากยังมีงานค้างอยู่");
                        return;
                    }
                }
                else if (cmbCocTeam.SelectedItem.Value != txtCurrentCocTeam.Text.Trim())
                {
                    //if (LeadBiz.CheckLastOwnerOnHand(txtEmpCode.Text.Trim()) == false)
                    //{
                    //    SaveData();
                    //}
                    //else
                    //{
                    //    AppUtil.ClientAlert(Page, "ไม่สามารถเปลี่ยนทีมพนักงานได้ เนื่องจากยังมีงานค้างอยู่");
                    //}

                    List <LeadDataPopupMonitoring> list = DoGetJobOnHandList();
                    if (list.Count > 0)
                    {
                        AppUtil.ClientAlert(Page, "ไม่สามารถเปลี่ยนทีมพนักงานได้ เนื่องจากยังมีงานค้างอยู่");
                        return;
                    }
                    else
                    {
                        string oldCocTeam = txtCurrentCocTeam.Text.Trim();
                        SaveData();

                        _log.Debug("==================== Start Log ====================");
                        _log.Debug("Action: Change COC Team");
                        _log.Debug("ActionBy: " + HttpContext.Current.User.Identity.Name);
                        _log.Debug("DateTime: " + DateTime.Now.ToString("dd-MM-") + DateTime.Now.Year.ToString() + " " + DateTime.Now.ToString("HH:mm:ss"));
                        _log.Debug("Username: "******"TeamFrom: " + oldCocTeam);
                        _log.Debug("TeamTo: " + cmbCocTeam.SelectedItem.Value);
                        _log.Debug("==================== End Log =====================");
                        _log.Debug(" ");
                    }
                }
                else
                {
                    SaveData();
                }
            }
            catch (Exception ex)
            {
                string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                _log.Debug(message);
                AppUtil.ClientAlert(Page, message);
            }
        }
예제 #22
0
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="absoluteTime">absolute time when this hint expires</param>
 public FixedExpiration(DateTime absoluteTime)
 {
     _hintType     = ExpirationHintType.FixedExpiration;
     _absoluteTime = AppUtil.DiffSeconds(absoluteTime);
     _milliseconds = AppUtil.DiffMilliseconds(absoluteTime);
 }
예제 #23
0
        /// <summary>
        /// Scans the registry and locates the configuration file.
        /// </summary>
        static public void ScanConfiguration()
        {
            string REGKEY = @"Software\Alachisoft\NCache";

            try
            {
                AppUtil myUtil = new AppUtil();
                s_configDir = AppUtil.InstallDir;
                if (s_configDir == null || s_configDir.Length == 0)
                {
                    throw new ManagementException("Missing installation folder information: ROOTKEY= " + RegHelper.ROOT_KEY);
                }

                s_configDir = Path.Combine(s_configDir, DIRNAME);
                if (!Directory.Exists(s_configDir))
                {
                    Directory.CreateDirectory(s_configDir);
                }
                s_configFileName = Path.Combine(s_configDir, FILENAME);



                if (!File.Exists(s_configFileName))
                {
                    /// Save a dummy configuration.
                    SaveConfiguration(null);
                }
            }
            catch (ManagementException)
            {
                s_configFileName = "";
                throw;
            }
            catch (Exception e)
            {
                s_configFileName = "";
                throw new ManagementException(e.Message, e);
            }

            try
            {
                object v = RegHelper.GetRegValue(REGKEY, "NCacheTcp.Port", 0);
                if (v != null)
                {
                    int port = Convert.ToInt32(v);
                    if (port >= System.Net.IPEndPoint.MinPort &&
                        port <= System.Net.IPEndPoint.MaxPort)
                    {
                        s_ncacheTcpPort = port;
                    }
                }
            }
            catch (FormatException) { }
            catch (OverflowException) { }


            try
            {
                object v = RegHelper.GetRegValue(REGKEY, "Http.Port", 0);
                if (v != null)
                {
                    int port = Convert.ToInt32(v);
                    if (port >= System.Net.IPEndPoint.MinPort &&
                        port <= System.Net.IPEndPoint.MaxPort)
                    {
                        s_httpPort = port;
                    }
                }
            }
            catch (FormatException) { }
            catch (OverflowException) { }
            try
            {
                object v = RegHelper.GetRegValue(REGKEY, "IPC.PortName", 0);
                if (v != null)
                {
                    string portName = Convert.ToString(v);
                    if (portName != null)
                    {
                        s_ipcPortName = portName;
                    }
                }
            }
            catch (System.ArgumentException) { }
            catch (OverflowException) { }
        }
예제 #24
0
 protected override void OnInit(EventArgs e)
 {
     base.OnInit(e);
     AppUtil.SetNotThaiCharacter(txtEmailTo);
 }
예제 #25
0
 /// <summary>
 /// Resets the time to live counter.
 /// </summary>
 internal override bool Reset(CacheRuntimeContext context)
 {
     _lastTimeStamp = AppUtil.DiffSeconds(DateTime.Now);
     return(base.Reset(context));
 }
예제 #26
0
        private bool SendOTPAndEmail(int UserId)
        {
            bool IsSuccess = false;

            #region Prepare OTP Data

            string UniqueString = AppUtil.GetUniqueGuidString();
            string OTPString    = AppUtil.GetUniqueRandomNumber(100000, 999999); // Generate a Six Digit OTP
            OTPBO  objOTP       = new OTPBO()
            {
                GUID = UniqueString, OTP = OTPString, CreatedDate = DateTime.Now, UserID = UserId, Attempts = 0
            };

            #endregion
            try
            {
                if (SecurityBusinessInstance.SaveOTP(objOTP))
                {
                    #region Send Email Servie and OTP
                    //string hostName = AppUtil.GetAppSettings(AspectEnums.ConfigKeys.HostName);
                    string resetUrl         = AppUtil.GetAppSettings(AspectEnums.ConfigKeys.ForgotPasswordURL);
                    string PasswordResetURL = resetUrl + UniqueString;
                    //string PasswordResetURL = Request.Url.AbsoluteUri.Split('/')[0] + Request.Url.AbsoluteUri.Split('/')[1]  + resetUrl + "?id=" + UniqueString;
                    EmailNotificationService eNotification = new EmailNotificationService();
                    var userProfile = UserBusinessInstance.DisplayUserProfile(UserId); // empBusinessInstance.DisplayEmpProfile(EmpId);
                    TemplateMasterBO            objEmailTemplate = EmailBusinessInstance.GetEmailTemplate((int)AspectEnums.EmailTemplateCode.ResetPassword);
                    List <TemplateMergeFieldBO> mergeFields      = EmailBusinessInstance.GetEmailMergeFields(objEmailTemplate.TemplateID);
                    foreach (var field in mergeFields)
                    {
                        if (field.SRC_FIELD == "{{PASSWORDRESETURL}}")
                        {
                            objEmailTemplate.TemplateContent = eNotification.FindReplace(objEmailTemplate.TemplateContent, "{{PASSWORDRESETURL}}", PasswordResetURL);
                        }

                        else if (field.SRC_FIELD == "{{TONAME}}")
                        {
                            objEmailTemplate.TemplateContent = eNotification.FindReplace(objEmailTemplate.TemplateContent, field.SRC_FIELD, userProfile.FirstName + " " + userProfile.LastName);
                        }
                    }
                    objEmailTemplate.TemplateContent = eNotification.FindReplace(objEmailTemplate.TemplateContent, "{{COMPANY}}", AppUtil.GetAppSettings(AspectEnums.ConfigKeys.CompanyName));


                    EmailServiceDTO emailService = new EmailServiceDTO();
                    emailService.Priority     = 1;
                    emailService.CreatedBy    = userProfile.UserID;
                    emailService.IsHtml       = true;
                    emailService.ToName       = userProfile.FirstName + " " + userProfile.LastName;
                    emailService.Body         = objEmailTemplate.TemplateContent;
                    emailService.Status       = (int)AspectEnums.EmailStatus.Pending;
                    emailService.ToEmail      = userProfile.Email;
                    emailService.FromName     = AppUtil.GetAppSettings(AspectEnums.ConfigKeys.FromName);
                    emailService.FromEmail    = AppUtil.GetAppSettings(AspectEnums.ConfigKeys.FromEmail);
                    emailService.Subject      = eNotification.FindReplace(objEmailTemplate.TemplateSubject, "{{COMPANY}}", AppUtil.GetAppSettings(AspectEnums.ConfigKeys.CompanyName));
                    emailService.IsAttachment = false;
                    emailService.TemplateID   = objEmailTemplate.TemplateID;
                    emailBusinessInstance.InsertEmailRecord(emailService);

                    eNotification.SendEmailNotification(emailService, objEmailTemplate);
                    IsSuccess = true;

                    #endregion
                }
            }
            catch (Exception ex)
            {
                IsSuccess = false;
            }


            return(IsSuccess);
        }
예제 #27
0
        //删除按钮点击事件
        void btnDeviceBaseDel_Click(object sender, EventArgs e)
        {
            TreeNode selectedNode = treeViewDeviceBase.SelectedNode;

            if ((selectedNode != null) && (selectedNode != rootNodeDeviceBase))                         //不能删除空节点
            {
                if ((selectedNode != rootNodeDeviceBase) && (selectedNode != rootNodeDeviceBase))       //不能删除根节点 和 二级子节点
                {
                    string path = ((string[])selectedNode.Tag)[0];
                    if (Directory.Exists(path))                                 //如果选中的是目录, 则删除路径就是当前目录
                    {
                        if (MessageBox.Show("您确定要删除“" + selectedNode.Text + "”目录吗?", "删除文件提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                        {
                            try
                            {
                                //写入按钮点击记录到日志文件中
                                worklog.LogQueue_Enqueue(LogCommand.getButtonClickRecord(BTNPANEL.DeviceBasePanel, (int)BtnOfDeviceBasePanel.DeleteBtn, ((string[])selectedNode.Tag)[0]));
                                Directory.Delete(((string[])selectedNode.Tag)[0], true);
                                Directory.Delete(((string[])selectedNode.Tag)[1], true);
                                treeViewDeviceBase.Nodes.Remove(selectedNode);
                            }
                            catch (Exception ex) { Console.WriteLine(ex.Message); log.Info(AppUtil.getExceptionInfo(ex)); }
                        }
                    }
                    else                                                                        //如果选中的是文件, 则删除路径就是当前文件的目录
                    {
                        if (MessageBox.Show("您确定要删除“" + selectedNode.Text + "”文件吗?", "删除文件提示", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                        {
                            try
                            {
                                //写入按钮点击记录到日志文件中
                                worklog.LogQueue_Enqueue(LogCommand.getButtonClickRecord(BTNPANEL.DeviceBasePanel, (int)BtnOfDeviceBasePanel.DeleteBtn, ((string[])selectedNode.Tag)[0]));
                                File.Delete(((string[])selectedNode.Tag)[0]);
                                Directory.Delete(((string[])selectedNode.Tag)[1], true);
                                treeViewDeviceBase.Nodes.Remove(selectedNode);
                            }
                            catch (Exception ex) { Console.WriteLine(ex.Message); log.Info(AppUtil.getExceptionInfo(ex)); }
                        }
                    }
                }
            }
        }
예제 #28
0
        /// <summary>
        /// Upload Geo tag Image through Stream
        /// </summary>
        /// <param name="image">geo image stream</param>
        /// <returns>returns image name if successfully uploaded else blank</returns>
        //[SecureOperation]
        public JsonResponse <string> UploadGeoImageStream(Stream image)
        {
            JsonResponse <string> response = new JsonResponse <string>();

            try
            {
                ExceptionEngine.AppExceptionManager.Process(() =>
                {
                    var parser = new MultipartFormDataParser(image);

                    var StoreID    = Convert.ToInt32(parser.Parameters["StoreID"].Data);
                    var Latitude   = Convert.ToString(parser.Parameters["Latitude"].Data);
                    var Longitude  = Convert.ToString(parser.Parameters["Longitude"].Data);
                    var UserID     = Convert.ToInt64(parser.Parameters["userid"].Data);
                    var UserOption = parser.Parameters["UserOption"].Data;

                    bool?UserOptionBool = null;
                    if (UserOption != null && UserOption != "null")
                    {
                        UserOptionBool = Convert.ToBoolean(UserOption);
                    }
                    // Files are stored in a list:
                    //var file = parser.Files.First();
                    // Loop through all the files
                    int counter          = 0;
                    string fileDirectory = string.Empty;
                    fileDirectory        = AppUtil.GetUploadDirectory(AspectEnums.ImageFileTypes.Store);
                    string newFileName   = null;
                    foreach (var file in parser.Files)
                    {
                        string filename = file.FileName;
                        if (Directory.Exists(fileDirectory))
                        {
                            FileStream fileData     = null;
                            newFileName             = AppUtil.GetUniqueKey().ToUpper() + DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("/", "") + counter.ToString() + ".jpeg";
                            string uploadedFileName = fileDirectory + @"\" + newFileName;

                            #region Step 1: Save Image
                            //fileData = new FileStream(file.Data);
                            using (fileData = new FileStream(uploadedFileName, FileMode.Create, FileAccess.Write, FileShare.None))
                            {
                                file.Data.CopyTo(fileData);
                                // fileData.Close();
                                file.Data.Close();
                                //fileData.Write(file.Data);
                            }

                            #endregion
                        }


                        //  response.SingleResult = newFileName;
                    }
                    #region Step 2: Save the Content
                    StoreGeoTagBO storeGeoTagBO = new StoreGeoTagBO()
                    {
                        StoreID         = StoreID,
                        UserID          = UserID,
                        Lattitude       = Latitude,
                        Longitude       = Longitude,
                        PictureFileName = newFileName,
                        UserOption      = UserOptionBool
                    };
                    int dataCount = StoreBusinessInstance.SubmitStoreGeoTag(storeGeoTagBO);
                    if (dataCount > 0)
                    {
                        response.IsSuccess = true;
                    }

                    #endregion


                    response.IsSuccess = true;
                }, AspectEnums.ExceptionPolicyName.ServiceExceptionPolicy.ToString());
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }
            return(response);
        }
예제 #29
0
        //添加按钮点击事件
        void btnDeviceBaseAdd_Click(object sender, EventArgs e)
        {
            TreeNode selectedNode = treeViewDeviceBase.SelectedNode;
            TreeNode ParentNode   = null;
            string   savePath     = null;

            if (selectedNode != null)                           //选中了节点
            {
                string path = ((string[])selectedNode.Tag)[0];  //源文件全路径
                // 若选中的节点在同步库中, 则将其改为本地库
                if (path.Contains("\\res\\DeviceBase\\SrcFiles\\同步库"))
                {
                    foreach (TreeNode node in rootNodeDeviceBase.Nodes)
                    {
                        if (node.Text == "本地库")
                        {
                            ParentNode = node;
                        }
                    }
                    savePath = ((string[])rootNodeDeviceBase.Tag)[0] + "\\本地库";
                }
                else
                {
                    if (Directory.Exists(path))
                    {
                        savePath = path; ParentNode = selectedNode;
                    }                                                                                                                                           //如果选中的是目录, 则保存路径就是当前目录
                    else
                    {
                        savePath = ((string[])selectedNode.Parent.Tag)[0]; ParentNode = selectedNode.Parent;
                    }                                                                                                                   //如果选中的是文件, 则保存路径就是当前文件的目录
                }
            }
            else                                                                //如果没有选中, 则保存路径就是本地库目录
            {
                foreach (TreeNode node in rootNodeDeviceBase.Nodes)
                {
                    if (node.Text == "本地库")
                    {
                        ParentNode = node;
                    }
                }
                savePath = ((string[])rootNodeDeviceBase.Tag)[0] + "\\本地库";
            }

            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter           = "Word|*.docx|Word|*.doc";
            openFileDialog.FilterIndex      = 0;
            openFileDialog.RestoreDirectory = true;                                     //保存对话框是否记忆上次打开的目录
            openFileDialog.Title            = "添加文件";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (AppUtil.CopyFileTo(openFileDialog.FileName, savePath))                      //若拷贝文件成功
                {
                    string   filePath    = savePath + "\\" + Path.GetFileName(openFileDialog.FileName);
                    TreeNode subFileNode = new TreeNode(Path.GetFileNameWithoutExtension(filePath));
                    subFileNode.Tag                = GetTagPath(Path.GetFullPath(filePath));
                    subFileNode.ImageIndex         = 1;
                    subFileNode.SelectedImageIndex = 1;
                    ParentNode.Nodes.Add(subFileNode);
                    //写入按钮点击记录到日志文件中
                    worklog.LogQueue_Enqueue(LogCommand.getButtonClickRecord(BTNPANEL.DeviceBasePanel, (int)BtnOfDeviceBasePanel.AddBtn, openFileDialog.FileName));
                }
            }
        }
예제 #30
0
파일: Log.cs 프로젝트: nonomal/NCache
        /// <summary>
        /// Start the cache logging functionality.
        /// </summary>
        internal static NewTrace Initialize(IDictionary properties, CacheRuntimeContext context, CacheInfo cacheInfo, bool isStartedAsMirror, bool inproc)
        {
            NewTrace nTrace = new NewTrace();

            if (properties.Contains("enabled"))
            {
                bool enabled = Convert.ToBoolean(properties["enabled"]);

                if (!enabled)
                {
                    nTrace.IsFatalEnabled = nTrace.IsErrorEnabled = false;
                    nTrace.IsWarnEnabled  = nTrace.isInfoEnabled = false;
                    nTrace.IsDebugEnabled = false;
                    return(nTrace);
                }
            }

            try
            {
                string cache_name = cacheInfo.Name;
                if (cacheInfo.CurrentPartitionId != null && cacheInfo.CurrentPartitionId != string.Empty)
                {
                    cache_name += "-" + cacheInfo.CurrentPartitionId;
                }

                if (isStartedAsMirror)
                {
                    cache_name += "-" + "replica";
                }

                if (inproc && !isStartedAsMirror)
                {
                    cache_name += "." + System.Diagnostics.Process.GetCurrentProcess().Id;
                }
                nTrace.SetOutputStream(cache_name, Log.GetLogPath());
            }
            catch (Exception e)
            {
                AppUtil.LogEvent("NCache", "Failed to open log. " + e, System.Diagnostics.EventLogEntryType.Error, EventCategories.Error, EventID.GeneralError);
            }

            if (properties.Contains("usehptime"))
            {
                nTrace.UseHPTime = Convert.ToBoolean(properties["usehptime"]);
            }

            if (properties.Contains("trace-errors"))
            {
                nTrace.IsErrorEnabled        = Convert.ToBoolean(properties["trace-errors"]);
                nTrace.IsCriticalInfoEnabled = Convert.ToBoolean(properties["trace-errors"]);
            }

            if (properties.Contains("trace-warnings"))
            {
                nTrace.IsWarnEnabled = Convert.ToBoolean(properties["trace-warnings"]);
            }

            if (properties.Contains("trace-debug"))
            {
                nTrace.IsInfoEnabled = Convert.ToBoolean(properties["trace-debug"]);
            }

            nTrace.IsFatalEnabled = nTrace.IsErrorEnabled;
            nTrace.IsDebugEnabled = nTrace.IsWarnEnabled = nTrace.IsInfoEnabled;


            return(nTrace);
        }