Esempio n. 1
0
        public override ResultInfo SendDelaySMS(List<string> listRecPhone, string strMsg, string strServName)
        {
            ResultInfo rvInfo = new ResultInfo();
            try
            {
                if (listRecPhone == null)
                {
                    rvInfo.isError = true;
                    rvInfo.messageText = "Params Invalid : data list is null";
                    return rvInfo;
                }
                if (listRecPhone.Count == 0)
                {
                    rvInfo.isError = true;
                    rvInfo.messageText = "Params Invalid : data list is empty";
                    return rvInfo;
                }

                rvInfo.boolValue = this._MsgDelaySender.SendBatchSms(listRecPhone.ToArray(), strMsg, strServName);

            }
            catch (Exception ex)
            {
                rvInfo.messageText = ex.Message;
                rvInfo.isError = true;
            }
            return rvInfo;
        }
Esempio n. 2
0
        public override ResultInfo SendMessageText(List<string> toPhoneList, string messageText)
        {
            ResultInfo resultInfo = new ResultInfo();
            string toPhones = string.Empty;

            if (toPhoneList != null && toPhoneList.Count > 0)
            {
                int count = 11;

                if (toPhoneList.Count < count)
                {
                    count = toPhoneList.Count;
                }

                for (int i = 0; i < count; i++)
                {
                    toPhones += toPhones.Trim() == "" ? toPhoneList[i].Trim() : "," + toPhoneList[i].Trim();
                }
            }
            else
            {
                resultInfo.boolValue = false;
                resultInfo.messageText = "To phone List is empty!";

                return resultInfo;
            }

            resultInfo = Send(toPhones, messageText);

            return resultInfo;
        }
Esempio n. 3
0
        public ActionResult CatchAdd(Site site)
        {
            ResultInfo resultInfo = new ResultInfo(1, "验证不通过");

            site.SaveUrl =string.Format("/Template/{0}",site.Title);

            string content = RemoteHelper.GetWebResult(site.SourceUrl);

            //string content = @"dsfgsdfg:url(../images/category-trangle-bg.png);";
            //string thumbnail = @"(.*)\/tb\/([a-zA-Z0-9_\-\/]+)\/([a-zA-Z0-9]+)_(\d+)x(\d+)_(\d+)\.(jpg|gif|png|bmp)$";

            string regu = @"url\((\.{0,2})\/img\/.{0,}\)";

            MatchCollection matches = Regex.Matches(content, regu);

            foreach (var matche in matches)
            {
                var imgUrl = matche.ToString();
                imgUrl = imgUrl.Replace("url(..", "").Replace(")", "");
                var saveImgUrl = site.SaveUrl + imgUrl;
                imgUrl = string.Format("http://www.flc.com.br/m/site{0}", imgUrl);

                WebClient client = new WebClient();

                client.DownloadFile(imgUrl, FileHelper.GetMapPath(saveImgUrl));
            }

            //FileHelper.SaveHtml(site.SaveUrl, content);

            return Json(resultInfo);
        }
Esempio n. 4
0
 public void Test_ResultInfo_Equality()
 {
     ResultInfo<string> a = new ResultInfo<string>(true, "My Data 1");
     ResultInfo<string> b = new ResultInfo<string>(true, "My Data 2");
     Assert.That(a.Equals(b), "Equals() comparater returned wrong value");
     Assert.That(a == (b),"== comparater returned wrong value");
     Assert.That(a != (b), Is.EqualTo(false), "!= comparater returned wrong value");
 }
        public static ResultInfo SendEmail(string to, string subject, string body)
        {
            ResultInfo returnInfo = new ResultInfo();

            try
            {
                //_emailService = ConfigurationSettings.AppSettings["EmailService"].Trim();
                //_emailUserID = ConfigurationSettings.AppSettings["EmailUserID"].Trim();
                //_emailUserPassWord = ConfigurationSettings.AppSettings["EmailUserPassWord"].Trim();
            }
            catch (Exception Ex)
            {
                returnInfo.boolValue = false;
                returnInfo.messageText = Ex.Message;

                return returnInfo;
            }

            if (_emailService.Trim() == "")
            {
                returnInfo.boolValue = false;
                returnInfo.messageText = "不存在邮件服务地址!";
                return returnInfo;
            }

            if (_emailUserID.Trim() == "")
            {
                returnInfo.boolValue = false;
                returnInfo.messageText = "不存在发件人地址!";
                return returnInfo;
            }

            if (to.Trim() == "")
            {
                returnInfo.boolValue = false;
                returnInfo.messageText = "不存在接收邮件地址!";
                return returnInfo;
            }

            AbstractSendEmail sendMessage = SendEmailFactory.GetSendSendEmail(_emailService, _emailUserID, _emailUserPassWord);

            ResultInfo resultInfo = null;

            string htmlBody = body.Replace("\r\n", "<br>");
            resultInfo = sendMessage.Send(to, "", subject, htmlBody);

            if (resultInfo != null)
            {
                returnInfo.boolValue = resultInfo.boolValue;
                returnInfo.isError = resultInfo.isError;
                returnInfo.messageText = resultInfo.messageText;
                returnInfo.ValueObject = resultInfo.ValueObject;
            }

            return returnInfo;
        }
Esempio n. 6
0
        public ActionResult ProductAdd(Product product)
        {
            ResultInfo resultInfo = new ResultInfo(1, "验证不通过");

            if (ModelState.IsValid)
            {
                resultInfo = _productService.Add(product);
            }

            return Json(resultInfo);
        }
Esempio n. 7
0
        public ActionResult AttrAdd(Attr attr)
        {
            ResultInfo resultInfo = new ResultInfo(1, "验证不通过");

            if (ModelState.IsValid)
            {
                resultInfo = _attrService.Add(attr);
            }

            return Json(resultInfo);
        }
Esempio n. 8
0
        public ActionResult CateAdd(Cate cate)
        {
            ResultInfo resultInfo = new ResultInfo(1, "验证不通过");

            if (ModelState.IsValid)
            {
                resultInfo = _cateService.Add(cate);
            }

            return Json(resultInfo);
        }
Esempio n. 9
0
        public ActionResult CustomAdd(CustomModel customModel)
        {
            ResultInfo resultInfo = new ResultInfo(1, "验证不通过");

            if (ModelState.IsValid)
            {
                customModel.Custom.Sql = _customService.GetProductSql(customModel.Custom.Quantity,customModel.ProductSearch);
                resultInfo = _customService.Add(customModel.Custom);
            }

            return Json(resultInfo);
        }
        /// <summary>
        /// This method should be used to call methods from site utils that might take a few seconds.
        /// It makes sure only one task at a time executes and has a timeout for the execution.
        /// It also catches Execeptions from the utils and writes errors to the log.
        /// </summary>
        /// <param name="task">a delegate pointing to the method to invoke in a background thread.</param>
        /// <param name="resultHandler">the method to invoke to handle the result of the background task</param>
        /// <param name="timeoutEnabled">default: true, watches the background task and tries to abort it when timeout has elapsed</param>
        /// <returns>true, if execution finished successfully before the timeout expired.</returns>
        public bool ExecuteInBackgroundAndCallback(Func<object> task, Action<ResultInfo> resultHandler, bool timeoutEnabled = true)
        {
            // make sure only one background task can be executed at a time
            if (!IsBusy && Monitor.TryEnter(this))
            {
                try
                {
                    IsBusy = true;
                    resultInfo = new ResultInfo();
                    currentResultHandler = resultHandler;
                    backgroundThread = new Thread(delegate()
                    {
                        try
                        {
                            resultInfo.ResultObject = task.Invoke();
                            resultInfo.TaskSuccess = true;
                        }
                        catch (ThreadAbortException)
                        {
                            if (!resultInfo.AbortedByUser) Log.Warn("Timeout waiting for results.");
                            Thread.ResetAbort();
                        }
                        catch (Exception threadException)
                        {
                            resultInfo.TaskError = threadException as OnlineVideosException;
                            Log.Warn(threadException.ToString());
                            resultInfo.TaskSuccess = false;
                        }
                        timeoutTimer.Stop();
                        TaskFinishedCallback();
                    }) { Name = "OnlineVideos", IsBackground = true };

                    backgroundThread.Start();
                    // only timeout when parameter was set and not debugging
                    if (timeoutEnabled && !System.Diagnostics.Debugger.IsAttached) timeoutTimer.Start();
                    // successfully started the background task
                    return true;
                }
                catch (Exception ex)
                {
                    Log.Error(ex);
                    IsBusy = false;
                    resultInfo = null;
                    return false; // could not start the background thread
                }
            }
            else
            {
                Log.Error("Another thread tried to execute a task in background.");
                return false;
            }
        }
Esempio n. 11
0
        public ActionResult Register(User user)
        {
            ResultInfo resultInfo = new ResultInfo(1, "传递的参数有误");

            if (ModelState.IsValid)
            {
                resultInfo = _userServices.Register(user);

                //成功后登入并跳转
                Response.Redirect("/member/");
            }

            return View(resultInfo);
        }
Esempio n. 12
0
        public ActionResult AttrEdit(Attr attr)
        {
            ResultInfo resultInfo = new ResultInfo(1, "验证不通过");

            if (ModelState.IsValid)
            {
                Attr oldAttr = _attrService.GetById(attr.AttrId);
                oldAttr.AttrName = attr.AttrName;
                oldAttr.Oid = attr.Oid;
                resultInfo = _attrService.Edit(oldAttr);
            }

            return Json(resultInfo);
        }
Esempio n. 13
0
        public ActionResult Login(string username, string password)
        {
            ResultInfo resultInfo = new ResultInfo(1, "传递的参数有误");

            if (ModelState.IsValid)
            {
                resultInfo = _userServices.Login(username,password);

                if (resultInfo.Status == 0)
                {
                    //成功后登入并跳转
                    Response.Redirect("/member/user/");
                }
            }

            return View(resultInfo);
        }
Esempio n. 14
0
        public static ResultInfo SendSMS(string toPhone, string messageText)
        {
            ResultInfo returnInfo = new ResultInfo();

            try
            {
                //_userID = ConfigurationSettings.AppSettings["SendMessageUserID"].Trim();
                //_passWord = ConfigurationSettings.AppSettings["SendMessagePassWord"].Trim();
            }
            catch (Exception Ex)
            {
                returnInfo.boolValue = false;
                returnInfo.messageText = Ex.Message;

                return returnInfo;
            }

            if (toPhone.Trim() == "")
            {
                returnInfo.boolValue = false;
                returnInfo.messageText = "不存在接收的电话号码!";
                return returnInfo;
            }

            //SendMessage.hsyzSoapClient hsc = new WinService.WebMonitor.SendMessage.hsyzSoapClient();
            //String s = hsc.SendSms(_userID, _passWord, toPhone, messageText);

            //AbstractSendMessage sendMessage = SendMessageFactory.GetSendMessage(_userID, _passWord);

            //ResultInfo resultInfo = null;
            //resultInfo = sendMessage.SendMessageText(toPhone, messageText);

            ServiceManage.SendMessage.AbstractSendMessage msg = ServiceManage.SendMessage.SendMessageFactory.GetSendMessage(_userID, _passWord);
            ServiceManage.ResultInfo resultInfo = msg.SendMessageText(toPhone, messageText);

            //if (resultInfo != null)
            //{
            //    returnInfo.boolValue = resultInfo.boolValue;
            //    returnInfo.isError = resultInfo.isError;
            //    returnInfo.messageText = resultInfo.messageText;
            //    returnInfo.ValueObject = resultInfo.ValueObject;
            //}

            return returnInfo;
        }
Esempio n. 15
0
        public ActionResult SetCartQuantity(Cart cart)
        {
            ResultInfo resultInfo = new ResultInfo(1, "传递的参数有误");

            if (ModelState.IsValid)
            {
                //User user = new User();
                //user.UserId = 1;
                //user.GuestId = "";

                cart.UserId = 1;
                cart.GuestId = "";

                resultInfo = _cartService.SetCartQuantity(cart);
            }

            return Json(resultInfo);
        }
Esempio n. 16
0
        public ActionResult CustomEdit(Custom custom)
        {
            ResultInfo resultInfo = new ResultInfo(1, "验证不通过");

            if (ModelState.IsValid)
            {
                Custom oldCustomItem = _customService.GetById(custom.CustomId);

                if (oldCustomItem == null)
                {
                    return Json(new ResultInfo(1, "该信息已被删除或不存在,请刷新列表!"));
                }

                oldCustomItem = custom;

                resultInfo = _customService.Edit(custom);
            }

            return Json(resultInfo);
        }
Esempio n. 17
0
        public ActionResult Index()
        {
            ResultInfo ri = new ResultInfo();

            try
            {
                if (IsLogin)
                {
                    ri.Msg = "您已登录,打开此链接无效!将自动关闭!";
                }
                else
                {
                    string uri    = Request.Url.ToString();
                    string uidStr = GetRequest("shareID");
                    string token  = GetRequest("shareToken");
                    string openId = GetRequest("shareOpenId");
                    if (MatchHelper.IsNum.IsMatch(uidStr))
                    {
                        long      _userID = Convert.ToInt64(uidStr);
                        ShareLink share   = ShareLinkBLL.Instance.GetLinkByUserID(_userID);
                        if (share == null)
                        {
                            ri.Msg = "您打开的链接不存在!";
                        }
                        else
                        {
                            if (_userID == share.UserID)
                            {
                                if (token == share.ShareToken)
                                {
                                    UserBase sharer = UserBaseBLL.Instance.GetUserInfo(_userID);
                                    if (sharer == null)
                                    {
                                        ri.Msg = "分享人帐号已被删除!";
                                    }
                                    else
                                    {
                                        //记录链接打开次数
                                        ShareLinkBLL.Instance.AddPVCount(share.ShareLinkID);
                                        ri.Ok = true;
                                        ShareViewModel vmodel = new ShareViewModel()
                                        {
                                            ShareLink  = share,
                                            UserInfo   = sharer,
                                            ShareID    = _userID,
                                            ShareToken = token,
                                        };
                                        ViewBag.ShareViewModel = vmodel;
                                        return(View());
                                    }
                                }
                                else
                                {
                                    ri.Msg = "分享链接异常!";
                                }
                            }
                            else
                            {
                                ri.Msg = "分享链接异常!";
                            }
                        }
                    }
                    else
                    {
                        ri.Msg = "分享链接异常!";
                    }
                }
            }
            catch (Exception e)
            {
                ri.Msg = "打开分享链接过程中出现了异常,请重新打开分享链接!";
            }
            if (ri.Ok)
            {
                return(View());
            }
            else
            {
                return(Content("<script>alert('{0}'||'异常');close();</script>".FormatWith(ri.Msg)));
            }
        }
        //---------------------------------------------------------------------------------------//
        public override ExperimentResultInfo Execute(ExperimentSpecification experimentSpecification)
        {
            const string STRLOG_MethodName = "Execute";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Determine how long it actually take to execute
            //
            DateTime startDateTime = DateTime.Now;

            // Typecast the specification so that it can be used here
            Specification specification = (Specification)experimentSpecification;

            //
            // Log the specification
            //
            string strDistanceList = null;
            for (int i = 0; i < specification.DistanceList.Length; i++)
            {
                if (i > 0)
                {
                    strDistanceList += Consts.CHR_CsvSplitter.ToString();
                }
                strDistanceList += specification.DistanceList[i].ToString();
            }
            string logMessage = STRLOG_Distance + strDistanceList;
            logMessage += Logfile.STRLOG_Spacer + STRLOG_Duration + specification.Duration.ToString();
            logMessage += Logfile.STRLOG_Spacer + STRLOG_Repeat + specification.Repeat.ToString();
            Logfile.Write(logMessage);

            //
            // Create an instance of the result info ready to fill in
            //
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.statusCode = StatusCodes.Running;
            resultInfo.dataType = DataTypes.Real;

            //
            // Create data structures to hold the results
            //
            resultInfo.dataVectors = new int[specification.DistanceList.Length, specification.Repeat];

            //
            // Initialise variables used in the state machine
            //
            int distanceIndex = 0;
            int repeatIndex = 0;
            int tubeHomeDistance = 0;
            char sourceHomeLocation = (char)0;
            char absorberHomeLocation = (char)0;

            try
            {
                //
                // First, check to see if the LabEquipment is online
                //
                LabEquipmentStatus labEquipmentStatus = this.equipmentServiceProxy.GetLabEquipmentStatus();
                if (labEquipmentStatus.online == false)
                {
                    throw new Exception(labEquipmentStatus.statusMessage);
                }

                //
                // Run the state machine to execute the experiment specification
                //
                States_Execute state = States_Execute.sCompleted;
                if (smTable_Execute.Length > 0)
                {
                    state = smTable_Execute[0].currentState;
                }
                while (state != States_Execute.sCompleted)
                {
                    //
                    // Find table entry
                    //
                    int index = -1;
                    for (int i = 0; i < smTable_Execute.Length; i++)
                    {
                        if (smTable_Execute[i].currentState == state)
                        {
                            // Entry found
                            index = i;
                            break;
                        }
                    }
                    if (index == -1)
                    {
                        throw new ArgumentOutOfRangeException(state.ToString(), STRERR_StateNotFound);
                    }

                    //
                    // Get table entry and save next state
                    //
                    SMTableEntry_Execute entry = smTable_Execute[index];
                    States_Execute nextState = entry.nextState;

                    logMessage = " [ " + STRLOG_MethodName + ": " + entry.currentState.ToString() + " ]";
                    Logfile.Write(logMessage);

                    Trace.WriteLine(logMessage);

                    //
                    // Check if experiment was cancelled
                    //
                    if (this.cancelExperiment != null && this.cancelExperiment.IsCancelled == true &&
                        resultInfo.statusCode == StatusCodes.Running)
                    {
                        //
                        // Experiment was cancelled
                        //
                        resultInfo.statusCode = StatusCodes.Cancelled;
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Process non-XML commands
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sSuspendPowerdown:
                            if (this.equipmentServiceProxy.SuspendPowerdown() == false)
                            {
                                //
                                // Command execution failed
                                //
                                resultInfo.statusCode = StatusCodes.Failed;
                                resultInfo.errorMessage = STRERR_SuspendPowerdown;
                                state = entry.exitState;
                            }
                            else
                            {
                                state = nextState;
                            }
                            continue;

                        case States_Execute.sResumePowerdown:
                            if (this.equipmentServiceProxy.ResumePowerdown() == false)
                            {
                                //
                                // Command execution failed
                                //
                                resultInfo.statusCode = StatusCodes.Failed;
                                resultInfo.errorMessage = STRERR_ResumePowerdown;
                                state = entry.exitState;
                            }
                            else
                            {
                                state = nextState;
                            }
                            continue;

                        default:
                            break;
                    }

                    //
                    // Add command arguments where required
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sSelectAbsorberMessageLine2:
                            entry.commandArguments[1, 1] = HttpUtility.UrlEncode(specification.AbsorberList[0].name);
                            break;

                        case States_Execute.sSelectAbsorber:
                            entry.commandArguments[0, 1] = specification.AbsorberList[0].location.ToString();
                            break;

                        case States_Execute.sSelectSourceMessageLine2:
                            entry.commandArguments[1, 1] = HttpUtility.UrlEncode(specification.SourceName);
                            break;

                        case States_Execute.sSelectSource:
                            entry.commandArguments[0, 1] = specification.SourceLocation.ToString();
                            break;

                        case States_Execute.sSetTubeDistanceMessageLine2:
                            entry.commandArguments[1, 1] = HttpUtility.UrlEncode(specification.DistanceList[distanceIndex].ToString() + STRLCD_Millimetres);
                            break;

                        case States_Execute.sSetTubeDistance:
                            entry.commandArguments[0, 1] = specification.DistanceList[distanceIndex].ToString();
                            break;

                        case States_Execute.sCaptureDataMessageLine2:
                            string lcdMessage = specification.DistanceList[distanceIndex].ToString() + STRLCD_Millimetres;
                            lcdMessage += STRLCD_Break + specification.Duration.ToString() + STRLCD_Seconds;
                            lcdMessage += STRLCD_Break + (repeatIndex + 1).ToString() + STRLCD_Of + specification.Repeat.ToString();
                            entry.commandArguments[1, 1] = HttpUtility.UrlEncode(lcdMessage);
                            break;

                        case States_Execute.sCaptureData:
                            entry.commandArguments[0, 1] = specification.Duration.ToString();
                            break;

                        case States_Execute.sReturnSource:
                            entry.commandArguments[0, 1] = sourceHomeLocation.ToString();
                            break;

                        case States_Execute.sReturnAbsorber:
                            entry.commandArguments[0, 1] = absorberHomeLocation.ToString();
                            break;

                        case States_Execute.sReturnTube:
                            entry.commandArguments[0, 1] = tubeHomeDistance.ToString();
                            break;

                        default:
                            break;
                    }

                    //
                    // Execute command and check response success
                    //
                    XmlDocument xmlRequestDocument = CreateXmlRequestDocument(entry.equipmentCommand, entry.commandArguments);
                    string xmlResponse = this.equipmentServiceProxy.ExecuteRequest(xmlRequestDocument.InnerXml);
                    XmlNode xmlResponseNode = CreateXmlResponseNode(xmlResponse);
                    if (XmlUtilities.GetBoolValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspSuccess, false) == false)
                    {
                        //
                        // Command execution failed
                        //
                        resultInfo.statusCode = StatusCodes.Failed;
                        resultInfo.errorMessage = XmlUtilities.GetXmlValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspErrorMessage, true);
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Extract response values where required
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sCaptureData:
                            resultInfo.dataVectors[distanceIndex, repeatIndex] = XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspCount, 0);
                            if (++repeatIndex == specification.Repeat)
                            {
                                if (++distanceIndex == specification.DistanceList.Length)
                                {
                                    // All distances completed
                                    break;
                                }

                                // Next distance
                                repeatIndex = 0;
                                nextState = States_Execute.sSetTubeDistanceMessageLine1;
                                break;
                            }

                            // Next repeat
                            nextState = States_Execute.sCaptureDataMessageLine1;
                            break;

                        case States_Execute.sGetSourceHomeLocation:
                            sourceHomeLocation = XmlUtilities.GetCharValue(xmlResponseNode, Consts.STRXML_RspSourceHomeLocation, (char)0);
                            break;

                        case States_Execute.sGetAbsorberHomeLocation:
                            absorberHomeLocation = XmlUtilities.GetCharValue(xmlResponseNode, Consts.STRXML_RspAbsorberHomeLocation, (char)0);
                            break;

                        case States_Execute.sGetTubeHomeDistance:
                            tubeHomeDistance = XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspTubeHomeDistance, 0);
                            break;

                        default:
                            break;
                    }

                    Trace.WriteLine("nextState: " + entry.nextState.ToString());

                    //
                    // Next state
                    //
                    state = nextState;
                }

                //
                // Update status code
                //
                if (resultInfo.statusCode == StatusCodes.Running)
                {
                    resultInfo.statusCode = StatusCodes.Completed;
                }
            }
            catch (Exception ex)
            {
                resultInfo.statusCode = StatusCodes.Failed;
                resultInfo.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            //
            // Calculate actual execution time and round to the nearest integer
            //
            TimeSpan timeSpan = DateTime.Now - startDateTime;
            int execTime = (int)(timeSpan.TotalSeconds + 0.5);

            logMessage = STRLOG_StatusCode + resultInfo.statusCode
                + Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + execTime.ToString();

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return resultInfo;
        }
Esempio n. 19
0
        public ActionResult Talk(long id, string message)
        {
            ResultInfo <Chat> ri = new ResultInfo <Chat>();

            if (id > 0)
            {
                if (id != UserID)
                {
                    if (!string.IsNullOrEmpty(message))
                    {
                        int sendCount = ConfigHelper.AppSettings("SendMsgCount").ToInt32();//用户每天最大发送消息数
                        //判断是否超次数(管理员不受此限制)
                        bool canSend = UserBaseBLL.Instance.IsMaster;
                        if (!canSend)
                        {
                            canSend = sendCount > ChatBLL.Instance.SendMsgCount(UserID) || UserID == 10009;
                        }
                        if (canSend)
                        {
                            string toUserName = UserBaseBLL.Instance.GetUserNameByUserID(id);
                            if (!string.IsNullOrEmpty(toUserName))
                            {
                                Chat chat = new Chat();
                                chat.ToID         = id;
                                chat.ToUserName   = toUserName;
                                chat.FromID       = UserID;
                                chat.FromUserName = UserInfo.UserName;
                                chat.IsRead       = 0;
                                chat.Message      = HttpUtility.UrlDecode(message);
                                chat.SendTime     = DateTime.Now;
                                chat.Batch        = false;

                                if (ChatBLL.Instance.Add(chat) > 0)
                                {
                                    ri.Ok   = true;
                                    ri.Msg  = "消息发送成功";
                                    ri.Data = new ChatBox()
                                    {
                                        FromID       = UserID,
                                        FromUserName = UserInfo.UserName,
                                        Message      = chat.Message,
                                        Head         = UserInfo.HeadUrl
                                    };
                                }
                                else
                                {
                                    ri.Msg = "消息发送失败";
                                }
                            }
                            else
                            {
                                ri.Msg = "目标用户不存在";
                            }
                        }
                        else
                        {
                            ri.Msg = "您今日发送次数已达上限";
                        }
                    }
                    else
                    {
                        ri.Msg = "消息内容不能为空";
                    }
                }
                else
                {
                    ri.Msg = "不能给自己发送消息";
                }
            }
            else
            {
                ri.Msg = "接收人不存在!";
            }
            return(Result(ri));
        }
Esempio n. 20
0
        public ResultInfo UpdateTakeMailer(string user, UpdateTakeMailerReceive info)
        {
            var result = new ResultInfo()
            {
                error = 0,
                msg   = "success"
            };
            var checkUser = db.BS_Employees.Where(p => p.UserLogin == user).FirstOrDefault();

            if (checkUser == null)
            {
                return(new ResultInfo()
                {
                    error = 1,
                    msg = "Sai thông tin"
                });
            }
            try
            {
                var checkDocument = db.MM_TakeMailers.Find(info.documentId);

                if (checkDocument == null)
                {
                    throw new Exception("Sai thông tin");
                }

                var checkMailer = db.MM_Mailers.Find(info.mailers);

                var findDetail = db.MM_TakeDetails.Where(p => p.DocumentID == checkDocument.DocumentID && p.MailerID == info.mailers).FirstOrDefault();

                if (findDetail == null || checkMailer == null)
                {
                    throw new Exception("Sai thông tin");
                }

                findDetail.StatusID        = 8;
                findDetail.TimeTake        = DateTime.Now;
                db.Entry(findDetail).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                checkMailer.CurrentStatusID = 8;
                checkMailer.LastUpdateDate  = DateTime.Now;
                checkMailer.Weight          = info.weight;


                var price = db.CalPrice(checkMailer.Weight, checkMailer.SenderID, checkMailer.RecieverProvinceID, checkMailer.MailerTypeID, checkMailer.PostOfficeAcceptID, DateTime.Now.ToString("yyyy-MM-dd")).FirstOrDefault();


                checkMailer.Price        = price;
                checkMailer.PriceDefault = price;
                checkMailer.Amount       = price + checkMailer.PriceCoD + checkMailer.PriceService;

                db.Entry(checkMailer).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                HandleHistory.AddTracking(8, info.mailers, checkMailer.CurrentPostOfficeID, "Đã lấy hàng, đang giao về kho. Cập nhật trọng lượng: " + info.weight + " Gram");

                var checkCount = db.TAKEMAILER_GETDETAILs(checkDocument.DocumentID).Where(p => p.CurrentStatusID == 7).ToList();

                if (checkCount.Count() == 0)
                {
                    checkDocument.StatusID        = 8;
                    db.Entry(checkDocument).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                result.msg   = e.Message;
                result.error = 1;
            }

            return(result);
        }
Esempio n. 21
0
        /// <summary>
        /// 向idf文件中写入
        /// </summary>
        /// <param name="citFilePath">cit文件路径----->来自里程快速校正中的选择cit文件的按钮</param
        /// <param name="numericUpDown1">跳变允许值----->来自里程快速校正中的  跳变容许值</param>
        /// <param name="innerdbpath">内部数据库-----></param>
        private string _writeIdf(String citFilePath, int numericUpDown1, string innerdbpath)
        {
            //String idfFileName = Path.GetFileNameWithoutExtension(citFilePath) + ".idf";

            //String idfFilePath = Path.Combine(Path.GetDirectoryName(citFilePath), idfFileName);

            //if (!File.Exists(idfFilePath))
            //{
            //    //MessageBox.Show("找不到波形索引文件!");
            //    Console.WriteLine("找不到波形索引文件!");
            //    return;
            //}

            //公共方法
            ResultInfo resultInfo = new ResultInfo();

            //读取cit文件
            List <AutoIndex> autoIndexClsList = _readCit(citFilePath, numericUpDown1);

            String idfFileName = Path.GetFileNameWithoutExtension(citFilePath) + "_MileageFix" + ".idf";

            String idfFilePath = Path.Combine(Path.GetDirectoryName(citFilePath), idfFileName);

            //设置附带数据库路径和链接字符串,流程修正使用
            InnerFileOperator.InnerFilePath   = innerdbpath;
            InnerFileOperator.InnerConnString = "Provider = Microsoft.Jet.OLEDB.4.0; Data Source = {0}; Persist Security Info = True; Mode = Share Exclusive; Jet OLEDB:Database Password = iicdc; ";
            //InnerFileOperator.InnerConnString = "provider=Microsoft.Ace.OLEDB.12.0;extended properties=excel 12.0; Data Source = {0}; Persist Security Info = True; Mode = Share Exclusive; Extended Properties=Excel 12.0:Database Password = iicdc; ";

            try
            {
                _op = new IndexOperator();
                _op.IndexFilePath = idfFilePath;
                CITFileProcess  cit        = new CITFileProcess();
                FileInformation fileforma  = cit.GetFileInformation(citFilePath);
                UserFixedTable  fixedTable = new UserFixedTable(_op, fileforma.iKmInc);
                fixedTable.Clear();
                for (int i = 0; i < autoIndexClsList.Count; i++)
                {
                    float           mile        = autoIndexClsList[i].km_current + autoIndexClsList[i].meter_current;
                    UserMarkedPoint markedPoint = new UserMarkedPoint();
                    markedPoint.ID             = (i + 1).ToString();
                    markedPoint.FilePointer    = autoIndexClsList[i].milePos;
                    markedPoint.UserSetMileage = mile;
                    fixedTable.MarkedPoints.Add(markedPoint);
                }
                fixedTable.Save();

                try
                {
                    MilestoneFix fix = new MilestoneFix(citFilePath, _op);
                    fix.RunFixingAlgorithm();
                    fix.SaveMilestoneFixTable();

                    resultInfo.flag = 1;
                    resultInfo.msg  = "";
                    resultInfo.data = idfFilePath;
                }
                catch (Exception ex)
                {
                    resultInfo.flag = 0;
                    resultInfo.msg  = ex.Message;
                }
            }
            catch (Exception ex)
            {
                resultInfo.flag = 0;
                resultInfo.msg  = ex.Message;
            }

            return(JsonConvert.SerializeObject(resultInfo));
        }
Esempio n. 22
0
 public ActionResult AppApiEntityAttachPV([Bind(Include = "AppID,SystemEntityID")] AppAPIEntity appAPIEntity)
 {
     ResultInfo.Result res = ResultInfo.GetResultByID(1);
     res = uof_repos.repoApps.AttachAppAPIEntity(appAPIEntity.AppID, appAPIEntity.SystemEntityID);
     return(Json(res));
 }
        //---------------------------------------------------------------------------------------//

        public override ExperimentResultInfo Execute(ExperimentSpecification experimentSpecification)
        {
            const string STRLOG_MethodName = "Execute";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Determine how long it actually take to execute
            //
            DateTime startDateTime = DateTime.Now;

            // Typecast the specification so that it can be used here
            Specification specification = (Specification)experimentSpecification;

            //
            // Log the specification
            //
            string logMessage = string.Empty;

            //
            // Create an instance of the result info ready to fill in
            //
            ResultInfo resultInfo = new ResultInfo();

            resultInfo.statusCode = StatusCodes.Running;

            //
            // Create data structures to hold the results
            //

            //
            // Initialise variables used in the state machine
            //

            try
            {
                //
                // First, check to see if the LabEquipment is online
                //
                LabEquipmentStatus labEquipmentStatus = this.equipmentServiceProxy.GetLabEquipmentStatus();
                if (labEquipmentStatus.online == false)
                {
                    throw new Exception(labEquipmentStatus.statusMessage);
                }

                //
                // Run the state machine to execute the experiment specification
                //
                States_Execute state = States_Execute.sCompleted;
                if (smTable_Execute.Length > 0)
                {
                    state = smTable_Execute[0].currentState;
                }
                while (state != States_Execute.sCompleted)
                {
                    //
                    // Find table entry
                    //
                    int index = -1;
                    for (int i = 0; i < smTable_Execute.Length; i++)
                    {
                        if (smTable_Execute[i].currentState == state)
                        {
                            // Entry found
                            index = i;
                            break;
                        }
                    }
                    if (index == -1)
                    {
                        throw new ArgumentOutOfRangeException(state.ToString(), STRERR_StateNotFound);
                    }

                    //
                    // Get table entry and save next state
                    //
                    SMTableEntry_Execute entry     = smTable_Execute[index];
                    States_Execute       nextState = entry.nextState;

                    logMessage = " [ " + STRLOG_MethodName + ": " + entry.currentState.ToString() + " ]";
                    Logfile.Write(logMessage);

                    Trace.WriteLine(logMessage);

                    //
                    // Check if experiment was cancelled
                    //
                    if (this.cancelExperiment != null && this.cancelExperiment.IsCancelled == true &&
                        resultInfo.statusCode == StatusCodes.Running)
                    {
                        //
                        // Experiment was cancelled
                        //
                        resultInfo.statusCode = StatusCodes.Cancelled;
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Process non-XML commands
                    //
                    switch (entry.currentState)
                    {
                    case States_Execute.sSuspendPowerdown:
                        if (this.equipmentServiceProxy.SuspendPowerdown() == false)
                        {
                            //
                            // Command execution failed
                            //
                            resultInfo.statusCode   = StatusCodes.Failed;
                            resultInfo.errorMessage = STRERR_SuspendPowerdown;
                            state = entry.exitState;
                        }
                        else
                        {
                            state = nextState;
                        }
                        continue;

                    case States_Execute.sResumePowerdown:
                        if (this.equipmentServiceProxy.ResumePowerdown() == false)
                        {
                            //
                            // Command execution failed
                            //
                            resultInfo.statusCode   = StatusCodes.Failed;
                            resultInfo.errorMessage = STRERR_ResumePowerdown;
                            state = entry.exitState;
                        }
                        else
                        {
                            state = nextState;
                        }
                        continue;

                    default:
                        break;
                    }

                    //
                    // Add command arguments where required
                    //
                    switch (entry.currentState)
                    {
                    case States_Execute.sGetTimeOfDay:

                        entry.commandArguments[0, 1] = specification.ServerUrl;
                        break;

                    default:
                        break;
                    }

                    //
                    // Execute command and check response success
                    //
                    XmlDocument xmlRequestDocument = CreateXmlRequestDocument(entry.equipmentCommand, entry.commandArguments);
                    string      xmlResponse        = this.equipmentServiceProxy.ExecuteRequest(xmlRequestDocument.InnerXml);
                    XmlNode     xmlResponseNode    = CreateXmlResponseNode(xmlResponse);
                    if (XmlUtilities.GetBoolValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspSuccess, false) == false)
                    {
                        //
                        // Command execution failed
                        //
                        resultInfo.statusCode   = StatusCodes.Failed;
                        resultInfo.errorMessage = XmlUtilities.GetXmlValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspErrorMessage, true);
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Extract response values where required
                    //
                    switch (entry.currentState)
                    {
                    case States_Execute.sGetTimeOfDay:

                        string strTimeOfDayBinary = XmlUtilities.GetXmlValue(xmlResponseNode, Consts.STRXML_RspTimeOfDay, false);
                        long   timeOfDay          = Convert.ToInt64(strTimeOfDayBinary);
                        resultInfo.dateTime = DateTime.FromBinary(timeOfDay);

                        //
                        // Save the timestamp string in the specified format
                        //
                        if (specification.FormatName.Equals(Consts.STRXML_Format_12Hour))
                        {
                            resultInfo.timeofday = resultInfo.dateTime.ToString(Consts.STR_DateTimeFormat_12Hour);
                        }
                        else if (specification.FormatName.Equals(Consts.STRXML_Format_24Hour))
                        {
                            resultInfo.timeofday = resultInfo.dateTime.ToString(Consts.STR_DateTimeFormat_24Hour);
                        }
                        break;

                    default:
                        break;
                    }

                    //
                    // Next state
                    //
                    state = nextState;
                }

                //
                // Update status code
                //
                if (resultInfo.statusCode == StatusCodes.Running)
                {
                    resultInfo.statusCode = StatusCodes.Completed;
                }
            }
            catch (Exception ex)
            {
                resultInfo.statusCode   = StatusCodes.Failed;
                resultInfo.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            //
            // Calculate actual execution time
            //
            TimeSpan timeSpan = DateTime.Now - startDateTime;

            logMessage = STRLOG_StatusCode + resultInfo.statusCode
                         + Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + timeSpan.TotalSeconds.ToString();

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return(resultInfo);
        }
Esempio n. 24
0
 public override bool CanFetch(ResultInfo resultInfo)
 {
     return(true);
 }
Esempio n. 25
0
        public async Task <IHttpActionResult> Post([FromBody] Param md)
        {
            var r = new ResultInfo <Param>();

            try
            {
                #region param
                var open = openLogic();

                open.setParmValue(ParmDefine.Email, md.Email);

                open.setParmValue(ParmDefine.AccountName, md.AccountName);
                open.setParmValue(ParmDefine.BankName, md.BankName);
                open.setParmValue(ParmDefine.BankCode, md.BankCode);
                open.setParmValue(ParmDefine.AccountNumber, md.AccountNumber);
                #endregion

                #region working
                using (var tx = defAsyncScope())
                {
                    using (var db0 = getDB0())
                    {
                        #region 運費
                        var ships = md.ship;
                        //每種付款方式,若有設定固定運費(isfixed=true)只能設一筆
                        foreach (var ship in ships)
                        {
                            var item = db0.Shipment.Find(ship.shipment_id);

                            item.limit_money  = ship.limit_money;
                            item.shipment_fee = ship.shipment_fee;
                            item.bank_charges = ship.bank_charges;
                            item.isfixed      = ship.isfixed;
                        }
                        #endregion

                        #region 折扣
                        //目前db有的
                        var discounts = await db0.Discount.ToListAsync();

                        List <Discount> del_ditem = new List <Discount>();

                        foreach (var item in discounts)
                        {
                            var md_d = md.discount.FirstOrDefault(x => x.discount_id == item.discount_id);
                            if (md_d != null)
                            {
                                item.limit_money = md_d.limit_money;
                                item.per         = md_d.per;
                                item.isuse       = md_d.isuse;
                            }
                            else
                            {//原本再資料庫,但找不到的須刪除資料
                                del_ditem.Add(item);
                            }
                        }
                        //加入沒寫進資料庫的資料
                        var add_dlist = md.discount.Where(x => x.edit_type == IEditType.Insert);
                        foreach (var item in add_dlist)
                        {
                            db0.Discount.Add(item);
                        }
                        db0.Discount.RemoveRange(del_ditem);
                        #endregion

                        await db0.SaveChangesAsync();

                        tx.Complete();
                    }
                }
                r.result = true;
                return(Ok(r));

                #endregion
            }
            catch (DbEntityValidationException ex) //欄位驗證錯誤
            {
                r.message = getDbEntityValidationException(ex);
                r.result  = false;
                return(Ok(r));
            }
            catch (Exception ex)
            {
                r.result  = false;
                r.message = ex.Message + "\r\n" + getErrorMessage(ex);
                return(Ok(r));
            }
        }
Esempio n. 26
0
        //---------------------------------------------------------------------------------------//

        public override ExperimentResultInfo Execute(ExperimentSpecification experimentSpecification)
        {
            const string STRLOG_MethodName = "Execute";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Determine how long it actually take to execute
            //
            DateTime startDateTime = DateTime.Now;

            // Typecast the specification so that it can be used here
            Specification specification = (Specification)experimentSpecification;

            //
            // Log the specification
            //
            string logMessage = string.Empty;
            //Logfile.Write(logMessage);

            //
            // Create an instance of the result info ready to fill in
            //
            ResultInfo resultInfo = new ResultInfo();

            resultInfo.statusCode = StatusCodes.Running;

            //
            // Initialise variables used in the state machine
            //
            int repeatCount = 0;

            try
            {
                //
                // First, check to see if the LabEquipment is online
                //
                LabEquipmentStatus labEquipmentStatus = this.equipmentServiceProxy.GetLabEquipmentStatus();
                if (labEquipmentStatus.online == false)
                {
                    throw new Exception(labEquipmentStatus.statusMessage);
                }

                //
                // Run the state machine to execute the experiment specification
                //
                States_Execute state = States_Execute.sCompleted;
                if (smTable_Execute.Length > 0)
                {
                    state = smTable_Execute[0].currentState;
                }
                while (state != States_Execute.sCompleted)
                {
                    //
                    // Find table entry
                    //
                    int index = -1;
                    for (int i = 0; i < smTable_Execute.Length; i++)
                    {
                        if (smTable_Execute[i].currentState == state)
                        {
                            // Entry found
                            index = i;
                            break;
                        }
                    }
                    if (index == -1)
                    {
                        throw new ArgumentOutOfRangeException(state.ToString(), STRERR_StateNotFound);
                    }

                    //
                    // Get table entry and save next state
                    //
                    SMTableEntry_Execute entry     = smTable_Execute[index];
                    States_Execute       nextState = entry.nextState;

                    logMessage = " [ " + STRLOG_MethodName + ": " + entry.currentState.ToString() + " ]";
                    Logfile.Write(logMessage);

                    Trace.WriteLine(logMessage);

                    //
                    // Check if experiment was cancelled
                    //
                    if (this.cancelExperiment != null && this.cancelExperiment.IsCancelled == true &&
                        resultInfo.statusCode == StatusCodes.Running)
                    {
                        //
                        // Experiment was cancelled
                        //
                        resultInfo.statusCode = StatusCodes.Cancelled;
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Process non-XML commands
                    //
                    switch (entry.currentState)
                    {
                    case States_Execute.sSuspendPowerdown:
                        if (this.equipmentServiceProxy.SuspendPowerdown() == false)
                        {
                            //
                            // Command execution failed
                            //
                            resultInfo.statusCode   = StatusCodes.Failed;
                            resultInfo.errorMessage = STRERR_SuspendPowerdown;
                            state = entry.exitState;
                        }
                        else
                        {
                            state = nextState;
                        }
                        continue;

                    case States_Execute.sResumePowerdown:
                        if (this.equipmentServiceProxy.ResumePowerdown() == false)
                        {
                            //
                            // Command execution failed
                            //
                            resultInfo.statusCode   = StatusCodes.Failed;
                            resultInfo.errorMessage = STRERR_ResumePowerdown;
                            state = entry.exitState;
                        }
                        else
                        {
                            state = nextState;
                        }
                        continue;

                    default:
                        break;
                    }

                    //
                    // Add command arguments where required
                    //
                    switch (entry.currentState)
                    {
                    //
                    // Nothing to do here
                    //

                    default:
                        break;
                    }

                    //
                    // Execute command and check response success
                    //
                    XmlDocument xmlRequestDocument = CreateXmlRequestDocument(entry.equipmentCommand, entry.commandArguments);
                    string      xmlResponse        = this.equipmentServiceProxy.ExecuteRequest(xmlRequestDocument.InnerXml);
                    XmlNode     xmlResponseNode    = CreateXmlResponseNode(xmlResponse);
                    if (XmlUtilities.GetBoolValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspSuccess, false) == false)
                    {
                        //
                        // Command execution failed
                        //
                        resultInfo.statusCode   = StatusCodes.Failed;
                        resultInfo.errorMessage = XmlUtilities.GetXmlValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspErrorMessage, true);
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Extract response values where required
                    //
                    switch (entry.currentState)
                    {
                    case States_Execute.sTakeMeasurement:

                        //
                        // Add in the values
                        //
                        resultInfo.voltage     += (float)XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspVoltageMut, 0.0);
                        resultInfo.current     += (float)XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspCurrentMut, 0.0);
                        resultInfo.powerFactor += (float)XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspPowerFactorMut, 0.0);
                        resultInfo.speed       += XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspSpeed, 0);
                        resultInfo.torque      += XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspTorque, 0);

                        //
                        // Check if all measurements have been taken
                        //
                        if (++repeatCount == this.measurementCount)
                        {
                            //
                            // All measurements taken, average the values
                            //
                            resultInfo.voltage     /= this.measurementCount;
                            resultInfo.current     /= this.measurementCount;
                            resultInfo.powerFactor /= this.measurementCount;
                            resultInfo.speed       /= this.measurementCount;
                            resultInfo.torque      /= this.measurementCount;
                            break;
                        }

                        // Next measurement
                        nextState = States_Execute.sTakeMeasurement;
                        break;

                    default:
                        break;
                    }

                    //
                    // Next state
                    //
                    state = nextState;
                }

                //
                // Update status code
                //
                if (resultInfo.statusCode == StatusCodes.Running)
                {
                    resultInfo.statusCode = StatusCodes.Completed;
                }
            }
            catch (Exception ex)
            {
                resultInfo.statusCode   = StatusCodes.Failed;
                resultInfo.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            //
            // Calculate actual execution time
            //
            TimeSpan timeSpan = DateTime.Now - startDateTime;

            logMessage = STRLOG_StatusCode + resultInfo.statusCode
                         + Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + timeSpan.TotalSeconds.ToString();

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return(resultInfo);
        }
Esempio n. 27
0
        public ResultInfo UpdateDelivery(string orderId, string productId, int quantity, string user, string token)
        {
            var log = new MongoHistoryAPI()
            {
                APIUrl     = "/api/order/updatedelivery",
                CreateTime = DateTime.Now,
                Sucess     = 1
            };

            var result = new ResultInfo()
            {
                id  = "1",
                msg = "success"
            };

            try
            {
                if (!mongoHelper.checkLoginSession(user, token))
                {
                    throw new Exception("Wrong token and user login!");
                }

                if (!isAdmin(user))
                {
                    throw new Exception("Sai thông tin");
                }

                var checkOrder = db.MOrders.Find(orderId);
                if (checkOrder == null)
                {
                    throw new Exception("Sai thông tin");
                }

                if (checkOrder.StatusId == "create")
                {
                    var oderProduct = checkOrder.ProductOrders.Where(p => p.ProductId == productId).FirstOrDefault();

                    if (oderProduct == null)
                    {
                        throw new Exception("Sai thông tin");
                    }

                    oderProduct.QuantityReal    = quantity;
                    db.Entry(oderProduct).State = EntityState.Modified;
                    db.SaveChanges();

                    double?total = 0;

                    foreach (var item in checkOrder.ProductOrders)
                    {
                        total += (item.QuantityReal * item.Price);
                    }

                    checkOrder.PriceReal       = total;
                    db.Entry(checkOrder).State = EntityState.Modified;
                    db.SaveChanges();

                    Util.Utils.send(checkOrder.MStaff.MUser, "Đơn hàng " + checkOrder.Code, "Đơn hàng " + checkOrder.Code + "\nĐã thay đổi số lượng thực: " + quantity + "\nSản phẩm: " + oderProduct.MProduct.PName, mongoHelper);
                }
                else
                {
                    throw new Exception("Sai thông tin");
                }
            }
            catch (Exception e)
            {
                log.Sucess = 0;
            }

            log.ReturnInfo = new JavaScriptSerializer().Serialize(result);

            mongoHelper.createHistoryAPI(log);

            return(result);
        }
Esempio n. 28
0
        public ResultInfo CreateOrder()
        {
            var log = new MongoHistoryAPI()
            {
                APIUrl     = "/api/order/createorder",
                CreateTime = DateTime.Now,
                Sucess     = 1
            };

            var result = new ResultInfo()
            {
                id  = "1",
                msg = "success"
            };

            try
            {
                var requestContent = Request.Content.ReadAsStringAsync().Result;
                var jsonserializer = new JavaScriptSerializer();
                var paser          = jsonserializer.Deserialize <CreateOrderRequest>(requestContent);
                log.Content = new JavaScriptSerializer().Serialize(paser);

                if (!mongoHelper.checkLoginSession(paser.user, paser.token))
                {
                    throw new Exception("Wrong token and user login!");
                }


                var checkStaff = db.MStaffs.Where(p => p.MUser == paser.user).FirstOrDefault();

                if (checkStaff == null)
                {
                    throw new Exception("Sai thông tin");
                }

                var checkAgency = db.MAgencies.Where(p => p.Code == paser.agencyId).FirstOrDefault();

                if (checkAgency == null)
                {
                    throw new Exception("Sai thông tin");
                }

                var newCode = GetCode(checkAgency.Code);

                Nullable <System.DateTime> sugestTime = DateTime.ParseExact(paser.suggestDate, "d/M/yyyy", null);


                if (sugestTime == null)
                {
                    sugestTime = DateTime.Now.AddDays(3);
                }

                var order = new MOrder()
                {
                    Id          = Guid.NewGuid().ToString(),
                    CreateTime  = DateTime.Now,
                    AgencyId    = checkAgency.Id,
                    CloseOrder  = 0,
                    ModifyTime  = DateTime.Now,
                    PriceReal   = 0,
                    StaffId     = checkStaff.Id,
                    StatusId    = "create",
                    Code        = newCode,
                    SuggestDate = sugestTime,
                    Discount    = checkAgency.Discount,
                    CDate       = DateTime.Now.ToString("ddMMyyyy")
                };

                db.MOrders.Add(order);
                db.SaveChanges();

                double?priceTotal = 0;

                foreach (var item in paser.products)
                {
                    var checkProduct = db.MProducts.Find(item.id);
                    if (checkProduct != null)
                    {
                        var price = checkProduct.Price * item.quantity;

                        priceTotal += price;

                        var productOder = new ProductOrder()
                        {
                            OrderId      = order.Id,
                            Price        = checkProduct.Price,
                            ProductId    = checkProduct.Id,
                            QuantityBuy  = item.quantity,
                            QuantityReal = item.quantity
                        };
                        db.ProductOrders.Add(productOder);
                        db.SaveChanges();
                    }
                }


                order.PriceOrder      = priceTotal;
                order.PriceReal       = priceTotal;
                db.Entry(order).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
            }
            catch (Exception e)
            {
                result.id  = "0";
                result.msg = e.Message;
                log.Sucess = 0;
            }

            log.ReturnInfo = new JavaScriptSerializer().Serialize(result);

            mongoHelper.createHistoryAPI(log);

            return(result);
        }
Esempio n. 29
0
        // cap nhat mailer
        public ResultInfo UpdateDelivery(UpdateDeliveryReceive info, string user)
        {
            var result = new ResultInfo()
            {
                error = 0,
                msg   = "success"
            };

            try
            {
                var checkUser = db.BS_Employees.Where(p => p.UserLogin == user).FirstOrDefault();

                if (checkUser == null)
                {
                    throw new Exception("Sai thông tin");
                }

                // check Document of employee
                var document = db.MM_MailerDelivery.Where(p => p.DocumentID == info.DocumentID && p.EmployeeID == checkUser.EmployeeID).FirstOrDefault();

                if (document == null)
                {
                    throw new Exception("Đơn này không được phân cho bạn phát");
                }

                // find detail
                var findDetail = db.MM_MailerDeliveryDetail.Where(p => p.DocumentID == info.DocumentID && p.MailerID == info.MailerID && p.DeliveryStatus == 3).FirstOrDefault();

                if (findDetail == null)
                {
                    throw new Exception("Sai thông tin");
                }


                DateTime deliverDate = DateTime.ParseExact(info.DeliveryDate, "dd/M/yyyy HH:mm", null);

                if (deliverDate == null)
                {
                    deliverDate = DateTime.Now;
                }

                //
                var mailerInfo = db.MM_Mailers.Find(findDetail.MailerID);

                if (mailerInfo == null)
                {
                    throw new Exception("Vận đơn sai");
                }

                findDetail.DeliveryStatus  = info.StatusID;
                mailerInfo.CurrentStatusID = info.StatusID;

                if (info.StatusID == 5)
                {
                    //  var findReason = db.BS_ReturnReasons.Where(p => p.ReasonID == info.ReturnReasonID).FirstOrDefault();

                    findDetail.DeliveryTo     = "";
                    findDetail.DeliveryNotes  = info.Note;
                    findDetail.ReturnReasonID = info.ReturnReasonID;
                    findDetail.DeliveryDate   = deliverDate;


                    mailerInfo.DeliveryTo    = "";
                    mailerInfo.DeliveryDate  = deliverDate;
                    mailerInfo.DeliveryNotes = info.Note;
                    mailerInfo.IsReturn      = true;
                    HandleHistory.AddTracking(5, info.MailerID, mailerInfo.CurrentPostOfficeID, "Trả lại hàng, vì lý do " + info.Note);
                }
                else if (info.StatusID == 6)
                {
                    findDetail.DeliveryTo    = "";
                    findDetail.DeliveryDate  = deliverDate;
                    findDetail.DeliveryNotes = info.Note;

                    mailerInfo.DeliveryTo    = "";
                    mailerInfo.DeliveryDate  = deliverDate;
                    mailerInfo.DeliveryNotes = info.Note;

                    HandleHistory.AddTracking(6, info.MailerID, mailerInfo.CurrentPostOfficeID, "Chưa phát được vì " + info.Note);
                }
                else if (info.StatusID == 4)
                {
                    findDetail.DeliveryTo     = info.Reciever;
                    findDetail.ReturnReasonID = null;
                    findDetail.DeliveryNotes  = "Đã phát";
                    findDetail.DeliveryDate   = deliverDate;

                    mailerInfo.DeliveryTo    = info.Reciever;
                    mailerInfo.DeliveryDate  = deliverDate;
                    mailerInfo.DeliveryNotes = "Đã phát";

                    if (mailerInfo.IsReturn == true)
                    {
                        findDetail.DeliveryNotes = "Đã hoàn";
                        mailerInfo.DeliveryNotes = "Đã hoàn";

                        findDetail.DeliveryStatus  = 11;
                        mailerInfo.CurrentStatusID = 11;

                        HandleHistory.AddTracking(11, info.MailerID, mailerInfo.CurrentPostOfficeID, "Ngày hoàn " + deliverDate.ToString("dd/MM/yyyy") + " lúc " + deliverDate.ToString("HH:mm") + ", người nhận: " + info.Reciever);
                    }
                    else
                    {
                        HandleHistory.AddTracking(4, info.MailerID, mailerInfo.CurrentPostOfficeID, "Ngày phát " + deliverDate.ToString("dd/MM/yyyy") + " lúc " + deliverDate.ToString("HH:mm") + ", người nhận: " + info.Reciever);

                        // save nhung don co thu tien COD
                        if (mailerInfo.COD > 0)
                        {
                            var saveCoDDebit = new EmpployeeDebitCOD()
                            {
                                Id = Guid.NewGuid().ToString(),
                                AccountantConfirm = 0,
                                COD         = Convert.ToDouble(mailerInfo.COD),
                                ConfirmDate = DateTime.Now,
                                CreateDate  = DateTime.Now,
                                DocumentID  = info.DocumentID,
                                EmployeeID  = checkUser.EmployeeID,
                                MailerID    = mailerInfo.MailerID
                            };

                            db.EmpployeeDebitCODs.Add(saveCoDDebit);
                        }
                    }
                }

                if (info.images != null)
                {
                    foreach (var image in info.images)
                    {
                        var saveImage = new MailerImage()
                        {
                            Id         = Guid.NewGuid().ToString(),
                            CreateTime = DateTime.Now,
                            MailerID   = info.MailerID,
                            PathImage  = image,
                            UserSend   = user
                        };

                        db.MailerImages.Add(saveImage);
                    }
                    db.SaveChanges();
                }

                db.Entry(mailerInfo).State = System.Data.Entity.EntityState.Modified;
                db.Entry(findDetail).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                UpdateDeliveryStatus(document.DocumentID);
            }
            catch (Exception e)
            {
                result.msg   = e.Message;
                result.error = 1;
            }

            return(result);
        }
Esempio n. 30
0
        public JsonResult Login(string DeviceToken, Login Info)
        {
            ResultInfo <Login> ResultInfo = new ResultInfo <Login>()
            {
                Status      = false,
                Description = "Failed|Login",
            };
            Global Glb = new Global();
            // Login lgn = new Login();
            User_Backend PageObj = new User_Backend();
            Login        objDett = new Login();
            string       Token   = "";

            try
            {
                if (Info != null)
                {
                    #region CHECK OBJECT IS NULL
                    string CheckedOb = Glb.ObjectNullChecking(Info);
                    Info = JsonConvert.DeserializeObject <Login>(CheckedOb);
                    #endregion

                    Info = PageObj.Login(Info.Email, Info.Password);
                    if (Info != null && Info.UID != 0)
                    {
                        objDett = PageObj.GetLoginDetails(Info.UID, Info.UserType_FK);

                        //objDett.IsOnline = PageObj.UpdateIsOnline(Convert.ToInt32(Info.UID));

                        ResultInfo.Info = objDett;
                        Token           = Glb.GenerateToken(Info.UID, Info.Email, Info.Password);
                        if (!string.IsNullOrEmpty(Token))
                        {
                            Glb.UpdateTokenId(Info.UID, Token);
                        }

                        ResultInfo.TokenId   = Token;
                        ResultInfo.ErrorCode = 200;
                        //  ResultInfo.IsSuccess = true;
                        ResultInfo.Description = "Success! User authenticated";
                    }
                    else
                    {
                        if (Info.Email != Info.Email)
                        {
                            ResultInfo.Description = "Failed!Wrong email address or password";
                        }
                        else if (Info.Password != Info.Password)
                        {
                            ResultInfo.Description = "Failed!Wrong  password";
                        }
                        else
                        {
                            ResultInfo.Description = "Failed!Wrong email address or password";
                        }
                    }
                }
                else
                {
                    ResultInfo.Description = "Failed!Invalid parameter";
                }
            }
            catch (Exception ex)
            {
                ResultInfo.Description = "Failed!" + ex.Message;
            }
            return(Json(ResultInfo, JsonRequestBehavior.AllowGet));
        }
Esempio n. 31
0
 public static AddParticipantResultEvent AddParticipantResultEvent(ResultInfo resultInfo = default, string operationContext = default, OperationStatus status = default)
 {
     return(new AddParticipantResultEvent(resultInfo, operationContext, status));
 }
        //---------------------------------------------------------------------------------------//
        public override ExperimentResultInfo Execute(ExperimentSpecification experimentSpecification)
        {
            const string STRLOG_MethodName = "Execute";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Determine how long it actually take to execute
            //
            DateTime startDateTime = DateTime.Now;

            // Typecast the specification so that it can be used here
            Specification specification = (Specification)experimentSpecification;

            //
            // Log the specification
            //
            string logMessage = string.Empty;

            //
            // Create an instance of the result info ready to fill in
            //
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.statusCode = StatusCodes.Running;

            //
            // Create data structures to hold the results
            //

            //
            // Initialise variables used in the state machine
            //

            try
            {
                //
                // First, check to see if the LabEquipment is online
                //
                LabEquipmentStatus labEquipmentStatus = this.equipmentServiceProxy.GetLabEquipmentStatus();
                if (labEquipmentStatus.online == false)
                {
                    throw new Exception(labEquipmentStatus.statusMessage);
                }

                //
                // Run the state machine to execute the experiment specification
                //
                States_Execute state = States_Execute.sCompleted;
                if (smTable_Execute.Length > 0)
                {
                    state = smTable_Execute[0].currentState;
                }
                while (state != States_Execute.sCompleted)
                {
                    //
                    // Find table entry
                    //
                    int index = -1;
                    for (int i = 0; i < smTable_Execute.Length; i++)
                    {
                        if (smTable_Execute[i].currentState == state)
                        {
                            // Entry found
                            index = i;
                            break;
                        }
                    }
                    if (index == -1)
                    {
                        throw new ArgumentOutOfRangeException(state.ToString(), STRERR_StateNotFound);
                    }

                    //
                    // Get table entry and save next state
                    //
                    SMTableEntry_Execute entry = smTable_Execute[index];
                    States_Execute nextState = entry.nextState;

                    logMessage = " [ " + STRLOG_MethodName + ": " + entry.currentState.ToString() + " ]";
                    Logfile.Write(logMessage);

                    Trace.WriteLine(logMessage);

                    //
                    // Check if experiment was cancelled
                    //
                    if (this.cancelExperiment != null && this.cancelExperiment.IsCancelled == true &&
                        resultInfo.statusCode == StatusCodes.Running)
                    {
                        //
                        // Experiment was cancelled
                        //
                        resultInfo.statusCode = StatusCodes.Cancelled;
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Process non-XML commands
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sSuspendPowerdown:
                            if (this.equipmentServiceProxy.SuspendPowerdown() == false)
                            {
                                //
                                // Command execution failed
                                //
                                resultInfo.statusCode = StatusCodes.Failed;
                                resultInfo.errorMessage = STRERR_SuspendPowerdown;
                                state = entry.exitState;
                            }
                            else
                            {
                                state = nextState;
                            }
                            continue;

                        case States_Execute.sResumePowerdown:
                            if (this.equipmentServiceProxy.ResumePowerdown() == false)
                            {
                                //
                                // Command execution failed
                                //
                                resultInfo.statusCode = StatusCodes.Failed;
                                resultInfo.errorMessage = STRERR_ResumePowerdown;
                                state = entry.exitState;
                            }
                            else
                            {
                                state = nextState;
                            }
                            continue;

                        default:
                            break;
                    }

                    //
                    // Add command arguments where required
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sGetTimeOfDay:

                            entry.commandArguments[0, 1] = specification.ServerUrl;
                            break;

                        default:
                            break;
                    }

                    //
                    // Execute command and check response success
                    //
                    XmlDocument xmlRequestDocument = CreateXmlRequestDocument(entry.equipmentCommand, entry.commandArguments);
                    string xmlResponse = this.equipmentServiceProxy.ExecuteRequest(xmlRequestDocument.InnerXml);
                    XmlNode xmlResponseNode = CreateXmlResponseNode(xmlResponse);
                    if (XmlUtilities.GetBoolValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspSuccess, false) == false)
                    {
                        //
                        // Command execution failed
                        //
                        resultInfo.statusCode = StatusCodes.Failed;
                        resultInfo.errorMessage = XmlUtilities.GetXmlValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspErrorMessage, true);
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Extract response values where required
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sGetTimeOfDay:

                            string strTimeOfDayBinary = XmlUtilities.GetXmlValue(xmlResponseNode, Consts.STRXML_RspTimeOfDay, false);
                            long timeOfDay = Convert.ToInt64(strTimeOfDayBinary);
                            resultInfo.dateTime = DateTime.FromBinary(timeOfDay);

                            //
                            // Save the timestamp string in the specified format
                            //
                            if (specification.FormatName.Equals(Consts.STRXML_Format_12Hour))
                            {
                                resultInfo.timeofday = resultInfo.dateTime.ToString(Consts.STR_DateTimeFormat_12Hour);
                            }
                            else if (specification.FormatName.Equals(Consts.STRXML_Format_24Hour))
                            {
                                resultInfo.timeofday = resultInfo.dateTime.ToString(Consts.STR_DateTimeFormat_24Hour);
                            }
                            break;

                        default:
                            break;
                    }

                    //
                    // Next state
                    //
                    state = nextState;
                }

                //
                // Update status code
                //
                if (resultInfo.statusCode == StatusCodes.Running)
                {
                    resultInfo.statusCode = StatusCodes.Completed;
                }
            }
            catch (Exception ex)
            {
                resultInfo.statusCode = StatusCodes.Failed;
                resultInfo.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            //
            // Calculate actual execution time
            //
            TimeSpan timeSpan = DateTime.Now - startDateTime;

            logMessage = STRLOG_StatusCode + resultInfo.statusCode
                + Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + timeSpan.TotalSeconds.ToString();

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return resultInfo;
        }
Esempio n. 33
0
        public async Task <IHttpActionResult> Post([FromBody] SendMsg md)
        {
            md.send_msg_id = GetNewId(ProcCore.Business.CodeTable.SendMsg);
            ResultInfo r = new ResultInfo();

            if (!ModelState.IsValid)
            {
                r.message = ModelStateErrorPack();
                r.result  = false;
                return(Ok(r));
            }

            try
            {
                #region working a
                db0 = getDB0();
                #region 發送條件新增對應
                if (md.send_type == (int)SendType.SendMsgByFactor)
                {
                    List <int> customer_id = new List <int>();
                    var        getItem     = db0.ScheduleDetail
                                             .Where(x => x.tel_day == md.send_day)
                                             .Select(x => new m_ScheduleDetail {
                        customer_id = x.customer_id, tel_reason = x.tel_reason
                    });
                    if (md.send_factor == (int)SendFactor.FirstPayment)
                    {
                        customer_id = getItem.Where(x => x.tel_reason == (int)SendFactor.FirstPayment).Select(x => x.customer_id).Distinct().ToList();
                    }
                    if (md.send_factor == (int)SendFactor.SesameOil)
                    {
                        customer_id = getItem.Where(x => x.tel_reason == (int)SendFactor.SesameOil).Select(x => x.customer_id).Distinct().ToList();
                    }
                    if (md.send_factor == (int)SendFactor.BalancePayment)
                    {
                        customer_id = getItem.Where(x => x.tel_reason == (int)SendFactor.BalancePayment).Select(x => x.customer_id).Distinct().ToList();
                    }

                    foreach (var id in customer_id)
                    {
                        var detailItem = new SendMsgOfCustomer()
                        {
                            customer_id      = id,
                            send_msg_id      = md.send_msg_id,
                            i_InsertUserID   = this.UserId,
                            i_InsertDateTime = DateTime.Now,
                            i_InsertDeptID   = this.departmentId,
                            i_Lang           = "zh-TW"
                        };
                        db0.SendMsgOfCustomer.Add(detailItem);
                    }
                }
                #endregion

                md.i_InsertUserID   = this.UserId;
                md.i_InsertDateTime = DateTime.Now;
                md.i_InsertDeptID   = this.departmentId;
                md.company_id       = this.companyId;
                md.i_Lang           = "zh-TW";

                db0.SendMsg.Add(md);
                await db0.SaveChangesAsync();

                r.result = true;
                r.id     = md.send_msg_id;
                return(Ok(r));

                #endregion
            }
            catch (Exception ex)
            {
                r.result  = false;
                r.message = ex.Message;
                return(Ok(r));
            }
            finally
            {
                db0.Dispose();
            }
        }
Esempio n. 34
0
		private static DataGridResultViewer InitializeResultViewer()
		{
			var columnHeaders =
				new[]
				{
					new ColumnHeader { ColumnIndex = 0, DatabaseDataType = "Varchar2", DataType = typeof (string), Name = "DUMMY1" },
					new ColumnHeader { ColumnIndex = 1, DatabaseDataType = "Date", DataType = typeof (DateTime), Name = "DUMMY_WITH_UNDERSCORES" },
					//new ColumnHeader { ColumnIndex = 2, DatabaseDataType = "Varchar2", DataType = typeof (string), Name = "\"'\\\"><?,.;:{}[]%$#@!~^&*()_+-§'''||(1/2*3+4-CASEWHEN1<=2OR2>=1THEN5ELSE6END)" }
				};

			var documentPage = new DocumentPage { CurrentConnection = ConfigurationProvider.ConnectionStrings[0] };
			documentPage.DatabaseModel.Dispose();
			
			var outputViewer = new OutputViewer(documentPage);

			var dataRows =
				new[]
				{
					new object[] {"Value \"1\" '2' <3>", new DateTime(2014, 8, 16, 22, 25, 34)},
					new object[] {"\"2.\"Value", new DateTime(2014, 8, 16)},
					//new object[] {"\"><?,.;:{}[]%$#@!~^&*()_+-§' ,5", new DateTime(2015, 5, 30) }
				};

			var resultInfo = new ResultInfo(null, "Test result", ResultIdentifierType.UserDefined);

			var executionResult =
				new StatementExecutionResult
				{
					StatementModel =
						new StatementExecutionModel
						{
							StatementText = "SELECT * FROM DUAL"
						},
					ResultInfoColumnHeaders =
						new Dictionary<ResultInfo, IReadOnlyList<ColumnHeader>>
						{
							{ resultInfo, columnHeaders }
						}
				};

			var resultViewer =
				new DataGridResultViewer(outputViewer, executionResult, resultInfo)
				{
					ResultGrid = { ItemsSource = dataRows }
				};

			DataGridHelper.InitializeDataGridColumns(resultViewer.ResultGrid, columnHeaders, outputViewer.StatementValidator, outputViewer.ConnectionAdapter);

			return resultViewer;
		}
Esempio n. 35
0
        public JsonResult PatientSocialLogIn(string DeviceToken, SocialUserInfo Info)
        {
            ResultInfo <string> ResultInfo = new ResultInfo <string>();

            ResultInfo.ErrorCode   = 400;
            ResultInfo.Status      = false;
            ResultInfo.Description = "Patient social login";
            ResultInfo.Info        = "Login Failed";
            Global       Glb     = new Global();
            User_Backend PageObj = new User_Backend();

            try
            {
                if (Info != null && Info.SocialUserId != "" && Info.SocialUserId != null)
                {
                    #region CHECK OBJECT IS NULL BY IMAD
                    string CheckedOb = Glb.ObjectNullChecking(Info);
                    Info = JsonConvert.DeserializeObject <SocialUserInfo>(CheckedOb);
                    #endregion

                    ResultInfo.Info = PageObj.UserSocialRegistration(Info);    // Function call for database store
                    string[] arr = ResultInfo.Info.Split('!');
                    if (arr[0] == "Success")
                    {
                        long insertedId = 0;
                        if (arr[1] != "")
                        {
                            insertedId = Convert.ToInt64(arr[1]);
                        }
                        if (ResultInfo.Info.Contains("NewUser"))
                        {
                            string Password = "";
                            if (arr[3] != "")
                            {
                                Password = arr[3];
                            }
                            string Token = Glb.GenerateToken(insertedId, Info.Email, Password);
                            if (!string.IsNullOrEmpty(Token))
                            {
                                Glb.UpdateTokenId(insertedId, Token);
                                ResultInfo.Info = "User Registration successfull.";
                            }
                            else
                            {
                                ResultInfo.Info = "Token is not generated.";
                            }
                            ResultInfo.TokenId        = Token;
                            ResultInfo.ErrorCode      = 200;
                            ResultInfo.Status         = true;
                            ResultInfo.LastModifiedId = insertedId;
                            ResultInfo.Description    = "Success! User authenticated";
                        }
                        else
                        {
                            if (insertedId > 0)
                            {
                                string Token = Glb.GetTokenByID(insertedId);
                                ResultInfo.TokenId        = Token;
                                ResultInfo.ErrorCode      = 200;
                                ResultInfo.Status         = true;
                                ResultInfo.LastModifiedId = insertedId;
                                ResultInfo.Info           = "User registration successfull.";
                            }
                        }
                    }
                }
                else
                {
                    ResultInfo.Info = "Details is not provided.";
                }
            }
            catch (Exception ex)
            {
                ResultInfo.Info = ex.Message;
            }
            return(Json(ResultInfo, JsonRequestBehavior.AllowGet));
        }
Esempio n. 36
0
        public void ProcessRequest(HttpContext context)
        {
            ResultInfo result = new ResultInfo();
            GCInfo     gc1    = new GCInfo();
            string     action = context.Request["action"].ToString();

            context.Response.ContentType = "text/plain";

            switch (action)
            {
            case "GetAll":
                context.Response.Write(GetAll());
                break;

            case "GetGC":
                string jt = HttpUtility.UrlDecode(context.Request["jt"]);
                context.Response.Write(GetGC(jt));
                break;

            case "Add":
                try
                {
                    gc1.Name        = context.Request.Form["Name"];
                    gc1.Address     = context.Request.Form["Address"];
                    gc1.PostAddress = context.Request.Form["PostAddress"];
                    gc1.Introduce   = context.Request.Form["Introduce"];
                    gc1.Phone       = context.Request.Form["Phone"];
                    gc1.Email       = context.Request.Form["Email"];
                    gc1.JTName      = context.Request.Form["JTName"];
                    gc1.JW          = context.Request.Form["JW"];
                    //保存数据到数据库中
                    result.Success = Add(gc1);
                    result.Message = "插入工厂信息" + ((result.Success == true) ? "成功" : "失败") + "!";
                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.Message = "异常:" + ex.Message;
                }
                //返回客户端信息
                context.Response.Write(JsonHelper <ResultInfo> .ObjectToJsonString(result));
                break;

            case "Update":
                try
                {
                    gc1             = new GCInfo();
                    gc1.Name        = context.Request.Form["Name"];
                    gc1.Address     = context.Request.Form["Address"];
                    gc1.PostAddress = context.Request.Form["PostAddress"];
                    gc1.Introduce   = context.Request.Form["Introduce"];
                    gc1.Phone       = context.Request.Form["Phone"];
                    gc1.Email       = context.Request.Form["Email"];
                    gc1.JTName      = context.Request.Form["JTName"];
                    gc1.JW          = context.Request.Form["JW"];
                    result.Success  = Update(gc1);
                    result.Message  = "更新工厂[" + gc1.Name + "]信息" + ((result.Success == true) ? "成功" : "失败") + "!";
                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.Message = "异常:" + ex.Message;
                }
                //返回客户端信息
                context.Response.Write(JsonHelper <ResultInfo> .ObjectToJsonString(result));
                break;

            case "Delete":
                try
                {
                    int      count = 0;
                    string   id    = context.Request["Id"];
                    string[] ids   = id.Split(',');
                    for (int i = 0; i < ids.Length; i++)
                    {
                        result.Success = Delete(ids[i]);
                        if (result.Success == false)
                        {
                            break;
                        }
                        count++;
                    }
                    result.Message = ((result.Success == true) ? "操作成功:" : "操作失败:") + "共删除" + count + "条信息!";
                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.Message = "异常:" + ex.Message;
                }
                //返回客户端信息
                context.Response.Write(JsonHelper <ResultInfo> .ObjectToJsonString(result));
                break;

            case "GetAllGCInfo":
                int page = int.Parse(context.Request.Form["page"]);
                int rows = int.Parse(context.Request.Form["rows"]);
                context.Response.Write(GetAllGCInfo(page, rows));
                break;

            case "GetAllGCJZInfo":
                int    menuid = int.Parse(CheckLoginStatus.node);
                string gcname = MenuHelper.GetMenuNameById(menuid);
                context.Response.Write(GetAllGCJZInfo(gcname));
                break;

            default:
                break;
            }
        }
Esempio n. 37
0
        /// <summary>
        /// 确认投资接口--解志辉
        /// </summary>
        /// <param name="reqst">The reqst.</param>
        /// <returns>ResultInfo&lt;System.Int32&gt;.</returns>
        ///  创 建 者:解志辉
        ///  创建日期:2016-05-31 18:01:28
        public ResultInfo<int> SubmitTender(RequestParam<RequestTender> reqst)
        {
            ResultInfo<int> res = new ResultInfo<int>("99999");

            var usrId = ConvertHelper.ParseValue(reqst.body.userId, 0);
            var targetId = ConvertHelper.ParseValue(reqst.body.targetId, 0);
            var bds = reqst.body.bonusIds;
            var investAmount = ConvertHelper.ParseValue(reqst.body.investAmount, 0M);
            //  var code = reqst.body.invitedcode;



            if (usrId <= 0)
            {
                res.code = "1000000015";
                res.message = Settings.Instance.GetErrorMsg(res.code);
                return res;
            }
            if (targetId <= 0)
            {
                res.code = "1000000014";
                res.message = Settings.Instance.GetErrorMsg(res.code);
                return res;
            }


            try
            {
                var ent = _logic.SelectBorrowDetail(targetId);

                //最低可投金额应该从标的记录获取
                if (investAmount < ent.minimum)
                {
                    res.code = "2000000000";
                    res.message = Settings.Instance.GetErrorMsg(res.code);
                    return res;
                }
                else if (investAmount + ent.fundraising_amount > ent.borrowing_balance)
                {//超过可投金额
                    res.code = "2000000002";
                    res.message = Settings.Instance.GetErrorMsg(res.code);
                    return res;
                }


                InvestmentParameters mp = new InvestmentParameters
                {
                    Amount = investAmount,
                    Circle = ConvertHelper.ParseValue(ent.life_of_loan, 0),
                    CircleType = ConvertHelper.ParseValue(ent.unit_day, 0),
                    NominalYearRate = ConvertHelper.ParseValue(ent.annual_interest_rate, 0D),
                    OverheadsRate = 0f,
                    RepaymentMode = ConvertHelper.ParseValue(ent.payment_options, 0),
                    RewardRate = 0f,
                    IsThirtyDayMonth = false,
                    InvestDate = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd")),

                    ReleaseDate = DateTime.Parse(ent.release_date.ToString()).ToString("yyyy-MM-dd"),
                    Investmentenddate =
                        DateTime.Parse(DateTime.Parse(ent.repayment_date.ToString()).ToString("yyyy-MM-dd")),
                    Payinterest = ConvertHelper.ParseValue(ent.month_payment_date, 0),
                    InvestObject = 1
                };

                List<InvestmentReceiveRecordInfo> records = InvestCalculator.CalculateReceiveRecord(mp);
                StringBuilder sb = new StringBuilder("");
                if (records != null && records.Any())
                {
                    int i = 1;
                    foreach (var item in records)
                    {
                        //current_investment_period,value_date,interest_payment_date,repayment_amount,interestpayment,Principal,TotalInstallments,interestDay
                        sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7}|", i, item.interestvalue_date, item.NominalReceiveDate, item.Balance, item.Interest, item.Principal, item.TotalInstallments, item.TotalDays);

                        i = i + 1;
                    }
                }

                //(int usrId, int targetId, decimal investAmount, List<int> bds, string code, string ordCode, decimal withoutInterest, string frozenidNo, decimal frozenidAmount, int cPeriod) 


                var resVal = _logic.SubmitTender(usrId, targetId, investAmount, bds, "", Settings.Instance.OrderCode
                    , ((records != null && records.Any()) ? records.Sum(t => t.Interest) : 0M), Settings.Instance.OrderCode
                    , 0M
                    , ((records != null && records.Any()) ? records.Count : 0), sb.ToString());

                if (resVal < 200)
                {

                    switch (resVal)
                    {
                        case -100:
                            {
                                res.code = "2000000001";
                            }
                            break;
                        case -200:
                            {
                                res.code = "2000000002";
                            }
                            break;
                        case -300:
                            {
                                res.code = "2000000003";
                            }
                            break;
                        case -400:
                            {
                                res.code = "2000000004";
                            }
                            break;
                        case -500:
                            {
                                res.code = "2000000007";
                            }
                            break;
                        case -600:
                            {
                                res.code = "2000000006";
                            }
                            break;
                    }
                }
                else
                {
                    res.code = "1";
                    res.body = resVal;
                }

                res.message = Settings.Instance.GetErrorMsg(res.code);
                return res;
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(ex.ToString());
                LoggerHelper.Error(JsonHelper.Entity2Json(reqst));
                res.code = "500";
                res.message = Settings.Instance.GetErrorMsg(res.code);
                return res;
            }
        }
Esempio n. 38
0
        public ResultInfo CancelTakeMailer(string user, UpdateTakeMailerReceive info)
        {
            var result = new ResultInfo()
            {
                error = 0,
                msg   = "success"
            };
            var checkUser = db.BS_Employees.Where(p => p.UserLogin == user).FirstOrDefault();

            if (checkUser == null)
            {
                return(new ResultInfo()
                {
                    error = 1,
                    msg = "Sai thông tin"
                });
            }
            try
            {
                var checkDocument = db.MM_TakeMailers.Find(info.documentId);

                if (checkDocument == null)
                {
                    throw new Exception("Sai thông tin");
                }


                var checkMailer = db.MM_Mailers.Find(info.mailers);

                var findDetail = db.MM_TakeDetails.Where(p => p.DocumentID == checkDocument.DocumentID && p.MailerID == info.mailers).FirstOrDefault();


                if (findDetail == null || checkMailer == null)
                {
                    throw new Exception("Sai thông tin");
                }

                findDetail.StatusID        = 10;
                db.Entry(findDetail).State = System.Data.Entity.EntityState.Modified;

                //
                checkMailer.CurrentStatusID = 10;
                checkMailer.LastUpdateDate  = DateTime.Now;
                db.Entry(checkMailer).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();

                HandleHistory.AddTracking(10, info.mailers, checkMailer.CurrentPostOfficeID, "KHÁCH HÀNG YÊU CẦU HỦY KHI ĐI LẤY HÀNG");

                var checkCount = db.TAKEMAILER_GETDETAILs(checkDocument.DocumentID).Where(p => p.CurrentStatusID == 7).ToList();

                if (checkCount.Count() == 0)
                {
                    checkDocument.StatusID        = 8;
                    db.Entry(checkDocument).State = System.Data.Entity.EntityState.Modified;
                    db.SaveChanges();
                }
            }
            catch (Exception e)
            {
                result.msg   = e.Message;
                result.error = 1;
            }

            return(result);
        }
Esempio n. 39
0
        public void NotifyOccured(NotifyType notifyType, Socket socket, BaseInfo baseInfo)
        {
            switch (notifyType)
            {
            case NotifyType.Reply_UpdateUser:
            {
                UserInfo userName = (UserInfo)baseInfo;
                Window1.main.nickName.Content = userName.Nickname;

                ToolTip tt = new ToolTip();
                tt.Content = userName.Nickname;
                Window1.main.nickName.ToolTip = tt;

                IniFileEdit _IniFileEdit = new IniFileEdit(Window1._UserPath);

                ImageBrush updateImg = new ImageBrush();
                updateImg.Stretch = Stretch.Fill;
                _IniFileEdit.SetIniValue("UserInfo", "userImage", userName.Icon);
                updateImg.ImageSource       = ImageDownloader.GetInstance().GetImage(userName.Icon);
                myPicture.Fill              = updateImg;
                Window1.main.memberImg.Fill = updateImg;

                ToolTip sign = new ToolTip();
                sign.Content = Window1._UserInfo.Sign;
                Window1.main.singBox.ToolTip = sign;
                Window1.main.singBox.Text    = Window1._UserInfo.Sign;

                if (selectGrid.Children.Count > 0 && selectGrid.Children[0] is MyInfoControl)
                {
                    MyInfoControl myInfoControl = (MyInfoControl)selectGrid.Children[0];

                    myInfoControl.buttonSave.IsEnabled = false;
                }

                MessageBoxCommon.Show("更新成功", MessageBoxType.Ok);
            }
            break;

            case NotifyType.Reply_VideoUpload:
            {
                MessageBoxCommon.Show("更改成功.", MessageBoxType.Ok);
            }
            break;

            case NotifyType.Reply_NewID:
            {
                UserInfo newUserInfo = (UserInfo)baseInfo;
                MessageBoxCommon.Show("帐号申请通过." + newUserInfo.Id, MessageBoxType.Ok);
                userInfoList.Add(newUserInfo);

                selectGrid.Children.Clear();
                NoticeMemberControl noticeMemberControl = new NoticeMemberControl();
                noticeMemberControl.listMember(userInfoList);
                selectGrid.Children.Add(noticeMemberControl);
            }
            break;

            case NotifyType.Reply_IconUpload:
            {
                IconInfo newIcon = (IconInfo)baseInfo;
                iconInfoList.Add(newIcon);

                selectGrid.Children.Clear();
                AlbermControl albermControl = new AlbermControl();
                albermControl.pictureList(iconInfoList);
                selectGrid.Children.Add(albermControl);
            }
            break;

            case NotifyType.Reply_Give:
            {
                PresentHistoryInfo presentHistoryInfo = (PresentHistoryInfo)baseInfo;

                presentHistoryList.Add(presentHistoryInfo);
                selectGrid.Children.Clear();
                InnerControl innerControl = new InnerControl();
                innerControl.InnerChatting(chatHistoryList);
                selectGrid.Children.Add(innerControl);



                for (int i = 0; i < userInfoList.Count; i++)
                {
                    if (userInfoList[i].Id == presentHistoryInfo.ReceiveId)
                    {
                        userInfoList[i].Cash = userInfoList[i].Cash + presentHistoryInfo.Cash;

                        selectGrid.Children.Clear();
                        NoticeMemberControl noticeMemberControl = new NoticeMemberControl();
                        noticeMemberControl.listMember(userInfoList);
                        selectGrid.Children.Add(noticeMemberControl);

                        break;
                    }
                }
            }
            break;

            case NotifyType.Reply_UpdatePercent:
            {
                UserInfo userPercent = (UserInfo)baseInfo;
                if (userPercent.Id == Window1._UserInfo.Id)
                {
                    selectGrid.Children.Clear();
                    MyInfoControl myInfoControl = new MyInfoControl();
                    myInfoControl.InitMyInfo(Window1._UserInfo);
                    selectGrid.Children.Add(myInfoControl);
                }
            }
            break;

            case NotifyType.Reply_IconRemove:
            {
                IconInfo newIcon = (IconInfo)baseInfo;
                for (int i = 0; i < iconInfoList.Count; i++)
                {
                    if (iconInfoList[i].Icon == newIcon.Icon)
                    {
                        iconInfoList.Remove(iconInfoList[i]);
                    }
                }

                selectGrid.Children.Clear();
                AlbermControl albermControl = new AlbermControl();
                albermControl.pictureList(iconInfoList);
                selectGrid.Children.Add(albermControl);
            }
            break;

            case NotifyType.Reply_Error:
            {
                ResultInfo errorInfo = (ResultInfo)baseInfo;
                ErrorType  errorType = errorInfo.ErrorType;

                //Window1.ShowError(errorType);
            }
            break;
            }
        }
Esempio n. 40
0
        private void onDataArrived(object sender, ResultInfo e)
        {
            Logging(LogLevel.Info, String.Format("Device|{0}|{1}:{2}|Received message|{3}", DeviceType, IP, Port, e.ReadString));

            var message = new
            {
                Id = SubscriptionName,
                Message = Regex.Replace(e.ReadString, @"[^\u0009^\u000A^\u000D^\u0020-\u007E]", ""),
                Timestamp = e.ResultArrivedAt
            };

            DeviceBroadcastManager.Broadcast(SubscriptionName, message);
            Logging(LogLevel.Info, String.Format("Device|{0}|{1}:{2}|Broadcast|Group {3}|Message|{4}", DeviceType, IP, Port, SubscriptionName, message.ToString()));
        }
Esempio n. 41
0
        public bool ExportExecutionDetailsToRQM(BusinessFlow businessFlow, ref string result, bool exectutedFromAutomateTab = false, PublishToALMConfig publishToALMConfig = null)
        {
            result = string.Empty;
            string bfExportedID = GetExportedIDString(businessFlow.ExternalID, "RQMID");

            if (string.IsNullOrEmpty(bfExportedID) || bfExportedID.Equals("0"))
            {
                result = GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + ": " + businessFlow.Name + " is missing ExternalID, cannot export RQM TestPlan execution results without External ID";
                return(false);
            }

            if (businessFlow.ActivitiesGroups.Count == 0)
            {
                result = GingerDicser.GetTermResValue(eTermResKey.BusinessFlow) + ": " + businessFlow.Name + " Must have at least one " + GingerDicser.GetTermResValue(eTermResKey.ActivitiesGroup);
                return(false);
            }

            LoginDTO loginData = new LoginDTO()
            {
                User = ALMCore.DefaultAlmConfig.ALMUserName, Password = ALMCore.DefaultAlmConfig.ALMPassword, Server = ALMCore.DefaultAlmConfig.ALMServerURL
            };

            //
            // get data about execution records per current test plan - start
            RQMTestPlan testPlan             = new RQMTestPlan();
            string      importConfigTemplate = System.IO.Path.Combine(RQMCore.ConfigPackageFolderPath, "RQM_Import", "RQM_ImportConfigs_Template.xml");

            if (File.Exists(importConfigTemplate))
            {
                XmlSerializer serializer = new
                                           XmlSerializer(typeof(RQMProjectListConfiguration));
                FileStream fs     = new FileStream(importConfigTemplate, FileMode.Open);
                XmlReader  reader = XmlReader.Create(fs);
                RQMProjectListConfiguration RQMProjectList;
                RQMProjectList = (RQMProjectListConfiguration)serializer.Deserialize(reader);
                fs.Close();

                RQMProject currentRQMProjectMapping;
                if (RQMProjectList.RQMProjects.Count > 0)
                {
                    currentRQMProjectMapping = RQMProjectList.RQMProjects.Where(x => x.Name == ALMCore.DefaultAlmConfig.ALMProjectName || x.Name == "DefaultProjectName").FirstOrDefault();
                    if (currentRQMProjectMapping != null)
                    {
                        testPlan = RQMConnect.Instance.GetRQMTestPlanByIdByProject(ALMCore.DefaultAlmConfig.ALMServerURL, ALMCore.DefaultAlmConfig.ALMUserName, ALMCore.DefaultAlmConfig.ALMPassword, ALMCore.DefaultAlmConfig.ALMProjectName, GetExportedIDString(businessFlow.ExternalID, "RQMID"));

                        if (testPlan == null)
                        {
                            result = "Recent Testing Plan not exists in connected RQM project.";
                            return(false);
                        }

                        testPlan.RQMExecutionRecords = RQMConnect.Instance.GetExecutionRecordsByTestPlan(loginData, reader, currentRQMProjectMapping, RQMCore.ALMProjectGroupName, RQMCore.ALMProjectGuid, testPlan.URLPathVersioned);
                    }
                }
            }
            // get data about execution records per current test plan - finish

            List <ExecutionResult> exeResultList = new List <ExecutionResult>();

            foreach (ActivitiesGroup activGroup in businessFlow.ActivitiesGroups)
            {
                if ((publishToALMConfig.FilterStatus == FilterByStatus.OnlyPassed && activGroup.RunStatus == eActivitiesGroupRunStatus.Passed) ||
                    (publishToALMConfig.FilterStatus == FilterByStatus.OnlyFailed && activGroup.RunStatus == eActivitiesGroupRunStatus.Failed) ||
                    publishToALMConfig.FilterStatus == FilterByStatus.All)
                {
                    ExecutionResult exeResult = GetExeResultforAg(businessFlow, bfExportedID, activGroup, ref result, testPlan);
                    if (exeResult != null)
                    {
                        exeResultList.Add(exeResult);
                    }
                    else
                    {
                        return(false);
                    }
                }
            }

            ResultInfo resultInfo = new ResultInfo();

            //
            // Updating of Execution Record Results (test plan level)
            try
            {
                resultInfo = RQMConnect.Instance.RQMRep.ExportExecutionResult(loginData, exeResultList, RQMCore.ALMProjectGuid, ALMCore.DefaultAlmConfig.ALMProjectName, RQMCore.ALMProjectGroupName);
            }
            catch
            {
                Reporter.ToLog(eLogLevel.ERROR, "Failed to Update Execution Record Results");
            }

            //
            // Creating Test Suite Log (per test suite)
            try
            {
                foreach (RQMTestSuite rQMTestSuite in testPlan.TestSuites)
                {
                    if ((rQMTestSuite.ACL_TestSuite_Copy != null) && (rQMTestSuite.TestSuiteExecutionRecord.CurrentTestSuiteResult.ACL_TestSuiteLog_Copy != null))
                    {
                        resultInfo = RQMConnect.Instance.RQMRep.CreateTestSuiteLog(loginData, RQMCore.ALMProjectGuid, ALMCore.DefaultAlmConfig.ALMProjectName, RQMCore.ALMProjectGroupName, rQMTestSuite.ACL_TestSuite_Copy, rQMTestSuite.TestSuiteExecutionRecord.CurrentTestSuiteResult.ACL_TestSuiteLog_Copy);
                    }
                }
            }
            catch
            {
                Reporter.ToLog(eLogLevel.ERROR, "Failed to Update Execution Record Results");
            }

            //
            // Attaching of Activity Groups Reports
            try
            {
                // Attach ActivityGroup Report if needed
                if ((publishToALMConfig.ToAttachActivitiesGroupReport) || (exectutedFromAutomateTab))
                {
                    foreach (ActivitiesGroup activGroup in businessFlow.ActivitiesGroups)
                    {
                        try
                        {
                            ACL_Data_Contract.Activity   currentActivity  = GetTestCaseFromActivityGroup(activGroup);
                            ACL_Data_Contract.Attachment reportAttachment = new ACL_Data_Contract.Attachment();
                            string activityGroupName = PathHelper.CleanInValidPathChars(activGroup.Name);
                            if ((activGroup.TempReportFolder != null) && (activGroup.TempReportFolder != string.Empty) &&
                                (System.IO.Directory.Exists(activGroup.TempReportFolder)))
                            {
                                //Creating the Zip file - start
                                string targetZipPath = System.IO.Directory.GetParent(activGroup.TempReportFolder).ToString();
                                string zipFileName   = targetZipPath + "\\" + activityGroupName.ToString().Replace(" ", "_") + "_GingerHTMLReport.zip";
                                if (!System.IO.File.Exists(zipFileName))
                                {
                                    ZipFile.CreateFromDirectory(activGroup.TempReportFolder, zipFileName);
                                }
                                else
                                {
                                    System.IO.File.Delete(zipFileName);
                                    ZipFile.CreateFromDirectory(activGroup.TempReportFolder, zipFileName);
                                }
                                System.IO.Directory.Delete(activGroup.TempReportFolder, true);
                                //Creating the Zip file - finish

                                //Attaching Zip file - start
                                reportAttachment.ClientFileName = activityGroupName.ToString().Replace(" ", "_") + "_GingerHTMLReport.zip";
                                reportAttachment.ServerLocation = targetZipPath + @"\" + reportAttachment.ClientFileName;
                                reportAttachment.CreatedBy      = Environment.UserName;
                                currentActivity.EntityId        = Convert.ToInt32(GetExportedIDString(activGroup.ExternalID.ToString(), "RQMID"));
                                currentActivity.ExportedID      = (long)currentActivity.EntityId;
                                currentActivity.ActivityData.AttachmentsColl = new Attachments();
                                currentActivity.ActivityData.AttachmentsColl.Add(reportAttachment);

                                string exportJarFilePath = Assembly.GetExecutingAssembly().Location.Replace(@"GingerCore.dll", "") + @"ALM\\RQM\\JAVA";
                                RQMConnect.Instance.RQMRep.UploadAttachmetToRQMAndGetIds(loginData, RQMCore.ALMProjectGuid, ALMCore.DefaultAlmConfig.ALMProjectName, RQMCore.ALMProjectGroupName, currentActivity, exportJarFilePath);
                                RQMConnect.Instance.RQMRep.UpdateTestCaseWithNewAttachmentID(loginData, RQMCore.ALMProjectGuid, ALMCore.DefaultAlmConfig.ALMProjectName, RQMCore.ALMProjectGroupName, currentActivity);

                                //Attaching Zip file - finish
                                System.IO.File.Delete(zipFileName);
                            }
                        }
                        catch
                        {
                            Reporter.ToLog(eLogLevel.ERROR, "Failed to attach report Per ActivityGroup - " + activGroup.Name);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                resultInfo.ErrorCode = 1;
                result = e.ToString();
            }

            if (resultInfo.ErrorCode == 0)
            {
                result = "Export execution details to RQM performed successfully.";
                return(true);
            }
            else
            {
                result = resultInfo.ErrorDesc;
            }

            Reporter.ToLog(eLogLevel.ERROR, "Failed to export execution details to RQM/ALM");
            return(false);
        }
Esempio n. 42
0
        public ResultInfo MainPostNumberSave(string fuPostNumber, string mainPostNumber)
        {
            ResultInfo result = new ResultInfo();

            MailTotalPackageInfo m  = new MailTotalPackageInfo();
            string mainCountryCode  = "";
            string fuCountryCode    = "";
            string fourBagNumberStr = GetMainPackageNumber(mainPostNumber);

            if (string.IsNullOrWhiteSpace(fourBagNumberStr))
            {
                result.Status  = false;
                result.Message = "[总包号]不合法.";
                return(result);
            }

            int fourBagNumber;

            int.TryParse(fourBagNumberStr, out fourBagNumber);

            m.MailTotalPackageNumber = DateTime.Now.ToString("yyyyMMdd") + fourBagNumberStr;
            m.TotalPackageNumber     = mainPostNumber;
            m.ShortNumber            = fourBagNumber;
            m.ScanTime    = DateTime.Now;
            m.TrackStatus = 0;
            m.CreatedBy   = _workContext.User.UserUame;
            m.CreatedOn   = DateTime.Now;

            DateTime?dt = null;

            m.TaiWanArrivedTime   = dt;
            m.TaiWanDepartureTime = dt;
            m.ToArrivedTime       = dt;
            m.FuZhouDepartureTime = dt;
            m.LastUpdatedOn       = DateTime.Now;
            m.LastUpdatedBy       = _workContext.User.UserUame;

            MailTotalPackageOrPostBagRelational re = new MailTotalPackageOrPostBagRelational();

            re.CreatedBy = _workContext.User.UserUame;
            re.CreatedOn = DateTime.Now;
            //re.MailTotalPackageNumber
            //获取客袋带牌号信息
            var mailPostBagInfo = _mailPostBagInfoRepository.GetYunExpressBagNumber(fuPostNumber);

            if (mailPostBagInfo != null)
            {
                re.PostBagNumber = mailPostBagInfo.PostBagNumber;
                fuCountryCode    = mailPostBagInfo.CountryCode.ToUpperInvariant();
            }
            re.ScanTime      = DateTime.Now;
            re.LastUpdatedOn = DateTime.Now;
            re.LastUpdatedBy = _workContext.User.UserUame;


            if (mainPostNumber.Length > 8)
            {
                mainCountryCode = mainPostNumber.Substring(6, 2).ToUpperInvariant();
            }

            // 国际小包U+ 总包号扫描校验客户袋牌与总包号对应国家是否一致。
            // Add by zhengsong
            if (string.IsNullOrWhiteSpace(mainCountryCode) || string.IsNullOrWhiteSpace(fuCountryCode) ||
                mainCountryCode != fuCountryCode)
            {
                result.Status  = false;
                result.Message = "客户袋牌与总包号对应国家不一致,请检查是否贴错!关联不成功!";
                return(result);
            }

            if (string.IsNullOrWhiteSpace(re.PostBagNumber))
            {
                result.Status  = false;
                result.Message = "未找到[福邮袋牌]或者[总包号].";
                return(result);
            }

            try
            {
                if (_mailTotalPackageInfoRepository.SaveMainPostBagTag(m, re))
                {
                    result.Status = true;
                    return(result);
                }
            }
            catch (BusinessLogicException ex)
            {
                result.Message = ex.Message;
            }
            catch (Exception ex)
            {
                Log.Exception(ex);
            }
            result.Status = false;

            if (string.IsNullOrWhiteSpace(result.Message))
            {
                result.Message = "服务器内部错误.";
            }

            return(result);
        }
Esempio n. 43
0
        protected void Page_Load(object sender, EventArgs e)
        {
            // Debug.WriteLine("Page_Load()");

            if (WebUtil.PrepareEnvironment(this,
    ref app,
    ref sessioninfo) == false)
                return;

            string strError = "";

            // 是否登录?
            if (sessioninfo.UserID == "")
            {
                if (this.Page.Request["forcelogin"] == "on")
                {
                    sessioninfo.LoginCallStack.Push(Request.RawUrl);
                    Response.Redirect("login.aspx", true);
                    return;
                }
                if (this.Page.Request["forcelogin"] == "userid")
                {
                    sessioninfo.LoginCallStack.Push(Request.RawUrl);
                    Response.Redirect("login.aspx?loginstyle=librarian", true);
                    return;
                }
                sessioninfo.LoginCallStack.Push(Request.RawUrl);
                Response.Redirect("login.aspx", true);
                return;
            }

            LoginState loginstate = GlobalUtil.GetLoginState(this.Page);
            if (loginstate != LoginState.Librarian)
            {
                strError = "只有工作人员身份才能使用本模块";
                goto ERROR1;
            }

            string strAction = this.Request["action"];

            string strName = this.Request["name"];
            if (string.IsNullOrEmpty(strName) == true)
                strName = "CacheBuilder";

            this.Label_taskName.Text = strName;

            ResultInfo result_info = new ResultInfo();

            if (strAction == "getinfo")
            {
                string strResultOffset = this.Request["result_offset"];
                string strMaxResultBytes = this.Request["max_result_bytes"];

                if (string.IsNullOrEmpty(strResultOffset) == true)
                {
                    result_info.ErrorString = "未指定 result_offset 参数";
                    goto END1;
                }
                long lResultOffset = 0;
                Int64.TryParse(strResultOffset, out lResultOffset);
                int nMaxResultBytes = 4096;
                Int32.TryParse(strMaxResultBytes, out nMaxResultBytes);

                BatchTaskInfo param = new BatchTaskInfo();
                BatchTaskInfo info = null;

                param.ResultOffset = lResultOffset;
                param.MaxResultBytes = nMaxResultBytes;

                Debug.WriteLine("GetBatchTaskInfo()");

                int nRet = app.GetBatchTaskInfo(strName,
                    param,
                    out info,
                    out strError);
                if (nRet == -1)
                {
                    result_info.ErrorString = strError;
                    goto END1;
                }

                result_info.Name = info.Name;
                result_info.MaxResultBytes = info.MaxResultBytes;
                result_info.ResultText = GetResultText(info.ResultText);
                result_info.ProgressText = info.ProgressText;
                result_info.ResultOffset = info.ResultOffset;
                result_info.ResultTotalLength = info.ResultTotalLength;
                result_info.ResultVersion = info.ResultVersion;

            END1:

                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ResultInfo));

                MemoryStream ms = new MemoryStream();
                ser.WriteObject(ms, result_info);
                string strResult = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();

                this.Response.Write(strResult);
                this.Response.End();
                return;
            }

            return;
        ERROR1:
            this.Response.Write(strError);
            this.Response.End();
        }
Esempio n. 44
0
        public JsonResult AddProject(ProjectRegister account)
        {
            ResultInfo info        = new ResultInfo();
            int        companyId   = CommonMethod.GetInt(ConfigSetting.eeeYoooId);
            string     companyName = ConfigSetting.eeeYoooName;

            account.PassWord = CommonMethod.PasswordMD5(account.PassWord);
            if (AccountDBOperate.GetAccountByMobile(account.Telephone, account.Role))
            {
                info.Message = "手机号已注册";
                return(Json(info));
            }
            if (AccountDBOperate.GetAccountByEmail(account.Email, account.Role))
            {
                info.Message = "邮箱已注册";
                return(Json(info));
            }
            var list = new List <PersonSetting>()
            {
            };
            var roles   = account.RoleId.Split(',');
            var joblist = JobListDBOperate.GetPublishList();

            foreach (var item in roles)
            {
                var job = joblist.FirstOrDefault(a => a.Id == Convert.ToInt32(item));
                if (job == null)
                {
                    continue;
                }
                var personSetting = new PersonSetting()
                {
                    CreateBy = account.Name, DepartId = Convert.ToInt32(item), DepartName = job.Name, Discount = 100, Month = account.Month, Price = job.Price, TotalPrice = job.Price * account.Month
                };
                list.Add(personSetting);
            }


            info.IsSuccess = AccountDBOperate.AddAccount(new Dto.CustomerCompany()
            {
                CompanyId     = companyId,
                CompanyName   = companyName,
                Address       = account.CompanyAddress,
                City          = account.City,
                Infos         = account.CompanyInfo,
                Name          = account.CompanyName,
                Status        = CustomerCompanyStatusEnum.NotStart.ToString(),
                CreateBy      = account.Name,
                TeamDesc      = account.TeamDesc,
                CompanyStatus = account.CompanyStatus,
                PartInfo      = account.PartInfo
            }, new CustomerMember()
            {
                CompanyId   = companyId,
                CompanyName = companyName,
                Email       = account.Email,
                Mobile      = account.Telephone,
                Name        = account.Name,
                CreateBy    = account.Name,
                Address     = account.MemberAddress
            }, new Account()
            {
                AccountName = account.Name,
                Mobile      = account.Telephone,
                Password    = account.PassWord,
                Email       = account.Email,
                Role        = account.Role,
                CreateBy    = account.Name,
            }, new ProjectManage()
            {
                CompanyId      = companyId,
                FullName       = account.ProjectName,
                Name           = account.ProjectName,
                CusCompanyName = account.CompanyName,
                CusMemberName  = account.Name,
                //LastPayDate = account.EndTime,
                Infos     = account.Info,
                IsDeleted = 0,
                Money     = 0,
                PayWay    = ProjectPayWayEnum.UnKnown.ToString(),
                //RelStartTime = account.StartTime,
                //StartTime = account.StartTime,
                EndTime = account.EndTime,
                Source  = SourceEnum.PC.ToString(),
                //RelEndTime = account.EndTime,
                Status         = CustomerCompanyStatusEnum.NotStart.ToString(),
                OpereateType   = account.OpereateType,
                DevLanguate    = account.DevLanguate,
                DevType        = account.DevType,
                NowStatus      = account.NowStatus,
                MarketProspect = account.MarketProspect,
                Month          = account.Month
            }, new HardWare()
            {
                CreateBy = account.Name,
                Infos    = account.HardWare
            }, list);
            //AccountDBOperate.LoginByMobileOrEmail(account.Telephone);
            return(Json(info));
        }
        //---------------------------------------------------------------------------------------//
        public override ExperimentResultInfo Execute(ExperimentSpecification experimentSpecification)
        {
            const string STRLOG_MethodName = "Execute";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Determine how long it actually take to execute
            //
            DateTime startDateTime = DateTime.Now;

            // Typecast the specification so that it can be used here
            Specification specification = (Specification)experimentSpecification;

            //
            // Log the specification
            //
            string logMessage = string.Empty;
            //
            // YOUR CODE HERE
            //
            Logfile.Write(logMessage);

            //
            // Create an instance of the result info ready to fill in
            //
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.statusCode = StatusCodes.Running;

            //
            // Initialise variables used in the state machine
            //

            try
            {
                //
                // Run the state machine to execute the experiment specification
                //
                States_Execute state = States_Execute.sCompleted;
                if (smTable_Execute.Length > 0)
                {
                    state = smTable_Execute[0].currentState;
                }
                while (state != States_Execute.sCompleted)
                {
                    //
                    // Find table entry
                    //
                    int index = -1;
                    for (int i = 0; i < smTable_Execute.Length; i++)
                    {
                        if (smTable_Execute[i].currentState == state)
                        {
                            // Entry found
                            index = i;
                            break;
                        }
                    }
                    if (index == -1)
                    {
                        throw new ArgumentOutOfRangeException(state.ToString(), STRERR_StateNotFound);
                    }

                    //
                    // Get table entry and save next state
                    //
                    SMTableEntry_Execute entry = smTable_Execute[index];
                    States_Execute nextState = entry.nextState;

                    logMessage = " [ " + STRLOG_MethodName + ": " + entry.currentState.ToString() + " ]";
                    Logfile.Write(logMessage);

                    Trace.WriteLine(logMessage);

                    //
                    // Check if experiment was cancelled
                    //
                    if (this.cancelExperiment != null && this.cancelExperiment.IsCancelled == true &&
                        resultInfo.statusCode == StatusCodes.Running)
                    {
                        //
                        // Experiment was cancelled
                        //
                        resultInfo.statusCode = StatusCodes.Cancelled;
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Process commands
                    //
                    switch (entry.currentState)
                    {
                        //
                        // YOUR CODE HERE
                        //

                        default:
                            break;
                    }

                    Trace.WriteLine("nextState: " + entry.nextState.ToString());

                    //
                    // Next state
                    //
                    state = nextState;
                }

                //
                // Update status code
                //
                if (resultInfo.statusCode == StatusCodes.Running)
                {
                    resultInfo.statusCode = StatusCodes.Completed;
                }
            }
            catch (Exception ex)
            {
                resultInfo.statusCode = StatusCodes.Failed;
                resultInfo.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            TimeSpan timeSpan = DateTime.Now - startDateTime;
            logMessage = STRLOG_ExecutionTime + timeSpan.TotalSeconds.ToString();

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return resultInfo;
        }
Esempio n. 46
0
        public ResultInfo AddMailer()
        {
            ResultInfo result = new ResultInfo()
            {
                error = 0,
                msg   = "Them moi thanh cong"
            };

            try
            {
                var requestContent = Request.Content.ReadAsStringAsync().Result;

                var jsonserializer = new JavaScriptSerializer();
                var paser          = jsonserializer.Deserialize <MailerIdentity>(requestContent);

                var findCus = db.BS_Customers.Where(p => p.CustomerCode == paser.SenderID).FirstOrDefault();

                if (findCus == null)
                {
                    throw new Exception("Sai thông tin");
                }

                if (String.IsNullOrEmpty(findCus.Address) || String.IsNullOrEmpty(findCus.ProvinceID) || String.IsNullOrEmpty(findCus.DistrictID) || String.IsNullOrEmpty(findCus.CustomerName))
                {
                    throw new Exception("Cập nhật lại thông tin cá nhân");
                }

                MailerHandleCommon mailerHandle = new MailerHandleCommon(db);
                var code = mailerHandle.GeneralMailerCode(findCus.PostOfficeID);
                //  var price = db.CalPrice(paser.Weight, findCus.CustomerID, paser.RecieverProvinceID, paser.MailerTypeID, findCus.PostOfficeID, DateTime.Now.ToString("yyyy-MM-dd")).FirstOrDefault();
                var codPrice = 0;

                decimal?price = 0;
                if (paser.COD > 0)
                {
                    var findDitrict = db.BS_Districts.Where(p => p.DistrictID == paser.RecieverDistrictID).FirstOrDefault();
                    int?vsvx        = findDitrict == null ? 1 : (findDitrict.VSVS == true ? 1 : 0);
                    price = db.CalPriceCOD(paser.Weight, findCus.CustomerID, paser.RecieverProvinceID, "CD", findCus.PostOfficeID, DateTime.Now.ToString("yyyy-MM-dd"), vsvx, paser.MailerTypeID == "ST" ? "CODTK" : "CODN").FirstOrDefault();
                }
                else
                {
                    price = db.CalPrice(paser.Weight, findCus.CustomerID, paser.RecieverProvinceID, paser.MailerTypeID, findCus.PostOfficeID, DateTime.Now.ToString("yyyy-MM-dd")).FirstOrDefault();
                }

                //
                var     checkRece    = db.BS_Districts.Where(p => p.DistrictID == paser.RecieverDistrictID).FirstOrDefault();
                decimal?priceService = 0;
                if (checkRece != null)
                {
                    if (checkRece.VSVS == true)
                    {
                        var findService = db.BS_Services.Where(p => p.ServiceID == "VSVX").FirstOrDefault();

                        if (findService.IsPercent == true)
                        {
                            priceService = (price * findService.Price) / 100;
                        }
                        else
                        {
                            priceService = findService.Price;
                        }

                        var mailerService = new MM_MailerServices()
                        {
                            MailerID     = code,
                            CreationDate = DateTime.Now,
                            SellingPrice = (decimal)priceService,
                            PriceDefault = (decimal)priceService,
                            ServiceID    = "VSVX"
                        };
                        db.MM_MailerServices.Add(mailerService);
                    }
                }

                // theem
                var mailerIns = new MM_Mailers()
                {
                    MailerID            = code,
                    AcceptTime          = DateTime.Now,
                    AcceptDate          = DateTime.Now,
                    COD                 = paser.COD,
                    CreationDate        = DateTime.Now,
                    CurrentStatusID     = 0,
                    HeightSize          = paser.HeightSize,
                    Weight              = paser.Weight,
                    LengthSize          = paser.LengthSize,
                    WidthSize           = paser.WidthSize,
                    Quantity            = paser.Quantity,
                    PostOfficeAcceptID  = findCus.PostOfficeID,
                    CurrentPostOfficeID = findCus.PostOfficeID,
                    EmployeeAcceptID    = "",
                    MailerDescription   = paser.MailerDescription,
                    MailerTypeID        = paser.MailerTypeID,
                    MerchandiseValue    = paser.MerchandiseValue,
                    MerchandiseID       = paser.MerchandiseID,
                    PriceDefault        = price,
                    Price               = price,
                    PriceService        = priceService,
                    Amount              = price + codPrice + priceService,
                    PriceCoD            = codPrice,
                    Notes               = paser.Notes,
                    PaymentMethodID     = paser.PaymentMethodID,
                    RecieverAddress     = paser.RecieverAddress,
                    RecieverName        = paser.RecieverName,
                    RecieverPhone       = paser.RecieverPhone,
                    RecieverDistrictID  = paser.RecieverDistrictID,
                    RecieverWardID      = paser.RecieverWardID,
                    RecieverProvinceID  = paser.RecieverProvinceID,
                    SenderID            = findCus.CustomerCode,
                    SenderAddress       = findCus.Address,
                    SenderDistrictID    = findCus.DistrictID,
                    SenderName          = findCus.CustomerName,
                    SenderPhone         = findCus.Phone,
                    SenderProvinceID    = findCus.ProvinceID,
                    SenderWardID        = findCus.WardID,
                    PaidCoD             = 0,
                    CreateType          = 1,
                    IsReturn            = false,
                    IsPayment           = 0
                };

                //
                db.MM_Mailers.Add(mailerIns);
                db.SaveChanges();
            }
            catch (Exception e)
            {
                result.error = 1;
                result.msg   = e.Message;
            }
            return(result);
        }
        //---------------------------------------------------------------------------------------//
        public override ExperimentResultInfo Execute(ExperimentSpecification experimentSpecification)
        {
            const string STRLOG_MethodName = "Execute";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Determine how long it actually take to execute
            //
            DateTime startDateTime = DateTime.Now;

            // Typecast the specification so that it can be used here
            Specification specification = (Specification)experimentSpecification;

            //
            // Log the specification
            //
            string strDistanceList = null;
            for (int i = 0; i < specification.DistanceList.Length; i++)
            {
                if (i > 0)
                {
                    strDistanceList += Consts.CHR_CsvSplitter.ToString();
                }
                strDistanceList += specification.DistanceList[i].ToString();
            }
            string logMessage = STRLOG_Distance + strDistanceList;
            logMessage += Logfile.STRLOG_Spacer + STRLOG_Duration + specification.Duration.ToString();
            logMessage += Logfile.STRLOG_Spacer + STRLOG_Repeat + specification.Repeat.ToString();
            Logfile.Write(logMessage);

            //
            // Create an instance of the result info ready to fill in
            //
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.statusCode = StatusCodes.Running;
            if (this.simActivity.SimulateDelays == true)
            {
                resultInfo.dataType = DataTypes.Simulated;
            }
            else
            {
                resultInfo.dataType = DataTypes.Calculated;
            }

            //
            // Create data structures to hold the results
            //
            resultInfo.dataVectors = new int[specification.DistanceList.Length, specification.Repeat];

            //
            // Initialise variables used in the state machine
            //
            int distanceIndex = 0;
            int repeatIndex = 0;
            int[] generatedData = null;

            try
            {
                //
                // Run the state machine to execute the experiment specification
                //
                States_Execute state = States_Execute.sCompleted;
                if (smTable_Execute.Length > 0)
                {
                    state = smTable_Execute[0].currentState;
                }
                while (state != States_Execute.sCompleted)
                {
                    //
                    // Find table entry
                    //
                    int index = -1;
                    for (int i = 0; i < smTable_Execute.Length; i++)
                    {
                        if (smTable_Execute[i].currentState == state)
                        {
                            // Entry found
                            index = i;
                            break;
                        }
                    }
                    if (index == -1)
                    {
                        throw new ArgumentOutOfRangeException(state.ToString(), STRERR_StateNotFound);
                    }

                    //
                    // Get table entry and save next state
                    //
                    SMTableEntry_Execute entry = smTable_Execute[index];
                    States_Execute nextState = entry.nextState;

                    logMessage = " [ " + STRLOG_MethodName + ": " + entry.currentState.ToString() + " ]";
                    Logfile.Write(logMessage);

                    Trace.WriteLine(logMessage);

                    //
                    // Check if experiment was cancelled
                    //
                    if (this.cancelExperiment != null && this.cancelExperiment.IsCancelled == true &&
                        resultInfo.statusCode == StatusCodes.Running)
                    {
                        //
                        // Experiment was cancelled
                        //
                        resultInfo.statusCode = StatusCodes.Cancelled;
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Process commands
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sSelectAbsorber:

                            //
                            // Get absorber location from specification
                            //
                            char absorberLocation = specification.AbsorberList[0].location;
                            Logfile.Write(STRLOG_AbsorberLocation + absorberLocation.ToString());

                            //
                            // Set absorber location
                            //
                            this.simActivity.SetAbsorberLocation(absorberLocation);
                            break;

                        case States_Execute.sSelectSource:

                            //
                            // Get source location from specification
                            //
                            char sourceLocation = specification.SourceLocation;
                            Logfile.Write(STRLOG_SourceLocation + sourceLocation.ToString());

                            //
                            // Set source location
                            //
                            this.simActivity.SetSourceLocation(sourceLocation);
                            break;

                        case States_Execute.sSetTubeDistance:

                            //
                            // Get tube distance from specification
                            //
                            int tubeDistance = specification.DistanceList[distanceIndex];
                            Logfile.Write(STRLOG_TubeDistance + tubeDistance.ToString());

                            //
                            // Set tube distance
                            //
                            this.simActivity.SetTubeDistance(tubeDistance);
                            break;

                        case States_Execute.sCaptureData:

                            if (repeatIndex == 0)
                            {
                                //
                                // Generate data for repeat counts at this distance
                                //
                                generatedData = this.simActivity.GenerateData(
                                    specification.DistanceList[distanceIndex], specification.Duration, specification.Repeat);
                            }

                            //
                            // Get capture data for this repeat count
                            //
                            int[] counts = new int[1];
                            this.simActivity.CaptureData(specification.Duration, counts, generatedData, repeatIndex);
                            resultInfo.dataVectors[distanceIndex, repeatIndex] = counts[0];
                            Logfile.Write(STRLOG_Duration + specification.Duration.ToString() +
                                Logfile.STRLOG_Spacer + STRLOG_Count + counts[0].ToString());

                            //
                            // Determine next state
                            //
                            if (++repeatIndex == specification.Repeat)
                            {
                                if (++distanceIndex == specification.DistanceList.Length)
                                {
                                    // All distances completed
                                    break;
                                }

                                // Next distance
                                repeatIndex = 0;
                                nextState = States_Execute.sSetTubeDistance;
                                break;
                            }

                            // Next repeat
                            nextState = States_Execute.sCaptureData;
                            break;

                        case States_Execute.sReturnSource:

                            //
                            // Get source home location
                            //
                            sourceLocation = this.simActivity.SourceHomeLocation;
                            Logfile.Write(STRLOG_SourceLocation + sourceLocation.ToString());

                            //
                            // Set source location
                            //
                            this.simActivity.SetSourceLocation(sourceLocation);
                            break;

                        case States_Execute.sReturnAbsorber:

                            //
                            // Get absorber home location
                            //
                            absorberLocation = this.simActivity.AbsorberHomeLocation;
                            Logfile.Write(STRLOG_AbsorberLocation + absorberLocation.ToString());

                            //
                            // Set absorber location
                            //
                            this.simActivity.SetAbsorberLocation(absorberLocation);
                            break;

                        case States_Execute.sReturnTube:

                            //
                            // Get tube home distance
                            //
                            tubeDistance = this.simActivity.TubeHomeDistance;
                            Logfile.Write(STRLOG_TubeDistance + tubeDistance.ToString());

                            //
                            // Set tube distance
                            //
                            this.simActivity.SetTubeDistance(tubeDistance);
                            break;

                        default:
                            break;
                    }

                    Trace.WriteLine("nextState: " + entry.nextState.ToString());

                    //
                    // Next state
                    //
                    state = nextState;
                }

                //
                // Update status code
                //
                if (resultInfo.statusCode == StatusCodes.Running)
                {
                    resultInfo.statusCode = StatusCodes.Completed;
                }
            }
            catch (Exception ex)
            {
                resultInfo.statusCode = StatusCodes.Failed;
                resultInfo.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            TimeSpan timeSpan = DateTime.Now - startDateTime;
            logMessage = STRLOG_ExecutionTime + timeSpan.TotalSeconds.ToString();

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return resultInfo;
        }
Esempio n. 48
0
        public ResultInfo GetMailers()
        {
            ResultInfo result = new ResultInfo()
            {
                error = 0,
                msg   = "Them moi thanh cong"
            };

            try
            {
                var requestContent = Request.Content.ReadAsStringAsync().Result;

                var jsonserializer = new JavaScriptSerializer();
                var paser          = jsonserializer.Deserialize <MailerShowRequest>(requestContent);

                int pageSize = 50;

                int pageNumber = (paser.page ?? 1);


                DateTime paserFromDate = DateTime.Now;
                DateTime paserToDate   = DateTime.Now;

                try
                {
                    paserFromDate = DateTime.ParseExact(paser.fromDate, "dd/MM/yyyy", null);
                    paserToDate   = DateTime.ParseExact(paser.toDate, "dd/MM/yyyy", null);
                }
                catch
                {
                    paserFromDate = DateTime.Now;
                    paserToDate   = DateTime.Now;
                }

                var findCus = db.BS_Customers.Where(p => p.CustomerCode == paser.customerId).FirstOrDefault();
                if (findCus == null)
                {
                    throw new Exception("sai thông tin");
                }

                var data = db.MAILER_GETALL(paserFromDate.ToString("yyyy-MM-dd"), paserToDate.ToString("yyyy-MM-dd"), "%" + findCus.PostOfficeID + "%", "%" + paser.search + "%").Where(p => p.SenderID.Contains(paser.customerId)).ToList();

                if (paser.status != -1)
                {
                    data = data.Where(p => p.CurrentStatusID == paser.status).ToList();
                }

                result = new ResultWithPaging()
                {
                    error      = 0,
                    msg        = "",
                    page       = pageNumber,
                    pageSize   = pageSize,
                    toltalSize = data.Count(),
                    data       = data.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList()
                };
            }
            catch (Exception e)
            {
                result.error = 1;
                result.msg   = e.Message;
            }
            return(result);
        }
        //---------------------------------------------------------------------------------------//
        public override ExperimentResultInfo Execute(ExperimentSpecification experimentSpecification)
        {
            const string STRLOG_MethodName = "Execute";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            // Typecast the specification so that it can be used here
            Specification specification = (Specification)experimentSpecification;

            //
            // Log the specification
            //
            string logMessage = string.Empty;
            //Logfile.Write(logMessage);

            //
            // Create an instance of the result info ready to fill in
            //
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.statusCode = StatusCodes.Running;

            //
            // Initialise variables used in the state machine
            //
            int repeatCount = 0;

            try
            {
                //
                // First, check to see if the LabEquipment is online
                //
                LabEquipmentStatus labEquipmentStatus = this.equipmentServiceProxy.GetLabEquipmentStatus();
                if (labEquipmentStatus.online == false)
                {
                    throw new Exception(labEquipmentStatus.statusMessage);
                }

                //
                // Run the state machine to execute the experiment specification
                //
                States_Execute state = States_Execute.sCompleted;
                if (smTable_Execute.Length > 0)
                {
                    state = smTable_Execute[0].currentState;
                }
                while (state != States_Execute.sCompleted)
                {
                    //
                    // Find table entry
                    //
                    int index = -1;
                    for (int i = 0; i < smTable_Execute.Length; i++)
                    {
                        if (smTable_Execute[i].currentState == state)
                        {
                            // Entry found
                            index = i;
                            break;
                        }
                    }
                    if (index == -1)
                    {
                        throw new ArgumentOutOfRangeException(state.ToString(), STRERR_StateNotFound);
                    }

                    //
                    // Get table entry and save next state
                    //
                    SMTableEntry_Execute entry = smTable_Execute[index];
                    States_Execute nextState = entry.nextState;

                    logMessage = " [ " + STRLOG_MethodName + ": " + entry.currentState.ToString() + " ]";
                    Logfile.Write(logMessage);

                    Trace.WriteLine(logMessage);

                    //
                    // Check if experiment was cancelled
                    //
                    if (this.cancelExperiment != null && this.cancelExperiment.IsCancelled == true &&
                        resultInfo.statusCode == StatusCodes.Running)
                    {
                        //
                        // Experiment was cancelled
                        //
                        resultInfo.statusCode = StatusCodes.Cancelled;
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Process non-XML commands
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sSuspendPowerdown:
                            if (this.equipmentServiceProxy.SuspendPowerdown() == false)
                            {
                                //
                                // Command execution failed
                                //
                                resultInfo.statusCode = StatusCodes.Failed;
                                resultInfo.errorMessage = STRERR_SuspendPowerdown;
                                state = entry.exitState;
                            }
                            else
                            {
                                state = nextState;
                            }
                            continue;

                        case States_Execute.sResumePowerdown:
                            if (this.equipmentServiceProxy.ResumePowerdown() == false)
                            {
                                //
                                // Command execution failed
                                //
                                resultInfo.statusCode = StatusCodes.Failed;
                                resultInfo.errorMessage = STRERR_ResumePowerdown;
                                state = entry.exitState;
                            }
                            else
                            {
                                state = nextState;
                            }
                            continue;

                        default:
                            break;
                    }

                    //
                    // Add command arguments where required
                    //
                    switch (entry.currentState)
                    {
                        //
                        // Nothing to do here
                        //

                        default:
                            break;
                    }

                    //
                    // Execute command and check response success
                    //
                    XmlDocument xmlRequestDocument = CreateXmlRequestDocument(entry.equipmentCommand, entry.commandArguments);
                    string xmlResponse = this.equipmentServiceProxy.ExecuteRequest(xmlRequestDocument.InnerXml);
                    XmlNode xmlResponseNode = CreateXmlResponseNode(xmlResponse);
                    if (XmlUtilities.GetBoolValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspSuccess, false) == false)
                    {
                        //
                        // Command execution failed
                        //
                        resultInfo.statusCode = StatusCodes.Failed;
                        resultInfo.errorMessage = XmlUtilities.GetXmlValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspErrorMessage, true);
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Extract response values where required
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sTakeMeasurement:

                            //
                            // Add in the values
                            //
                            resultInfo.voltage += (float)XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspVoltageMut, 0.0);
                            resultInfo.current += (float)XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspCurrentMut, 0.0);
                            resultInfo.powerFactor += (float)XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspPowerFactorMut, 0.0);
                            resultInfo.speed += XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspSpeed, 0);
                            resultInfo.torque += XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspTorque, 0);

                            //
                            // Check if all measurements have been taken
                            //
                            if (++repeatCount == this.measurementCount)
                            {
                                //
                                // All measurements taken, average the values
                                //
                                resultInfo.voltage /= this.measurementCount;
                                resultInfo.current /= this.measurementCount;
                                resultInfo.powerFactor /= this.measurementCount;
                                resultInfo.speed /= this.measurementCount;
                                resultInfo.torque /= this.measurementCount;
                                break;
                            }

                            // Next measurement
                            nextState = States_Execute.sTakeMeasurement;
                            break;

                        default:
                            break;
                    }

                    //
                    // Next state
                    //
                    state = nextState;
                }

                //
                // Update status code
                //
                if (resultInfo.statusCode == StatusCodes.Running)
                {
                    resultInfo.statusCode = StatusCodes.Completed;
                }
            }
            catch (Exception ex)
            {
                resultInfo.statusCode = StatusCodes.Failed;
                resultInfo.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            logMessage = STRLOG_StatusCode + resultInfo.statusCode;

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return resultInfo;
        }
        //---------------------------------------------------------------------------------------//
        public override ExperimentResultInfo Execute(ExperimentSpecification experimentSpecification)
        {
            const string STRLOG_MethodName = "Execute";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Determine how long it actually take to execute
            //
            DateTime startDateTime = DateTime.Now;

            // Typecast the specification so that it can be used here
            Specification specification = (Specification)experimentSpecification;

            //
            // Log the specification
            //
            string logMessage = STRLOG_SetupId + specification.SetupId;
            Logfile.Write(logMessage);

            //
            // Create an instance of the result info ready to fill in
            //
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.statusCode = StatusCodes.Running;

            //
            // Initialise variables used in the state machine
            //

            try
            {
                //
                // First, check to see if the LabEquipment is online
                //
                LabEquipmentStatus labEquipmentStatus = this.equipmentServiceProxy.GetLabEquipmentStatus();
                if (labEquipmentStatus.online == false)
                {
                    throw new Exception(labEquipmentStatus.statusMessage);
                }

                //
                // Run the state machine to execute the experiment specification
                //
                States_Execute state = States_Execute.sCompleted;
                if (smTable_Execute.Length > 0)
                {
                    state = smTable_Execute[0].currentState;
                }
                while (state != States_Execute.sCompleted)
                {
                    //
                    // Find table entry
                    //
                    int index = -1;
                    for (int i = 0; i < smTable_Execute.Length; i++)
                    {
                        if (smTable_Execute[i].currentState == state)
                        {
                            // Entry found
                            index = i;
                            break;
                        }
                    }
                    if (index == -1)
                    {
                        throw new ArgumentOutOfRangeException(state.ToString(), STRERR_StateNotFound);
                    }

                    //
                    // Get table entry and save next state
                    //
                    SMTableEntry_Execute entry = smTable_Execute[index];
                    States_Execute nextState = entry.nextState;

                    logMessage = " [ " + STRLOG_MethodName + ": " + entry.currentState.ToString() + " ]";
                    Logfile.Write(logMessage);

                    Trace.WriteLine(logMessage);

                    //
                    // Check if experiment was cancelled
                    //
                    if (this.cancelExperiment != null && this.cancelExperiment.IsCancelled == true &&
                        resultInfo.statusCode == StatusCodes.Running)
                    {
                        //
                        // Experiment was cancelled
                        //
                        resultInfo.statusCode = StatusCodes.Cancelled;
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Process non-XML commands
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sSuspendPowerdown:
                            if (this.equipmentServiceProxy.SuspendPowerdown() == false)
                            {
                                //
                                // Command execution failed
                                //
                                resultInfo.statusCode = StatusCodes.Failed;
                                resultInfo.errorMessage = STRERR_SuspendPowerdown;
                                state = entry.exitState;
                            }
                            else
                            {
                                state = nextState;
                            }
                            continue;

                        case States_Execute.sResumePowerdown:
                            if (this.equipmentServiceProxy.ResumePowerdown() == false)
                            {
                                //
                                // Command execution failed
                                //
                                resultInfo.statusCode = StatusCodes.Failed;
                                resultInfo.errorMessage = STRERR_ResumePowerdown;
                                state = entry.exitState;
                            }
                            else
                            {
                                state = nextState;
                            }
                            continue;

                        default:
                            break;
                    }

                    //
                    // Add command arguments where required
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sStartExecution:
                            entry.commandArguments[0, 1] = specification.ToString();
                            break;

                        default:
                            break;
                    }

                    //
                    // Execute command and check response success
                    //
                    XmlDocument xmlRequestDocument = CreateXmlRequestDocument(entry.equipmentCommand, entry.commandArguments);
                    string xmlResponse = this.equipmentServiceProxy.ExecuteRequest(xmlRequestDocument.InnerXml);
                    XmlNode xmlResponseNode = CreateXmlResponseNode(xmlResponse);
                    if (XmlUtilities.GetBoolValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspSuccess, false) == false)
                    {
                        //
                        // Command execution failed
                        //
                        resultInfo.statusCode = StatusCodes.Failed;
                        resultInfo.errorMessage = XmlUtilities.GetXmlValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspErrorMessage, true);
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Extract response values where required
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sGetExecutionStatus:
                            //
                            // Get the execution status
                            //
                            string strExecutionStatus = XmlUtilities.GetXmlValue(xmlResponseNode, Consts.STRXML_RspExecutionStatus, false);
                            Trace.WriteLine("ExecutionStatus: " + strExecutionStatus);

                            //
                            // Get the execution time remaining
                            //
                            int executionTimeRemaining = XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspExecutionTimeRemaining, -1);
                            Trace.WriteLine("ExecutionTimeRemaining: " + executionTimeRemaining.ToString());

                            //
                            // Convert to an ExecutionStatus enum type
                            //
                            ExecutionStatus executionStatus = (ExecutionStatus)Enum.Parse(typeof(ExecutionStatus), strExecutionStatus);

                            //
                            // Check if execution has completed
                            //
                            if (executionStatus != ExecutionStatus.Completed)
                            {
                                //
                                // Not yet, wait a bit and then check again
                                //
                                int secondsToWait = 1;
                                if (executionTimeRemaining > 40)
                                {
                                    secondsToWait = 20;
                                }
                                else if (executionTimeRemaining > 5)
                                {
                                    secondsToWait = executionTimeRemaining / 2;
                                }
                                else
                                {
                                    secondsToWait = 2;
                                }

                                for (int i = 0; i < secondsToWait; i++)
                                {
                                    Trace.Write(".");
                                    Thread.Sleep(1000);
                                }

                                nextState = States_Execute.sGetExecutionStatus;
                            }
                            break;

                        case States_Execute.sGetExecutionResultStatus:
                            //
                            // Get the execution result status
                            //
                            string strExecutionResultStatus = XmlUtilities.GetXmlValue(xmlResponseNode, Consts.STRXML_RspExecutionResultStatus, false);
                            Trace.WriteLine("ExecutionResultStatus: " + strExecutionResultStatus);

                            //
                            // Convert to an ExecutionStatus enum type
                            //
                            ExecutionStatus executionResultStatus = (ExecutionStatus)Enum.Parse(typeof(ExecutionStatus), strExecutionResultStatus);

                            //
                            // Check if results are available
                            //
                            if (executionResultStatus != ExecutionStatus.Completed)
                            {
                                resultInfo.statusCode = StatusCodes.Failed;
                                //resultInfo.errorMessage = ;
                            }
                            break;

                        case States_Execute.sGetExecutionResults:
                            //
                            // Get the execution results
                            //
                            resultInfo.xmlMeasurements = XmlUtilities.GetXmlValue(xmlResponseNode, Consts.STRXML_RspExecutionResults, false);
                            Trace.WriteLine("ExecutionResults: " + resultInfo.xmlMeasurements);
                            break;

                        default:
                            break;
                    }

                    //
                    // Next state
                    //
                    state = nextState;
                }

                //
                // Update status code
                //
                if (resultInfo.statusCode == StatusCodes.Running)
                {
                    resultInfo.statusCode = StatusCodes.Completed;
                }
            }
            catch (Exception ex)
            {
                resultInfo.statusCode = StatusCodes.Failed;
                resultInfo.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            //
            // Calculate actual execution time
            //
            TimeSpan timeSpan = DateTime.Now - startDateTime;

            logMessage = STRLOG_StatusCode + resultInfo.statusCode
                + Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + timeSpan.TotalSeconds.ToString();

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return resultInfo;
        }
Esempio n. 51
0
        //private string UserName = "******";
        //private string Pwd = "qiandt.com";
        private AsyncCompletedEventArgs GetEventArgs(string result, object userToken)
        {
            if (string.IsNullOrWhiteSpace(result)) {
                return new AsyncCompletedEventArgs(new ApplicationException("调用远程短信发送接口,返回未知的状态错误"), false, userToken);
            }

            int index;

            if (int.TryParse(result, out index)) {
                var info = new ResultInfo();
                if (index == 1) {
                    return new AsyncCompletedEventArgs(null, false, userToken);
                }
                return new AsyncCompletedEventArgs(new ApplicationException(info.GetErrorInfo(index)), false, userToken);
            }

            return new AsyncCompletedEventArgs(new ApplicationException("未知错误"), false, userToken);
        }
        //---------------------------------------------------------------------------------------//
        public override ExperimentResultInfo Execute(ExperimentSpecification experimentSpecification)
        {
            const string STRLOG_MethodName = "Execute";

            Logfile.WriteCalled(STRLOG_ClassName, STRLOG_MethodName);

            //
            // Determine how long it actually take to execute
            //
            DateTime startDateTime = DateTime.Now;

            // Typecast the specification so that it can be used here
            Specification specification = (Specification)experimentSpecification;

            //
            // Log the specification
            //
            string logMessage = STRLOG_SpeedMin + specification.Speed.min.ToString() +
                Logfile.STRLOG_Spacer + STRLOG_SpeedMax + specification.Speed.max.ToString() +
                Logfile.STRLOG_Spacer + STRLOG_SpeedStep + specification.Speed.step.ToString();
            Logfile.Write(logMessage);

            //
            // Create an instance of the result info ready to fill in
            //
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.statusCode = StatusCodes.Running;

            //
            // Create data structures to hold the results
            //
            int vectorLength = ((specification.Speed.max - specification.Speed.min) / specification.Speed.step) + 1;
            resultInfo.speedVector = new int[vectorLength];
            resultInfo.voltageVector = new int[vectorLength];
            resultInfo.loadVector = new int[vectorLength];
            resultInfo.fieldVector = new float[vectorLength];

            //
            // Initialise variables used in the state machine
            //
            int vectorIndex = 0;
            int repeatCount = 0;

            try
            {
                //
                // First, check to see if the LabEquipment is online
                //
                LabEquipmentStatus labEquipmentStatus = this.equipmentServiceProxy.GetLabEquipmentStatus();
                if (labEquipmentStatus.online == false)
                {
                    throw new Exception(labEquipmentStatus.statusMessage);
                }

                //
                // Run the state machine to execute the experiment specification
                //
                States_Execute state = States_Execute.sCompleted;
                if (smTable_Execute.Length > 0)
                {
                    state = smTable_Execute[0].currentState;
                }
                while (state != States_Execute.sCompleted)
                {
                    //
                    // Find table entry
                    //
                    int index = -1;
                    for (int i = 0; i < smTable_Execute.Length; i++)
                    {
                        if (smTable_Execute[i].currentState == state)
                        {
                            // Entry found
                            index = i;
                            break;
                        }
                    }
                    if (index == -1)
                    {
                        throw new ArgumentOutOfRangeException(state.ToString(), STRERR_StateNotFound);
                    }

                    //
                    // Get table entry and save next state
                    //
                    SMTableEntry_Execute entry = smTable_Execute[index];
                    States_Execute nextState = entry.nextState;

                    logMessage = " [ " + STRLOG_MethodName + ": " + entry.currentState.ToString() + " ]";
                    Logfile.Write(logMessage);

                    Trace.WriteLine(logMessage);

                    //
                    // Check if experiment was cancelled
                    //
                    if (this.cancelExperiment != null && this.cancelExperiment.IsCancelled == true &&
                        resultInfo.statusCode == StatusCodes.Running)
                    {
                        //
                        // Experiment was cancelled
                        //
                        resultInfo.statusCode = StatusCodes.Cancelled;
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Process non-XML commands
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sSuspendPowerdown:
                            if (this.equipmentServiceProxy.SuspendPowerdown() == false)
                            {
                                //
                                // Command execution failed
                                //
                                resultInfo.statusCode = StatusCodes.Failed;
                                resultInfo.errorMessage = STRERR_SuspendPowerdown;
                                state = entry.exitState;
                            }
                            else
                            {
                                state = nextState;
                            }
                            continue;

                        case States_Execute.sResumePowerdown:
                            if (this.equipmentServiceProxy.ResumePowerdown() == false)
                            {
                                //
                                // Command execution failed
                                //
                                resultInfo.statusCode = StatusCodes.Failed;
                                resultInfo.errorMessage = STRERR_ResumePowerdown;
                                state = entry.exitState;
                            }
                            else
                            {
                                state = nextState;
                            }
                            continue;

                        default:
                            break;
                    }

                    //
                    // Add command arguments where required
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sSetSpeedACDrive:
                            int speedACDrive = specification.Speed.min + (vectorIndex * specification.Speed.step);
                            entry.commandArguments[0, 1] = speedACDrive.ToString();
                            break;

                        case States_Execute.sResetSpeedACDrive:
                            speedACDrive = 0;
                            entry.commandArguments[0, 1] = speedACDrive.ToString();
                            break;

                        default:
                            break;
                    }

                    //
                    // Execute command and check response success
                    //
                    XmlDocument xmlRequestDocument = CreateXmlRequestDocument(entry.equipmentCommand, entry.commandArguments);
                    string xmlResponse = this.equipmentServiceProxy.ExecuteRequest(xmlRequestDocument.InnerXml);
                    XmlNode xmlResponseNode = CreateXmlResponseNode(xmlResponse);
                    if (XmlUtilities.GetBoolValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspSuccess, false) == false)
                    {
                        //
                        // Command execution failed
                        //
                        resultInfo.statusCode = StatusCodes.Failed;
                        resultInfo.errorMessage = XmlUtilities.GetXmlValue(xmlResponseNode, LabServerEngine.Consts.STRXML_RspErrorMessage, true);
                        state = entry.exitState;
                        continue;
                    }

                    //
                    // Extract response values where required
                    //
                    switch (entry.currentState)
                    {
                        case States_Execute.sTakeMeasurement:

                            //
                            // Add in the values
                            //
                            resultInfo.speedVector[vectorIndex] += XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspSpeed, 0);
                            resultInfo.voltageVector[vectorIndex] += XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspVoltage, 0);
                            resultInfo.loadVector[vectorIndex] += XmlUtilities.GetIntValue(xmlResponseNode, Consts.STRXML_RspLoad, 0);
                            resultInfo.fieldVector[vectorIndex] += (float)XmlUtilities.GetRealValue(xmlResponseNode, Consts.STRXML_RspFieldCurrent, 0.0);

                            //
                            // Check if all measurements have been taken for this field value
                            //
                            if (++repeatCount == this.measurementCount)
                            {
                                //
                                // All measurements have been taken for this field value, average the values
                                //
                                resultInfo.speedVector[vectorIndex] /= measurementCount;
                                resultInfo.voltageVector[vectorIndex] /= measurementCount;
                                resultInfo.fieldVector[vectorIndex] /= measurementCount;
                                resultInfo.loadVector[vectorIndex] /= measurementCount;

                                //
                                // Check if field values have been completed
                                //
                                if (++vectorIndex == vectorLength)
                                {
                                    //
                                    // All measurements have been taken
                                    //
                                    break;
                                }

                                //
                                // Next field value
                                //
                                repeatCount = 0;
                                nextState = States_Execute.sSetSpeedACDrive;
                                break;
                            }

                            // Next measurement at the same field value
                            nextState = States_Execute.sTakeMeasurement;
                            break;

                        default:
                            break;
                    }

                    //
                    // Next state
                    //
                    state = nextState;
                }

                //
                // Update status code
                //
                if (resultInfo.statusCode == StatusCodes.Running)
                {
                    resultInfo.statusCode = StatusCodes.Completed;
                }
            }
            catch (Exception ex)
            {
                resultInfo.statusCode = StatusCodes.Failed;
                resultInfo.errorMessage = ex.Message;
                Logfile.WriteError(ex.Message);
            }

            //
            // Calculate actual execution time
            //
            TimeSpan timeSpan = DateTime.Now - startDateTime;

            logMessage = STRLOG_StatusCode + resultInfo.statusCode
                + Logfile.STRLOG_Spacer + STRLOG_ExecutionTime + timeSpan.TotalSeconds.ToString();

            Logfile.WriteCompleted(STRLOG_ClassName, STRLOG_MethodName, logMessage);

            return resultInfo;
        }
Esempio n. 53
0
        public ResultInfo CoDBill()
        {
            ResultInfo result = new ResultInfo()
            {
                error = 0,
                msg   = "Them moi thanh cong"
            };

            try
            {
                var requestContent = Request.Content.ReadAsStringAsync().Result;

                var jsonserializer = new JavaScriptSerializer();
                var paser          = jsonserializer.Deserialize <CoDShowRequest>(requestContent);

                int pageSize = 50;

                int pageNumber = (paser.page ?? 1);


                DateTime paserFromDate = DateTime.Now;
                DateTime paserToDate   = DateTime.Now;

                try
                {
                    paserFromDate = DateTime.ParseExact(paser.fromDate, "dd/MM/yyyy", null);
                    paserToDate   = DateTime.ParseExact(paser.toDate, "dd/MM/yyyy", null);
                }
                catch
                {
                    paserFromDate = DateTime.Now;
                    paserToDate   = DateTime.Now;
                }

                var findCus = db.BS_Customers.Where(p => p.CustomerCode == paser.customerId).FirstOrDefault();
                if (findCus == null)
                {
                    throw new Exception("sai thông tin");
                }

                var findGroup = db.BS_CustomerGroups.Find(findCus.CustomerGroupID);

                if (findGroup == null)
                {
                    throw new Exception("sai thông tin");
                }

                var data = db.CUSTOMER_COD_DEBIT_GETDOCUMENTS(paserFromDate.ToString("yyyy-MM-dd"), paserToDate.ToString("yyyy-MM-dd"), "%" + findGroup.CustomerGroupCode + "%").ToList();

                result = new ResultWithPaging()
                {
                    error      = 0,
                    msg        = "",
                    page       = pageNumber,
                    pageSize   = pageSize,
                    toltalSize = data.Count(),
                    data       = data.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToList()
                };
            }
            catch (Exception e)
            {
                result.error = 1;
                result.msg   = e.Message;
            }
            return(result);
        }
Esempio n. 54
0
        public ActionResult GetShareCoin(int coin = 0, long coinID = 0)
        {
            ResultInfo ri = new ResultInfo();

            if (coin > 0)
            {
                if (coinID > 0)
                {
                    //查找对应奖励
                    var sharecoin = BBSEnumBLL.Instance.GetItem(coinID);
                    if (sharecoin == null)
                    {
                        ri.Msg = "您领取的对应奖励不存在!";
                    }
                    else
                    {
                        if (sharecoin.EnumDesc == coin.ToString())
                        {
                            //判断当前用户分享的注册用户数是否已达标
                            int registCount = ShareRegistLogBLL.Instance.GetRegistCount(UserID);
                            if (registCount >= sharecoin.SortIndex)
                            {
                                BeginTran();
                                if (UserExtBLL.Instance.AddScore(UserID, coin, 1, Tran))
                                {
                                    if (ScoreCoinLogBLL.Instance.Log(coin, 1, CoinSourceEnum.ShareCoin, UserID, UserInfo.UserName, Tran, coinID))
                                    {
                                        ri.Ok = true;
                                        Commit();
                                    }
                                    else
                                    {
                                        RollBack();
                                    }
                                }
                                else
                                {
                                    RollBack();
                                }
                            }
                            else
                            {
                                ri.Msg = "您未达标,无法领取奖励";
                            }
                        }
                        else
                        {
                            ri.Msg = "奖励分数异常";
                        }
                    }
                }
                else
                {
                    ri.Msg = "奖励分数异常";
                }
            }
            else
            {
                ri.Msg = "奖励分数异常";
            }
            return(Result(ri));
        }
Esempio n. 55
0
 public Gen(ResultInfo resultInfo)
 {
     _resultInfo = resultInfo;
 }
Esempio n. 56
0
 public static PlayAudioResultEvent PlayAudioResultEvent(ResultInfo resultInfo = default, string operationContext = default, OperationStatus status = default)
 {
     return(new PlayAudioResultEvent(resultInfo, operationContext, status));
 }
Esempio n. 57
0
        public ActionResult CateOperate()
        {
            ResultInfo resultInfo;

            string action = RequestHelper.All("action").ToLower();
            string ids = RequestHelper.All("ids").ToLower();

            if (action == "")
            {
                resultInfo = new ResultInfo((int)ResultStatus.Error, "未选择任何操作!");
                return Json(resultInfo);
            }

            if (ids == "")
            {
                resultInfo = new ResultInfo((int)ResultStatus.Error, "未选择任何操作项!");
                return Json(resultInfo);
            }

            switch (action)
            {
                case "delete":
                    _cateService.Delete(Utils.StrToInt(ids));
                    break;
            }

            return Json(new ResultInfo("操作成功"));
        }
Esempio n. 58
0
 public static PlayAudioResult PlayAudioResult(string operationId = default, OperationStatus status = default, string operationContext = default, ResultInfo resultInfo = default)
 {
     return(new PlayAudioResult(operationId, status, operationContext, resultInfo));
 }
Esempio n. 59
0
        public ActionResult CateEdit(Cate cate)
        {
            ResultInfo resultInfo = new ResultInfo(1, "验证不通过");

            if (ModelState.IsValid)
            {
                Cate oldCate = _cateService.GetById(cate.CateId);

                if (oldCate == null)
                {
                    resultInfo = new ResultInfo(1, "该信息已被删除或不存在,请刷新列表!");
                    return Json(resultInfo);
                }

                int oldPid = oldCate.Pid;
                oldCate.CateId = cate.CateId;
                oldCate.CateName = cate.CateName;
                oldCate.Pid = cate.Pid;

                resultInfo = _cateService.Update(oldCate, oldPid);
            }

            return Json(resultInfo);
        }
Esempio n. 60
0
 public static CancelAllMediaOperationsResult CancelAllMediaOperationsResult(string operationId = default, OperationStatus status = default, string operationContext = default, ResultInfo resultInfo = default)
 {
     return(new CancelAllMediaOperationsResult(operationId, status, operationContext, resultInfo));
 }