private void AddCountryToDataSet(ResultData resultData, IPublishedContent landkosten, string goalCurrency, String localizedYear)
        {
            var kostenland = new CountryCost(landkosten, goalCurrency);

            for (int i = 1; i <= 20; i++)
            {

                int jaarTakseInGoalCurrency = kostenland.GetYear(i) ?? default(int);

                if (jaarTakseInGoalCurrency > resultData.MaxTakse)
                {
                    resultData.MaxTakse = jaarTakseInGoalCurrency;
                }

                resultData.AddDataPoint(i, jaarTakseInGoalCurrency, localizedYear);
            }

            string stepWidthString = (resultData.MaxTakse / 10).ToString();
            int biggestInt = Convert.ToInt32(stepWidthString[0].ToString()) + 1;
            string nextBigNumberforStep = biggestInt.ToString();

            for (int i = 0; i < stepWidthString.Length - 1; i++)
            {
                nextBigNumberforStep += "0";
            }

            int nextBigNumberForStepInt = Convert.ToInt32(nextBigNumberforStep);
            resultData.StepWidth = nextBigNumberForStepInt;
        }
 void OnEnable()
 {
     Main.Instance.GameState = EGameState.Result;
     mResultData = Main.Instance.ResultData;
     if (mResultData == null)
     {
         mResultData = new ResultData(1, 7);
     }
     Mask.sprite = Main.Instance.GameContent.Masks[mResultData.PlayerMask];
     PlayerSprite.color = Main.Instance.GameContent.PlayerColors[mResultData.PlayerWon];
 }
        //
        // GET: /CountryData/
        public ActionResult Get()
        {
            var kostenLandIdString = Request.Params.Get("landId");
            var currency = Request.Params.Get("currency");
            var langCode = Request.Params.Get("lang");

            int landId = Convert.ToInt32(kostenLandIdString);

            if (kostenLandIdString == null || currency == null)
            {
                return HttpNotFound();
            }

            string vulkleur = PvSettings.Get("grafiekenVulkleur");
            string lijnkleur = PvSettings.Get("grafiekenLijnkleur");

            var resultData = new ResultData(vulkleur, lijnkleur, 1.0);

            var landkosten = Umbraco.TypedContent(landId);

            AddCountryToDataSet(resultData, landkosten, currency, DictionaryHelper.ItemForKeyAndLanguage("Jaar", langCode));

            return Json(resultData, JsonRequestBehavior.AllowGet);
        }
Beispiel #4
0
        /// <summary>
        /// call StoredProcedure 但是參數可有output
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <param name="hasReturnParameter"></param>
        /// <returns></returns>
        public DataTable ExecuteStoredProcedureEx(string sql, List <DbParameterEx> parameters, bool hasReturnParameter)
        {
            ResultData resultData = new ResultData();

            resultData.Status = ResultStatus.Fail;

            try {
                var           connection = CreateConnection();
                OracleCommand command    = new OracleCommand(sql, (OracleConnection)connection); //ken
                command.CommandType = CommandType.StoredProcedure;                               //ken

                if (parameters != null)
                {
                    foreach (DbParameterEx everyPara in parameters)
                    {
                        DbParameter dbParam = command.CreateParameter();

                        dbParam = TransformToDbParameter(dbParam, everyPara);

                        command.Parameters.Add(dbParam);
                    }
                }

                DbParameter dbParamReturn = null;

                if (hasReturnParameter)
                {
                    if (command is OracleCommand)
                    {
                        dbParamReturn = command.CreateParameter();
                        dbParamReturn.ParameterName = "RETURNPARAMETER";
                        dbParamReturn.Direction     = ParameterDirection.Output;
                        ((OracleParameter)dbParamReturn).OracleDbType = OracleDbType.RefCursor;//ken
                        command.Parameters.Add(dbParamReturn);
                    }
                }

                command.ExecuteNonQuery();                                   //ken
                OracleDataAdapter da       = new OracleDataAdapter(command); //ken
                DataTable         dtResult = new DataTable();
                da.Fill(dtResult);

                //ken,如果有多個output cursor,則需要用以下寫法
                //DataTable dtResult = (DataTable)command.Parameters[2];

                return(dtResult);
            } catch (Exception ex) {
                string errorStr = "";

                if (ex is AseException)
                {
                    AseException aseEx = ((AseException)ex);

                    foreach (AseError error in aseEx.Errors)
                    {
                        errorStr += Environment.NewLine + error.ProcName + Environment.NewLine +
                                    error.MessageNumber + Environment.NewLine +
                                    "LineNum:" + error.LineNum;
                    }
                }

                Exception exNew = new Exception(ExceptionHelper.TranformException(ex).Message + errorStr);

                throw exNew;
            }
        }
Beispiel #5
0
        //protected override ResultStatus Run(PokeBall args)
        //{
        //    this.BeginInvoke(new MethodInvoker(() => {
        //        args.GridControlMain = gcMain;
        //        args.GridControlSecond = gcLogsp;
        //        args.OcfDate = txtOcfDate.DateTimeValue;
        //        args.OcfType = OCF_TYPE;
        //    }));

        //    ResultStatus result = base.RunAsync(args);

        //    return result;
        //}

        /// <summary>
        /// 1系列功能使用
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        protected override ResultStatus Run(PokeBall args)
        {
            DateTime OcfDate = txtOcfDate.DateTimeValue;

            this.Invoke(new MethodInvoker(() => {
                FormWait formWait = new FormWait();

                SplashScreenManager.ShowForm(this, typeof(FormWait), true, true);

                //SplashScreenManager.ShowForm(this , typeof(FormWait) , true , true , SplashFormStartPosition.Manual , pointWait , ParentFormState.Locked);
            }));

            GridView gv = gvMain;


            DataTable dtLOGSPForRuned = servicePrefix1.ListLogspForRunned(OcfDate, _ProgramID, OCF_TYPE);
            DataView  dvLOGSPForRuned = new DataView(dtLOGSPForRuned);



            servicePrefix1.SetTXF1(" ", _ProgramID);

            for (int i = 0; i < gv.RowCount; i++)
            {
                string TXF_SERVER   = gv.GetRowCellValue(i, "TXF_SERVER").AsString();
                string TXF_DB       = gv.GetRowCellValue(i, "TXF_DB").AsString();
                string TXF_TXN_ID   = gv.GetRowCellValue(i, "TXF_TXN_ID").AsString();
                int    TXF_SEQ_NO   = gv.GetRowCellValue(i, "TXF_SEQ_NO").AsInt();
                string TXF_TYPE     = gv.GetRowCellValue(i, "TXF_TYPE").AsString();
                string TXF_TID      = gv.GetRowCellValue(i, "TXF_TID").AsString();
                string TXF_TID_NAME = gv.GetRowCellValue(i, "TXF_TID_NAME").AsString();
                string TXF_DESC     = gv.GetRowCellValue(i, "TXF_DESC").AsString();
                string TXF_DEFAULT  = gv.GetRowCellValue(i, "TXF_DEFAULT").AsString();
                string TXF_REDO     = gv.GetRowCellValue(i, "TXF_REDO").AsString();
                string TXF_ARG      = gv.GetRowCellValue(i, "TXF_ARG").AsString();
                string TXF_PERIOD   = gv.GetRowCellValue(i, "TXF_PERIOD").AsString();
                string TXF_SERVICE  = gv.GetRowCellValue(i, "TXF_SERVICE").AsString();
                string TXF_FOLDER   = gv.GetRowCellValue(i, "TXF_FOLDER").AsString();
                string TXF_AP_NAME  = gv.GetRowCellValue(i, "TXF_AP_NAME").AsString();
                args.TXF_TID      = TXF_TID;
                args.TXF_TID_NAME = TXF_TID_NAME;

                if (TXF_DEFAULT == "1")
                {
                    DateTime LOGSP_DATE       = OcfDate;
                    string   LOGSP_TXN_ID     = _ProgramID;
                    int      LOGSP_SEQ_NO     = TXF_SEQ_NO;
                    string   LOGSP_TID        = TXF_DESC;
                    string   LOGSP_TID_NAME   = TXF_TID_NAME;
                    DateTime LOGSP_BEGIN_TIME = new DateTime();
                    DateTime LOGSP_END_TIME   = new DateTime();
                    string   LOGSP_MSG        = "";


                    //判斷是否可重覆執行
                    if (TXF_REDO == "N")
                    {
                        dvLOGSPForRuned.RowFilter = "LOGSP_TID='" + LOGSP_TID + "' AND NOT ISNULL(LOGSP_BEGIN_TIME)";
                        if (dvLOGSPForRuned.Count != 0)
                        {
                            if (MessageDisplay.Choose(TXF_TID + " ★★★曾經執行過且不可重覆執行,是否強迫繼續執行 ?") == DialogResult.No)
                            {
                                return(ResultStatus.Fail);
                            }
                        }
                    }


                    #region 開始執行
                    LOGSP_BEGIN_TIME = DateTime.Now;

                    string nextYmd = PbFunc.f_ocf_date(2, _DB_TYPE);
                    if (!string.IsNullOrEmpty(TXF_PERIOD))
                    {
                        switch (TXF_PERIOD)
                        {
                        case "M":    //月底執行
                            if (OcfDate.ToString("yyyyMM") == PbFunc.Left(nextYmd, 6))
                            {
                                LOGSP_MSG = "完成! (今日非月底,不需執行)";
                                this.Invoke(new MethodInvoker(() => { gv.SetRowCellValue(i, "TXF_DEFAULT", 0); }));
                            }
                            break;

                        case "W":    //週最後一天執行
                            if (Convert.ToInt32(OcfDate.DayOfWeek) < Convert.ToInt32(nextYmd.AsDateTime("yyyyMMdd").DayOfWeek))
                            {
                                LOGSP_MSG = "完成! (今日非本週最後1天,不需執行)";
                                this.Invoke(new MethodInvoker(() => { gv.SetRowCellValue(i, "TXF_DEFAULT", 0); }));
                            }
                            break;

                        case "Y":    //年底執行
                            if (OcfDate.ToString("yyyy") == PbFunc.Left(nextYmd, 4))
                            {
                                LOGSP_MSG = "完成! (今日非本年度最後1日,不需執行)";
                                this.Invoke(new MethodInvoker(() => { gv.SetRowCellValue(i, "TXF_DEFAULT", 0); }));
                            }
                            break;
                        }
                        LOGSP_END_TIME = DateTime.Now;

                        servicePrefix1.SaveLogsp(LOGSP_DATE, LOGSP_TXN_ID, LOGSP_SEQ_NO, LOGSP_TID, LOGSP_TID_NAME, LOGSP_BEGIN_TIME, LOGSP_END_TIME, LOGSP_MSG, OCF_TYPE);
                        continue;
                    }


                    //開始前執行特別的Function
                    string rtnText = RunBeforeEveryItem(args);
                    if (!string.IsNullOrEmpty(rtnText))
                    {
                        if (PbFunc.Left(rtnText, 4) == "不需執行")
                        {
                            LOGSP_MSG = "完成! (" + rtnText + ")";
                            gv.SetRowCellValue(i, "ERR_MSG", LOGSP_MSG);
                            gv.SetRowCellValue(i, "TXF_DEFAULT", 0);
                            LOGSP_END_TIME = DateTime.Now;

                            servicePrefix1.SaveLogsp(LOGSP_DATE, LOGSP_TXN_ID, LOGSP_SEQ_NO, LOGSP_TID, LOGSP_TID_NAME, LOGSP_BEGIN_TIME, LOGSP_END_TIME, LOGSP_MSG, OCF_TYPE);
                        }
                        else
                        {
                            if (MessageDisplay.Choose($"{rtnText}是否強迫繼續執行?", MessageBoxDefaultButton.Button2).AsInt() == 2)
                            {
                                gv.SetRowCellValue(i, "ERR_MSG", rtnText);
                                continue;
                            }
                        }
                    }

                    //記錄正在執行
                    servicePrefix1.SetTXF1(TXF_TID, _ProgramID);

                    servicePrefix1.SaveLogs(LOGSP_DATE, TXF_TID, DateTime.Now, GlobalInfo.USER_ID, "開始執行");

                    ResultData resultData = new ResultData();
                    string     fileName   = "";
                    switch (TXF_TYPE)
                    {
                    //Informatica
                    case "I":
                        fileName   = $@"{GlobalInfo.DEFAULT_BATCH_ErrSP_DIRECTORY_PATH}\{TXF_SERVER}_{TXF_TXN_ID}_{TXF_SEQ_NO}_infor";
                        resultData = serviceCommon.ExecuteInfoWorkFlow(TXF_TID, UserProgInfo, TXF_FOLDER, TXF_SERVICE, TXF_AP_NAME, fileName);
                        break;

                    //SP
                    case "S":
                        List <DbParameterEx> listParams = null;

                        // 如果這個SP有參數的話
                        if (TXF_ARG == "Y")
                        {
                            DataTable dtTXFPARM = serviceCommon.ListTXFPARM(TXF_SERVER, TXF_DB, TXF_TXN_ID, TXF_TID);

                            if (dtTXFPARM.Rows.Count > 0)
                            {
                                listParams = new List <DbParameterEx>();
                            }

                            foreach (DataRow row in dtTXFPARM.Rows)
                            {
                                string TXFPARM_ARG      = row["TXFPARM_ARG"].AsString();
                                string TXFPARM_ARG_TYPE = row["TXFPARM_ARG_TYPE"].AsString();
                                string TXFPARM_DEFAULT  = row["TXFPARM_DEFAULT"].AsString();

                                DbParameterEx paramEx;

                                switch (TXFPARM_ARG)
                                {
                                case "":
                                    paramEx = new DbParameterEx("", TXFPARM_DEFAULT);
                                    listParams.Add(paramEx);
                                    break;

                                case "em_ymd":
                                    paramEx = new DbParameterEx("", OcfDate.ToString("yyyyMMdd"));
                                    listParams.Add(paramEx);
                                    break;

                                case "em_ym":
                                    paramEx = new DbParameterEx("", OcfDate.ToString("yyyyMM"));
                                    listParams.Add(paramEx);
                                    break;

                                case "em_date":
                                    paramEx        = new DbParameterEx();
                                    paramEx.DbType = DbTypeEx.Date;
                                    paramEx.Name   = "";
                                    paramEx.Value  = OcfDate;
                                    listParams.Add(paramEx);
                                    break;

                                default:
                                    break;
                                }
                            }
                        }

                        ConnectionInfo connectionInfo = SettingDragons.Instance.GetConnectionInfo(TXF_DB);

                        try
                        {
                            resultData = serviceCommon.ExecuteStoredProcedure(connectionInfo, string.Format("{0}.{1}", TXF_DB, TXF_TID), listParams, true);
                        }
                        catch (Exception ex)
                        {
                            resultData.Status = ResultStatus.Fail;
                            string msg =
                                fileName = $@"{GlobalInfo.DEFAULT_BATCH_ErrSP_DIRECTORY_PATH}\{TXF_SERVER}_{TXF_TXN_ID}_{TXF_SEQ_NO}.err";
                            System.IO.File.WriteAllText(fileName, ex.Message);
                            resultData.returnString = $"請通知「{TXF_AP_NAME}」 作業執行失敗!\n{ex.Message}";
                        }

                        break;

                    //視窗功能
                    case "W":
                        this.Invoke(new MethodInvoker(() => { resultData = ExecuteForm(args); }));

                        break;

                    default:
                        break;
                    }

                    LOGSP_END_TIME = DateTime.Now;

                    if (resultData.Status == ResultStatus.Success)
                    {
                        LOGSP_MSG = "執行正常完成!";
                    }
                    else
                    {
                        LOGSP_MSG = "作業執行失敗!";

                        servicePrefix1.SaveLogsp(LOGSP_DATE, LOGSP_TXN_ID, LOGSP_SEQ_NO, LOGSP_TID, LOGSP_TID_NAME, LOGSP_BEGIN_TIME, LOGSP_END_TIME, LOGSP_MSG, OCF_TYPE);

                        //MessageDisplay.Error("序號" + LOGSP_SEQ_NO + "的" + LOGSP_TID + "," + LOGSP_MSG);
                        MessageDisplay.Error(resultData.returnString);

                        this.Invoke(new MethodInvoker(() => {
                            SplashScreenManager.CloseForm();
                            gv.SetRowCellValue(i, "ERR_MSG", LOGSP_MSG);
                        }));

                        return(ResultStatus.Fail);
                    }

                    this.Invoke(new MethodInvoker(() => { gv.SetRowCellValue(i, "ERR_MSG", LOGSP_MSG); }));

                    servicePrefix1.SaveLogsp(LOGSP_DATE, LOGSP_TXN_ID, LOGSP_SEQ_NO, LOGSP_TID, LOGSP_TID_NAME, LOGSP_BEGIN_TIME, LOGSP_END_TIME, LOGSP_MSG, OCF_TYPE);
                    servicePrefix1.SaveLogs(LOGSP_DATE, TXF_TID, DateTime.Now, GlobalInfo.USER_ID, "執行完畢");

                    #endregion 開始執行


                    #region 執行特別的程式


                    this.Invoke(new MethodInvoker(() => {
                        gv.SetRowCellValue(i, "TXF_DEFAULT", 0);
                        RunAfterEveryItem(args);
                    }));

                    #endregion 執行特別的程式

                    //流程時間控制
                    DataTable dtJRF = servicePrefix1.ListJrf(_ProgramID, TXF_TID);
                    if (dtJRF.Rows.Count > 0)
                    {
                        string JRF_DO_TXN_ID   = dtJRF.Rows[0]["JRF_DO_TXN_ID"].AsString();
                        string JRF_DO_JOB_TYPE = dtJRF.Rows[0]["JRF_DO_TXN_ID"].AsString();
                        string JRF_DO_SEQ_NO   = dtJRF.Rows[0]["JRF_DO_TXN_ID"].AsString();
                        string JRF_SW_CODE     = dtJRF.Rows[0]["JRF_DO_TXN_ID"].AsString();
                        servicePrefix1.UpdateJsw(JRF_DO_TXN_ID, JRF_DO_JOB_TYPE, JRF_DO_SEQ_NO, JRF_SW_CODE, OcfDate, DateTime.Now, GlobalInfo.USER_ID);
                    }
                }
                else
                {
                    // 沒勾選項目的話清空狀態
                    this.Invoke(new MethodInvoker(() => { gv.SetRowCellValue(i, "ERR_MSG", ""); }));
                }
                if (i == gv.RowCount - 1 && OCF_TYPE == "D")
                {
                    servicePrefix1.setCIOCF();
                }
            }


            //全部結束
            servicePrefix1.SetTXF1(" ", _ProgramID);

            this.Invoke(new MethodInvoker(() => { SplashScreenManager.CloseForm(); }));

            return(ResultStatus.Success);
        }
        public ResultData SetEditOrder(string[] values)
        {
            ResultData ret = new ResultData();

            try
            {
                ServiceIF serv = new ServiceIF();

                HospMst[] hospList;
                HospMst   hospMst = new HospMst();
                serv.GetHospList_Serv(out hospList);

                foreach (var hosp in hospList)
                {
                    if (values[0] == hosp.HospID.ToString())
                    {
                        hospMst = hosp;
                        break;
                    }
                }
                LogControl.WriteLog(LogType.ORE, "SetEditOrder", "【変更依頼】 施設ID:" + hospMst.Name + " オーダーID:" + values[1] + " 患者ID:" + values[2] + " モダリティ:" + values[5] + " 検査日:" + values[6]);
                var fileName = "【変更】" + hospMst.Name + "_" + values[1] + ".txt";

                string backDef = System.IO.Path.Combine(ConfigurationManager.AppSettings["BackDir"], hospMst.CD);
                backDef = System.IO.Path.Combine(backDef, DateTime.Now.ToString("yyyyMMdd"));

                if (!System.IO.Directory.Exists(backDef))
                {
                    System.IO.Directory.CreateDirectory(backDef);
                }

                using (var sw = new System.IO.StreamWriter(System.IO.Path.Combine(ConfigurationManager.AppSettings["OrderDir"], fileName)))
                {
                    sw.WriteLine(values[2]);
                    sw.WriteLine("");
                    sw.WriteLine("【" + values[3] + "(" + values[4] + ")】");
                    sw.WriteLine("");
                    sw.WriteLine(values[5]);
                    sw.WriteLine("");
                    sw.WriteLine(values[6]);
                }

                using (var sw = new System.IO.StreamWriter(System.IO.Path.Combine(backDef, fileName)))
                {
                    sw.WriteLine(values[2]);
                    sw.WriteLine("");
                    sw.WriteLine("【" + values[3] + "(" + values[4] + ")】");
                    sw.WriteLine("");
                    sw.WriteLine(values[5]);
                    sw.WriteLine("");
                    sw.WriteLine(values[6]);
                }
                ret.Result = true;
            }
            catch (Exception e)
            {
                ret.Result  = false;
                ret.Message = "処理中に障害が発生いたしました。\nシステム管理者にお問い合わせください。";
                LogControl.WriteLog(LogType.ERR, "SetEditOrder", e.Message);
            }
            return(ret);
        }
        /// <summary>
        /// Do NOT call this method from update thread.
        /// </summary>
        public static ResultData DownloadModsBlocking(List<SubscribedItem> mods)
        {
            int counter = 0;
            string numMods = mods.Count.ToString();
            VRage.Collections.CachingList<SubscribedItem> failedMods = new VRage.Collections.CachingList<SubscribedItem>();
            VRage.Collections.CachingList<SubscribedItem> mismatchMods = new VRage.Collections.CachingList<SubscribedItem>();
            bool downloadingFailed = false;

            long startTime = Stopwatch.GetTimestamp();
            Parallel.ForEach<SubscribedItem>(mods, delegate(SubscribedItem mod)
            {
                if (!MySteam.IsOnline)
                {
                    downloadingFailed = true;
                    return;
                }

                if (m_stop)
                {
                    downloadingFailed = true;
                    return;
                }


                bool devTagMismatch = mod.Tags != null && mod.Tags.Contains(MySteamWorkshop.WORKSHOP_DEVELOPMENT_TAG) && MyFinalBuildConstants.IS_STABLE;

                if (devTagMismatch)
                {
                    mismatchMods.Add(mod);
                }

                var localPackedModFullPath = Path.Combine(m_workshopModsPath, mod.PublishedFileId + m_workshopModSuffix);

                // If mod is up to date, no need to download it.
                if (!IsModUpToDateBlocking(localPackedModFullPath, mod, true))
                {
                    // If the mod fails to download, we need to flag it for failure, log it, then stop
                    if (!DownloadItemBlocking(localPackedModFullPath, mod.UGCHandle))
                    {
                        failedMods.Add(mod);
                        downloadingFailed = true;
                        m_stop = true;
                    }
                }
                else
                {
                    MySandboxGame.Log.WriteLineAndConsole(string.Format("Up to date mod: Id = {0}, title = '{1}'", mod.PublishedFileId, mod.Title));
                }

                if (m_asyncDownloadScreen != null)
                {
                    using (m_modLock.AcquireExclusiveUsing())
                    {
                        counter++;
                        m_asyncDownloadScreen.ProgressTextString = MyTexts.GetString(MyCommonTexts.ProgressTextDownloadingMods) + " " + counter.ToString() + " of " + numMods;
                    }
                }
                
            });

            long endTime = Stopwatch.GetTimestamp();

            if (downloadingFailed)
            {
                failedMods.ApplyChanges();
                if (failedMods.Count > 0)
                {
                    foreach (var mod in failedMods)
                    {
                        MySandboxGame.Log.WriteLineAndConsole(string.Format("Failed to download mod: Id = {0}, title = '{1}'", mod.PublishedFileId, mod.Title));
                    }
                }
                else if (!m_stop)
                {
                    MySandboxGame.Log.WriteLineAndConsole(string.Format("Failed to download mods because Steam is not in Online Mode."));
                }
                else
                {
                    MySandboxGame.Log.WriteLineAndConsole(string.Format("Failed to download mods because download was stopped."));
                }
                return new ResultData();
            }

            ResultData ret = new ResultData();
            ret.Success = true;
            ret.MismatchMods = "";
            mismatchMods.ApplyChanges();
            foreach(var mod in mismatchMods)
            {
                ret.MismatchMods += mod.Title + Environment.NewLine; 
            }

            double duration = (double)(endTime - startTime) / (double)Stopwatch.Frequency;
            MySandboxGame.Log.WriteLineAndConsole(string.Format("Mod download time: {0:0.00} seconds", duration));
            return ret;
        }
Beispiel #8
0
        public void ProcessGeocachingComGPXWaypoints(ResultData data, string gpxDoc)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(gpxDoc);
                XmlElement root = doc.DocumentElement;
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("x", root.NamespaceURI);

                _gpxDataTime = DateTime.Parse(root.SelectSingleNode("x:time", nsmgr).InnerText);

                XmlNodeList wps = root.SelectNodes("x:wpt", nsmgr);
                if (wps != null)
                {
                    foreach (XmlNode n in wps)
                    {
                        Framework.Data.Waypoint wp = new Framework.Data.Waypoint();

                        wp.Code = n.SelectSingleNode("x:name", nsmgr).InnerText;
                        wp.GeocacheCode = string.Concat("GC",wp.Code.Substring(2));
                        wp.DataFromDate = _gpxDataTime;
                        wp.Comment = n.SelectSingleNode("x:cmt", nsmgr).InnerText;
                        wp.Lat = Utils.Conversion.StringToDouble(n.Attributes["lat"].InnerText);
                        wp.Lon = Utils.Conversion.StringToDouble(n.Attributes["lon"].InnerText);
                        wp.Description = n.SelectSingleNode("x:desc", nsmgr).InnerText;
                        wp.ID = wp.Code;
                        wp.Name = wp.Code;
                        wp.Comment = n.SelectSingleNode("x:cmt", nsmgr).InnerText;
                        wp.Time = DateTime.Parse(n.SelectSingleNode("x:time", nsmgr).InnerText);
                        wp.Url = n.SelectSingleNode("x:url", nsmgr).InnerText;
                        wp.UrlName = n.SelectSingleNode("x:urlname", nsmgr).InnerText;
                        wp.WPType = DataAccess.GetWaypointType(_core.WaypointTypes, n.SelectSingleNode("x:sym", nsmgr).InnerText);

                        data.Waypoints.Add(wp);
                    }
                }

            }
            catch
            {
            }
        }
        /// <summary>
        /// 在执行前
        /// </summary>
        private void _onBeforeExecution(ActionExecutingContext context)
        {
            Logger.Info("请求开始");
            foreach (string IgnoreUrl in _IgnoreUrls)
            {
                string UpperPath = context.HttpContext.Request.Path.Value.ToUpper();
                //如果是开放的接口,让其管道短路
                if (UpperPath == IgnoreUrl.ToUpper() || UpperPath == $"/{IgnoreUrl.ToUpper()}")
                {
                    return;
                }
            }
            try
            {
                Logger.Info("Header信息:验证登陆");
                IHeaderDictionary Headers    = context.HttpContext.Request.Headers;
                StringValues      EncryptStr = Headers["EncryptStr"];
                StringValues      UnionId    = Headers["UnionId"];

                if (string.IsNullOrWhiteSpace(EncryptStr) || string.IsNullOrWhiteSpace(UnionId))
                {
                    Logger.Info("未登录");
                    ResultData <string> notLoginData = new ResultData <string>()
                    {
                        Code = 300, Message = "请先登陆", Result = null
                    };
                    context.Result = new JsonResult(notLoginData);
                    return;
                }
                else
                {
                    Logger.Info("通过登陆验证,开始验证加密认证");
                    JsonData WeChatConfig = AppConfig.Configs["PrjectConfig"]["WeChat"];
                    string   EncryptSky   = WeChatConfig["EncryptStr"].ToString();

                    string MD5Encrypt;
                    using (MD5 md5Hash = MD5.Create())
                    {
                        MD5Encrypt = Md5Helper.GetMd5Hash(md5Hash, EncryptSky + UnionId);
                    }

                    if (MD5Encrypt != EncryptStr)
                    {
                        Logger.Info("认证失败");
                        ResultData <string> loginFailureData = new ResultData <string>()
                        {
                            Code = 300, Message = "认证失败", Result = null
                        };
                        context.Result = new JsonResult(loginFailureData);
                        return;
                    }
                    Logger.Info("加密认证通过");
                }
            }
            catch (Exception e)
            {
                Logger.Error("执行动作之前失败:", e);
                ResultData <string> errorResult = new ResultData <string>()
                {
                    Code = 400, Message = e.Message, Result = null
                };
                context.Result = new JsonResult(errorResult);
                return;
            }
        }
Beispiel #10
0
        /// <summary>
        /// 提交软件反馈
        /// </summary>
        /// <param name="ChangeAuth"></param>
        /// <returns></returns>
        public ActionResult SubmitFeedback(FeedbackOperateDTO dto)
        {
            bool             result         = true;
            ResultData <int> feedbackresult = new ResultData <int>();
            UserLoginDTO     user           = (UserLoginDTO)Session["UserLoginInfo"];

            dto.FeedbackDate  = DateTime.Now;
            dto.FeedbackStaus = 0;
            dto.UserID        = user.UserID;
            try
            {
                feedbackresult = SystemProvider.AddFeedback(dto);
                if (feedbackresult.SubmitResult)
                {
                    List <MasterData.DTO.Common.AdminDTO> lstadmin = UserApplyProvider.GetAdminInfo(new MasterData.DTO.Common.AdminSearchDTO {
                        RoleIdList = new List <int> {
                            99
                        }
                    });

                    EmailHelper.SendMessage("问题反馈", WebConfiger.ProblemFeedbackMessage, lstadmin.Select(g => g.Email).Distinct().ToList(), null, null);
                }
            }
            catch (Exception ex)
            {
                feedbackresult.SubmitResult = false;
                feedbackresult.Message      = ex.Message;
                result = false;
            }
            if (Request.Files.Count > 0 && result == true)
            {
                HttpPostedFileBase Filedata         = Request.Files[0];
                string             FileName         = Guid.NewGuid().ToString();                                            //保存的文件名
                string             FileExtenSrcName = Filedata.FileName.Substring(Filedata.FileName.LastIndexOf("\\") + 1); //原文件名带扩展名
                string             FileSrcName      = FileExtenSrcName.Substring(0, FileExtenSrcName.LastIndexOf("."));     //原文件名不带扩展名
                string             FilePath         = null;
                string             FileExtenName    = Path.GetExtension(Filedata.FileName);                                 // 文件扩展名

                string strSaveDir = this.Server.MapPath("~/Attachments/Feedback");                                          //存储目录
                if (!System.IO.Directory.Exists(strSaveDir))
                {
                    System.IO.Directory.CreateDirectory(strSaveDir);
                }
                FilePath = strSaveDir + "\\" + FileName;
                Filedata.SaveAs(FilePath);

                List <AttachFileOperateDTO> attachlist = new List <AttachFileOperateDTO>();
                AttachFileOperateDTO        attach     = new AttachFileOperateDTO();
                attach.BelongModulePrimaryKey  = feedbackresult.Object.ToString();
                attach.AttachFileID            = Guid.NewGuid();
                attach.AttachFileSrcName       = FileSrcName;
                attach.BelongModule            = 1;
                attach.AttachFileExtentionName = FileExtenName;
                attach.AttachFileName          = FileName;
                attach.CreateTime = DateTime.Now;
                attach.CreateUser = user.FullName;
                attachlist.Add(attach);
                ResultData <object> attachresult = new ResultData <object>();
                attachresult = HomeProvider.AddAttachFileList(attachlist);
                if (!attachresult.SubmitResult)
                {
                    result = false;
                }
            }

            return(Json(result));
        }
Beispiel #11
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            //if (!dxValidationProvider1.Validate()) return;

            Trade = Trade ?? new T_ERP_Trade();

            Trade.Created = dateCreated.DateTime;
            Trade.Creator = Trade.Updator = this.CurUser;
            Trade.Reserved2 = string.Empty;
            Trade.Remark = txtRemark.Text;
            Trade.IsUrgent = chkIsUrgent.Checked;
            Trade.ProDelDate = dateProDelDate.DateTime;
            Trade.ReceiverName = txtReceiverName.Text;
            Trade.RecvOprUser = txtRecvOprUser.Text;

            Trade.LogisAddress = txtLogisAddress.Text;
            Trade.LogisName = txtLogisName.Text;
            Trade.ReceiverState = txtReceiverState.Text;
            Trade.ReceiverCity=txtReceiverCity.Text;
            Trade.ReceiverDistrict=txtReceiverDistrict.Text;
            Trade.ReceiverAddress = txtReceiverAddress.Text;
            Trade.ReceiverMobile = txtReceiverMobile.Text;

            var comp=companyGridEdit1.GetSelectedValue();
            if(comp!=null){
                Trade.CompanyName = comp.CompanyName;
                Trade.CompanyMobile = comp.CompanyMobile;
                Trade.CompanyAddress = comp.CompanyAddress;
            }

            var odrs = gcOrder.GetDataSource<T_ERP_Order>();
            if (odrs == null || odrs.Count < 1) {
                MsgBox.ShowErrMsg("没有添加商品,不能保存!");
                return;
            }

            if (odrs.Any(k => string.IsNullOrEmpty(k.ItemName))) {
                MsgBox.ShowErrMsg("必须选择商品!");
                return;
            }

            if (odrs.Any(k => string.IsNullOrEmpty(k.TradeMark))) {
                MsgBox.ShowErrMsg("必须选择商商标!");
                return;
            }

            //if (odrs.Any(k => string.IsNullOrEmpty(k.Surface))) {
            //    MsgBox.ShowErrMsg("商品必须选择皮料!");
            //    return;
            //}

            //if (EditMode == Ultra.Business.Core.Define.EnViewEditMode.New) {
            //    Trade.TradeNo = TradeNo;
            //    Trade.Guid = Guid.NewGuid();

            //    var rd=SerNoCaller.Calr_Order.Add(odrs);
            //    rd = SerNoCaller.Calr_Trade.Add(Trade);

            //} else {

            //    var rd =SerNoCaller.Calr_Order.ExecSql(" delete t_erp_order where tradeno=@0",Trade.TradeNo);

            //    rd=SerNoCaller.Calr_Order.Add(odrs);
            //    rd=SerNoCaller.Calr_Trade.Edt(Trade);
            //}

            var orders = odrs.Where(k => k.IsDynamicAdd).ToList();
            var rd=new ResultData();
            if (orders != null && orders.Count > 0) {
                rd = SerNoCaller.Calr_Order.Add(orders);
            }
            rd = SerNoCaller.Calr_Order.BatchEdt(odrs);
            if (rd.IsOK) {
                SerNoCaller.Calr_Order.ExecSql("exec P_FAS_SCUpdateTrdOrders @0,@1",Trade.TradeNo,this.CurUser);
            }

            DialogResult = DialogResult.OK;
            Close();
        }
Beispiel #12
0
            public void AddResult(ResultData r)
            {
                Boolean match = false;
                int indx = -1;
                foreach (MainResults MaRe in results)
                {
                    //match = (MaRe.Latitude == r.Latitude && MaRe.Longitude == r.Longitude);
                    match = (MaRe.OrganizationLocationID == r.OrganizationLocationID);
                    if (match)
                    {
                        indx = results.IndexOf(MaRe);
                        break;
                    }
                }
                if (!match)
                {
                    MainResults mr = new MainResults();
                    mr.TaxID = new String[] { r.TaxID };
                    mr.NPI = new String[] { r.NPI };
                    mr.PracticeName = r.PracticeName;
                    mr.ProviderName = new String[] { r.ProviderName };
                    mr.PracticeRangeMin = String.Format("{0:c0}", decimal.Parse(r.RangeMin));
                    mr.RangeMin = new String[] { r.RangeMin };
                    mr.PracticeRangeMax = String.Format("{0:c0}", decimal.Parse(r.RangeMax));
                    mr.RangeMax = new String[] { r.RangeMax };
                    mr.PracticeYourCostMin = String.Format("{0:c0}", decimal.Parse(r.YourCostMin));
                    mr.YourCostMin = new String[] { r.YourCostMin };
                    mr.PracticeYourCostMax = String.Format("{0:c0}", decimal.Parse(r.YourCostMax));
                    mr.YourCostMax = new String[] { r.YourCostMax };
                    mr.Latitude = r.Latitude;
                    mr.Longitude = r.Longitude;
                    mr.OrganizationLocationID = r.OrganizationLocationID;
                    mr.LocationAddress1 = r.LocationAddress1;
                    mr.LocationCity = r.LocationCity;
                    mr.LocationState = r.LocationState;
                    mr.LocationZip = r.LocationZip;
                    mr.Distance = r.Distance;
                    mr.NumericDistance = r.NumericDistance;
                    mr.PracticeFairPrice = r.FairPrice;
                    mr.FairPrice = new Boolean[] { r.FairPrice };
                    mr.HGRecognized = new Int32[] { r.HGRecognized };
                    switch (r.HGRecognized)
                    {
                        case -1:
                            mr.PracticeHGRecognized = "N/A";
                            break;
                        case 0:
                            mr.PracticeHGRecognized = "0/1 Physicians";
                            break;
                        case 1:
                            mr.PracticeHGRecognized = "1/1 Physicians";
                            break;
                        default:
                            mr.PracticeHGRecognized = "N/A";
                            break;
                    }
                    mr.PracticeAvgRating = r.HGOverallRating;
                    mr.HGOverallRating = new Double[] { r.HGOverallRating };
                    mr.HGPatientCount = new int[] { r.HGPatientCount };
                    results.Add(mr);
                }
                else
                {
                    MainResults mr = results[indx];

                    String[] s = new String[mr.TaxID.Length + 1];
                    mr.TaxID.CopyTo(s, 0);
                    s[s.Length - 1] = r.TaxID;
                    mr.TaxID = (String[])s.Clone();
                    mr.NPI.CopyTo(s, 0);
                    s[s.Length - 1] = r.NPI;
                    mr.NPI = (String[])s.Clone();
                    mr.ProviderName.CopyTo(s, 0);
                    s[s.Length - 1] = r.ProviderName;
                    mr.ProviderName = (String[])s.Clone();

                    mr.RangeMin.CopyTo(s, 0);
                    s[s.Length - 1] = r.RangeMin;
                    mr.RangeMin = (String[])s.Clone();
                    mr.PracticeRangeMin = String.Format("{0:c0}", ((double.Parse(mr.PracticeRangeMin.Replace("$", "")) + double.Parse(r.RangeMin)) / 2.0));
                    mr.RangeMax.CopyTo(s, 0);
                    s[s.Length - 1] = r.RangeMax;
                    mr.RangeMax = (String[])s.Clone();
                    mr.PracticeRangeMax = String.Format("{0:c0}", ((double.Parse(mr.PracticeRangeMax.Replace("$", "")) + double.Parse(r.RangeMax)) / 2.0));

                    mr.YourCostMin.CopyTo(s, 0);
                    s[s.Length - 1] = r.YourCostMin;
                    mr.YourCostMin = (String[])s.Clone();
                    mr.PracticeYourCostMin = String.Format("{0:c0}", ((double.Parse(mr.PracticeYourCostMin.Replace("$", "")) + double.Parse(r.YourCostMin)) / 2.0));
                    mr.YourCostMax.CopyTo(s, 0);
                    s[s.Length - 1] = r.YourCostMax;
                    mr.YourCostMax = (String[])s.Clone();
                    mr.PracticeYourCostMax = String.Format("{0:c0}", ((double.Parse(mr.PracticeYourCostMax.Replace("$", "")) + double.Parse(r.YourCostMax)) / 2.0));

                    Boolean[] b = new Boolean[mr.FairPrice.Length + 1];
                    mr.FairPrice.CopyTo(b, 0);
                    b[b.Length - 1] = r.FairPrice;
                    mr.FairPrice = (Boolean[])b.Clone();
                    if (!mr.PracticeFairPrice && r.FairPrice) { mr.PracticeFairPrice = r.FairPrice; }

                    Int32[] i32 = new Int32[mr.HGRecognized.Length + 1];
                    mr.HGRecognized.CopyTo(i32, 0);
                    i32[i32.Length - 1] = r.HGRecognized;
                    mr.HGRecognized = (Int32[])i32.Clone();
                    switch (r.HGRecognized)
                    {
                        case -1:
                            //Do Nothing
                            break;
                        case 0:
                            if (mr.PracticeHGRecognized == "N/A") { mr.PracticeHGRecognized = "0/0 Physicians"; }
                            String[] str0 = mr.PracticeHGRecognized.Replace("Physicians", "").Trim().Split('/');
                            mr.PracticeHGRecognized = String.Format("{0}/{1} Physicians",
                                str0[0],
                                (Convert.ToInt32(str0[1]) + 1).ToString());
                            break;
                        case 1:
                            if (mr.PracticeHGRecognized == "N/A") { mr.PracticeHGRecognized = "0/0 Physicians"; }
                            String[] str1 = mr.PracticeHGRecognized.Replace("Physicians", "").Trim().Split('/');
                            mr.PracticeHGRecognized = String.Format("{0}/{1} Physicians",
                                (Convert.ToInt32(str1[0]) + 1).ToString(),
                                (Convert.ToInt32(str1[1]) + 1).ToString());
                            break;
                        default:
                            break;
                    }

                    Double[] d = new Double[mr.HGOverallRating.Length + 1];
                    mr.HGOverallRating.CopyTo(d, 0);
                    d[d.Length - 1] = r.HGOverallRating;
                    mr.HGOverallRating = (Double[])d.Clone();
                    mr.PracticeAvgRating = ((mr.PracticeAvgRating + r.HGOverallRating) / 2.0);

                    int[] i = new int[mr.HGPatientCount.Length + 1];
                    mr.HGPatientCount.CopyTo(i, 0);
                    i[i.Length - 1] = r.HGPatientCount;
                    mr.HGPatientCount = (int[])i.Clone();

                    results[indx] = mr;
                }
            }
Beispiel #13
0
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";
            context.Response.ContentEncoding = Encoding.UTF8;

            // The Request QueryString here is protected against XSS attacks by Request Validation
            QuerySettings settings = CCHSerializer.DeserializeSettings<QuerySettings>(context.Request.QueryString);
            if (settings.Lat == null) { settings.Lat = context.GetLatitude<String>(); }
            if (settings.Lng == null) { settings.Lng = context.GetLongitude<String>(); }

            ResultsBack rb = new ResultsBack();
            using (GetDoctorsForService gdfs = new GetDoctorsForService())
            {
                gdfs.ServiceName = context.GetServiceName<String>();
                gdfs.Latitude = settings.Lat;
                gdfs.Longitude = settings.Lng;
                gdfs.SpecialtyID = context.GetSpecialtyID<Int32>();
                //gdfs.MemberMedicalID = ThisSession.SubscriberMedicalID;
                gdfs.CCHID = context.GetCCHID<Int32>();
                gdfs.UserID = context.GetUserLogginID<String>();
                gdfs.SessionID = context.GetSessionID<String>();
                gdfs.Domain = context.GetDomain<String>();
                gdfs.GetData();
                if (!gdfs.HasErrors)
                {
                    ResultData rd = new ResultData();
                    gdfs.ForEachResult(delegate(object Result)
                    {
                        rd = CCHSerializer.DeserializeDataRow<ResultData>(Result);
                        rd.Distance = String.Format("{0:#0.0 mi}", Convert.ToDouble(rd.NumericDistance));
                        rb.AddResult(rd);
                    });
                }
            }

            JavaScriptSerializer jss = new JavaScriptSerializer();
            String jsonBack = jss.Serialize(rb);

            context.Response.Write(jsonBack);
        }
Beispiel #14
0
 public void AddResult(ResultData r)
 {
     this.results.Add(r);
 }
        /// <summary>
        /// 再帰検索処理.
        /// </summary>
        /// <param name="resultData">結果を格納</param>
        /// <param name="uppserSet">上位検索セット</param>
        /// <param name="remainingPartList">残未確定部位リスト</param>
        /// <param name="abstractArmorMode">仮想防具モードかどうか</param>
        /// <param name="upperReport">上位検索状況情報</param>
        /// <param name="nest">再帰階層</param>
        /// <param name="pBegin">この処理の開始時点の進捗</param>
        /// <param name="pEnd">この処理の終了時点の進捗</param>
        /// <returns>この処理で確定したセットの数(マイナスの場合は処理中断)</returns>
        private int RecursionSearch(ResultData resultData, SearchSet uppserSet, SearchReport upperReport, List <PartDataBase> remainingPartList, bool abstractArmorMode, int nest, int pBegin, int pEnd)
        {
            // 呼び出され回数をインクリメント
            this.TotalCalled++;

            // 階層をインクリメント.
            var curNest = nest + 1;

            // キャンセルされたか調べる
            if (this.IsCancel())
            {
                // キャンセルされたとき
                return(-1);
            }

            // ネストで見つかった確定セット数を格納する.
            var determined = 0;

            // この処理での進捗幅.
            var partUnit = pEnd - pBegin;

            // このネストで検索する部位.
            var part = remainingPartList.ElementAt(0);

            // 残りの部位.
            var unsettledPartList = remainingPartList.ToList();

            unsettledPartList.RemoveAt(0);

            // 候補装備リスト管理データを作成.
            var candidateListCtrl = abstractArmorMode
                ? this.CandidateSet.GetArmorAbstract(part.Part, upperReport)
                : this.CandidateSet.GetCandidate(part.Part, upperReport);

            // 候補装備数.
            var allCount = candidateListCtrl.GetCount();

            // 検索セットを複製.
            var searchSet = new SearchSet(uppserSet);

            // 装備毎に走査.
            // 進捗管理の為に i が必要.
            for (var i = 0; i < allCount; i++)
            {
                var candidateData = candidateListCtrl.GetAt(i);

                // 無効装備は無視.
                if (null == candidateData || !candidateData.Enable)
                {
                    continue;
                }

                // 候補装備.
                var candidate = candidateData.PartData;

                // 進捗の最小単位を計算.
                var begin = pBegin;
                var end   = pBegin;
                if (0 < partUnit)
                {
                    // 候補装備毎の進捗単位を計算.
                    // 要素数を取得.
                    var candidateUnit = partUnit / allCount;
                    if (0 < candidateUnit)
                    {
                        begin = pBegin + (i * candidateUnit);
                        end   = begin + candidateUnit;
                    }
                }

                // 新たな候補をセットして.
                searchSet.SetPart(part.Part, candidate);

                // 検索数上限に到達しているかどうかをチェック.
                if (0 < Ssm.Config.SerchLimitCount &&
                    Ssm.Config.SerchLimitCount <= resultData.GetSatisfiedCount())
                {
                    Log.Write("検索結果上限[{0}件]に到達したので処理中断".Fmt(Ssm.Config.SerchLimitCount));
                    break;
                }

                // 検索状況リポートを生成.
                var searchReport = this.CreateSearchReport(searchSet);

                // 現状のセットが検索条件を満たすかどうかチェック.
                // スキルが要求を満たしている場合.
                if (!searchReport.UnsatisfyList.Any())
                {
                    ////////////////
                    // スキル満足 //
                    ////////////////

                    // スロットが必要数を満たしている場合.
                    if (!searchReport.LackSlotList.Any())
                    {
                        //////////
                        // 完成 //
                        //////////
                        resultData.AddSatisfiedSet(new ResultSet(searchSet));
                        determined += 1;

                        // 上位互換装備を候補リストから除く.
                        candidateListCtrl.RemoveUpwardCompatibility(candidate, searchReport);
                        continue;
                    }

                    // スロットが不足している場合、下記条件のいずれかにヒットしたら検索終了
                    // ・未確定防具が残っていない場合.
                    // ・抽象化防具を使用しない場合.
                    var abstractPartList = searchSet.GetUnsettledArmorList();
                    if (!abstractPartList.Any() || !Ssm.Config.UseArmorAbstract)
                    {
                        //////////////////////////
                        // スロット不足 → 終了 //
                        //////////////////////////

                        // 解析を実施する場合は解析結果に追加.
                        if (this.AnalyzeFactors)
                        {
                            // スロット不足で不十分な組み合わせ.
                            resultData.AddShortageSlot(searchReport.GetLackSlotKey(), new ResultSet(searchSet));
                        }

                        // これ以上の検索は不要.
                        continue;
                    }

                    //////////////////////////////////////////
                    // スロット不足 → 抽象化防具検索モード //
                    //////////////////////////////////////////
                    // >>>>再帰呼び出し<<<< //
                    // 検索処理を再帰呼び出し.
                    var result = this.RecursionSearch(resultData, searchSet, searchReport, abstractPartList, true, curNest, begin, end);
                    // >>>>再帰呼び出し<<<<

                    // 条件を満たす組み合わせが見つかった場合.
                    if (0 < result)
                    {
                        // 結果に登録.
                        determined += result;
                    }
                    else if (result < 0)
                    {
                        // 処理中断の場合.
                        return(result);
                    }
                }
                else
                {
                    ////////////////
                    // スキル不足 //
                    ////////////////

                    // 残りの部位が残っていない場合はスキル不足で不十分な組み合わせ.
                    if (!unsettledPartList.Any())
                    {
                        // 下記の条件を全て満たしている場合は解析結果に登録.
                        // ・不足しているスキルが一つ
                        // ・スロットは満たしている
                        // ・解析を実施する場合.
                        if (this.AnalyzeFactors &&
                            !searchReport.LackSlotList.Any() &&
                            1 == searchReport.UnsatisfyList.Count)
                        {
                            // スキル不足で不十分な組み合わせ.
                            resultData.AddShortageSkill(searchReport.GetUnsatisfyKey(), new ResultSet(searchSet));
                        }

                        // これ以上の検索は不要.
                        continue;
                    }

                    //////////////////////////////////
                    // スキル不足 → 通常検索モード //
                    //////////////////////////////////
                    // >>>>再帰呼び出し<<<<
                    // 検索処理を再帰呼び出し.
                    var result = this.RecursionSearch(resultData, searchSet, searchReport, unsettledPartList, false, curNest, begin, end);
                    // >>>>再帰呼び出し<<<<

                    // 条件を満たす組み合わせが見つかった場合.
                    if (0 < result)
                    {
                        // 結果に登録.
                        determined += result;
                    }
                    else if (result < 0)
                    {
                        // 処理中断の場合.
                        return(result);
                    }
                }
            }

            // 進捗を更新.
            if (0 < partUnit)
            {
                this.SetProgress((int)pEnd);
            }

            return(determined);
        }
Beispiel #16
0
        protected override ResultStatus Save(PokeBall poke)
        {
            gvMain.CloseEditor();
            gvMain.UpdateCurrentRow();

            DataTable dt       = (DataTable)gcMain.DataSource;
            DataTable dtChange = dt.GetChanges();

            //存檔前檢查
            try {
                //無法經由資料列存取已刪除的資料列資訊。
                if (dtChange != null)
                {
                    //if (dt.Rows.Count <= 0) {
                    //   MessageDisplay.Warning("下方視窗無資料無法進行存檔,請先執行「讀取/預覽」!");
                    //   ShowMsg("轉檔有誤!");
                    //   return ResultStatus.Fail;
                    //}

                    //重新產置資料儲存確認
                    string isYMD     = YMDlookUpEdit.EditValue.ToString();
                    int    dataCount = b30290.DataCount(isYMD);

                    if (dataCount > 0)
                    {
                        DialogResult ChooseResult = MessageDisplay.Choose("已存在相同生效日期資料,請問是否繼續儲存?");
                        if (ChooseResult == DialogResult.Yes)
                        {
                            if (retrieveChoose == DialogResult.No) //一開始讀取資料按「否」重新產至資料
                            {
                                if (!b30290.DeleteData(isYMD))     //刪除已有的資料
                                {
                                    return(ResultStatus.Fail);
                                }
                            }
                        }
                    }

                    //變更儲存日期以及USER_ID
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (dr.RowState != DataRowState.Deleted)
                        {
                            dr["PLP13_W_TIME"]    = DateTime.Now;
                            dr["PLP13_W_USER_ID"] = GlobalInfo.USER_ID;
                        }
                    }
                }
                if (dtChange != null)
                {
                    try {
                        dtChange    = dt.GetChanges();
                        this.Cursor = Cursors.WaitCursor;
                        ShowMsg("存檔中...");
                        //儲存PLP13
                        ResultData myResultData = b30290.UpdateData(dtChange);
                        //初始訊息選擇狀態
                        retrieveChoose = DialogResult.None;
                    }
                    catch (Exception ex) {
                        WriteLog(ex);
                    }
                    //Write LOGF
                    WriteLog("變更資料 " + logtxt, "Info", "I", false);
                    return(ResultStatus.Success);
                }
                else
                {
                    MessageBox.Show("沒有變更資料,不需要存檔!", "注意", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex) {
                WriteLog(ex);
            }
            finally {
                Export();//存檔後轉出Excel
            }

            return(ResultStatus.Success);
        }
Beispiel #17
0
        /// <summary>
        /// 修改付款条款信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public static ResultData <object> UpdatePayment(PaymentOperateDTO dto)
        {
            ResultData <object> blResult = PutAPI <ResultData <object> >(WebConfiger.MasterDataServicesUrl + "Payment", dto);

            return(blResult);
        }
Beispiel #18
0
        public void ModifyReachValues()
        {
            string resultFilepath = System.IO.Path.Combine(ExampleBase.ExampleRoot, @"Results\vida96-3.res1d");

            // load a result file
            IResultData resultData = new ResultData();

            resultData.Connection = Connection.Create(resultFilepath);
            Diagnostics resultDiagnostics = new Diagnostics("Example");

            resultData.Load(resultDiagnostics);

            if (resultDiagnostics.ErrorCountRecursive > 0)
            {
                // Do some error reporting
                throw new Exception("File could not be loaded");
            }

            Quantity wlQuantity = Quantity.Create(PredefinedQuantity.WaterLevel);

            // The ResultDataSearch helps doing searching of results efficiently
            ResultDataSearch searcher = new ResultDataSearch(resultData);

            // Find all branches named "VIDAA-NED" - there are three, due to junction splits
            IList <IRes1DReach> reaches = searcher.FindReaches("VIDAA-NED");

            foreach (IRes1DReach reach in reaches)
            {
                // Find the water level data item, and update the water level with 0.2 between
                // chainage 7000 and 1000 for all time steps

                IDataItem wlData = reach.GetDataItem(wlQuantity);

                for (int i = 0; i < wlData.NumberOfElements; i++)
                {
                    // Index of grid point where element value i belongs to
                    int igp = wlData.IndexList[i];
                    // Chainage of grid point where element value i belongs to
                    double gpChainage = reach.GridPoints[igp].Chainage;
                    if (7000 < gpChainage && gpChainage < 10000)
                    {
                        // Update for all time steps
                        for (int j = 0; j < wlData.NumberOfTimeSteps; j++)
                        {
                            float val = wlData.TimeData.GetValue(j, i);
                            val += 0.2f;
                            wlData.TimeData.SetValue(j, i, val);
                        }
                    }
                }

                // Also check if the end-node is on this span
                if (7000 < reach.LocationSpan.EndChainage && reach.LocationSpan.EndChainage < 10000)
                {
                    IDataItem wlNodeData = resultData.Nodes[reach.EndNodeIndex].GetDataItem(wlQuantity);
                    // Update for all time steps
                    for (int j = 0; j < wlNodeData.NumberOfTimeSteps; j++)
                    {
                        // In a node there is only one element value, so i = 0
                        float val = wlNodeData.TimeData.GetValue(j, 0);
                        val += 0.2f;
                        wlNodeData.TimeData.SetValue(j, 0, val);
                    }
                }
            }

            // Save file with a new name
            resultData.Connection.FilePath.FileNameWithoutExtension += "-testModify";
            resultData.Save();
        }
Beispiel #19
0
        public ResultData GetDataPaging(string storeName, string sort, int page, int limit, string where, string columns = "*", params object[] arrParams)
        {
            ResultData oResultData = new ResultData {
                Success = true, Code = System.Net.HttpStatusCode.OK
            };

            try
            {
                where = where.Replace("CustomerID", "cus.CustomerID");
                DbParameter pOutput = null;
                using (DbCommand command = this.DB.GetStoredProcCommand(storeName))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    this.DB.DiscoverParameters(command);
                    if (command.Parameters.Count > 0)
                    {
                        command.Parameters.RemoveAt(0);
                        int paramIndex = 0;

                        for (int i = 0; i <= command.Parameters.Count - 1; i++)
                        {
                            DbParameter dbParam   = command.Parameters[i];
                            string      paramName = dbParam.ParameterName.Replace("@", "").ToLower();

                            switch (paramName)
                            {
                            case "sort":
                                if (!string.IsNullOrEmpty(sort))
                                {
                                    dbParam.Value = sort;
                                }
                                else
                                {
                                    dbParam.Value = DBNull.Value;
                                }
                                break;

                            case "page":
                                dbParam.Value = page;
                                break;

                            case "limit":
                                dbParam.Value = limit;
                                break;

                            case "where":
                                dbParam.Value = where;
                                break;

                            case "columns":
                                if (!string.IsNullOrEmpty(columns))
                                {
                                    dbParam.Value = columns;
                                }
                                else
                                {
                                    dbParam.Value = "*";
                                }
                                break;

                            case "totalcount":
                                pOutput       = command.Parameters[i];
                                pOutput.Value = 0;
                                break;

                            default:
                                if (arrParams != null)
                                {
                                    if (arrParams[paramIndex] != null)
                                    {
                                        dbParam.Value = arrParams[paramIndex];
                                    }
                                    else
                                    {
                                        dbParam.Value = DBNull.Value;
                                    }
                                    paramIndex++;
                                }
                                break;
                            }
                        }
                    }

                    using (IDataReader rd = this.DB.ExecuteReader(command))
                    {
                        oResultData.Data = rd.FillCollection <MedicalRecord>(false);
                        if (rd.NextResult())
                        {
                            Dictionary <string, object> dicSummary = new Dictionary <string, object>();
                            while (rd.Read())
                            {
                                for (int i = 0; i < rd.FieldCount; i++)
                                {
                                    dicSummary.Add(rd.GetName(i), rd[i]);
                                }
                            }
                            oResultData.SummaryData = dicSummary;
                        }
                        ;
                    }
                    if (pOutput != null)
                    {
                        oResultData.Total = pOutput.Value as int? ?? default(int);
                    }
                }
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                oResultData.SetError(ex);
                throw ex;
            }
            catch (Exception ex)
            {
                oResultData.SetError(ex);
                throw ex;
            }
            return(oResultData);
        }
Beispiel #20
0
        /// <summary>
        /// Example stepping through the structure of the
        /// ResultData object
        /// </summary>
        /// <param name="resultFilepath">Path to a result file</param>
        public static void FirstExample(string resultFilepath)
        {
            // load a result file
            IResultData resultData = new ResultData();

            resultData.Connection = Connection.Create(resultFilepath);
            Diagnostics resultDiagnostics = new Diagnostics("Example");

            resultData.Load(resultDiagnostics);

            if (resultDiagnostics.ErrorCountRecursive > 0)
            {
                // Do some error reporting
                throw new Exception("File could not be loaded");
            }

            // Time definition of the time step stored
            int      numtimesteps = resultData.NumberOfTimeSteps;
            DateTime startTime    = resultData.StartTime;
            DateTime endTime      = resultData.EndTime;
            // times for all timesteps
            IListDateTimes times = resultData.TimesList;

            // Results are stored in DataItem’s, where one DataItem contains e.g. water level.
            // Nodes, Reaches, Catchments and GlobalData of the resultData object will have a
            // number of data items.
            // A data item will store data for a number of elements and for a number
            // of time steps.
            // In reaches there will be more than one "element", since a reach will store
            // data for several grid points. Nodes and catchments will always only have
            // one element per data item

            IRes1DNodes      nodes      = resultData.Nodes;
            IRes1DReaches    reaches    = resultData.Reaches;
            IRes1DCatchments catchments = resultData.Catchments;
            IRes1DGlobalData globals    = resultData.GlobalData;

            // Generic loop over catchments/nodes/reaches (just replace catchments with nodes)
            foreach (IRes1DDataSet dataSet in catchments)
            {
                // Each dataset has a number of data items
                IDataItems dataItems = dataSet.DataItems;

                // Loop over all data items
                foreach (IDataItem dataItem in dataItems)
                {
                    // A dataitem contains data for one quantity
                    IQuantity quantity = dataItem.Quantity;

                    // You can check the type of quantity in the data item
                    if (quantity.Equals(Quantity.Create(PredefinedQuantity.WaterLevel)))
                    {
                    }
                }
            }

            // The example will now show how to extract data from a reach.

            // Get the first reach in the list of reaches
            IRes1DReach reach = reaches[0];

            // Extract first data item for reach (there will be more than one)
            // For a HD result file, this will be a water level.
            IDataItem wlDataItem = reach.DataItems[0];

            // Take data for all elements (subset of grid points) for the initial time step
            // For water level quantity: One value for each H-grid point
            float[] wlValues = wlDataItem.TimeData.GetValues(0);

            // For a reach, if the IndexList is defined (not null), this
            // gives the relation to the grid point where the values in
            // a data item belongs to.
            // For each value in the data item, it indicates the index of the grid point
            // it belongs to, i.e. the size matches the number of elements in the data item.
            // i.g. for water level: 0, 2, 4, 6, 8,...
            // and  for discharge  : 1, 3, 5, 7,...
            // The IndexList can be null, in which case information on the geometry of the
            // data in the data item exist in the element set
            int[] indexList = wlDataItem.IndexList;

            // Loop over all elements (subset of grid points) in the data item
            for (int i = 0; i < wlDataItem.NumberOfElements; i++)
            {
                // Time series values for this element (grid point)
                float[] wlDataForElement = wlDataItem.CreateTimeSeriesData(i);

                // Check if there is a grid-point relation
                if (indexList != null)
                {
                    // Index of grid point in list of grid opints
                    int gridPointIndex = wlDataItem.IndexList[i];

                    // Grid point where values belong to.
                    IRes1DGridPoint gridPoint = reach.GridPoints[gridPointIndex];

                    // More detailed information exist in the derived grid point classes
                    if (gridPoint is IRes1DHGridPoint)
                    {
                        IRes1DHGridPoint hGridPoint = gridPoint as IRes1DHGridPoint;

                        // An H-grid point also has a cross section.
                        IRes1DCrossSection crossSection = hGridPoint.CrossSection;

                        // More detailed information on the cross section exist in the derived types
                        if (crossSection is IRes1DOpenCrossSection)
                        {
                            // The open cross section has all the raw points and cross section markers
                            IRes1DOpenCrossSection  openXs        = crossSection as IRes1DOpenCrossSection;
                            IRes1DCrossSectionPoint lowestXsPoint = openXs.Points[openXs.LowestPoint];
                        }
                    }
                }
            }
        }
Beispiel #21
0
        public ResultData ProcessGeocachingComGPXFile(string filename)
        {
            ResultData result = new ResultData();
            //zip or gpx?
            try
            {
                if (filename.ToLower().EndsWith("-wpts.gpx"))
                {
                    ProcessGeocachingComGPXWaypoints(result, System.IO.File.ReadAllText(filename));
                }
                else if (filename.ToLower().EndsWith(".gpx"))
                {
                    ProcessGeocachingComGPXCaches(result, System.IO.File.ReadAllText(filename));
                }
                else
                {
                    //zip - containts waypoints and caches
                    using (var fs = System.IO.File.OpenRead(filename))
                    using (ZipInputStream s = new ZipInputStream(fs))
                    {
                        ZipEntry theEntry = s.GetNextEntry();
                        byte[] data = new byte[1024];
                        while (theEntry != null)
                        {
                            StringBuilder sb = new StringBuilder();
                            while (true)
                            {
                                int size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    if (sb.Length == 0 && data[0] == 0xEF && size > 2)
                                    {
                                        sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 3, size - 3));
                                    }
                                    else
                                    {
                                        sb.Append(System.Text.ASCIIEncoding.UTF8.GetString(data, 0, size));
                                    }
                                }
                                else
                                {
                                    break;
                                }
                            }

                            if (theEntry.Name.ToLower().IndexOf("-wpts.") > 0)
                            {
                                ProcessGeocachingComGPXWaypoints(result, sb.ToString());
                            }
                            else
                            {
                                ProcessGeocachingComGPXCaches(result, sb.ToString());
                            }

                            try
                            {
                                theEntry = s.GetNextEntry();
                            }
                            catch
                            {
                                //opencaching.de zip files generates an exception
                                theEntry = null;
                            }
                        }
                    }
                }
            }
            catch
            {
                result = null;
            }
            return result;
        }
Beispiel #22
0
        public EyeMove TryFindEyeMove(int id, int spotStartIndex, int spotEndIndex, ResultData results)
        {
            //Moze zaczac od sakady i w ciagu 500 ms powinien zaczac antysakade
            //(wtedy zaliczamy jako prawidlowa antysakade) czyli ruch oka w kierunku przeciwnym do plamki
            //- jesli takiego nie wykonuje to zaliczamy jako zly wynik.

            var controlWindowCoords = EyeMoveSearchToolBox.GetControlWindow(results, spotStartIndex, config.ControlWindowLength);

            var meanControlAmplitude = EyeMoveSearchToolBox.CalculateControlAmplitude(controlWindowCoords, config.ControlAmpDivider);
            var minLenght            = config.MinLength;             //0.3;
            var anitSaccadeLatency   = config.MinLatency;            //15;

            var eyeStartIndex = spotStartIndex + anitSaccadeLatency; // 500ms
            var antiSaccadeStartFindCoords = results.EyeCoords.Skip(eyeStartIndex).Take(config.MoveSearchWindowLength).ToArray();

            var spotStartOscilationXPosition = results.SpotCoords[spotStartIndex];
            var spotEndOscilationXPosition   = results.SpotCoords[spotStartIndex + 1];
            var isRising = !EyeMoveSearchToolBox.IsRising(spotStartOscilationXPosition, spotEndOscilationXPosition);

            bool   isStartFound        = false;
            double controlAmpTestValue = -1;
            double minLengthTestValue  = -1;

            EyeMoveSearchToolBox.FindStartByMoveDirection(ref antiSaccadeStartFindCoords, ref eyeStartIndex,
                                                          spotStartOscilationXPosition, isRising, meanControlAmplitude, minLenght,
                                                          ref isStartFound, ref controlAmpTestValue, ref minLengthTestValue);

            bool isEndFound = false;
            var  endIndex   = EyeMoveSearchToolBox.GetEndBySpeedChange(antiSaccadeStartFindCoords, eyeStartIndex, config, ref isEndFound);

            // hamowanie odwrotne
            var antiSaccadeStartIndex = eyeStartIndex;
            var antiSaccadeEndIndex   = endIndex;

            if (antiSaccadeStartIndex > results.EyeCoords.Length)
            {
                return(null);
            }
            else if (isStartFound == false || isEndFound == false)
            {
                return(null);
            }
            else
            {
                return(new EyeMove
                {
                    Id = id,
                    IsFirstMove = DataAnalyzer.IsEven(id),

                    IsStartFound = isStartFound,
                    EyeStartIndex = antiSaccadeStartIndex,
                    EyeStartTime = results.TimeDeltas[antiSaccadeStartIndex],
                    EyeStartCoord = results.EyeCoords[antiSaccadeStartIndex],
                    ControlAmpTestValue = controlAmpTestValue,
                    MinLengthTestValue = minLengthTestValue,

                    IsEndFound = isEndFound,
                    EyeEndIndex = antiSaccadeEndIndex,
                    EyeEndTime = results.TimeDeltas[antiSaccadeEndIndex],
                    EyeEndCoord = results.EyeCoords[antiSaccadeEndIndex],

                    EyeMoveType = Enums.EyeMoveTypes.AntiSaccade,

                    SpotMove = new Spot.SpotMove
                    {
                        SpotStartIndex = spotStartIndex,
                        SpotStartTimeDelta = results.TimeDeltas[spotStartIndex],
                        SpotStartCoord = results.SpotCoords[spotStartIndex],

                        SpotEndIndex = spotEndIndex,
                        SpotEndTimeDelta = results.TimeDeltas[spotEndIndex],
                        SpotEndCoord = results.SpotCoords[spotEndIndex]
                    }
                });
            }
        }
 public DownloadModsResult(List<MyObjectBuilder_Checkpoint.ModItem> mods, Action<bool,string> onFinishedCallback)
 {
     callback = onFinishedCallback;
     Task = Parallel.Start(() =>
     {
         Result = DownloadWorldModsBlocking(mods);
     });
 }
Beispiel #24
0
 public TestRun(RunData theRunData, ResultData theExpectedResult)
 {
     runData        = theRunData;
     expectedResult = theExpectedResult;
 }
        public static List <ResultData> GetResults(eTaskType taskType, int phoneNumberId = 0)
        {
            var results = new List <ResultData>();

            using (var ctx = new NovaAlertContext())
            {
                //var list = ctx.ViewResults.Where(r => r.TaskType == (byte)taskType && r.PhoneNumberId != null).OrderBy(r => r.Id).ToList();

                var list = new List <ViewResult>();
                if (phoneNumberId == 0)
                {
                    list = ctx.ViewResults.Where(r => r.TaskType == (byte)taskType && r.PhoneNumberId != null).OrderBy(r => r.Id).ToList();
                }
                else
                {
                    list = ctx.ViewResults.Where(r => r.TaskType == (byte)taskType && r.PhoneNumberId == phoneNumberId).OrderBy(r => r.Id).ToList();
                }

                foreach (var item in list)
                {
                    var re = new ResultData()
                    {
                        DisplayId     = item.Id,
                        PhoneNumberId = item.PhoneNumberId.Value,
                        UnitName      = item.UnitName,
                        Task          = (eTask)(item.Task ?? 0),
                        Level         = (eTaskLevel)(item.Level ?? 0),
                        Result        = (eTaskResult)(item.Result ?? 0),
                        TaskType      = (eTaskType)item.TaskType
                    };

                    if (re.Result == eTaskResult.NL)
                    {
                        if (item.Duration.HasValue)
                        {
                            re.TimeReceive     = item.CreatedDate;
                            re.IntervalReceive = TimeSpan.FromSeconds(item.Duration.Value);
                        }
                    }
                    else if (re.Result == eTaskResult.CTT)
                    {
                        if (item.Duration.HasValue)
                        {
                            re.TimeChange     = item.CreatedDate;
                            re.IntervalChange = TimeSpan.FromSeconds(item.Duration.Value);
                        }

                        var temp = ctx.GroupUnitTasks.Where(r => r.Result == (byte)eTaskResult.NL && r.PhoneNumberId == item.PhoneNumberId &&
                                                            r.TaskType == (byte)eTaskType.CTT).OrderByDescending(r => r.Id).FirstOrDefault();
                        if (temp != null)
                        {
                            if (temp.Duration.HasValue)
                            {
                                re.TimeReceive     = temp.CreatedDate;
                                re.IntervalReceive = TimeSpan.FromSeconds(temp.Duration.Value);
                            }
                        }
                    }

                    results.Add(re);
                }
            }

            return(results);
        }
Beispiel #26
0
        public static EyeMove GetSaccadePositionItem(int id, int saccadeStartIndex, int saccadeEndIndex, int spotOverMeanStartIndex, int spotOverMeanEndIndex, ResultData results)
        {
            return(new EyeMove
            {
                Id = id,
                EyeStartIndex = saccadeStartIndex,
                EyeStartTime = results.TimeDeltas[saccadeStartIndex],
                EyeStartCoord = results.EyeCoords[saccadeStartIndex],

                EyeEndIndex = saccadeEndIndex,
                EyeEndTime = results.TimeDeltas[saccadeEndIndex],
                EyeEndCoord = results.EyeCoords[saccadeEndIndex],

                SpotMove = new Spot.SpotMove
                {
                    SpotStartIndex = spotOverMeanStartIndex,
                    SpotStartTimeDelta = results.TimeDeltas[spotOverMeanStartIndex],
                    SpotStartCoord = results.SpotCoords[spotOverMeanStartIndex],

                    SpotEndIndex = spotOverMeanEndIndex,
                    SpotEndTimeDelta = results.TimeDeltas[spotOverMeanEndIndex],
                    SpotEndCoord = results.SpotCoords[spotOverMeanEndIndex]
                }
            });
        }
        public WebResult SetPreOrder(string[] values)
        {
            WebResult ret = new WebResult();

            try
            {
                ServiceIF serv  = new ServiceIF();
                PreOrder  order = new PreOrder();
                string    msg   = "";
                string    msg2  = "";
                string    msg3  = "";

                List <string> pastIds = new List <string>();

                order.HospID = Convert.ToInt32(values[0]);
                if (!string.IsNullOrEmpty(values[1]))
                {
                    order.OrderID = Convert.ToInt32(values[1]);
                }
                else
                {
                    order.OrderID = 0;
                }
                order.PatID       = values[2];
                order.PatName     = values[3];
                order.PatName_H   = values[4];
                order.PatAge      = Convert.ToInt32(values[5]);
                order.BirthDay    = values[6];
                order.Modality    = values[7];
                order.Date        = values[8];
                order.Time        = values[9];
                order.BodyPart    = values[10];
                order.Type        = values[11];
                order.ImgCnt      = Convert.ToInt32(values[12]);
                order.IsEmergency = Convert.ToInt32(values[13]);
                order.IsMail      = Convert.ToInt32(values[14]);
                order.Comment     = values[15];
                order.Sex         = Convert.ToInt32(values[16]);
                order.Status      = 1;
                if (values[17] != "")
                {
                    msg2 = "別途依頼票あり";
                }

                if (order.IsMail == 1)
                {
                    msg3 = values[19] + " " + values[18];
                }

                if (values.Length > 20)
                {
                    for (int i = 20; i < values.Length; i++)
                    {
                        pastIds.Add(values[i]);
                    }
                }

                int key = 0;

                serv.SetPatient_Serv(order, out key);
                order.Key = key;

                ResultData inRet = serv.SetPreOrder_Serv(order);

                if (inRet.Result)
                {
                    LogControl.WriteLog(LogType.ORE, "SetPreOrder", "【オーダー登録】 施設ID:" + order.HospID + " 患者ID:" + order.PatID + " モダリティ:" + order.Modality + " 検査日:" + order.Date);

                    OrderTool_Serv.Class.Search search = new OrderTool_Serv.Class.Search();
                    search.PatID = order.PatID;

                    PreOrder[] tmpOrders;

                    serv.GetPreOrder_Serv(search, out tmpOrders);
                    var msg4 = "";
                    foreach (var odr in tmpOrders)
                    {
                        if (pastIds.Contains(odr.OrderID.ToString()))
                        {
                            odr.Status = 2;
                            serv.SetPreOrder_Serv(odr);

                            if (!string.IsNullOrEmpty(msg))
                            {
                                msg  += "、";
                                msg4 += "、";
                            }
                            msg  += odr.Date.Substring(4, 2) + "/" + odr.Date.Substring(6, 2);
                            msg4 += odr.Date.Substring(0, 4) + "/" + odr.Date.Substring(4, 2) + "/" + odr.Date.Substring(6, 2);
                            if (order.Modality != odr.Modality)
                            {
                                msg4 += " ";
                                msg4 += odr.Modality;
                                msg  += " ";
                                msg  += odr.Modality;
                            }
                            msg += " ";
                            msg += odr.ImgCnt.ToString();
                        }
                        else if (order.Date == odr.Date &&
                                 order.Modality == odr.Modality &&
                                 order.PatID == odr.PatID &&
                                 order.Time == odr.Time)
                        {
                            if (order.OrderID == 0)
                            {
                                order.OrderID = odr.OrderID;
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(msg4))
                    {
                        msg4 = "比較参照お願いします。(" + msg4 + ")" + msg2;
                    }
                    else
                    {
                        msg4 = msg2;
                    }

                    string cA = order.ImgCnt.ToString();
                    string cB = msg;

                    if (string.IsNullOrEmpty(msg))
                    {
                        msg = order.ImgCnt.ToString();
                    }
                    else
                    {
                        msg = order.ImgCnt.ToString() + "(" + msg + ")";
                    }

                    WriteCSV(order, msg, msg2, msg3, msg4, cA, cB);

                    ret.Result = inRet.Result;
                }
                else
                {
                    ret.Message = inRet.Message;
                }

                ret.Result = inRet.Result;
            }
            catch (Exception e)
            {
                ret.Result  = false;
                ret.Message = "処理中に障害が発生いたしました。\nシステム管理者にお問い合わせください。";
                LogControl.WriteLog(LogType.ERR, "WebGetList", e.Message);
            }

            return(ret);
        }
Beispiel #28
0
        public static EyeMove GetSaccadePositionItem(int id, int saccadeStartIndex, int saccadeEndIndex, EyeMove prevoiusSaccadeItem, ResultData results)
        {
            var eyeMove = new EyeMove
            {
                Id            = id,
                IsStartFound  = prevoiusSaccadeItem.IsStartFound,
                EyeStartIndex = saccadeStartIndex,
                EyeStartTime  = results.TimeDeltas[saccadeStartIndex],
                EyeStartCoord = results.EyeCoords[saccadeStartIndex],

                IsEndFound  = prevoiusSaccadeItem.IsEndFound,
                EyeEndIndex = saccadeEndIndex,
                EyeEndTime  = results.TimeDeltas[saccadeEndIndex],
                EyeEndCoord = results.EyeCoords[saccadeEndIndex],

                SpotMove = prevoiusSaccadeItem.SpotMove
            };

            eyeMove = EyeMoveSearchToolBox.CountTestValuesForEyeMove(eyeMove, results);
            return(eyeMove);
        }
Beispiel #29
0
        /// <summary>
        /// call StoredProcedure 但是參數可以有一個int16的output參數
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <param name="hasReturnParameter"></param>
        /// <returns></returns>
        public ResultData ExecuteStoredProcedure(string sql, List <DbParameterEx> parameters, bool hasReturnParameter)
        {
            ResultData resultData = new ResultData();

            resultData.Status = ResultStatus.Fail;

            try {
                var connection = CreateConnection();

                using (var command = CreateCommand(sql, connection, CommandType.StoredProcedure)) {
                    if (parameters != null)
                    {
                        foreach (DbParameterEx everyPara in parameters)
                        {
                            DbParameter dbParam = command.CreateParameter();

                            dbParam = TransformToDbParameter(dbParam, everyPara);

                            command.Parameters.Add(dbParam);
                        }
                    }

                    DbParameter dbParamReturn = null;

                    if (hasReturnParameter)
                    {
                        if (command is OracleCommand)
                        {
                            dbParamReturn = command.CreateParameter();
                            dbParamReturn.ParameterName = "RETURNPARAMETER";
                            dbParamReturn.Direction     = ParameterDirection.Output;
                            dbParamReturn.DbType        = DbType.Int16;
                            command.Parameters.Add(dbParamReturn);
                        }
                        else if (command is AseCommand)
                        {
                            dbParamReturn           = command.CreateParameter();
                            dbParamReturn.Direction = ParameterDirection.ReturnValue;
                            dbParamReturn.DbType    = DbType.Int32;
                            command.Parameters.Add(dbParamReturn);
                        }
                    }

                    using (var adapter = CreateAdapter(command)) {
                        DataTable dt = new DataTable();
                        adapter.Fill(dt);
                        resultData.ReturnData = dt;

                        if (dbParamReturn != null)
                        {
                            resultData.ReturnObject = dbParamReturn.Value;
                        }
                    }

                    int returnValueInt = 0;
                    int.TryParse((resultData.ReturnObject is null) ? "0" : resultData.ReturnObject.ToString(), out returnValueInt);

                    if (returnValueInt == 0)
                    {
                        resultData.Status = ResultStatus.Success;
                    }
                    else
                    {
                        resultData.Status = ResultStatus.Fail;
                    }

                    // 如果是外部Transaction的話這裡會有值,就先不要關閉連線
                    if (!IsTransaction)
                    {
                        connection.Close();
                    }

                    return(resultData);
                }
            } catch (Exception ex) {
                string errorStr = "";

                if (ex is AseException)
                {
                    AseException aseEx = ((AseException)ex);

                    foreach (AseError error in aseEx.Errors)
                    {
                        errorStr += Environment.NewLine + error.ProcName + Environment.NewLine +
                                    error.MessageNumber + Environment.NewLine +
                                    "LineNum:" + error.LineNum;
                    }
                }

                Exception exNew = new Exception(ExceptionHelper.TranformException(ex).Message + errorStr);

                throw exNew;
            }
        }
Beispiel #30
0
        public static EyeMove FindSaccade(int id, int spotStartIndex, int spotEndIndex, int latency, int minDuration, ResultData results)
        {
            var distanceFromScreen      = 30;
            var trackerFrequency        = 60;
            var controlWindowLength     = 12;
            var saccadeFindWindowLength = 12;//controlWindowLength / 2;/// 2;


            var eyeStartIndex = spotStartIndex + latency;
            var spotStartOscilationXPosition = results.SpotCoords[spotStartIndex];
            var spotEndOscilationXPosition   = results.SpotCoords[spotStartIndex + 1];

            var controlWindowStartIndex = spotStartIndex;



            var roundCoef = 5;
            int numberOfControlWindows = 6;

            var windowsBeforeSpot           = new List <double[]>();
            var windowsBeforeSpotVelocities = new List <double>();
            var windowsBeforeSpotAmplitudes = new List <double>();
            var currentStartIndex           = controlWindowStartIndex - controlWindowLength;

            for (int i = 0; i < numberOfControlWindows; i++)
            {
                var currentWindowCoords     = results.EyeCoords.Skip(currentStartIndex).Take(controlWindowLength).ToArray();
                var currentControlVelocity  = Math.Round(GetAvergeVelocityForSection(currentWindowCoords, distanceFromScreen, trackerFrequency), roundCoef);
                var currentControlAmplitude = Math.Round(GetAmplitudeForSection(currentWindowCoords, distanceFromScreen), roundCoef);

                windowsBeforeSpot.Add(currentWindowCoords);
                windowsBeforeSpotVelocities.Add(currentControlVelocity);
                windowsBeforeSpotAmplitudes.Add(currentControlAmplitude);

                currentStartIndex = currentStartIndex - controlWindowLength;
            }


            var controlVelocity = windowsBeforeSpotVelocities.Average();
            //var controlAmplitude = windowsBeforeSpotAmplitudes.Average();

            var fixStartIndex = eyeStartIndex; //spotStartIndex;

            var numberOfStartWindows = 3;
            var startCoords          = results.EyeCoords.Skip(fixStartIndex).Take(saccadeFindWindowLength * numberOfStartWindows).ToArray();

            eyeStartIndex = GetByStartIndexByCoords(startCoords, fixStartIndex, spotStartOscilationXPosition, spotEndOscilationXPosition);

            var startIndexByVelocityWindow = GetStartIndexByVelocity(results.EyeCoords, eyeStartIndex, controlVelocity, spotStartIndex,
                                                                     saccadeFindWindowLength, numberOfStartWindows, roundCoef, distanceFromScreen, trackerFrequency, minDuration);



            var saccadeStartIndex = eyeStartIndex;//startIndexByVelocityWindow;

            var saccadeStartXPosition = results.EyeCoords[saccadeStartIndex];

            var endWindowStartIndex = saccadeStartIndex + minDuration;

            double[] endWindowCoords;
            if (results.EyeCoords.Skip(endWindowStartIndex).Take(5).Count() == 0)
            {
                endWindowCoords = new double[2] {
                    results.EyeCoords[results.EyeCoords.Count() - 1], results.EyeCoords.Last()
                };
            }
            else
            {
                endWindowCoords = results.EyeCoords.Skip(endWindowStartIndex).Take(10).ToArray();
            }

            var endWindowFrameDistances        = CalculateDistances(endWindowCoords);
            var endWindowMaxFrameDistance      = endWindowFrameDistances.Max();
            var endWindowMaxFrameDistanceIndex = Array.IndexOf(endWindowFrameDistances, endWindowMaxFrameDistance);

            var saccadeEndIndex = endWindowStartIndex + (endWindowMaxFrameDistanceIndex);

            if (saccadeStartIndex >= results.EyeCoords.Length)
            {
                saccadeStartIndex = results.EyeCoords.Length - minDuration;
            }
            if (saccadeEndIndex >= results.EyeCoords.Length)
            {
                saccadeEndIndex = results.EyeCoords.Length - 1;
            }

            return(new EyeMove
            {
                Id = id,
                IsFirstMove = DataAnalyzer.IsEven(id),

                EyeStartIndex = saccadeStartIndex,
                EyeStartTime = results.TimeDeltas[saccadeStartIndex],
                EyeStartCoord = results.EyeCoords[saccadeStartIndex],

                EyeEndIndex = saccadeEndIndex,
                EyeEndTime = results.TimeDeltas[saccadeEndIndex],
                EyeEndCoord = results.EyeCoords[saccadeEndIndex],

                SpotMove = new Spot.SpotMove
                {
                    SpotStartIndex = spotStartIndex,
                    SpotStartTimeDelta = results.TimeDeltas[spotStartIndex],
                    SpotStartCoord = results.SpotCoords[spotStartIndex],

                    SpotEndIndex = spotEndIndex,
                    SpotEndTimeDelta = results.TimeDeltas[spotEndIndex],
                    SpotEndCoord = results.SpotCoords[spotEndIndex]
                }
            });
        }
Beispiel #31
0
 /// <summary>
 /// List user Manager 
 /// Accept Admin only
 /// </summary>
 public JsonResult UserManager(long UserID, gModels.UserFillter fillter, int Page = 1, int Pagezise = 10)
 {
     ResultData<dynamic> kq = new ResultData<dynamic>();
     if (UserID != 0)
     {
         kq.Data = new
         {
             Filter = fillter,
             List = _userService.GetListUserByUser(UserID, Page, Pagezise, fillter)
         };
     }
     else
     {
         kq.Data = null;
     }
     return Json(kq, JsonRequestBehavior.AllowGet);
 }
Beispiel #32
0
        //[System.Xml.Serialization.XmlIgnore]
        //public bool IsTest { get; set; }
        //[System.Xml.Serialization.XmlIgnore]
        //[Newtonsoft.Json.JsonIgnore]
        //public bool? PassFail { get; set; }
        //public string Unit { get; set; }
        public void CalcInfo()
        {
            if (ResultData == null || ResultData.Count == 0)
            {
                return;
            }
            for (int i = 0; i < ResultData.Count(); i++)
            {
                ResultData[i] = new XYData()
                {
                    X = ResultData[i].X, Y = ResultData[i].Y + Compensation
                };
            }
            foreach (var spec in TestSpecList)
            {
                foreach (var marker in spec.TestMarkerList)
                {
                    #region
                    if (marker is XYTestMarker)
                    {
                        var xyMarker = marker as XYTestMarker;
                        xyMarker.MarkerResult.Clear();
                        switch (xyMarker.Type)
                        {
                        case XYTestMarkerTypeEnum.Normal:
                            double[] lstXData = ResultData.Select(x => x.X).ToArray();
                            double[] lstYData = ResultData.Select(x => x.Y).ToArray();

                            double xData = xyMarker.Start;

                            double yData = GeneFun.LinearInterp(lstXData, lstYData, xData);
                            xyMarker.MarkerResult.Add(new XYData(xData, yData));
                            break;

                        case XYTestMarkerTypeEnum.Max:
                            double ymax = ResultData.Select(x => x.Y).Max();
                            double xmax = ResultData.Find(x => x.Y == ymax).X;
                            xyMarker.MarkerResult.Add(new XYData(xmax, ymax));
                            break;

                        case XYTestMarkerTypeEnum.Min:
                            double ymin = ResultData.Select(x => x.Y).Min();
                            double xmin = ResultData.Find(x => x.Y == ymin).X;
                            xyMarker.MarkerResult.Add(new XYData(xmin, ymin));
                            break;

                        case XYTestMarkerTypeEnum.ABSMax:
                            double yAbsmax = ResultData.Select(x => Math.Abs(x.Y)).Max();
                            double xAbsmax = ResultData.Find(x => Math.Abs(x.Y) == yAbsmax).X;
                            xyMarker.MarkerResult.Add(new XYData(xAbsmax, yAbsmax));
                            break;

                        case XYTestMarkerTypeEnum.ABSMin:
                            double yAbsmin = ResultData.Select(x => Math.Abs(x.Y)).Min();
                            double xAbsmin = ResultData.Find(x => Math.Abs(x.Y) == yAbsmin).X;
                            xyMarker.MarkerResult.Add(new XYData(xAbsmin, yAbsmin));
                            break;

                        case XYTestMarkerTypeEnum.Peak:
                            double y1Max = ResultData.Select(x => x.Y).Max();
                            double x1Max = ResultData.Find(x => x.Y == y1Max).X;
                            double y1Min = ResultData.Select(x => x.Y).Min();
                            double x1Min = ResultData.Find(x => x.Y == y1Min).X;
                            if (Math.Abs(y1Max) >= Math.Abs(y1Min))
                            {
                                xyMarker.MarkerResult.Add(new XYData(x1Max, y1Max));
                            }
                            else
                            {
                                xyMarker.MarkerResult.Add(new XYData(x1Min, y1Max));
                            }
                            break;

                        case XYTestMarkerTypeEnum.Mean:
                            double avg = ResultData.Select(x => x.Y).Average();
                            double xx  = ResultData.Select(x => x.X).First();
                            xyMarker.MarkerResult.Add(new XYData(xx, avg));
                            break;

                        case XYTestMarkerTypeEnum.PhaseRipple:
                            double phaseNolin = GeneFun.CalcPhaseNonlin(ResultData.Select(x => x.Y).ToArray(),
                                                                        10000, 0.01);
                            xyMarker.MarkerResult.Add(new XYData(ResultData.Select(x => x.X).First(), phaseNolin));
                            break;

                        case XYTestMarkerTypeEnum.Ripple:
                            double ymin1 = ResultData.Select(x => x.Y).Min();
                            double ymax1 = ResultData.Select(x => x.Y).Max();
                            xyMarker.MarkerResult.Add(new XYData(ResultData.Select(x => x.X).First(),
                                                                 ymax1 - ymin1));
                            break;

                        case XYTestMarkerTypeEnum.InRange:
                            xyMarker.MarkerResult.Add(new XYData(0, 0));
                            break;

                        case XYTestMarkerTypeEnum.Target:
                            xyMarker.MarkerResult.Add(new XYData(0, 0));
                            break;

                        case XYTestMarkerTypeEnum.Q_Value:
                            xyMarker.MarkerResult.Add(new XYData(0, 0));
                            break;

                        case XYTestMarkerTypeEnum.BandWidth:
                            xyMarker.MarkerResult.Add(new XYData(0, 0));
                            break;

                        case XYTestMarkerTypeEnum.LeftFreq:
                            xyMarker.MarkerResult.Add(new XYData(0, 0));
                            break;

                        case XYTestMarkerTypeEnum.RightFreq:
                            xyMarker.MarkerResult.Add(new XYData(0, 0));
                            break;

                        case XYTestMarkerTypeEnum.CenterFreq:
                            xyMarker.MarkerResult.Add(new XYData(0, 0));
                            break;

                        case XYTestMarkerTypeEnum.InsertionLoss:
                            xyMarker.MarkerResult.Add(new XYData(0, 0));
                            break;

                        case XYTestMarkerTypeEnum.Pin_NdB:
                            xyMarker.MarkerResult.Add(new XYData(0, 0));
                            break;

                        case XYTestMarkerTypeEnum.Po_NdB:
                            xyMarker.MarkerResult.Add(new XYData(0, 0));
                            break;

                        case XYTestMarkerTypeEnum.RippleInRange:
                            xyMarker.MarkerResult.Add(new XYData(0, 0));
                            break;

                        case XYTestMarkerTypeEnum.RippleHalf:
                            double ymin2 = ResultData.Select(x => x.Y).Min();
                            double ymax2 = ResultData.Select(x => x.Y).Max();
                            xyMarker.MarkerResult.Add(new XYData(ResultData.Select(x => x.X).First(),
                                                                 (ymax2 - ymin2) / 2));
                            break;

                        case XYTestMarkerTypeEnum.PowerMean:
                            double avg1 = ResultData.Select(x => Math.Pow(10, ((x.Y - 30) / 10))).Average();
                            double xx1  = ResultData.Select(x => x.Y).First();
                            xyMarker.MarkerResult.Add(new XYData(xx1, avg1));
                            break;

                        default:
                            break;
                        }
                    }
                    marker.JudgePassFail();
                    #endregion
                }
                if (!spec.TestLimit.Enable)
                {
                    bool?specPassFail = null;
                    if (spec.UpLimit != null && spec.LowLimit != null)
                    {
                        int upCount  = ResultData.Where(x => x.Y > spec.UpLimit).Count();
                        int lowCount = ResultData.Where(x => x.Y < spec.LowLimit).Count();
                        if (upCount > 0 || lowCount > 0)
                        {
                            specPassFail = false;
                        }
                        else
                        {
                            specPassFail = true;
                        }
                    }
                    else if (spec.UpLimit != null && spec.LowLimit == null)
                    {
                        int upCount = ResultData.Where(x => x.Y > spec.UpLimit).Count();
                        if (upCount > 0)
                        {
                            specPassFail = false;
                        }
                        else
                        {
                            specPassFail = true;
                        }
                    }
                    else if (spec.UpLimit == null && spec.LowLimit != null)
                    {
                        int lowCount = ResultData.Where(x => x.Y < spec.LowLimit).Count();
                        if (lowCount > 0)
                        {
                            specPassFail = false;
                        }
                        else
                        {
                            specPassFail = true;
                        }
                    }
                    else
                    {
                        specPassFail = null;
                    }
                    spec.PassFail = GeneFun.NullBoolAnd(GeneFun.NullBoolAndList(spec.TestMarkerList.Select(x => x.PassFail).ToList()), specPassFail);
                }
            }
            PassFail = GeneFun.NullBoolAndList(TestSpecList.Select(x => x.PassFail).ToList());
        }
 /// <summary>
 /// 検索実行.
 /// </summary>
 protected override void Execute()
 {
     this.ResultData = this.Search();
 }
Beispiel #34
0
        public ResultData AddData(WinOCRResultData data, int index)
        {
            ResultData resultData = new ResultData();

            resultData.index = index;

            //Util.ShowLog("line = " + point.lineCount);
            int count = 0;

            for (int i = 0; i < data.lineCount; i++)
            {
                LineData lineData   = new LineData();
                string   lineString = "";
                //Util.ShowLog("----line start----");

                for (int j2 = 0; j2 < data.wordCounts[i]; j2++)
                {
                    lineString += data.words[count] + " ";

                    Rectangle rect = new Rectangle((int)data.x[count], (int)data.y[count], (int)data.sizeX[count], (int)data.sizeY[count]);
                    lineData.wordList.Add(data.words[count]);
                    lineData.wordRectList.Add(rect);

                    count++;
                }
                Rectangle lineRect = new Rectangle();
                //줄 처리.
                if (lineData.wordRectList.Count > 1)
                {
                    lineRect = lineData.wordRectList[0];
                    for (int j = 1; j < lineData.wordRectList.Count; j++)
                    {
                        lineRect = Rectangle.Union(lineRect, lineData.wordRectList[j]);
                    }
                    lineData.lineRect = lineRect;
                }
                else if (lineData.wordRectList.Count == 1)
                {
                    lineRect          = lineData.wordRectList[0];
                    lineData.lineRect = lineRect;
                }

                lineData.lineString = lineString;
                resultData.lineDataList.Add(lineData);

                if (lineRect.Height > lineRect.Width * 1.5f)
                {
                    lineData.angleType = WordAngleType.Vertical;
                }
                else
                {
                    lineData.angleType = WordAngleType.Horizontal;
                }
            }

            //전체 영역 처리.
            if (resultData.lineDataList.Count == 1)
            {
                resultData.resultRect = resultData.lineDataList[0].lineRect;
            }
            else if (resultData.lineDataList.Count > 1)
            {
                resultData.resultRect = resultData.lineDataList[0].lineRect;
                for (int i = 1; i < resultData.lineDataList.Count; i++)
                {
                    resultData.resultRect = Rectangle.Union(resultData.resultRect, resultData.lineDataList[i].lineRect);
                }
            }
            resultData.InitLine();
            dataList.Add(resultData);



            return(resultData);
        }
Beispiel #35
0
        /// <summary>
        /// 删除付款条款信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public static ResultData <object> DeletePayment(PaymentSearchDTO dto)
        {
            ResultData <object> blResult = DeleteAPI <ResultData <object> >(WebConfiger.MasterDataServicesUrl + "Payment?PaymentSearchDTO=" + TransformHelper.ConvertDTOTOBase64JsonString(dto));

            return(blResult);
        }
Beispiel #36
0
        public ContentResult Add()
        {
            ResultData <string> rt = new ResultData <string>();

            BLocation location = GetAdd <BLocation>();

            //非空验证和属性格式验证
            string msg = lService.CheckLocation(location);

            if (!string.IsNullOrEmpty(msg))
            {
                rt.message = msg;
                rt.status  = -1;
                return(ReturnResult(rt));
            }

            //判断是否子存储单元,添加顶级存储单元
            if (location.ParentID > 0)
            {
                BLocation parent = lService.GetLocationById(location.ParentID);
                location.TopLocationID = parent.TopLocationID;
                location.LocationLevel = parent.LocationLevel + 1;
                ////如果是货位,默认货区的类型
                //if (location.LocationLevel == 3)
                //{
                //    location.LocationClass = parent.LocationClass;
                //}
            }
            else
            {
                location.LocationLevel = 1;
            }


            //判断是否存在其他货位也是默认货位
            //if (location.LocationLevel == 2)
            //{
            //    if (location.IsDefault > 0)
            //    {
            //        BLocation dftLocation = lService.GetDefaultLocation(location.ParentID, location.LocationClass);
            //        if (dftLocation != null)
            //        {
            //            rt.status = -1;
            //            rt.message = "当前仓库已经存在默认货区(" + dftLocation.LocationCode + ")";
            //            return ReturnResult(rt);
            //        }
            //    }
            //}

            //是否存在
            if (lService.IsNotExits(location, false))
            {
                location.CreateBy   = this.CurrentUser.ID;
                location.CreateDate = DateTime.Now;
                location.UpdateDate = DateTime.Now;
                int locId = lService.AddLocation(location);

                //如果添加为仓库,则跟新顶级存储单元ID
                if (location.ParentID < 1)
                {
                    location.ID            = locId;
                    location.TopLocationID = locId;
                    lService.UpdateLocation(location);
                }
            }
            else
            {
                rt.status  = -1;
                rt.message = "存储单元已经存在.";
            }


            return(ReturnResult(rt));
        }
Beispiel #37
0
        //[ValidateAntiForgeryToken]
        public JsonResult GetPayCalculation(ClassHourStatisticsInput input)
        {
            var result = _teacherClassHoursStatisticsAppService.GetClassHourStatistics(input).Items;

            /*说明:
             * --续学人数 通过group统计 某个学生上课总时长 是否达到15
             * --基本工资 通过计算总课时 是否达到70 如果达到了 其他的一些福利 再进行计算,如果在40-70之间就只是拿到底薪4k
             * --早课和晚课通过 上课开始时间是否小于早上七点半 和开始时间是否大于晚上七点 进行统计
             * --1对1课时数和班级数 通过课程类型来统计
             * --外派次数 通过上课类型来统计
             * --学生当前月上课是否80%达标,防止学生随意请假,影响老师收益(如果学生当月需要上课20小时,然后请假次数太多导致不够80% 也就是不够16个小时 那么缺少的课时按照正常课时的80%费用收取 如仅仅上了8个小时,那么就是缺少8个小时也就是需要补贴老师8*50*0.8=320元) 这里暂只处理 1对1
             * --统计输出的话 就是按照自定义的格式综合输出
             */
            var            classResult     = result.Where(r => r.ClassType == CourseManagerConsts.ClassClassType && r.Type != CourseManagerConsts.NoCourseSignInRecordType).ToList();
            var            one2OneResult   = result.Where(r => r.ClassType == CourseManagerConsts.One2OneClassType && r.Type != CourseManagerConsts.NoCourseSignInRecordType).ToList();
            List <decimal> durations       = new List <decimal>();
            var            totalDuration   = decimal.Round(result.Sum(r => r.Duration) / 60, 1);
            var            one2oneDuration = one2OneResult.Sum(r => r.Duration);
            var            classDuration   = classResult.Sum(r => r.Duration);
            var            beginTimeDay    = input.BeginTime.Day;
            var            endTimeDay      = input.EndTime.Day;

            decimal[] classHoursArray           = new decimal[endTimeDay - beginTimeDay + 1]; //取得的值是大于等于开始时间 小于结束时间
            decimal[] one2OneDurationsArray     = new decimal[endTimeDay - beginTimeDay + 1];
            decimal[] classCourseDurationsArray = new decimal[endTimeDay - beginTimeDay + 1];
            PayCalculationViewModel vm          = new PayCalculationViewModel();
            var totalOfficeHours = 0.0M;

            for (int i = beginTimeDay - 1; i < endTimeDay; i++)
            {
                var duration = 0.0M;
                classHoursArray[i] = duration;
                if (result.Any(v => v.EndTime.Day == i + 1))
                {
                    duration           = decimal.Round(result.Where(r => r.EndTime.Day == i + 1).Sum(c => c.Duration) / 60, 1);
                    classHoursArray[i] = duration;
                }
                if (one2OneResult.Any(v => v.EndTime.Day == i + 1))
                {
                    one2OneDurationsArray[i] = decimal.Round(one2OneResult.Where(r => r.EndTime.Day == i + 1).Sum(c => c.Duration) / 60, 1);
                }
                if (classResult.Any(v => v.EndTime.Day == i + 1))
                {
                    classCourseDurationsArray[i] = decimal.Round(classResult.Where(r => r.EndTime.Day == i + 1).Sum(c => c.Duration) / 60, 1);
                }
                var totalMinutes = 0.0;
                if (result.Any(r => r.EndTime.Day == i + 1))
                {
                    var maxEndTime   = result.Where(r => r.EndTime.Day == i + 1).Max(t => t.EndTime);
                    var minBeginTime = result.Where(r => r.EndTime.Day == i + 1).Min(t => t.BeginTime);
                    totalMinutes = (maxEndTime - minBeginTime).TotalMinutes;
                }
                totalOfficeHours += decimal.Round(Convert.ToDecimal(totalMinutes) / 60, 1);
            }
            vm.TeacherName = string.IsNullOrEmpty(input.TeacherName) ? "胡盼" : input.TeacherName;
            decimal basicSalary = CourseManagerConsts.BasicSalary;

            //底薪说明:20小时以下2000元,20小时~40小时3000元,40以上4000元
            if (totalDuration < CourseManagerConsts.BasicSalaryHours)
            {
                if (totalDuration < 20)
                {
                    basicSalary = 2000;
                }
                else if (totalDuration > 20 && totalDuration < 40)
                {
                    basicSalary = 3000;
                }
            }
            vm.BasicSalary         = basicSalary;
            vm.One2OneDuration     = decimal.Round(one2oneDuration / 60, 1);
            vm.ClassDuration       = decimal.Round(classDuration / 60, 1);
            vm.TotalDuration       = totalDuration;
            vm.EarlyCourseTimes    = result.Where(r => r.BeginTime.Hour <= CourseManagerConsts.EarlyHour).Count();
            vm.NightCourseTimes    = result.Where(r => r.BeginTime.Hour >= CourseManagerConsts.NigthHour).Count();
            vm.AssignmentTimes     = result.Where(r => r.CourseAddressType == CourseManagerConsts.OutSideCourseType).Count(); //外派
            vm.OfficeHours         = totalOfficeHours;
            vm.AllOfficeHoursBonus = totalOfficeHours >= CourseManagerConsts.JuneOfficeHours ? CourseManagerConsts.AllOfficeHoursBonus : 0.0M;

            #region 统计各个学生当前月需要上课多少个小时 以及续学学生
            CountUpStudentCourses(input, result, vm);
            #endregion

            ResultData data = new ResultData()
            {
                returnData = new Dictionary <string, object> {
                    { "result", vm }
                }
            };
            return(Json(data, JsonRequestBehavior.AllowGet));
        }
Beispiel #38
0
        /// <summary>
        /// 根据入库通知添加入库
        /// </summary>
        /// <param name="inNotice"></param>
        /// <returns></returns>
        public ResultData <string> AddTransferIn(WTransferInNotice inNotice, int createBy)
        {
            ResultData <string> rData = new ResultData <string>();

            if (inNotice.NoticeStatus == NoticeStatusEnum.Complete)
            {
                rData.status  = -1;
                rData.message = "单据已完成不能入库.";
                return(rData);
            }
            //克隆主表
            WTransferIn transferIn = CloneInNotice(inNotice);

            transferIn.CreateBy = createBy;

            foreach (var item in inNotice.Lines)
            {
                if (item.InPutCount <= 0)
                {
                    continue;
                }
                //如果通知数量+下推数量+完成数量>当前入库数量
                if (item.InPutCount + item.DownCount + item.CompleteCount > item.InCount)
                {
                    rData.status  = -1;
                    rData.message = BuilderNoticeLessMessage(item);
                    return(rData);
                }
                //克隆明细
                transferIn.Lines.Add(CloneInNoticeLine(item));
                //更新下推数量和当前输入数量
                item.DownCount = item.DownCount + item.InPutCount;
            }

            if (transferIn.Lines.Count < 1)
            {
                rData.status  = -1;
                rData.message = "入库明细为空.";
                return(rData);
            }

            rData = CheckValid(transferIn);
            if (rData.status != 0)
            {
                return(rData);
            }

            DatabaseContext dbContext = tiRepository.DbCondext;

            try
            {
                dbContext.BeginTransaction();

                //添加入库单
                transferIn.CreateDate     = DateTime.Now;
                transferIn.StockStatus    = StockStatusEnum.New;
                transferIn.TransferInCode = nuRepository.GetNextNumber("DBRK");
                tiRepository.Insert(transferIn);
                foreach (var line in transferIn.Lines)
                {
                    line.ParentID   = transferIn.ID;
                    line.CreateBy   = transferIn.CreateBy;
                    line.CreateDate = DateTime.Now;
                    line.Batch      = string.IsNullOrEmpty(line.Batch) ? "" : line.Batch;
                    tilRepository.Insert(line);
                }

                //更新通知单
                foreach (var item in inNotice.Lines)
                {
                    tinlRepository.AddDownCount(item);
                }

                dbContext.CompleteTransaction();
            }
            catch (Exception ex)
            {
                dbContext.AbortTransaction();
                throw ex;
            }

            //没有放到事务,因为状态更新不是很重要,不影响业务
            bool isAll = tinlRepository.IsAllDownload(inNotice.ID);

            if (isAll)
            {
                tinRepository.UpdateNoticeStatus(NoticeStatusEnum.Complete, inNotice.ID);
            }
            else
            {
                tinRepository.UpdateNoticeStatus(NoticeStatusEnum.Executing, inNotice.ID);
            }
            return(rData);
        }
Beispiel #39
0
 public ResultData GetOutputData(string key, Dictionary<string, string> outputDic,
                             Dictionary<string, object> resultDic, Dictionary<string, string> tolDic)
 {
     ResultData data = new ResultData();
     string tolVal = "";
     if (outputDic.ContainsKey(key))
     {
         outputDic.TryGetValue(key, out data.output);
     }
     if (resultDic == null)
     {
         data.missing = true;
         data.match = false;
         return data;
     }
     object resultObj = null;
     if (resultDic.ContainsKey(key))
     {
         resultDic.TryGetValue(key, out resultObj);
     }
     else
     {
         data.missing = true;
         data.match = false;
         return data;
     }
     if (data.output == "")
     {
         if (resultObj != null)
         {
             data.result = resultObj.ToString();
         }
     }
     else if (data.output.ToUpper() == "NULL")
     {
         if (resultObj == null || resultObj.ToString() == "")
         {
             data.match = true;
         }
         else
         {
             data.match = false;
         }
     }
     else
     {
         if (resultObj != null)
         {
             if (tolDic != null)
             {
                 tolDic.TryGetValue(key, out tolVal);
             }
             data.match = IsDataMatching(data.output, resultObj, tolVal);
             data.result = resultObj.ToString();
         }
         else
         {
             data.match = false;
         }
     }
     return data;
 }
Beispiel #40
0
        protected override ResultStatus Save(PokeBall pokeBall)
        {
            try {
                #region ue_save_before
                gvMain.CloseEditor();
                gvMain.UpdateCurrentRow();

                string   stockID, ymd, kindID, adjTypeName, opType, dbname, stockIDCk;
                string   issueBeginYmd, tradeYmd, mocfYmd, nextYmd, level, currencyType;
                int      currRow, found, count, row, col, prodSeq;
                decimal  ldblRate;
                DateTime ldtWTIME = DateTime.Now;

                DataTable dtGrid = (DataTable)gcMain.DataSource;
                found = dtGrid.Rows.IndexOf(dtGrid.Select("OP_TYPE <> ' '").FirstOrDefault());
                if (found + dtDel.Rows.Count == -1)
                {
                    MessageDisplay.Warning("沒有變更資料,不需要存檔!");
                    return(ResultStatus.FailButNext);
                }
                DataTable dtMGD2;                             //ids_mgd2
                DataTable dtMGD2Log = dao40071.d_40071_log(); //ids_old
                dtMGD2Log.Clear();                            //只取schema

                this.ymd      = txtSDate.DateTimeValue.ToString("yyyyMMdd");
                issueBeginYmd = this.ymd;
                dtMGD2        = dao40071.d_40071(this.ymd, isAdjType);

                foreach (DataRow dr in dtGrid.Rows)
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }
                    opType  = dr["OP_TYPE"].ToString();
                    stockID = dr["STOCK_ID"].AsString();
                    kindID  = dr["KIND_ID"].AsString();
                    level   = dr["M_LEVEL"].AsString();

                    //檢查調整後級距為從其高且商品類別為選擇權時,是否有輸入保證金B值
                    if (level == "Z" && dr["PROD_TYPE"].AsString() == "O")
                    {
                        if (dr["CM_B"] == DBNull.Value || dr["MM_B"] == DBNull.Value || dr["IM_B"] == DBNull.Value)
                        {
                            MessageDisplay.Error(stockID + "," + kindID + "的保證金B值未輸入完成");
                            return(ResultStatus.FailButNext);
                        }
                    }

                    //檢查有異動的資料
                    if (opType != " ")
                    {
                        //資料修改,將修改前舊資料寫入log
                        if (opType == "U")
                        {
                            dtMGD2.Filter("mgd2_kind_id = '" + kindID + "'");
                            foreach (DataRow drU in dtMGD2.Rows)
                            {
                                currRow = dtMGD2Log.Rows.Count;
                                dtMGD2Log.Rows.Add();
                                for (col = 0; col < dtMGD2.Columns.Count; col++)
                                {
                                    //先取欄位名稱,因為兩張table欄位順序不一致
                                    dbname = dtMGD2.Columns[col].ColumnName;
                                    if (dbname == "CPSORT")
                                    {
                                        continue;            //這個欄位是拿來排序用的,故無需複製
                                    }
                                    dtMGD2Log.Rows[currRow][dbname] = drU[col];
                                }
                                dtMGD2Log.Rows[currRow]["MGD2_L_TYPE"]    = "U";
                                dtMGD2Log.Rows[currRow]["MGD2_L_USER_ID"] = GlobalInfo.USER_ID;
                                dtMGD2Log.Rows[currRow]["MGD2_L_TIME"]    = ldtWTIME;
                            }
                        }

                        /*******************************************
                        *  檢查商品與類別是否符合
                        *******************************************/
                        prodSeq = dao40074.getProd(kindID, dr["PROD_SUBTYPE"].AsString());
                        if (prodSeq != dr["PROD_SEQ_NO"].AsInt())
                        {
                            MessageDisplay.Error(kindID + "與商品類別不符,請確認");
                            return(ResultStatus.FailButNext);
                        }

                        /*****************************************
                         * 檢查商品代號是否存在及相關資料是否正確
                         ******************************************/
                        DataTable dtCheck = dao40074.checkProd(kindID);
                        if (dtCheck.Rows.Count == 0)
                        {
                            MessageDisplay.Error(kindID + "不存在,請重新設定商品代號");
                            return(ResultStatus.FailButNext);
                        }
                        count        = dtCheck.Rows[0]["LI_COUNT"].AsInt();
                        currencyType = dtCheck.Rows[0]["LS_CURRENCY_TYPE"].AsString();
                        stockIDCk    = dtCheck.Rows[0]["LS_STOCK_ID_CK"].AsString();

                        if (count == 0)
                        {
                            MessageDisplay.Error(kindID + "不存在,請重新設定商品代號");
                            return(ResultStatus.FailButNext);
                        }
                        else
                        {
                            if (dr["CURRENCY_TYPE"].AsString() != currencyType)
                            {
                                MessageDisplay.Error(kindID + "的幣別設定錯誤,請重新設定填寫");
                                return(ResultStatus.FailButNext);
                            }
                            if (dr["prod_subtype"].AsString() == "S" && stockID != stockIDCk)
                            {
                                MessageDisplay.Error(kindID + "的股票代號設定錯誤,請重新設定填寫");
                                return(ResultStatus.FailButNext);
                            }
                        }

                        /******************************************
                        *  確認商品是否在同一交易日不同情境下設定過
                        ******************************************/
                        DataTable dtSet = dao40071.IsSetOnSameDay(kindID, this.ymd, isAdjType);
                        if (dtSet.Rows.Count == 0)
                        {
                            MessageDisplay.Info("MGD2 " + kindID + " 無任何資料!");
                            return(ResultStatus.FailButNext);
                        }
                        count       = dtSet.Rows[0]["LI_COUNT"].AsInt();
                        adjTypeName = dtSet.Rows[0]["LS_ADJ_TYPE_NAME"].AsString();
                        if (count > 0)
                        {
                            MessageDisplay.Error(kindID + ",交易日(" + this.ymd + ")在" + adjTypeName + "已有資料");
                            return(ResultStatus.FailButNext);
                        }

                        /*********************************
                         * 確認商品是否在同一生效日區間設定過
                         * 生效起日若與生效迄日相同,不重疊
                         * ex: 10/11的至10/31一般交易時段結束止,10/30的從10/31一般交易時段結束後始>>應不重疊
                         *************************************/
                        dtSet       = dao40071.IsSetInSameSession(kindID, this.ymd, issueBeginYmd);
                        count       = dtSet.Rows[0]["LI_COUNT"].AsInt();
                        adjTypeName = dtSet.Rows[0]["LS_ADJ_TYPE_NAME"].AsString();
                        tradeYmd    = dtSet.Rows[0]["LS_TRADE_YMD"].AsString();
                        if (count > 0)
                        {
                            MessageDisplay.Error(kindID + "," + adjTypeName + ",交易日(" + tradeYmd + ")在同一生效日區間內已有資料");
                            return(ResultStatus.FailButNext);
                        }
                    } //if (ls_op_type != " ")
                }     //foreach (DataRow dr in dtGrid.Rows)

                //把刪除的資料寫進log
                foreach (DataRow drDel in dtDel.Rows)
                {
                    kindID = drDel["KIND_ID"].AsString();
                    dtMGD2.Filter("mgd2_kind_id = '" + kindID + "'");
                    foreach (DataRow drD in dtMGD2.Rows)
                    {
                        currRow = dtMGD2Log.Rows.Count;
                        dtMGD2Log.Rows.Add();
                        for (col = 0; col < dtMGD2.Columns.Count; col++)
                        {
                            //先取欄位名稱,因為兩張table欄位順序不一致
                            dbname = dtMGD2.Columns[col].ColumnName;
                            if (dbname == "CPSORT")
                            {
                                continue;              //這個欄位是拿來排序用的,故無需複製
                            }
                            dtMGD2Log.Rows[currRow][dbname] = drD[col];
                        }
                        dtMGD2Log.Rows[currRow]["MGD2_L_TYPE"]    = "D";
                        dtMGD2Log.Rows[currRow]["MGD2_L_USER_ID"] = GlobalInfo.USER_ID;
                        dtMGD2Log.Rows[currRow]["MGD2_L_TIME"]    = ldtWTIME;
                    }
                }
                #endregion

                string    prodType;
                DataTable dtTemp = dao40072.d_40072(); //ids_tmp

                foreach (DataRow dr in dtGrid.Rows)
                {
                    if (dr.RowState == DataRowState.Deleted)
                    {
                        continue;
                    }
                    opType = dr["OP_TYPE"].ToString();
                    //只更新有異動的資料
                    if (opType != " ")
                    {
                        kindID = dr["KIND_ID"].AsString();
                        //stockID = dr["KIND_ID"].AsString();
                        stockID = dr["STOCK_ID"].ToString();

                        //刪除已存在資料
                        if (daoMGD2.DeleteMGD2(this.ymd, isAdjType, stockID, kindID) < 0)
                        {
                            MessageDisplay.Error("MGD2資料刪除失敗");
                            return(ResultStatus.FailButNext);
                        }

                        currRow  = dtTemp.Rows.Count;
                        prodType = dr["PROD_TYPE"].AsString();
                        dtTemp.Rows.Add();
                        dtTemp.Rows[currRow]["MGD2_YMD"]       = this.ymd;
                        dtTemp.Rows[currRow]["MGD2_PROD_TYPE"] = prodType;
                        dtTemp.Rows[currRow]["MGD2_KIND_ID"]   = kindID;
                        dtTemp.Rows[currRow]["MGD2_STOCK_ID"]  = stockID;
                        dtTemp.Rows[currRow]["MGD2_ADJ_TYPE"]  = isAdjType;

                        dtTemp.Rows[currRow]["MGD2_ADJ_CODE"]        = dr["ADJ_CODE"];
                        dtTemp.Rows[currRow]["MGD2_PUB_YMD"]         = dr["PUB_YMD"];
                        dtTemp.Rows[currRow]["MGD2_ISSUE_BEGIN_YMD"] = issueBeginYmd;
                        dtTemp.Rows[currRow]["MGD2_PROD_SUBTYPE"]    = dr["PROD_SUBTYPE"].AsString();
                        dtTemp.Rows[currRow]["MGD2_PARAM_KEY"]       = dr["PARAM_KEY"];

                        dtTemp.Rows[currRow]["MGD2_CUR_CM"]    = 0;
                        dtTemp.Rows[currRow]["MGD2_CUR_MM"]    = 0;
                        dtTemp.Rows[currRow]["MGD2_CUR_IM"]    = 0;
                        dtTemp.Rows[currRow]["MGD2_CUR_LEVEL"] = 0;
                        dtTemp.Rows[currRow]["MGD2_CM"]        = dr["CM_A"];

                        dtTemp.Rows[currRow]["MGD2_MM"]            = dr["MM_A"];
                        dtTemp.Rows[currRow]["MGD2_IM"]            = dr["IM_A"];
                        dtTemp.Rows[currRow]["MGD2_LEVEL"]         = dr["M_LEVEL"];
                        dtTemp.Rows[currRow]["MGD2_CURRENCY_TYPE"] = dr["CURRENCY_TYPE"];
                        dtTemp.Rows[currRow]["MGD2_SEQ_NO"]        = dr["SEQ_NO"];

                        dtTemp.Rows[currRow]["MGD2_OSW_GRP"]   = dr["OSW_GRP"];
                        dtTemp.Rows[currRow]["MGD2_AMT_TYPE"]  = dr["AMT_TYPE"];
                        dtTemp.Rows[currRow]["MGD2_W_TIME"]    = ldtWTIME;
                        dtTemp.Rows[currRow]["MGD2_W_USER_ID"] = GlobalInfo.USER_ID;

                        /******************************
                         *    AB TYTPE:	-期貨
                         *                A選擇權A值
                         *                B選擇權B值
                         *******************************/
                        if (prodType == "F")
                        {
                            dtTemp.Rows[currRow]["MGD2_AB_TYPE"] = "-";
                        }
                        else
                        {
                            dtTemp.Rows[currRow]["MGD2_AB_TYPE"] = "A";
                            //複製一筆一樣的,AB Type分開存
                            dtTemp.ImportRow(dtTemp.Rows[currRow]);
                            //dtTemp.Rows.Add(dtTemp.Rows[ii_curr_row]);//會跳錯
                            currRow = dtTemp.Rows.Count - 1;
                            dtTemp.Rows[currRow]["MGD2_AB_TYPE"] = "B";
                            dtTemp.Rows[currRow]["MGD2_CM"]      = dr["CM_B"];
                            dtTemp.Rows[currRow]["MGD2_MM"]      = dr["MM_B"];
                            dtTemp.Rows[currRow]["MGD2_IM"]      = dr["IM_B"];
                        }
                    } //if (ls_op_type != " ")
                }     //foreach (DataRow dr in dtGrid.Rows)

                //刪除資料
                foreach (DataRow drDel in dtDel.Rows)
                {
                    kindID  = drDel["KIND_ID"].AsString();
                    stockID = drDel["STOCK_ID"].ToString();
                    if (daoMGD2.DeleteMGD2(this.ymd, isAdjType, stockID, kindID) < 0)
                    {
                        MessageDisplay.Error("MGD2資料刪除失敗");
                        return(ResultStatus.FailButNext);
                    }
                }

                //Update DB
                //ids_tmp.update()
                if (dtTemp.Rows.Count > 0)
                {
                    ResultData myResultData = daoMGD2.UpdateMGD2(dtTemp);
                    if (myResultData.Status == ResultStatus.Fail)
                    {
                        MessageDisplay.Error("更新資料庫MGD2錯誤! ");
                        return(ResultStatus.FailButNext);
                    }
                }
                //ids_old.update()
                if (dtMGD2Log.Rows.Count > 0)
                {
                    ResultData myResultData = daoMGD2L.UpdateMGD2L(dtMGD2Log);
                    if (myResultData.Status == ResultStatus.Fail)
                    {
                        MessageDisplay.Error("更新資料庫MGD2L錯誤! ");
                        return(ResultStatus.FailButNext);
                    }
                }
                //Write LOGF
                WriteLog("變更資料 ", "Info", "I");
                //報表儲存pdf
                ReportHelper            _ReportHelper   = new ReportHelper(gcMain, _ProgramID, this.Text);
                CommonReportLandscapeA3 reportLandscape = new CommonReportLandscapeA3();//設定為橫向列印
                reportLandscape.printableComponentContainerMain.PrintableComponent = gcMain;
                reportLandscape.IsHandlePersonVisible = false;
                reportLandscape.IsManagerVisible      = false;
                _ReportHelper.Create(reportLandscape);
                _ReportHelper.Export(FileType.PDF, _ReportHelper.FilePath);
                MessageDisplay.Info("報表儲存完成!");
            } catch (Exception ex) {
                SetSaveFlagValue();
                MessageDisplay.Error("儲存錯誤");
                throw ex;
            }
            SetSaveFlagValue();
            return(ResultStatus.Success);
        }
Beispiel #41
0
        public void ProcessGeocachingComGPXCaches(ResultData data, string gpxDoc)
        {
            bool isGeoSpy = false;
            try
            {
                string firstPart;
                if (gpxDoc.Length < 2000)
                {
                    firstPart = gpxDoc;
                }
                else
                {
                    firstPart = gpxDoc.Substring(0, 2000);
                }
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(gpxDoc);
                XmlElement root = doc.DocumentElement;
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

                if (firstPart.IndexOf("http://www.topografix.com/GPX/1/1", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    nsmgr.AddNamespace("x", "http://www.topografix.com/GPX/1/1");
                }
                else
                {
                    nsmgr.AddNamespace("x", "http://www.topografix.com/GPX/1/0");
                }

                if (firstPart.IndexOf("http://geoget.ararat.cz/GpxExtensions/v2", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    //GeoSpy
                    isGeoSpy = true;
                    _cachesGpxVersion = new Version(1, 0, 0);
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                }
                else if (firstPart.IndexOf("http://www.groundspeak.com/cache/1/0/2", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0/2");
                    _cachesGpxVersion = new Version(1,0,2);
                }
                else if (firstPart.IndexOf("http://www.groundspeak.com/cache/1/0/1", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    if (firstPart.IndexOf("creator=\"Opencaching.de - http://www.opencaching.de\"") > 0)
                    {
                        nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                    }
                    else if (firstPart.IndexOf("http://www.opencaching.com/xmlschemas/opencaching/1/0") > 0)
                    {
                        nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                    }
                    else
                    {
                        nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0/1");
                    }
                    _cachesGpxVersion = new Version(1, 0, 1);
                }
                else if (firstPart.IndexOf("http://www.groundspeak.com/cache/1/1", StringComparison.OrdinalIgnoreCase) > 0)
                {
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/1");
                    _cachesGpxVersion = new Version(1, 1, 0);
                }
                else
                {
                    nsmgr.AddNamespace("y", "http://www.groundspeak.com/cache/1/0");
                    _cachesGpxVersion = new Version(1, 0, 0);
                }

                if (isGeoSpy)
                {
                    _gpxDataTime = DateTime.Parse(root.SelectSingleNode("x:metadata", nsmgr).SelectSingleNode("x:time", nsmgr).InnerText);
                }
                else
                {
                    _gpxDataTime = DateTime.Parse(root.SelectSingleNode("x:time", nsmgr).InnerText);
                }

                XmlNodeList wps = root.SelectNodes("x:wpt", nsmgr);
                if (wps != null)
                {
                    Version V102 = new Version(1, 0, 2);
                    foreach (XmlNode wp in wps)
                    {
                        XmlNode n;
                        if (isGeoSpy)
                        {
                            n = wp.SelectSingleNode("x:extensions", nsmgr).SelectSingleNode("y:cache", nsmgr);
                        }
                        else
                        {
                            n = wp.SelectSingleNode("y:cache", nsmgr);
                        }
                        if (n == null)
                        {
                            //assume Child waypoint
                            //check if it is a child waypoint by checking the name
                            Framework.Data.Geocache parentGeocache = null;
                            string wpname = wp.SelectSingleNode("x:name", nsmgr).InnerText.Substring(2);
                            parentGeocache = (from g in data.Geocaches where g.Code.Substring(2) == wpname select g).FirstOrDefault();
                            if (parentGeocache == null)
                            {
                                parentGeocache = (from Framework.Data.Geocache g in _core.Geocaches where g.Code.Substring(2) == wpname select g).FirstOrDefault();
                                if (parentGeocache == null)
                                {
                                    //parent is not available
                                    //now what?
                                    continue;
                                }
                            }

                            Framework.Data.Waypoint cwp = new Framework.Data.Waypoint();

                            cwp.Code = wp.SelectSingleNode("x:name", nsmgr).InnerText;
                            cwp.GeocacheCode = string.Concat(parentGeocache.Code.Substring(0,2), cwp.Code.Substring(2));
                            cwp.DataFromDate = _gpxDataTime;
                            cwp.Comment = wp.SelectSingleNode("x:cmt", nsmgr).InnerText;
                            if (SafeAttributeInnerText(wp, "lat", "").Length > 0)
                            {
                                cwp.Lat = Utils.Conversion.StringToDouble(wp.Attributes["lat"].InnerText);
                                cwp.Lon = Utils.Conversion.StringToDouble(wp.Attributes["lon"].InnerText);
                                if (Math.Abs((double)cwp.Lat) < 0.0001 && Math.Abs((double)cwp.Lon) < 0.0001)
                                {
                                    cwp.Lat = null;
                                    cwp.Lon = null;
                                }
                            }
                            else
                            {
                                cwp.Lat = null;
                                cwp.Lon = null;
                            }
                            cwp.Description = wp.SelectSingleNode("x:desc", nsmgr).InnerText;
                            cwp.ID = cwp.Code;
                            cwp.Name = cwp.Code;
                            cwp.Comment = wp.SelectSingleNode("x:cmt", nsmgr).InnerText;
                            cwp.Time = DateTime.Parse(wp.SelectSingleNode("x:time", nsmgr).InnerText);
                            cwp.Url = SafeInnerText(wp.SelectSingleNode("x:url", nsmgr),"");
                            cwp.UrlName = SafeInnerText(wp.SelectSingleNode("x:urlname", nsmgr),"");
                            cwp.WPType = DataAccess.GetWaypointType(_core.WaypointTypes, wp.SelectSingleNode("x:sym", nsmgr).InnerText);

                            data.Waypoints.Add(cwp);

                            continue;
                        }

                        Framework.Data.Geocache gc = new Framework.Data.Geocache();

                        gc.Lat = Utils.Conversion.StringToDouble(SafeAttributeInnerText(wp, "lat", "0.0"));
                        gc.Lon = Utils.Conversion.StringToDouble(SafeAttributeInnerText(wp, "lon", "0.0"));
                        gc.Code = wp.SelectSingleNode("x:name", nsmgr).InnerText;
                        gc.Title = n.SelectSingleNode("y:name", nsmgr).InnerText;
                        gc.DataFromDate = _gpxDataTime;
                        gc.PublishedTime = DateTime.Parse(wp.SelectSingleNode("x:time", nsmgr).InnerText);
                        if (isGeoSpy)
                        {
                            gc.Url = wp.SelectSingleNode("x:link", nsmgr).Attributes["href"].Value;
                        }
                        else
                        {
                            gc.Url = SafeInnerText(wp.SelectSingleNode("x:url", nsmgr), "");
                        }
                        if (SafeInnerText(wp.SelectSingleNode("x:sym", nsmgr), "").EndsWith(" Found"))
                        {
                            gc.Found = true;
                        }
                        gc.Available = bool.Parse(n.Attributes["available"].InnerText);
                        gc.Archived = bool.Parse(SafeInnerText(n.Attributes["archived"], "False"));
                        gc.Country = SafeInnerText(n.SelectSingleNode("y:country", nsmgr), "");
                        gc.State = SafeInnerText(n.SelectSingleNode("y:state", nsmgr), "");
                        gc.ID = SafeInnerText(n.Attributes["id"], "");
                        gc.OwnerId = SafeAttributeInnerText(n.SelectSingleNode("y:owner", nsmgr), "id", "");
                        if (_cachesGpxVersion >= V102)
                        {
                            gc.GeocacheType = DataAccess.GetGeocacheType(_core.GeocacheTypes, int.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:type", nsmgr), "id", "-1")));
                            gc.Container = DataAccess.GetGeocacheContainer(_core.GeocacheContainers, int.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:container", nsmgr), "id", "-1")));
                            gc.Favorites = int.Parse(SafeInnerText(n.SelectSingleNode("y:favorite_points", nsmgr), "0"));
                            gc.MemberOnly = bool.Parse(SafeInnerText(n.Attributes["memberonly"], "False"));
                            gc.CustomCoords = bool.Parse(SafeInnerText(n.Attributes["customcoords"], "False"));
                            gc.PersonaleNote = SafeInnerText(n.Attributes["personal_note"], "");
                        }
                        else
                        {
                            string srchTxt = SafeInnerText(n.SelectSingleNode("y:type", nsmgr), "Unknown");
                            if (!srchTxt.StartsWith("Groundspeak"))
                            {
                                if (srchTxt.Contains("Trash"))
                                {
                                    srchTxt = "Trash";
                                }
                                else
                                {
                                    int pos = srchTxt.IndexOf(' ');
                                    if (pos > 0)
                                    {
                                        srchTxt = srchTxt.Substring(0, pos);
                                    }
                                }
                            }
                            gc.GeocacheType = DataAccess.GetGeocacheType(_core.GeocacheTypes, srchTxt);
                            if (isGeoSpy)
                            {
                                gc.Container = DataAccess.GetGeocacheContainer(_core.GeocacheContainers, "Virtual");
                            }
                            else
                            {
                                gc.Container = DataAccess.GetGeocacheContainer(_core.GeocacheContainers, SafeInnerText(n.SelectSingleNode("y:container", nsmgr), "Unknown"));
                            }
                        }
                        gc.PlacedBy = SafeInnerText(n.SelectSingleNode("y:placed_by", nsmgr),"");
                        gc.Owner = SafeInnerText(n.SelectSingleNode("y:owner", nsmgr),"");
                        gc.Terrain = Conversion.StringToDouble(SafeInnerText(n.SelectSingleNode("y:terrain", nsmgr), "1"));
                        gc.Difficulty = Conversion.StringToDouble(SafeInnerText(n.SelectSingleNode("y:difficulty", nsmgr), "1"));
                        gc.ShortDescription = SafeInnerText(n.SelectSingleNode("y:short_description", nsmgr), "");
                        gc.ShortDescriptionInHtml = bool.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:short_description", nsmgr), "html", "False"));
                        gc.LongDescription = SafeInnerText(n.SelectSingleNode("y:long_description", nsmgr), "");
                        gc.LongDescriptionInHtml = bool.Parse(SafeAttributeInnerText(n.SelectSingleNode("y:long_description", nsmgr), "html", "False"));
                        gc.EncodedHints = SafeInnerText(n.SelectSingleNode("y:encoded_hints", nsmgr), "");

                        XmlNode attrs = n.SelectSingleNode("y:attributes", nsmgr);
                        if (attrs != null && attrs.ChildNodes!=null)
                        {
                            foreach (XmlNode attr in attrs.ChildNodes)
                            {
                                int attrId = int.Parse(attr.Attributes["id"].InnerText);
                                int attrInc = int.Parse(SafeAttributeInnerText(attr, "inc", "1"));
                                if (attrInc == 1)
                                {
                                    gc.AttributeIds.Add(attrId);
                                }
                                else
                                {
                                    gc.AttributeIds.Add(-1*attrId);
                                }
                            }
                        }

                        Calculus.SetDistanceAndAngleGeocacheFromLocation(gc, _core.CenterLocation);

                        data.Geocaches.Add(gc);

                        //Logs
                        XmlNode ln = n.SelectSingleNode("y:logs", nsmgr);
                        if (ln != null)
                        {
                            XmlNodeList logs = ln.SelectNodes("y:log", nsmgr);
                            if (logs != null)
                            {
                                foreach (XmlNode l in logs)
                                {
                                    Framework.Data.Log lg = new Framework.Data.Log();

                                    lg.GeocacheCode = gc.Code;
                                    string lid = SafeAttributeInnerText(l, "id", "");

                                    if (lid.StartsWith("GL"))
                                    {
                                        lg.ID = lid;
                                    }
                                    else
                                    {
                                        if (string.IsNullOrEmpty(lid) || lid.StartsWith("-"))
                                        {
                                            continue;
                                        }
                                        try
                                        {
                                            lg.ID = string.Concat("GL", Utils.Conversion.GetCacheCodeFromCacheID(int.Parse(lid)).Substring(2));
                                        }
                                        catch
                                        {
                                            continue;
                                        }
                                    }

                                    lg.DataFromDate = _gpxDataTime;
                                    lg.Date = DateTime.Parse(l.SelectSingleNode("y:date", nsmgr).InnerText);
                                    lg.Encoded = bool.Parse(l.SelectSingleNode("y:text", nsmgr).Attributes["encoded"].InnerText);
                                    if (isGeoSpy)
                                    {
                                        lg.Text = Conversion.StripHtmlTags(System.Web.HttpUtility.HtmlDecode(l.SelectSingleNode("y:text", nsmgr).InnerText).Replace("</p>", "\r\n\r\n"));
                                    }
                                    else
                                    {
                                        lg.Text = l.SelectSingleNode("y:text", nsmgr).InnerText;
                                    }
                                    lg.Finder = l.SelectSingleNode("y:finder", nsmgr).InnerText;
                                    if (l.SelectSingleNode("y:finder", nsmgr).Attributes["id"] != null)
                                    {
                                        lg.FinderId = l.SelectSingleNode("y:finder", nsmgr).Attributes["id"].InnerText;
                                    }
                                    else
                                    {
                                        //GCTour has no finder id
                                        lg.FinderId = "1";
                                    }
                                    if (_cachesGpxVersion >= V102)
                                    {
                                        lg.LogType = DataAccess.GetLogType(_core.LogTypes, int.Parse(l.SelectSingleNode("y:type", nsmgr).Attributes["id"].InnerText));
                                    }
                                    else
                                    {
                                        lg.LogType = DataAccess.GetLogType(_core.LogTypes, l.SelectSingleNode("y:type", nsmgr).InnerText);
                                    }

                                    data.Logs.Add(lg);

                                    //log images
                                    XmlNode lni = l.SelectSingleNode("y:images", nsmgr);
                                    if (lni != null)
                                    {
                                        XmlNodeList logis = lni.SelectNodes("y:image", nsmgr);
                                        if (logis != null)
                                        {
                                            foreach (XmlNode li in logis)
                                            {
                                                Framework.Data.LogImage lgi = new Framework.Data.LogImage();

                                                lgi.Url = li.SelectSingleNode("y:url", nsmgr).InnerText;
                                                lgi.ID = lgi.Url;
                                                lgi.LogID = lg.ID;
                                                lgi.Name = li.SelectSingleNode("y:name", nsmgr).InnerText;
                                                lgi.DataFromDate = _gpxDataTime;

                                                data.LogImages.Add(lgi);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch
            {
            }

        }
Beispiel #42
0
        protected override ResultStatus Save(PokeBall pokeBall)
        {
            try {
                DataTable dtMainCur = (DataTable)gcMain.DataSource;
                gvMain.CloseEditor();
                gvMain.UpdateCurrentRow();

                DataTable dtMainChange      = dtMainCur.GetChanges();
                DataTable dtMainForAdd      = dtMainCur.GetChanges(DataRowState.Added);
                DataTable dtMainForModified = dtMainCur.GetChanges(DataRowState.Modified);
                DataTable dtMainForDeleted  = dtMainCur.GetChanges(DataRowState.Deleted);

                DataTable dtSubCur = (DataTable)gcSub.DataSource;
                gvSub.CloseEditor();
                gvSub.UpdateCurrentRow();

                DataTable dtSubChange      = dtSubCur.GetChanges();
                DataTable dtSubForAdd      = dtSubCur.GetChanges(DataRowState.Added);
                DataTable dtSubForModified = dtSubCur.GetChanges(DataRowState.Modified);
                DataTable dtSubForDeleted  = dtSubCur.GetChanges(DataRowState.Deleted);

                if (dtMainChange == null && dtSubChange == null)
                {
                    MessageDisplay.Warning("沒有變更資料,不需要存檔!", GlobalInfo.WarningText);
                    return(ResultStatus.Fail);
                }

                //若資料為null 用 Rows.Count 會造成exception
                //if (dtMainChange.Rows.Count == 0 && dtSubChange.Rows.Count == 0) {
                //   MessageDisplay.Warning("沒有變更資料,不需要存檔!",GlobalInfo.WarningText);
                //   return ResultStatus.Fail;
                //}

                if (dtMainChange != null)
                {
                    foreach (DataRow drMain in dtMainCur.Rows)
                    {
                        if (drMain.RowState == DataRowState.Added || drMain.RowState == DataRowState.Modified)
                        {
                            drMain["RPTF_TXN_ID"] = _ProgramID;
                            drMain["RPTF_TXD_ID"] = _ProgramID;
                            drMain["RPTF_KEY"]    = mainKey;
                        }
                    }
                    dtMainChange = dtMainCur.GetChanges();
                }

                if (dtSubChange != null)
                {
                    foreach (DataRow drSub in dtSubCur.Rows)
                    {
                        if (drSub.RowState == DataRowState.Added || drSub.RowState == DataRowState.Modified)
                        {
                            drSub["RPTF_TXN_ID"] = _ProgramID;
                            drSub["RPTF_TXD_ID"] = _ProgramID;
                            drSub["RPTF_KEY"]    = subKey;
                        }
                    }
                    dtSubChange = dtSubCur.GetChanges();
                }

                ResultData result = new ResultData();
                if (dtMainChange != null && dtSubChange != null)
                {
                    dtMainChange.Merge(dtSubChange);
                    result = new RPTF().UpdateData(dtMainChange);
                }
                else if (dtMainChange != null && dtSubChange == null)
                {
                    result = new RPTF().UpdateData(dtMainChange);
                }
                else
                {
                    result = new RPTF().UpdateData(dtSubChange);
                }

                if (result.Status == ResultStatus.Fail)
                {
                    return(ResultStatus.Fail);
                }
            } catch (Exception ex) {
                WriteLog(ex);
            }
            _IsPreventFlowPrint = true; //不要自動列印
            return(ResultStatus.Success);
        }
 internal GroupResult(ResultsPerGroupForm form, DisplayRow displayRow, GroupKey groupKey, ResultData resultData)
 {
     _form = form;
     _displayRow = displayRow;
     _groupKey = groupKey;
     _resultData = resultData;
 }
Beispiel #44
0
        public ResultData SendLinkActive([FromUri] string userName, [FromUri] string capcha, [FromUri] string emailConfirm)
        {
            ResultData oResultData = new ResultData();

            try
            {
                if (!string.IsNullOrWhiteSpace(userName) && !string.IsNullOrWhiteSpace(capcha))
                {
                    //Kiểm tra user có tồn tại không
                    ApplicationUser user = UserManager.FindByName <ApplicationUser, string>(userName);
                    if (user != null)
                    {
                        //Kiểm tra capcha có hợp lệ không
                        object objCapcha = MemoryCacheHelper.GetValue(Commonkey.Capcha);
                        if (objCapcha == null && !string.IsNullOrWhiteSpace(capcha))
                        {
                            oResultData.Success      = false;
                            oResultData.ErrorMessage = MT.Resources.GlobalResource.WarnCodeExpried;
                        }
                        if (!objCapcha.ToString().Equals(capcha, StringComparison.OrdinalIgnoreCase))
                        {
                            oResultData.Success      = false;
                            oResultData.ErrorMessage = MT.Resources.GlobalResource.WarnCodeInValid;
                        }
                        else
                        {
                            MemoryCacheHelper.Delete(Commonkey.Capcha);
                        }
                        if (user.Email == emailConfirm)
                        {
                            Guid token = Guid.NewGuid();

                            MemoryCacheHelper.Add(token.ToString(), userName, DateTimeOffset.Now.AddDays(1));

                            string hostName = MT.Library.CommonFunction.GetDomainBEcore();

                            string pathEmail = MT.Library.CommonFunction.GetMapPathEmail();

                            //var destinationPath = Path.Combine(pathEmail, "ConfirmPassword.html");
                            var destinationPath = Path.Combine(pathEmail, "SetNewPassword.html");

                            string strBody = MT.Library.CommonFunction.ReadData(destinationPath);

                            strBody = strBody.Replace("#Link#", hostName);

                            strBody = strBody.Replace("#Token#", token.ToString());
                            //Gửi mail kích hoạt tài khoản
                            EmailUltility.SendMail(user.Email, "", MT.Resources.GlobalResource.Title_ActiveLink, strBody, null);
                            oResultData.Success = true;
                            oResultData.Data    = user.Email;
                        }
                        else
                        {
                            oResultData.Success      = false;
                            oResultData.ErrorMessage = MT.Resources.GlobalResource.InvalidEmailConfirm;
                        }
                    }
                    else
                    {
                        oResultData.Success      = false;
                        oResultData.ErrorMessage = MT.Resources.GlobalResource.UserNameInValid;
                    }
                }
                else
                {
                    oResultData.Success      = false;
                    oResultData.ErrorMessage = MT.Resources.GlobalResource.WarnUserNameOrCodeBlank;
                }
            }
            catch (Exception ex)
            {
                oResultData.SetError(ex);
            }
            return(oResultData);
        }
        //dont even try to understand the following function

        /// <summary>
        /// Do NOT call this method from update thread.
        /// </summary>
        public static ResultData DownloadWorldModsBlocking(List<MyObjectBuilder_Checkpoint.ModItem> mods)
        {
            ResultData ret = new ResultData();
            ret.Success = true;
            if (!MyFakes.ENABLE_WORKSHOP_MODS)
            {             
                return ret;
            }

            MySandboxGame.Log.WriteLine("Downloading world mods - START");
            MySandboxGame.Log.IncreaseIndent();

            m_stop = false;

            if (mods != null && mods.Count > 0)
            {
                var publishedFileIds = new List<ulong>();
                foreach (var mod in mods)
                {
                    if (mod.PublishedFileId != 0)
                    {
                        publishedFileIds.Add(mod.PublishedFileId);
                    }
                    else if (MySandboxGame.IsDedicated)
                    {
                        MySandboxGame.Log.WriteLineAndConsole("Local mods are not allowed in multiplayer.");
                        MySandboxGame.Log.DecreaseIndent();
                        return new ResultData();
                    }
                }

                // Check if the world doesn't contain duplicate mods, if it does, log it and remove the duplicate entry
                publishedFileIds.Sort();
                for (int i = 0; i < publishedFileIds.Count - 1;)
                {
                    ulong id1 = publishedFileIds[i];
                    ulong id2 = publishedFileIds[i + 1];
                    if (id1 == id2)
                    {
                        MySandboxGame.Log.WriteLine(string.Format("Duplicate mod entry for id: {0}", id1));
                        publishedFileIds.RemoveAt(i + 1);
                    }
                    else
                    {
                        i++;
                    }
                }

                if (MySandboxGame.IsDedicated)
                {
                    using (ManualResetEvent mrEvent = new ManualResetEvent(false))
                    {
                        string xml = "";

                        MySteamWebAPI.GetPublishedFileDetails(publishedFileIds, delegate(bool success, string data)
                        {
                            if (!success)
                            {
                                MySandboxGame.Log.WriteLine("Could not retrieve mods details.");
                            }
                            else
                            {
                                xml = data;
                            }
                            ret.Success = success;
                            mrEvent.Set();
                        });

                        while (!mrEvent.WaitOne(17))
                        {
                            mrEvent.Reset();
                            if (MySteam.Server != null)
                                MySteam.Server.RunCallbacks();
                            else
                            {
                                MySandboxGame.Log.WriteLine("Steam server API unavailable");
                                ret.Success = false;
                                break;
                            }
                        }

                        if (ret.Success)
                        {
                            try
                            {
                                System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings()
                                {
                                    DtdProcessing = System.Xml.DtdProcessing.Ignore,
                                };
                                using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(new StringReader(xml), settings))
                                {
                                    reader.ReadToFollowing("result");

                                    Result xmlResult = (Result)reader.ReadElementContentAsInt();

                                    if (xmlResult != Result.OK)
                                    {
                                        MySandboxGame.Log.WriteLine(string.Format("Failed to download mods: result = {0}", xmlResult));
                                        ret.Success = false;
                                    }

                                    reader.ReadToFollowing("resultcount");
                                    int count = reader.ReadElementContentAsInt();

                                    if (count != publishedFileIds.Count)
                                    {
                                        MySandboxGame.Log.WriteLine(string.Format("Failed to download mods details: Expected {0} results, got {1}", publishedFileIds.Count, count));
                                    }

                                    var array = mods.ToArray();

                                    for (int i = 0; i < array.Length; ++i)
                                    {
                                        array[i].FriendlyName = array[i].Name;
                                    }

                                    var processed = new List<ulong>(publishedFileIds.Count);

                                    for (int i = 0; i < publishedFileIds.Count; ++i)
                                    {
                                        mrEvent.Reset();

                                        reader.ReadToFollowing("publishedfileid");
                                        ulong publishedFileId = Convert.ToUInt64(reader.ReadElementContentAsString());

                                        if (processed.Contains(publishedFileId))
                                        {
                                            MySandboxGame.Log.WriteLineAndConsole(string.Format("Duplicate mod: id = {0}", publishedFileId));
                                            continue;
                                        }
                                        processed.Add(publishedFileId);

                                        reader.ReadToFollowing("result");
                                        Result itemResult = (Result)reader.ReadElementContentAsInt();

                                        if (itemResult != Result.OK)
                                        {
                                            MySandboxGame.Log.WriteLineAndConsole(string.Format("Failed to download mod: id = {0}, result = {1}", publishedFileId, itemResult));
                                            ret.Success = false;
                                            continue;
                                        }

                                        reader.ReadToFollowing("consumer_app_id");
                                        int appid = reader.ReadElementContentAsInt();
                                        if (appid != MySteam.AppId)
                                        {
                                            MySandboxGame.Log.WriteLineAndConsole(string.Format("Failed to download mod: id = {0}, wrong appid, got {1}, expected {2}", publishedFileId, appid, MySteam.AppId));
                                            ret.Success = false;
                                            continue;
                                        }

                                        reader.ReadToFollowing("file_size");
                                        long fileSize = reader.ReadElementContentAsLong();

                                        reader.ReadToFollowing("file_url");
                                        string url = reader.ReadElementContentAsString();

                                        reader.ReadToFollowing("title");
                                        string title = reader.ReadElementContentAsString();

                                        for (int j = 0; j < array.Length; ++j)
                                        {
                                            if (array[j].PublishedFileId == publishedFileId)
                                            {
                                                array[j].FriendlyName = title;
                                                break;
                                            }
                                        }

                                        reader.ReadToFollowing("time_updated");
                                        uint timeUpdated = (uint)reader.ReadElementContentAsLong();

                                        var mod = new SubscribedItem() { Title = title, PublishedFileId = publishedFileId, TimeUpdated = timeUpdated };

                                        if (IsModUpToDateBlocking(Path.Combine(MyFileSystem.ModsPath, publishedFileId.ToString() + ".sbm"), mod, false, fileSize))
                                        {
                                            MySandboxGame.Log.WriteLineAndConsole(string.Format("Up to date mod:  id = {0}", publishedFileId));
                                            continue;
                                        }

                                        MySandboxGame.Log.WriteLineAndConsole(string.Format("Downloading mod: id = {0}, size = {1,8:0.000} MiB", publishedFileId, (double)fileSize / 1024f / 1024f));

                                        if (fileSize > 10 * 1024 * 1024) // WTF Steam
                                        {
                                            if (!DownloadModFromURLStream(url, publishedFileId, delegate(bool success)
                                            {
                                                if (!success)
                                                {
                                                    MySandboxGame.Log.WriteLineAndConsole(string.Format("Could not download mod: id = {0}, url = {1}", publishedFileId, url));
                                                }
                                                mrEvent.Set();
                                            }))
                                            {
                                                ret.Success = false;
                                                break;
                                            }
                                        }
                                        else
                                        {
                                            if (!DownloadModFromURL(url, publishedFileId, delegate(bool success)
                                            {
                                                if (!success)
                                                {
                                                    MySandboxGame.Log.WriteLineAndConsole(string.Format("Could not download mod: id = {0}, url = {1}", publishedFileId, url));
                                                }
                                                mrEvent.Set();
                                            }))
                                            {
                                                ret.Success = false;
                                                break;
                                            }
                                        }

                                        while (!mrEvent.WaitOne(17))
                                        {
                                            mrEvent.Reset();
                                            if (MySteam.Server != null)
                                                MySteam.Server.RunCallbacks();
                                            else
                                            {
                                                MySandboxGame.Log.WriteLine("Steam server API unavailable");
                                                ret.Success = false;
                                                break;
                                            }
                                        }
                                    }
                                    mods.Clear();
                                    mods.AddArray(array);
                                }
                            }
                            catch (Exception e)
                            {
                                MySandboxGame.Log.WriteLine(string.Format("Failed to download mods: {0}", e));
                                ret.Success = false;
                            }
                        }
                    }
                }
                else // client
                {
                    var toGet = new List<SubscribedItem>(publishedFileIds.Count);

                    if (!GetItemsBlocking(toGet, publishedFileIds))
                    {
                        MySandboxGame.Log.WriteLine("Could not obtain workshop item details");
                       ret.Success = false;
                    }
                    else if (publishedFileIds.Count != toGet.Count)
                    {
                        MySandboxGame.Log.WriteLine(string.Format("Could not obtain all workshop item details, expected {0}, got {1}", publishedFileIds.Count, toGet.Count));
                        ret.Success = false;
                    }
                    else
                    {
                        m_asyncDownloadScreen.ProgressTextString = MyTexts.GetString(MyCommonTexts.ProgressTextDownloadingMods) + " 0 of " + toGet.Count.ToString();
                       
                        ret = DownloadModsBlocking(toGet);
                        if (ret.Success == false)
                        {
                            MySandboxGame.Log.WriteLine("Downloading mods failed");
                        }
                        else
                        {
                            var array = mods.ToArray();

                            for (int i = 0; i < array.Length; ++i)
                            {
                                var mod = toGet.Find(x => x.PublishedFileId == array[i].PublishedFileId);
                                if (mod != null)
                                {
                                    array[i].FriendlyName = mod.Title;
                                }
                                else
                                {
                                    array[i].FriendlyName = array[i].Name;
                                }
                            }
                            mods.Clear();
                            mods.AddArray(array);
                        }
                    }
                }
            }
            MySandboxGame.Log.DecreaseIndent();
            MySandboxGame.Log.WriteLine("Downloading world mods - END");
            return ret;
        }
Beispiel #46
0
 /// <summary>
 /// @brief リザルトデータとそのプレイヤーの順位を受け取る関数
 /// </summary>
 /// <param name="argDatas">キャラクター情報</param>
 /// <param name="argrank">プレイヤーの順位</param>
 public void SetResultData(ResultData argData, int argRank)
 {
     resultDatas.Add(argData);
     playerRank = argRank;
 }
 /// <summary>
 /// 获取文件夹已经下载的文件信息
 /// </summary>
 /// <returns></returns>
 public static async Task<ResultData> GetList(DownloadType type)
 {
     try
     {
         IReadOnlyList<StorageFile> files = null;
         StorageFolder folder = null;
         folder = await KnownFolders.MusicLibrary.CreateFolderAsync("kgdownload", CreationCollisionOption.OpenIfExists);
         switch (type)
         {
             case DownloadType.song:
                 folder = await folder.CreateFolderAsync("song", CreationCollisionOption.OpenIfExists);
                 break;
             case DownloadType.mv:
                 folder = await folder.CreateFolderAsync("mv", CreationCollisionOption.OpenIfExists);
                 break;
             case DownloadType.other:
                 folder = await folder.CreateFolderAsync("other", CreationCollisionOption.OpenIfExists);
                 break;
             default:
                 break;
         }
         files = await folder.GetFilesAsync();                
         //DataConnect.transfersModel = transfers;//未下载成功的文件Item
         //DataConnect.filesModel = files;//下载成功的文件Item
         //await DiscoverActiveDownloadsAsync(type);
         var result = new ResultData();
         result.transfers = new ObservableCollection<TransferModel>();
         result.files = files.ToList();
         if(transfers.Count>0)
         {
             foreach (var item in transfers)
             {
                 string flag = "";
                 switch (type)
                 {
                     case DownloadType.song:
                         flag = "song";
                         break;
                     case DownloadType.mv:
                         flag = "mv";
                         break;
                     case DownloadType.other:
                         flag = "other";
                         break;
                     default:
                         break;
                 }
                 if(item.DownloadOperation.TransferGroup.Name==flag)
                 {
                     result.transfers.Add(item);
                 }
             }
         }
         return result;
     }
     catch { return null; }
 }
        private ResultData CalculateHalfLife(ICollection<ProcessedRowData> rowDatas)
        {
            IEnumerable<ProcessedRowData> filteredRowDatas;
            if (EvviesFilter != EvviesFilterEnum.None)
            {
                var applicableRowDatas = new List<ProcessedRowData>();
                var values = new Dictionary<double, List<double>>();
                var filteredRowDataList = new List<ProcessedRowData>();
                foreach (var rowData in rowDatas)
                {
                    Debug.Assert(RejectReason.EvviesFilter != rowData.RejectReason);
                    if (null != rowData.RejectReason)
                    {
                        continue;
                    }
                    var value = rowData.Turnover;
                    if (!value.HasValue || double.IsNaN(value.Value) || double.IsInfinity(value.Value))
                    {
                        continue;
                    }
                    var timePoint = GetTimePoint(rowData.RawRowData);
                    if (!timePoint.HasValue)
                    {
                        filteredRowDataList.Add(rowData);
                        continue;
                    }
                    List<double> list;
                    if (!values.TryGetValue(timePoint.Value, out list))
                    {
                        list = new List<double>();
                        values.Add(timePoint.Value, list);
                    }
                    list.Add(value.Value);
                    applicableRowDatas.Add(rowData);
                }
                if (EvviesFilter == EvviesFilterEnum.Oct2011)
                {
                    foreach (var entry in values.ToArray())
                    {
                        var statistics = new Statistics(entry.Value.ToArray());
                        var min = statistics.Median() - 3*statistics.StdDev();
                        var max = statistics.Median() + 3*statistics.StdDev();
                        if (statistics.Median() + 2 * statistics.StdDev() >= .99)
                        {
                            // Throw away any values of 100% or 99% if they are more than 2 SD above the median.
                            max = Math.Min(.99, max);
                        }
                        var newValues = entry.Value.Where(v => v >= min && v <= max).ToList();
                        if (newValues.Count != entry.Value.Count)
                        {
                            values[entry.Key] = newValues;
                        }
                    }
                }

                var cutoffs = new Dictionary<double, KeyValuePair<double, double>>();
                foreach (var entry in values)
                {
                    var statistics = new Statistics(entry.Value.ToArray());
                    var mean = statistics.Mean();
                    var stdDev = statistics.StdDev();
                    double cutoff;
                    if (EvviesFilter == EvviesFilterEnum.TwoStdDev)
                    {
                        cutoff = 2*stdDev;
                    }
                    else
                    {
                        if (stdDev / mean < .3)
                        {
                            cutoff = 2 * stdDev;
                        }
                        else
                        {
                            cutoff = stdDev;
                        }
                    }
                    cutoffs.Add(entry.Key, new KeyValuePair<double, double>(mean - cutoff, mean + cutoff));
                }
                foreach (var rowData in applicableRowDatas)
                {
                    var cutoff = cutoffs[GetTimePoint(rowData.RawRowData).Value];
                    var value = rowData.Turnover;
                    rowData.EvviesFilterMin = cutoff.Key;
                    rowData.EvviesFilterMax = cutoff.Value;
                    // Only apply Evvie's Filter to rows that has a time point.
                    if (GetTimePoint(rowData.RawRowData).HasValue)
                    {
                        if (value.Value < cutoff.Key || value.Value > cutoff.Value)
                        {
                            Debug.Assert(null == rowData.RejectReason);
                            rowData.RejectReason = RejectReason.EvviesFilter;
                            continue;
                        }
                    }
                    filteredRowDataList.Add(rowData);
                }
                filteredRowDatas = filteredRowDataList;
            }
            else
            {
                filteredRowDatas = rowDatas.Where(rowData=>null == rowData.RejectReason).ToArray();
            }
            if (HalfLifeSettings.SimpleLinearRegression)
            {
                var timePoints = new List<double>();
                var logValues = new List<double>();
                foreach (var rowData in filteredRowDatas)
                {
                    if (null != rowData.RejectReason)
                    {
                        continue;
                    }
                    double? logValue = Math.Log(1-rowData.Turnover.Value);
                    if (!logValue.HasValue || double.IsNaN(logValue.Value) || double.IsInfinity(logValue.Value))
                    {
                        rowData.RejectReason = RejectReason.ValueOutOfRange;
                        continue;
                    }
                    double? timePoint = GetTimePoint(rowData.RawRowData);
                    if (!timePoint.HasValue || ExcludedTimePoints.Contains(timePoint.Value))
                    {
                        rowData.RejectReason = RejectReason.NoTimePoint;
                        continue;
                    }
                    logValues.Add(logValue.Value);
                    timePoints.Add(timePoint.Value);
                }
                var statsTimePoints = new Statistics(timePoints.ToArray());
                var statsLogValues = new Statistics(logValues.ToArray());
                double rateConstant, stDevRateConstant, rateConstantError, yIntercept;
                double? rSquared = null;
                if (FixedInitialPercent)
                {
                    rateConstant = statsLogValues.SlopeWithoutIntercept(statsTimePoints);
                    stDevRateConstant = Statistics.StdDevSlopeWithoutIntercept(statsLogValues, statsTimePoints);
                    rateConstantError = stDevRateConstant * GetErrorFactor(timePoints.Count - 1);
                    yIntercept = 0;
                }
                else
                {
                    rateConstant = statsLogValues.Slope(statsTimePoints);
                    stDevRateConstant = Statistics.StdDevB(statsLogValues, statsTimePoints);
                    rateConstantError = stDevRateConstant * GetErrorFactor(timePoints.Count - 2);
                    yIntercept = Statistics.Intercept(statsLogValues, statsTimePoints);
                    rSquared = Math.Pow(Statistics.R(statsLogValues, statsTimePoints), 2);
                }
                return new ResultData
                {
                    RateConstant = rateConstant,
                    RateConstantStdDev = stDevRateConstant,
                    RateConstantError = rateConstantError,
                    PointCount = timePoints.Count,
                    YIntercept = yIntercept,
                    RSquared = rSquared,
                    RowDatas = rowDatas.ToArray(),
                    FilteredRowDatas = filteredRowDatas.ToArray(),
                };
            }
            else
            {
                var dataPoints = new List<KeyValuePair<double, double>>();
                foreach (var rowData in filteredRowDatas)
                {
                    double? time = rowData.RawRowData.MsDataFile.TimePoint;
                    double? y;
                    y = 1-rowData.Turnover;
                    if (!y.HasValue || !time.HasValue)
                    {
                        continue;
                    }
                    dataPoints.Add(new KeyValuePair<double, double>(time.Value, y.Value));
                }
                var timePoints =
                    Workspace.MsDataFiles.Select(msDataFile => msDataFile.TimePoint)
                    .Where(timePoint => timePoint.HasValue).ToList();
                var resultData = new ResultData
                                     {
                                         PointCount = dataPoints.Count,
                                         FilteredRowDatas = filteredRowDatas.ToArray(),
                                         RowDatas = rowDatas.ToArray(),
                                     };
                if (resultData.RowDatas.Count == 0 || timePoints.Count == 0)
                {
                    resultData.RateConstant = double.NaN;
                    resultData.YIntercept = double.NaN;
                    return resultData;
                }
                NelderMeadSimplex.SimplexConstant[] initialParameters;
                double convergenceTolerance = 0;
                int maxEvaluations = 1000;
                if (FixedInitialPercent)
                {
                    timePoints.Add(0);
                    double timePointDifference = timePoints.Max().Value - timePoints.Min().Value;
                    initialParameters = new[] {new NelderMeadSimplex.SimplexConstant(1/timePointDifference, 1.0/10/timePointDifference)};
                    var regressionResult = NelderMeadSimplex.Regress(initialParameters, convergenceTolerance,
                                                                     maxEvaluations,
                                                                     constants =>
                                                                     SumOfResidualsSquared(
                                                                         x => Math.Exp(-constants[0]*x), dataPoints));
                    resultData.RateConstant = -regressionResult.Constants[0];
                }
                else
                {
                    double timePointDifference = timePoints.Max().Value - timePoints.Min().Value;
                    initialParameters = new[]
                                            {
                                                new NelderMeadSimplex.SimplexConstant(1/timePointDifference,
                                                                                      1.0/10/timePointDifference),
                                                new NelderMeadSimplex.SimplexConstant(0, .1),
                                            };
                    var regressionResult = NelderMeadSimplex.Regress(initialParameters, convergenceTolerance, maxEvaluations,
                        constants=>SumOfResidualsSquared(x=>Math.Exp(-constants[0] * x + constants[1]), dataPoints));
                    resultData.RateConstant = -regressionResult.Constants[0];
                    resultData.YIntercept = regressionResult.Constants[1];
                }
                return resultData;
            }
        }