示例#1
0
        private void OCR()
        {
            if (IsPauseFlag)
            {
                if (IsOCRingFlag == false)
                {
                    IsOCRingFlag = true;

                    int j = 0;

                    for (; j < 3; j++)
                    {
                        Thread.Sleep(Common.UsingOCRDelay);

                        string srcText = Common.ocr.OCRProcess();
                        GC.Collect();

                        if (!string.IsNullOrEmpty(srcText))
                        {
                            Application.Current.Dispatcher.BeginInvoke((Action)(() =>
                            {
                                //0.清除面板
                                SourceTextPanel.Children.Clear();

                                //1.得到原句
                                string source = srcText;

                                _currentsrcText = source;

                                if (_isShowSource)
                                {
                                    //3.分词
                                    List <MecabWordInfo> mwi = _mecabHelper.SentenceHandle(source);
                                    //分词后结果显示
                                    for (int i = 0; i < mwi.Count; i++)
                                    {
                                        TextBlock textBlock = new TextBlock();
                                        if (!string.IsNullOrEmpty(SourceTextFont))
                                        {
                                            FontFamily fontFamily = new FontFamily(SourceTextFont);
                                            textBlock.FontFamily = fontFamily;
                                        }
                                        textBlock.Text = mwi[i].Word;
                                        textBlock.Margin = new Thickness(10, 0, 0, 10);
                                        textBlock.FontSize = SourceTextFontSize;
                                        textBlock.Background = Brushes.Transparent;
                                        textBlock.MouseLeftButtonDown += DictArea_MouseLeftButtonDown;
                                        //根据不同词性跟字体上色
                                        switch (mwi[i].PartOfSpeech)
                                        {
                                        case "名詞":
                                            textBlock.Foreground = Brushes.AliceBlue;
                                            break;

                                        case "助詞":
                                            textBlock.Foreground = Brushes.LightGreen;
                                            break;

                                        case "動詞":
                                            textBlock.Foreground = Brushes.Red;
                                            break;

                                        case "連体詞":
                                            textBlock.Foreground = Brushes.Orange;
                                            break;

                                        default:
                                            textBlock.Foreground = Brushes.White;
                                            break;
                                        }

                                        SourceTextPanel.Children.Add(textBlock);
                                    }
                                }

                                if (Convert.ToBoolean(Common.appSettings.EachRowTrans))
                                {
                                    //需要分行翻译
                                    source = source.Replace("<br>", string.Empty).Replace("</br>", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty).Replace("\r", string.Empty);
                                }
                                //去乱码
                                source = source.Replace("_", string.Empty).Replace("-", string.Empty).Replace("+", string.Empty);

                                //4.翻译前预处理
                                string beforeString = _beforeTransHandle.AutoHandle(source);

                                //5.提交翻译
                                string transRes1 = string.Empty;
                                string transRes2 = string.Empty;
                                if (_translator1 != null)
                                {
                                    transRes1 = _translator1.Translate(beforeString, Common.UsingDstLang, Common.UsingSrcLang);
                                }
                                if (_translator2 != null)
                                {
                                    transRes2 = _translator2.Translate(beforeString, Common.UsingDstLang, Common.UsingSrcLang);
                                }

                                //6.翻译后处理
                                string afterString1 = _afterTransHandle.AutoHandle(transRes1);
                                string afterString2 = _afterTransHandle.AutoHandle(transRes2);

                                //7.翻译结果显示到窗口上
                                FirstTransText.Text = afterString1;
                                FirstTransTextShadow.Text = FirstTransText.Text;

                                //8.翻译结果记录到队列
                                if (_gameTextHistory.Count > 5)
                                {
                                    _gameTextHistory.Dequeue();
                                }
                                _gameTextHistory.Enqueue(source + "\n" + afterString1 + "\n" + afterString2);
                            }));

                            IsOCRingFlag = false;
                            break;
                        }
                    }

                    if (j == 3)
                    {
                        Application.Current.Dispatcher.BeginInvoke((Action)(() =>
                        {
                            FirstTransText.Text = "[OCR]自动识别三次均为空,请自行刷新!";
                        }));

                        IsOCRingFlag = false;
                    }
                }
            }
        }
示例#2
0
        public void RunExcelMacro(string excelFileName, string macro, bool visible)
        {
            //### improve & cleanup code


            // Define Workbooks
            Excel2.Application oExcel   = null;
            Excel2.Workbooks   oBooks   = null;
            Excel2._Workbook   oBook    = null;
            object             oMissing = System.Reflection.Missing.Value;

            try
            {
                //### test thread culture
                System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-FR");

                FileInfo fi = new FileInfo(excelFileName);

                // Create an instance of Microsoft Excel
                //Excel2.ApplicationClass oExcel = new Excel2.ApplicationClass();

                oExcel = new Excel2.Application();

                oExcel.Visible       = visible;
                oExcel.DisplayAlerts = true;

                oBooks = oExcel.Workbooks;

                //Open the file, using the 'path' variable
                oBook = oBooks.Open(excelFileName, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                                    oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);


                //### activate
                //Object[] oRunArgs = { "'" + fi.Name + "'!FULL.FULL" };

                Object[] oRunArgs = { "'" + fi.Name + "'!" + macro };
                oExcel.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null,
                                              oExcel, oRunArgs);


                //oRunArgs = new object[] { fi.Name + "!exportFile" };
                //oExcel.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null,
                //    oExcel, oRunArgs);

                //save excel file
                oBook.Save();

                // Quit Excel and clean up.
                oBook.Close(false, oMissing, oMissing);

                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
                oBook = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks);
                oBooks = null;
                oExcel.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
                oExcel = null;

                //Garbage collection
                GC.Collect();
            }
            catch (Exception ex)
            {
                if (oBook != null)
                {
                    try
                    {
                        oBook.Close(false, oMissing, oMissing);
                    }
                    catch (Exception ex2) { }

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
                    oBook = null;
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks);
                    oBooks = null;
                }

                if (oExcel != null)
                {
                    try
                    {
                        oExcel.Quit();
                    }
                    catch (Exception ex2) { }

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
                    oExcel = null;
                }

                log.Error("Error :: RunExcelMacro : " + ex.Message);
                throw ex;
            }
        }
示例#3
0
 private void IBProjectViewCP_Unloaded(object sender, RoutedEventArgs e)
 {
     GC.Collect();
 }
示例#4
0
        //public void Init(Stream rptFile)
        //{
        //    rptDoc.Load( //.Load(rptFile);

        //}

        /// <summary>
        /// Load the Report and Generate a Base64 Data
        /// </summary>
        /// <param name="report"></param>
        public void Load(Rpt report = null)
        {
            try
            {
                if (DataSource == null)
                {
                    throw new Exception("Please provide Report Data Source");
                }

                report?.Invoke(rptDoc); //nat 20160630
                rptDoc.SetDatabaseLogon(Credentials.User, Credentials.Password, Credentials.Server, Credentials.Database);
                rptDoc.SetDataSource(this.DataSource);

                foreach (ReportDocument ireport in rptDoc.Subreports)
                {
                    foreach (IConnectionInfo dsc in ireport.DataSourceConnections)
                    {
                        dsc.SetConnection(Credentials.Server, Credentials.Database, Credentials.User, Credentials.Password);
                    }
                }

                if (SubReportSource.Count > 0)
                {
                    SubReportSource.ForEach(x =>
                    {
                        var gg = rptDoc.Subreports.Cast <ReportDocument>().Where(y => y.Name == x.Name);
                        if (gg.Any())
                        {
                            gg.Single().SetDataSource(x.DataSource);
                        }
                    });
                }

                //if(SubReportSource.Count > 0)
                //{
                //    foreach(ReportDocument rd in rptDoc.Subreports)
                //    {
                //        if (SubReportSource.Any(x => x.Name == rd.Name))
                //            rd.SetDataSource(SubReportSource.Single(x => x.Name == rd.Name));
                //        else
                //            foreach (IConnectionInfo dsc in rd.DataSourceConnections)
                //                dsc.SetConnection(Credentials.Server, Credentials.Database, Credentials.User, Credentials.Password);
                //    }
                //}


                var ggs = GetParameterKeys();
                foreach (var g in this.rParameters)
                {
                    if (ggs.Contains(g.Key))
                    {
                        rptDoc.SetParameterValue(g.Key, g.Value);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (File.Exists(tmp))
                {
                    File.Delete(tmp);
                }
                GC.Collect();
            }
        }
示例#5
0
        private void patcher_PatchingStateChanged(object sender, PatchingEventArgs e)
        {
            switch (e.State)
            {
            case PatchingState.PatchStart:
                AppendStateText("패치중" + e.Part.FileName + "\r\n");
                break;

            case PatchingState.VerifyOldChecksumBegin:
                AppendStateText("  이전파일 checksum...");
                break;

            case PatchingState.VerifyOldChecksumEnd:
                AppendStateText("  완료 \r\n");
                break;

            case PatchingState.VerifyNewChecksumBegin:
                AppendStateText("  새파일 checksum...");
                break;

            case PatchingState.VerifyNewChecksumEnd:
                AppendStateText("  완료 \r\n");
                break;

            case PatchingState.TempFileCreated:
                AppendStateText("  임시파일 생성중 \r\n");
                progressBarX1.Maximum = e.Part.NewFileLength;
                break;

            case PatchingState.TempFileBuildProcessChanged:
                progressBarX1.Value = (int)e.CurrentFileLength;
                progressBarX1.Text  = string.Format("{0:N0}/{1:N0}", e.CurrentFileLength, e.Part.NewFileLength);
                break;

            case PatchingState.TempFileClosed:
                AppendStateText("  임시파일 삭제중 \r\n");
                progressBarX1.Value   = 0;
                progressBarX1.Maximum = 0;
                progressBarX1.Text    = string.Empty;

                if (!string.IsNullOrEmpty(this.compareFolder) &&
                    e.Part.Type == 1 &&
                    Path.GetExtension(e.Part.FileName).Equals(".wz", StringComparison.CurrentCultureIgnoreCase) &&
                    !Path.GetFileName(e.Part.FileName).Equals("list.wz", StringComparison.CurrentCultureIgnoreCase))
                {
                    Wz_Structure wznew = new Wz_Structure();
                    Wz_Structure wzold = new Wz_Structure();
                    try
                    {
                        AppendStateText("  (comparer)파일비교중 \r\n");
                        EasyComparer comparer = new EasyComparer();
                        comparer.OutputPng              = chkOutputPng.Checked;
                        comparer.OutputAddedImg         = chkOutputAddedImg.Checked;
                        comparer.OutputRemovedImg       = chkOutputRemovedImg.Checked;
                        comparer.Comparer.PngComparison = (WzPngComparison)cmbComparePng.SelectedItem;
                        wznew.Load(e.Part.TempFilePath, false);
                        wzold.Load(e.Part.OldFilePath, false);
                        comparer.EasyCompareWzFiles(wznew.wz_files[0], wzold.wz_files[0], this.compareFolder);
                    }
                    catch (Exception ex)
                    {
                        txtPatchState.AppendText(ex.ToString());
                    }
                    finally
                    {
                        wznew.Clear();
                        wzold.Clear();
                        GC.Collect();
                    }
                }

                if (this.deadPatch && e.Part.Type == 1)
                {
                    ((WzPatcher)sender).SafeMove(e.Part.TempFilePath, e.Part.OldFilePath);
                    AppendStateText("  (deadpatch)파일적용중\r\n");
                }
                break;
            }
        }
        public override void Calc()
        {
            DateTime   start__full_time = DateTime.Now;
            List <int> gen_index        = prepare_generate_to_Calc();
            List <int> leant_index      = prepare_learn_to_Calc();

            make_Log(Log_line.Start, TimerValue: start__full_time);
            int currentstep = 0;
            int all_step    = (Rules_generator.Count() + Learn_algorithms.Count() * Repeat_into) * Repeat_renew_global;

            currentstep = Make_inform_back_process(currentstep, all_step);

            //   Parallel.For(0, Repeat_renew_global, i =>
            LOG = "";
            for (int i = 0; i < Repeat_renew_global; i++)
            {
                Approx_Singletone = new TSAFuzzySystem(Approx_learn_set, Approx_test_set);
                DateTime start__curle_time = DateTime.Now;
                #region Генерация аппроксиматора

                make_Log(Log_line.StartGenerate, TimerValue: start__curle_time);
                if (Rules_generator.Count() == 0 && (is_UFS))
                {
                    Approx_Singletone = TSAFSUFSLoader.loadUFS(Approx_Singletone, UFS_file_name);
                }
                for (int ad = 0; ad < Rules_generator.Count(); ad++)
                {
                    make_Log(Log_line.PreGenerate_log, name_Alg: Rules_generator[ad].ToString());

                    Approx_Singletone =
                        Rules_generator[ad].Generate(Approx_Singletone as TSAFuzzySystem, Rules_generator_conf[gen_index[ad]]) as TSAFuzzySystem;

                    currentstep = Make_inform_back_process(currentstep, all_step);

                    make_Log(Log_line.PostGenerate_log, Approx_Singletone, name_Alg: Rules_generator[ad].ToString(true));
                    if (is_autosave)
                    {
                        save_FS(Approx_Singletone, Name_alg: Rules_generator[ad].ToString());
                    }
                    GC.Collect();
                }

                #endregion

                make_Log(Log_line.StartOptimaze, Approx_Singletone);

                for (int j = 0; j < Repeat_into; j++)
                {
                    #region Оптимизация аппроксиматора
                    for (int l = 0; l < Learn_algorithms.Count(); l++)
                    {
                        make_Log(Log_line.PreOptimaze_log, name_Alg: Learn_algorithms[l].ToString());
                        Approx_Singletone =
                            Learn_algorithms[l].TuneUpFuzzySystem(Approx_Singletone as TSAFuzzySystem, Learn_algorithm_conf[leant_index[l]]) as TSAFuzzySystem;

                        currentstep = Make_inform_back_process(currentstep, all_step);

                        make_Log(Log_line.PostOptimaze_log, FS: Approx_Singletone, name_Alg: Learn_algorithms[l].ToString(true));

                        if (is_autosave)
                        {
                            save_FS(Approx_Singletone, Learn_algorithms[l].ToString());
                        }
                        GC.Collect();
                    }
                    #endregion
                }
                make_Log(Log_line.EndCircle, TimerSpan: (DateTime.Now - start__curle_time));

                GC.Collect();
            }
            //  );
            make_Log(Log_line.End, TimerSpan: DateTime.Now - start__full_time);
        }
示例#7
0
 public void Dispose()
 {
     GC.Collect();
 }
示例#8
0
 /// <summary>
 /// Clear out the cache
 /// </summary>
 public void Setup()
 {
     ProjectCollection.GlobalProjectCollection.UnloadAllProjects();
     GC.Collect();
 }
示例#9
0
        public override bool LoadExcelAndInsertList(string filepath, Int32 GoodsAttrType, bool bFixedType, string goodsname)
        {
            LQStructures.LQCrawlerInfo pCrawlerInfo = CrawlerManager.Instance.GetCrawlerInfo();

            Microsoft.Office.Interop.Excel.Application ap = null;
            Workbook wb = null;
            Worksheet ws = null;
            HKExcelHelper.GetWorkSheet(filepath, ref ap, ref wb, ref ws);


            Range tRange = null;
            string tempString = "";
            string comparesitename = "";

            Int32 nCurrentRow = 0;
            Int32 ExData_Option = 0;
            Int32 ExData_Coupncode = 0;
            Int32 ExData_Buyer = 0;
            Int32 ExData_Cancel = 0;

            Int32 ExData_Use = 0;
            Int32 ExData_Buyphone = 0;
            Int32 ExData_Price = 0;
            Int32 ExData_BuyDate = 0;
            Int32 ExData_BuyCount = 0;

            if (bFixedType == true)
            {// 레저큐 양식일때는 고정값으로
                nCurrentRow = 2;
                ExData_Option = 4;
                ExData_Coupncode = 3;
                ExData_Buyer = 1;
                ExData_Cancel = 6;
                ExData_Use = 6;
                ExData_Buyphone = 2;
                ExData_Price = 5;
                ExData_BuyDate = 7;
                ExData_BuyCount = 8;
            }
            else
            {
                nCurrentRow = pCrawlerInfo.ExData_Start_;
                ExData_Option = pCrawlerInfo.ExData_Option_;
                ExData_Coupncode = pCrawlerInfo.ExData_Coupncode_;
                ExData_Buyer = pCrawlerInfo.ExData_Buyer_;
                ExData_Cancel = pCrawlerInfo.ExData_Cancel_;
                ExData_Use = pCrawlerInfo.ExData_Use_;
                ExData_Buyphone = pCrawlerInfo.ExData_Buyphone_;
                ExData_Price = pCrawlerInfo.ExData_Price_;
                ExData_BuyDate = pCrawlerInfo.ExData_Buydate_;
                ExData_BuyCount = pCrawlerInfo.ExData_Count_;

                // 티몬을 위한 변경
                if (GoodsAttrType == 1)
                {
                    nCurrentRow = 3;
                    ExData_Option = 6;
                    ExData_Coupncode = 3;
                    ExData_Buyer = 1;
                    ExData_Cancel = 8;
                    ExData_Use = 8;
                    ExData_Buyphone = 2;
                    ExData_Price = 7;
                    ExData_BuyDate = 9;
                }
            }

            while (true)
            {
                try
                {
                    tRange = ws.Cells[nCurrentRow, 1];
                    comparesitename = Convert.ToString(tRange.Value2);

                    tRange = ws.Cells[nCurrentRow, ExData_Option];
                    if (tRange == null)
                        break;

                    tempString = tRange.Value2;
                    if (tempString == null)
                    {
                        break;
                    }

                    Int32 tempgoodSeq = -1;
                    tblOrderData pExcelData = new tblOrderData();
                    pExcelData.channelSeq_ = pCrawlerInfo.Channel_Idx_;
                    pExcelData.authoritySeq_ = pCrawlerInfo.AuthoritySeq_;
                    //pExcelData.goodsCode_ = pGoodInfo.Goods_Code_;
                    pExcelData.goodsSeq_ = tempgoodSeq;
                    pExcelData.ExData_Option_ = tempString;
                    pExcelData.ExData_OptionOriginal_ = tempString;
                    if (string.IsNullOrEmpty(goodsname) == false)
                    {
                        pExcelData.ExData_GoodsName_ = goodsname;
                    }

                    tRange = ws.Cells[nCurrentRow, ExData_Coupncode];
                    if (tRange == null)
                        break;

                    pExcelData.channelOrderCode_ = Convert.ToString(tRange.Value2);
                    if (pExcelData.channelOrderCode_ == null)
                        break;
                    pExcelData.channelOrderCode_ = pExcelData.channelOrderCode_.Replace("'", "");
                    pExcelData.channelOrderCode_ = pExcelData.channelOrderCode_.Trim();   // 공백 제거

                    tRange = ws.Cells[nCurrentRow, ExData_Buyer];
                    pExcelData.orderName_ = Convert.ToString(tRange.Value2);
                    if (pExcelData.orderName_ == null) pExcelData.orderName_ = "";

                    tRange = ws.Cells[nCurrentRow, ExData_Cancel];
                    pExcelData.ExData_Cancel_ = tRange.Value2;
                    if (pExcelData.ExData_Cancel_ == null) pExcelData.ExData_Cancel_ = "";

                    tRange = ws.Cells[nCurrentRow, ExData_Use];
                    pExcelData.ExData_Use_ = tRange.Value2;
                    if (pExcelData.ExData_Use_ == null) pExcelData.ExData_Use_ = "";

                    tRange = ws.Cells[nCurrentRow, ExData_Buyphone];
                    pExcelData.orderPhone_ = Convert.ToString(tRange.Value2);
                    if (pExcelData.orderPhone_ == null || pExcelData.orderPhone_ == "")
                    {
                        tRange = ws.Cells[nCurrentRow, 31];
                        pExcelData.orderPhone_ = Convert.ToString(tRange.Value2);
                    }

                    pExcelData.orderPhone_ = pExcelData.orderPhone_.Replace("'", "");
                    

                    if (ExData_Price != 0)
                    {
                        tRange = ws.Cells[nCurrentRow, ExData_Price];

                        if (tRange.Value2 != null)
                        {// 돈에 , 가 있으면 제거하자.
                            tempString = Convert.ToString(tRange.Value2);
                            tempString = tempString.Replace(",", "");
                            pExcelData.orderSettlePrice_ = Convert.ToInt32(tempString);
                        }
                    }

                    tRange = ws.Cells[nCurrentRow, ExData_BuyDate];
                    double temp = Convert.ToDouble(tRange.Value2);
                    DateTime dta = DateTime.FromOADate(temp);
                    pExcelData.BuyDate_ = dta.ToString("u");
                    pExcelData.BuyDate_ = pExcelData.BuyDate_.Replace("Z", "");
                    
                    if (ExData_BuyCount != 0)// 구매갯수를 따로 뽑아야 하는 채널에서만
                    {
                        tRange = ws.Cells[nCurrentRow, ExData_BuyCount];
                        pExcelData.BuyCount_ = Convert.ToInt32(tRange.Value2);
                    }

                    SplitDealAndInsertExcelData(pExcelData, comparesitename);

                }
                catch (System.Exception ex)
                {
                    LogManager.Instance.Log(string.Format("엑셀 파싱 에러 : {0}", ex.Message));
                    nCurrentRow++;
                    continue;
                }

                nCurrentRow++;
            }

            wb.Close(false, Type.Missing, Type.Missing);
            ap.Quit();

            Marshal.FinalReleaseComObject(ws);
            Marshal.FinalReleaseComObject(wb);
            Marshal.FinalReleaseComObject(ap);
            ws = null;
            wb = null;
            ap = null;
            GC.Collect();

            return true;
        }
示例#10
0
        /// <summary>
        /// Archive the region requested.
        /// </summary>
        /// <exception cref="System.IO.IOException">if there was an io problem with creating the file</exception>
        public void ArchiveRegion(Dictionary <string, object> options)
        {
            m_options = options;

            if (options.ContainsKey("all") && (bool)options["all"])
            {
                MultiRegionFormat = true;
            }

            if (options.ContainsKey("noassets") && (bool)options["noassets"])
            {
                SaveAssets = false;
            }

            if (options.TryGetValue("checkPermissions", out Object temp))
            {
                FilterContent = (string)temp;
            }


            // Find the regions to archive
            ArchiveScenesGroup scenesGroup = new ArchiveScenesGroup();

            if (MultiRegionFormat)
            {
                m_log.InfoFormat("[ARCHIVER]: Saving {0} regions", SceneManager.Instance.Scenes.Count);
                SceneManager.Instance.ForEachScene(delegate(Scene scene)
                {
                    scenesGroup.AddScene(scene);
                });
            }
            else
            {
                scenesGroup.AddScene(m_rootScene);
            }
            scenesGroup.CalcSceneLocations();

            m_archiveWriter = new TarArchiveWriter(m_saveStream);

            try
            {
                // Write out control file. It should be first so that it will be found ASAP when loading the file.
                m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(scenesGroup));
                m_log.InfoFormat("[ARCHIVER]: Added control file to archive.");

                // Archive the regions

                Dictionary <UUID, sbyte> assetUuids           = new Dictionary <UUID, sbyte>();
                HashSet <UUID>           failedIDs            = new HashSet <UUID>();
                HashSet <UUID>           uncertainAssetsUUIDs = new HashSet <UUID>();

                scenesGroup.ForEachScene(delegate(Scene scene)
                {
                    string regionDir = MultiRegionFormat ? scenesGroup.GetRegionDir(scene.RegionInfo.RegionID) : "";
                    ArchiveOneRegion(scene, regionDir, assetUuids, failedIDs, uncertainAssetsUUIDs);
                });

                // Archive the assets

                if (SaveAssets)
                {
                    m_log.DebugFormat("[ARCHIVER]: Saving {0} assets", assetUuids.Count);

                    AssetsRequest ar = new AssetsRequest(
                        new AssetsArchiver(m_archiveWriter), assetUuids,
                        failedIDs.Count,
                        m_rootScene.AssetService, m_rootScene.UserAccountService,
                        m_rootScene.RegionInfo.ScopeID, options, null);
                    ar.Execute();
                    assetUuids = null;
                }
                else
                {
                    m_log.DebugFormat("[ARCHIVER]: Not saving assets since --noassets was specified");
                    //                    CloseArchive(string.Empty);
                }
                CloseArchive(string.Empty);
            }
            catch (Exception e)
            {
                CloseArchive(e.Message);
                throw;
            }

            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.Default;
        }
示例#11
0
        private void ArchiveOneRegion(Scene scene, string regionDir, Dictionary <UUID, sbyte> assetUuids,
                                      HashSet <UUID> failedIDs, HashSet <UUID> uncertainAssetsUUIDs)
        {
            m_log.InfoFormat("[ARCHIVER]: Writing region {0}", scene.Name);

            EntityBase[]            entities     = scene.GetEntities();
            List <SceneObjectGroup> sceneObjects = new List <SceneObjectGroup>();

            int numObjectsSkippedPermissions = 0;

            // Filter entities so that we only have scene objects.
            // FIXME: Would be nicer to have this as a proper list in SceneGraph, since lots of methods
            // end up having to do this
            IPermissionsModule permissionsModule = scene.RequestModuleInterface <IPermissionsModule>();

            foreach (EntityBase entity in entities)
            {
                if (entity is SceneObjectGroup)
                {
                    SceneObjectGroup sceneObject = entity as SceneObjectGroup;

                    if (!sceneObject.IsDeleted && !sceneObject.IsAttachment && !sceneObject.IsTemporary && !sceneObject.inTransit)
                    {
                        if (!CanUserArchiveObject(scene.RegionInfo.EstateSettings.EstateOwner, sceneObject, FilterContent, permissionsModule))
                        {
                            // The user isn't allowed to copy/transfer this object, so it will not be included in the OAR.
                            ++numObjectsSkippedPermissions;
                        }
                        else
                        {
                            sceneObjects.Add(sceneObject);
                        }
                    }
                }
            }

            if (SaveAssets)
            {
                UuidGatherer assetGatherer = new UuidGatherer(scene.AssetService, assetUuids, failedIDs, uncertainAssetsUUIDs);
                int          prevAssets    = assetUuids.Count;

                foreach (SceneObjectGroup sceneObject in sceneObjects)
                {
                    int curErrorCntr = assetGatherer.ErrorCount;
                    int possible     = assetGatherer.possibleNotAssetCount;
                    assetGatherer.AddForInspection(sceneObject);
                    assetGatherer.GatherAll();
                    curErrorCntr = assetGatherer.ErrorCount - curErrorCntr;
                    possible     = assetGatherer.possibleNotAssetCount - possible;
                    if (curErrorCntr > 0)
                    {
                        m_log.ErrorFormat("[ARCHIVER]: object {0} '{1}', at {2}, contains {3} references to missing or damaged assets",
                                          sceneObject.UUID, sceneObject.Name, sceneObject.AbsolutePosition.ToString(), curErrorCntr);
                        if (possible > 0)
                        {
                            m_log.WarnFormat("[ARCHIVER Warning]: object also contains {0} references that may not be assets or are missing", possible);
                        }
                    }
                    else if (possible > 0)
                    {
                        m_log.WarnFormat("[ARCHIVER Warning]: object {0} '{1}', at {2}, contains {3} references that may not be assets or are missing",
                                         sceneObject.UUID, sceneObject.Name, sceneObject.AbsolutePosition.ToString(), possible);
                    }
                }

                assetGatherer.GatherAll();

                GC.Collect();

                int errors = assetGatherer.FailedUUIDs.Count;
                m_log.DebugFormat(
                    "[ARCHIVER]: {0} region scene objects to save reference {1} possible assets",
                    sceneObjects.Count, assetUuids.Count - prevAssets + errors);
                if (errors > 0)
                {
                    m_log.DebugFormat("[ARCHIVER]: {0} of these have problems or are not assets and will be ignored", errors);
                }
            }

            if (numObjectsSkippedPermissions > 0)
            {
                m_log.DebugFormat(
                    "[ARCHIVER]: {0} scene objects skipped due to lack of permissions",
                    numObjectsSkippedPermissions);
            }

            // Make sure that we also request terrain texture assets
            RegionSettings regionSettings = scene.RegionInfo.RegionSettings;

            if (regionSettings.TerrainTexture1 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_1)
            {
                assetUuids[regionSettings.TerrainTexture1] = (sbyte)AssetType.Texture;
            }

            if (regionSettings.TerrainTexture2 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_2)
            {
                assetUuids[regionSettings.TerrainTexture2] = (sbyte)AssetType.Texture;
            }

            if (regionSettings.TerrainTexture3 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_3)
            {
                assetUuids[regionSettings.TerrainTexture3] = (sbyte)AssetType.Texture;
            }

            if (regionSettings.TerrainTexture4 != RegionSettings.DEFAULT_TERRAIN_TEXTURE_4)
            {
                assetUuids[regionSettings.TerrainTexture4] = (sbyte)AssetType.Texture;
            }

            if (scene.RegionEnvironment != null)
            {
                scene.RegionEnvironment.GatherAssets(assetUuids);
            }

            List <ILandObject> landObjects = scene.LandChannel.AllParcels();

            foreach (ILandObject lo in landObjects)
            {
                if (lo.LandData != null && lo.LandData.Environment != null)
                {
                    lo.LandData.Environment.GatherAssets(assetUuids);
                }
            }

            Save(scene, sceneObjects, regionDir);
            GC.Collect();
        }
示例#12
0
        public void ShowUI(EUiId nextUiId, SceneTransType transType = SceneTransType.Null, Transform parent = null, string EventTypeName = null, params object[] param)
        {
            Resources.UnloadUnusedAssets();
            GC.Collect();
            if (isInit)
            {
                AudioManager.Instance.PlayAudio();
            }
            if (!isInit)
            {
                isInit = true;
            }

            BaseUI currentUI = GetBaseUI(CurrentId);

            SceneTransition.ShowTranstion(transType,
                                          () =>
            {
                if (transType == SceneTransType.Newspaper)
                {
                }
            },
                                          () =>
            {
                if (currentUI != null && parent == null)
                {
                    //父级baseUI
                    EUiId parentUiId = EUiId.NullUI;
                    BaseUI parentUI  = currentUI.transform.GetComponentUpwards <BaseUI>();
                    if (parentUI != null)
                    {
                        parentUiId = parentUI.UiId;
                    }

                    BaseUI[] childUI = currentUI.GetComponentsInFirstHierarchyChildren <BaseUI>(true);

                    //如果父级有baseUI并且直接打开的是别的UI的话就删除
                    if (parentUiId != EUiId.NullUI && nextUiId != parentUiId)
                    {
                        Destroy(parentUI.gameObject);
                    }
                    else
                    {
                        Destroy(currentUI.gameObject);
                    }

                    RemoveUiId(CurrentId);
                    if (childUI != null)
                    {
                        for (int i = 0; i < childUI.Length; i++)
                        {
                            EUiId chiidUiId = childUI[i].UiId;
                            RemoveUiId(chiidUiId);
                        }
                    }
                    if (parentUiId != EUiId.NullUI && nextUiId != parentUiId)
                    {
                        RemoveUiId(parentUiId);
                    }
                }

                BaseUI baseUI = JudgeShowUI(nextUiId, parent);
                if (baseUI != null)
                {
                    baseUI.HideUI();
                    if (EventTypeName != null)
                    {
                        SwanEngine.Events.Dispatcher.Instance.DispathEvent(EventTypeName, param);
                    }
                    //CurrentId = nextUiId;
                    baseUI.ShowUI();

                    /* 到时候可能要改成这样,因为在OnEnable的时候Enable还为false,不能调用协程
                     * baseUI.ShowUI();
                     * if (EventTypeName != null)
                     *  SwanEngine.Events.Dispatcher.Instance.DispathEvent(EventTypeName, param);
                     */
                }
                CurrentId = nextUiId;
            });
            Resources.UnloadUnusedAssets();
            GC.Collect();
        }
示例#13
0
        public void ProcessRequest(HttpContext context)
        {
            this.MyUtility.InitLog("T24UpdateTransState");

            context.Response.Clear();
            context.Response.ContentType = "application/json";

            string json = string.Empty, data = string.Empty, message = string.Empty;

            SysCode code = SysCode.A000;

            XmlDocument xmlDoc = null;

            string xPath = string.Empty, strSql = string.Empty;

            List <IDataParameter> para = null;

            string USERID = string.Empty, SESSION_KEY = string.Empty, TRANS_STATE = string.Empty;

            string year_and_month = DateTime.Now.ToString("yyyyMM");

            DataTable dt = null;

            int result = -1;

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

            try
            {
                #region 取得參數

                data = context.GetRequest("data");

                if (String.IsNullOrEmpty(data))
                {
                    throw new Utility.ProcessException(string.Format("參數為空值"), ref code, SysCode.E004);
                }

                this.MyUtility.WriteLog(Mode.LogMode.DEBUG, context, string.Format("DATA.JSON:{0}", data));

                #endregion

                xmlDoc = JsonConvert.DeserializeXmlNode(data);

                XmlNode xmlNodeProcessInfo = xmlDoc.SelectSingleNode(xPath = string.Format("./CHANGINGTEC/PROCESS_INFO"));

                if (xmlNodeProcessInfo == null)
                {
                    throw new Utility.ProcessException(xPath, ref code, SysCode.E003);
                }

                SESSION_KEY = xmlNodeProcessInfo.SelectSingleNode("SESSION_KEY", ref code);

                TRANS_STATE = xmlNodeProcessInfo.SelectSingleNode("TRANS_STATE", ref code);

                this.MyUtility.WriteLog(Mode.LogMode.INFO, context, string.Format("SESSION_KEY:{0}", SESSION_KEY));

                this.MyUtility.DBLog(context, SysCode.A001, "T24UpdateTransState", SESSION_KEY, USERID, string.Empty);

                bool is_delete = TRANS_STATE.Trim().ToUpper().Equals("DELE");

                this.MyUtility.CheckAndCreateTable(context, year_and_month, ref code);

                strSql = this.MyUtility.Select.CASE_TABLE_T24_Trans(year_and_month, SESSION_KEY, ref para);

                #region SQL Debug

                this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql);

                this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog());

                #endregion

                dt = this.MyUtility.DBConnTransac.GeneralSqlCmd.ExecuteToDataTable(strSql, para);

                this.MyUtility.WriteLog(Mode.LogMode.INFO, context, string.Format("dt.Rows.Count:{0}", dt.Rows.Count.ToString()));

                bool case_data_check = dt != null && dt.Rows.Count > 0;

                if (!case_data_check)
                {
                    year_and_month = year_and_month.GetPreviousYM();

                    strSql = this.MyUtility.Select.CASE_TABLE_T24_Trans(year_and_month, SESSION_KEY, ref para);

                    #region SQL Debug

                    this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql);

                    this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog());

                    #endregion

                    dt = this.MyUtility.DBConnTransac.GeneralSqlCmd.ExecuteToDataTable(strSql, para);

                    case_data_check = dt != null && dt.Rows.Count > 0;
                }
                if (!case_data_check)
                {
                    throw new Utility.ProcessException(string.Format("查詢資料不存在"), ref code, SysCode.E007);
                }

                if (is_delete)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i]["CASE_STATE"].ToString() == "0")
                        {
                            strSql = this.MyUtility.Update.FILE_TABLE_STOP(year_and_month, dt.Rows[i]["SESSION_KEY"].ToString(), ref para);

                            #region SQL Debug

                            this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql);

                            this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog());

                            #endregion

                            result = this.MyUtility.DBConnTransac.GeneralSqlCmd.ExecuteNonQuery(strSql, para);

                            this.MyUtility.WriteLog(Mode.LogMode.INFO, context, string.Format("Result:{0}", result));
                        }
                    }
                }
                this.MyUtility.WriteLog(Mode.LogMode.INFO, context, string.Format("TRANS_STATE:{0}", TRANS_STATE));

                strSql = this.MyUtility.Update.CASE_TABLE_T24_TRANS_STATE_Trans(year_and_month, SESSION_KEY, TRANS_STATE.ToUpper(), USERID, ref para);

                #region SQL Debug

                this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, strSql);

                this.MyUtility.WriteLog(Log.Mode.LogMode.DEBUG, context, para.ToLog());

                #endregion

                result = this.MyUtility.DBConnTransac.GeneralSqlCmd.ExecuteNonQuery(strSql, para);

                this.MyUtility.WriteLog(Mode.LogMode.INFO, context, string.Format("Result:{0}", result));

                this.MyUtility.DBConnTransac.GeneralSqlCmd.Transaction.Commit();

                this.MyUtility.DBLog(context, SysCode.A002, "T24UpdateTransState", SESSION_KEY, USERID, string.Empty);
            }
            catch (System.Exception ex)
            {
                this.MyUtility.Rollback();

                message = ex.Message;

                this.MyUtility.WriteLog(Mode.LogMode.ERROR, context, ex.ToString());

                code = !code.Equals(SysCode.A000) ? code : SysCode.E999;

                this.MyUtility.DBLog(context, code, "T24UpdateTransState", SESSION_KEY, USERID, ex.Message);

                this.MyUtility.SendEMail(context, "T24UpdateTransState", SESSION_KEY, code);
            }
            finally
            {
                json = JsonConvert.SerializeObject(new T24UPDATE_STATE_RESPOSE_RESPOSE()
                {
                    CHANGINGTEC = new T24UPDATE_STATE_RESPOSE_SYSTEM_CLASS()
                    {
                        SYSTEM = new SYSTEM_INFO_CLASS()
                        {
                            CODE    = code.ToString(),
                            MESSAGE = message.EncryptBase64()
                        }
                    }
                });
                dt = null;

                xmlDoc = null;

                para = null;

                this.MyUtility.CloseConnTransac();

                xmlDoc = null;

                GC.Collect(); GC.WaitForPendingFinalizers();

                context.Response.Write(json);
                context.Response.End();
            }
        }
示例#14
0
        void RunRenderWindow()
        {
            bool winStarted = false;
            Task winthread  = new Task(() =>
            {
                win        = new RenderWindow(renderer, midifile, settings);
                winStarted = true;
                win.Run();
            });

            winthread.Start();
            SpinWait.SpinUntil(() => winStarted);
            double    time      = 0;
            int       nc        = -1;
            long      maxRam    = 0;
            long      avgRam    = 0;
            long      ramSample = 0;
            Stopwatch timewatch = new Stopwatch();

            timewatch.Start();
            IPluginRender render      = null;
            double        lastWinTime = double.NaN;

            bool tryToParse()
            {
                lock (midifile)
                {
                    return((midifile.ParseUpTo((win.midiTime + win.lastDeltaTimeOnScreen +
                                                (win.tempoFrameStep * 20 * settings.tempoMultiplier * (win.lastMV > 1 ? win.lastMV : 1)))) ||
                            nc != 0) && settings.running);
                }
            }

            try
            {
                while (tryToParse())
                {
                    //SpinWait.SpinUntil(() => lastWinTime != win.midiTime || render != renderer.renderer || !settings.running);
                    if (!settings.running)
                    {
                        break;
                    }
                    Note   n;
                    double cutoffTime          = win.midiTime;
                    bool   manualDelete        = false;
                    double noteCollectorOffset = 0;
                    bool   receivedInfo        = false;
                    while (!receivedInfo)
                    {
                        try
                        {
                            render       = renderer.renderer;
                            receivedInfo = true;
                        }
                        catch
                        { }
                    }
                    manualDelete        = render.ManualNoteDelete;
                    noteCollectorOffset = render.NoteCollectorOffset;
                    cutoffTime         += noteCollectorOffset;
                    if (!settings.running)
                    {
                        break;
                    }
                    lock (midifile.globalDisplayNotes)
                    {
                        var i = midifile.globalDisplayNotes.Iterate();
                        if (manualDelete)
                        {
                            while (i.MoveNext(out n))
                            {
                                if (n.delete)
                                {
                                    i.Remove();
                                }
                                else
                                {
                                    nc++;
                                }
                            }
                        }
                        else
                        {
                            while (i.MoveNext(out n))
                            {
                                if (n.hasEnded && n.end < cutoffTime)
                                {
                                    i.Remove();
                                }
                                if (n.start > cutoffTime)
                                {
                                    break;
                                }
                            }
                        }
                        GC.Collect();
                    }
                    try
                    {
                        double progress = win.midiTime / midifile.maxTrackTime;
                        if (settings.timeBasedNotes)
                        {
                            progress = win.midiTime / 1000 / midifile.info.secondsLength;
                        }
                        Console.WriteLine(
                            Math.Round(progress * 10000) / 100 +
                            "\tNotes drawn: " + renderer.renderer.LastNoteCount +
                            "\tRender FPS: " + Math.Round(settings.liveFps) + "        "
                            );
                    }
                    catch
                    {
                    }
                    long ram = Process.GetCurrentProcess().PrivateMemorySize64;
                    if (maxRam < ram)
                    {
                        maxRam = ram;
                    }
                    avgRam = (long)((double)avgRam * ramSample + ram) / (ramSample + 1);
                    ramSample++;
                    lastWinTime = win.midiTime;
                    Stopwatch s = new Stopwatch();
                    s.Start();
                    SpinWait.SpinUntil(() =>
                                       (
                                           s.ElapsedMilliseconds > 1000.0 / settings.fps * 10 ||
                                           win.midiTime + win.lastDeltaTimeOnScreen + (win.tempoFrameStep * 10 * settings.tempoMultiplier * win.lastMV) > midifile.currentSyncTime ||
                                           lastWinTime != win.midiTime || render != renderer.renderer || !settings.running
                                       )
                                       );;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("An error occurred while opeining render window. Please try again.\n\n" + ex.Message + "\n" + ex.StackTrace);
                settings.running = false;
            }
            winthread.GetAwaiter().GetResult();
            settings.running = false;
            Console.WriteLine("Reset midi file");
            midifile.Reset();
            win.Dispose();
            win = null;
            GC.Collect();
            GC.WaitForFullGCComplete();
            Console.ForegroundColor = ConsoleColor.Blue;
            Console.WriteLine(
                "Finished render\nRAM usage (Private bytes)\nPeak: " + Math.Round((double)maxRam / 1000 / 1000 / 1000 * 100) / 100 +
                "GB\nAvg: " + Math.Round((double)avgRam / 1000 / 1000 / 1000 * 100) / 100 +
                "GB\nMinutes to render: " + Math.Round((double)timewatch.ElapsedMilliseconds / 1000 / 60 * 100) / 100);
            Console.ResetColor();
            Dispatcher.Invoke(() =>
            {
                Resources["notRendering"]  = true;
                Resources["notPreviewing"] = true;
            });
        }
示例#15
0
 static void EnableGC()
 {
     GarbageCollector.GCMode = GarbageCollector.Mode.Enabled;
     // Trigger a collection to free memory.
     GC.Collect();
 }
示例#16
0
            // Early code... index a full zip archive.
            public static async void LoadZIPDirectory(string folder = @"d:\beatsaver")
            {
                if (MapDatabase.DatabaseLoading)
                {
                    return;
                }

                await Task.Run(() =>
                {
                    var startingmem = GC.GetTotalMemory(true);

                    Instance.QueueChatMessage($"Starting to read archive.");
                    int addcount = 0;
                    var StarTime = DateTime.Now;

                    var di = new DirectoryInfo(folder);

                    foreach (FileInfo f in di.GetFiles("*.zip"))
                    {
                        try
                        {
                            var x    = System.IO.Compression.ZipFile.OpenRead(f.FullName);
                            var info = x.Entries.First <ZipArchiveEntry>(e => (e.Name.EndsWith("info.json")));

                            string id      = "";
                            string version = "";
                            GetIdFromPath(f.Name, ref id, ref version);

                            if (MapDatabase.MapLibrary.ContainsKey(id))
                            {
                                if (MapLibrary[id].path != "")
                                {
                                    MapLibrary[id].path = f.FullName;
                                }
                                continue;
                            }

                            JSONObject song = JSONObject.Parse(readzipjson(x)).AsObject;

                            string hash;

                            JSONNode difficultylevels = song["difficultyLevels"].AsArray;
                            var FileAccumulator       = new StringBuilder();
                            foreach (var level in difficultylevels)
                            {
                                try
                                {
                                    FileAccumulator.Append(readzipjson(x, level.Value));
                                }
                                catch
                                {
                                    //Instance.QueueChatMessage($"key={level.Key} value={level.Value}");
                                    //throw;
                                }
                            }

                            hash = CreateMD5FromString(FileAccumulator.ToString());

                            string levelId = string.Join("∎", hash, song["songName"].Value, song["songSubName"].Value, song["authorName"], song["beatsPerMinute"].AsFloat.ToString()) + "∎";

                            if (LevelId.ContainsKey(levelId))
                            {
                                LevelId[levelId].path = f.FullName;
                                continue;
                            }

                            addcount++;

                            song.Add("id", id);
                            song.Add("version", version);
                            song.Add("hashMd5", hash);

                            new SongMap(song, levelId, f.FullName);

                            x = null;
                        }
                        catch (Exception)
                        {
                            Instance.QueueChatMessage($"Failed to process {f.FullName}");
                            //Instance.QueueChatMessage(ex.ToString());
                        }
                    }
                    Instance.QueueChatMessage($"Archive indexing done, {addcount} files added. ({(DateTime.Now-StarTime).TotalSeconds} secs.");
                    GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
                    GC.Collect();
                    Instance.QueueChatMessage($"hashentries: {SongMap.hashcount} memory: {(GC.GetTotalMemory(false) - startingmem) / 1048576} MB");
                });


                MapDatabase.DatabaseLoading = false;
            }
示例#17
0
        public void saveToFile(long lenghtOutputByteArray, List <string> items, string path, Mixer mixer)
        {
            Wave outputWave = new Wave();
            Wave chunkWave  = new Wave();

            byte[] outputArray = new byte[lenghtOutputByteArray];
            long   iterator    = 0;

            foreach (string chunk in items)
            {
                //get patametest from file to var in object
                chunkWave.WaveHeaderIN(fileStream[chunk]);
                outputWave.addWave(chunkWave);

                for (int i = 0; i < lenghtArrayByte[chunk]; i++)
                {
                    outputArray[iterator] = fileByte[chunk][i];
                    iterator++;
                }
            }

            if (items.Count <= 0)
            {
                return;
            }

            //set headers in output file from first item
            chunkWave.WaveHeaderIN(fileStream[items[0]]);

            FileStream outputFile;

            if (!File.Exists(soundTmpTrack + fileOuptutWavName))
            {
                outputFile = new FileStream(soundTmpTrack + fileOuptutWavName, FileMode.Create);
                outputFile.Close();
            }
            outputFile = new FileStream(soundTmpTrack + fileOuptutWavName, FileMode.Open, FileAccess.Write);
            BinaryWriter binaryWriter = new BinaryWriter(outputFile);

            outputWave.BitsPerSample = chunkWave.BitsPerSample;
            outputWave.channels      = chunkWave.channels;
            outputWave.samplerate    = chunkWave.samplerate;
            outputWave.WaveHeaderOUT(outputFile, binaryWriter);

            outputFile.Close();
            binaryWriter.Close();

            //save raw data to output file
            outputFile   = new FileStream(soundTmpTrack + fileOuptutWavName, FileMode.Append, FileAccess.Write);
            binaryWriter = new BinaryWriter(outputFile);

            binaryWriter.Write(outputArray);


            // close output file
            binaryWriter.Close();
            outputFile.Close();

            binaryWriter = null;
            outputFile   = null;
            outputArray  = null;
            GC.Collect();

            bool isMixed = mixer.makeLoud(soundTmpTrack + fileOuptutWavName, soundTmpTrack + fileMix);

            //convert wave to mp3
            Process cmd = new Process();

            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.RedirectStandardInput  = true;
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.CreateNoWindow         = true;
            cmd.StartInfo.UseShellExecute        = false;
            cmd.Start();
            if (isMixed)
            {
                cmd.StandardInput.WriteLine(
                    "lame -b " + kbpsInMp3.ToString() + " " + soundTmpTrack + fileMix + " " + path
                    );
            }
            else
            {
                cmd.StandardInput.WriteLine(
                    "lame -b " + kbpsInMp3.ToString() + " " + soundTmpTrack + fileOuptutWavName + " " + path
                    );
            }

            cmd.StandardInput.Flush();
            cmd.StandardInput.Close();
            cmd.WaitForExit();
        }
示例#18
0
        /// <summary>
        /// 检查炸弹爆炸时的伤害
        /// </summary>
        /// <returns>是否炸到玩家</returns>
        private bool CheckBlast(List <Cell> SmokePoints, Graphics UnityGraphics)
        {
            int       EnemyIndex = 0;
            Rectangle TempRectangle;

            while (EnemyIndex >= 0 && EnemyIndex < EnemyList.Count)
            {
                foreach (Cell SmokePoint in SmokePoints)
                {
                    TempRectangle = new Rectangle(EnemyList[EnemyIndex].Location, GameMap.CellSize);
                    TempRectangle.Intersect(new Rectangle(SmokePoint.Location, GameMap.CellSize));
                    if ((double)(TempRectangle.Width * TempRectangle.Height) / (double)(GameMap.CellSize.Width * GameMap.CellSize.Width) > 0.3)
                    {
                        lock (EnemyDeadCellImage)
                        {
                            UnityGraphics.DrawImageUnscaled(EnemyDeadCellImage, EnemyList[EnemyIndex].Location);
                            EnemyList[EnemyIndex].Dispose();//结束敌人的巡逻线程,否则不会释放内存
                            EnemyList[EnemyIndex].Patrol -= new EnemyModel.PatrolEventHander(EnemyPatrol);
                            EnemyList.RemoveAt(EnemyIndex);
                            EnemyIndex--;
                            break;
                        }
                    }
                }
                EnemyIndex++;
            }
            //if (((List<Cell>)SmokePoints).FirstOrDefault(X => new Rectangle(X.Location,GameMap.CellSize).IntersectsWith(new Rectangle(EnemyList[EnemyIndex].Location,GameMap.CellSize))) != null)
            //{
            //    //Debug.Print("敌人 {0} : {1},{2} 被炸伤,退出战场!剩余敌人总数:{3}", EnemyIndex, EnemyList[EnemyIndex].TabelLocation.X, EnemyList[EnemyIndex].TabelLocation.Y, EnemyList.Count - 1);
            //    lock(EnemyDeadCellImage)
            //        UnityGraphics.DrawImageUnscaled(EnemyDeadCellImage, EnemyList[EnemyIndex].Location);
            //    EnemyList[EnemyIndex].Dispose();//结束敌人的巡逻线程,否则不会释放内存
            //    EnemyList[EnemyIndex].Patrol -= new EnemyModel.PatrolEventHander(EnemyPatrol);
            //    EnemyList.RemoveAt(EnemyIndex);
            //}
            //else
            //    EnemyIndex++;
            GC.Collect();
#if (!God)
            foreach (Cell SmokePoint in SmokePoints)
            {
                TempRectangle = new Rectangle(SmokePoint.Location, GameMap.CellSize);
                TempRectangle.Intersect(new Rectangle(Player.Location, GameMap.CellSize));
                if ((double)(TempRectangle.Width * TempRectangle.Height) / (double)(GameMap.CellSize.Width * GameMap.CellSize.Width) > 0.3)
                {
                    //Debug.Print("玩家被炸弹炸伤,重新开始游戏!");
                    UnityGraphics.DrawImage(UnityResource.Player_Lose, new Rectangle(Player.Location, GameMap.CellSize));
                    StopGame();
                    MessageBox.Show(this, "玩家被炸弹炸伤!游戏结束!");
                    ResetGame();
                    return(true);
                }
            }
#endif
#if (Fly)
            this.CreateGraphics().DrawImageUnscaled(PlayerCellImage, Player.Location);
#endif
            return(false);

            //if (((List<Cell>)SmokePoints).FirstOrDefault(X => new Rectangle(X.Location, GameMap.CellSize).IntersectsWith(new Rectangle(Player.Location, GameMap.CellSize))) != null)
            //{
            //    //Debug.Print("玩家被炸弹炸伤,重新开始游戏!");
            //    UnityGraphics.DrawImage(UnityResource.Player_Lose, new Rectangle(Player.Location, GameMap.CellSize));
            //    StopGame();
            //    MessageBox.Show("玩家被炸弹炸伤!游戏结束!");
            //    ResetGame();
            //    return true;
            //}
            //else
            //    return false;
        }
示例#19
0
 private void btnGC_Click(object sender, EventArgs e)
 {
     GC.Collect();
 }
示例#20
0
 private void GameForm_Load(object sender, EventArgs e)
 {
     this.Icon            = UnityResource.BomberMan;
     this.BackgroundImage = GameMap.Ground;
     GC.Collect();
 }
        public override bool Play(string strFile)
        {
            _isCDA       = false;
            _graphState  = PlayState.Init;
            _currentFile = strFile;

            Log.Info("AudioPlayerWMP9: Disabling DX9 exclusive mode");
            GUIMessage msg = new GUIMessage(GUIMessage.MessageType.GUI_MSG_SWITCH_FULL_WINDOWED, 0, 0, 0, 0, 0, null);

            GUIWindowManager.SendMessage(msg);

            _notifyPlaying = true;
            GC.Collect();
            CreateInstance();

            LoadStreamingSettings();

            if (_wmp10Player == null)
            {
                return(false);
            }
            if (_wmp10Player.cdromCollection == null)
            {
                return(false);
            }
            VideoRendererStatistics.VideoState = VideoRendererStatistics.State.VideoPresent;

            _wmp10Player.PlayStateChange += new _WMPOCXEvents_PlayStateChangeEventHandler(OnPlayStateChange);

            _wmp10Player.Buffering += new _WMPOCXEvents_BufferingEventHandler(OnBuffering);

            //_wmp10Player.enableContextMenu = false;
            //_wmp10Player.Ctlenabled = false;
            if (strFile.IndexOf("cdda:") >= 0)
            {
                string strTrack = strFile.Substring(5);
                int    iTrack   = Convert.ToInt32(strTrack);
                if (_wmp10Player.cdromCollection.count <= 0)
                {
                    return(false);
                }
                if (_wmp10Player.cdromCollection.Item(0).Playlist == null)
                {
                    return(false);
                }
                if (iTrack > _wmp10Player.cdromCollection.Item(0).Playlist.count)
                {
                    return(false);
                }
                _wmp10Player.currentMedia = _wmp10Player.cdromCollection.Item(0).Playlist.get_Item(iTrack - 1);
                if (_wmp10Player.currentMedia == null)
                {
                    return(false);
                }
                _isCDA = true;
                Log.Info("Audioplayer: play track:{0}/{1}", iTrack, _wmp10Player.cdromCollection.Item(0).Playlist.count);
            }
            else if (strFile.IndexOf(".cda") >= 0)
            {
                string strTrack = "";
                int    pos      = strFile.IndexOf(".cda");
                if (pos >= 0)
                {
                    pos--;
                    while (Char.IsDigit(strFile[pos]) && pos > 0)
                    {
                        strTrack = strFile[pos] + strTrack;
                        pos--;
                    }
                }

                if (_wmp10Player.cdromCollection.count <= 0)
                {
                    return(false);
                }
                string strDrive = strFile.Substring(0, 1);
                strDrive += ":";
                int iCdRomDriveNr = 0;
                while ((_wmp10Player.cdromCollection.Item(iCdRomDriveNr).driveSpecifier != strDrive) &&
                       (iCdRomDriveNr < _wmp10Player.cdromCollection.count))
                {
                    iCdRomDriveNr++;
                }

                int iTrack = Convert.ToInt32(strTrack);
                if (_wmp10Player.cdromCollection.Item(iCdRomDriveNr).Playlist == null)
                {
                    return(false);
                }
                int tracks = _wmp10Player.cdromCollection.Item(iCdRomDriveNr).Playlist.count;
                if (iTrack > tracks)
                {
                    return(false);
                }
                _wmp10Player.currentMedia = _wmp10Player.cdromCollection.Item(iCdRomDriveNr).Playlist.get_Item(iTrack - 1);
                if (_wmp10Player.currentMedia == null)
                {
                    return(false);
                }

                /*
                 * string strStart=strFile.Substring(0,2)+@"\";
                 * int ipos=strFile.LastIndexOf("+");
                 * if (ipos >0) strStart += strFile.Substring(ipos+1);
                 * strFile=strStart;
                 * _currentFile=strFile;
                 * Log.Info("Audioplayer:play {0}", strFile);*/
                //_wmp10Player.URL=strFile;
                _currentFile = strFile;
                _isCDA       = true;
            }
            else
            {
                Log.Info("Audioplayer:play {0}", strFile);
                _wmp10Player.URL = strFile;
            }
            _wmp10Player.Ctlcontrols.play();
            _wmp10Player.ClientSize = new Size(0, 0);
            _wmp10Player.Visible    = false;

            // When file is internetstream
            if (_wmp10Player.URL.StartsWith("http") || _wmp10Player.URL.StartsWith("mms") ||
                _wmp10Player.URL.StartsWith("HTTP") || _wmp10Player.URL.StartsWith("MMS"))
            {
                _bufferCompleted = false;
                using (WaitCursor waitcursor = new WaitCursor())
                {
                    GUIGraphicsContext.Overlay = false;
                    while (_bufferCompleted != true)
                    {
                        {
                            // if true then could not load stream
                            if (_wmp10Player.playState.Equals(WMPPlayState.wmppsReady))
                            {
                                _bufferCompleted = true;
                            }
                            if (GUIGraphicsContext.Overlay)
                            {
                                GUIGraphicsContext.Overlay = false;
                            }
                            _graphState = PlayState.Playing;
                            GUIWindowManager.Process();
                        }
                    }
                    GUIGraphicsContext.Overlay = true;
                }
                if (_bufferCompleted && _wmp10Player.playState.Equals(WMPPlayState.wmppsReady))
                {
                    Log.Info("Audioplayer: failed to load {0}", strFile);
                    return(false);
                }
            }

            GUIMessage msgPb = new GUIMessage(GUIMessage.MessageType.GUI_MSG_PLAYBACK_STARTED, 0, 0, 0, 0, 0, null);

            msgPb.Label = strFile;

            GUIWindowManager.SendThreadMessage(msgPb);
            _graphState = PlayState.Playing;
            GC.Collect();
            _needUpdate   = true;
            _isFullScreen = GUIGraphicsContext.IsFullScreenVideo;
            _positionX    = GUIGraphicsContext.VideoWindow.Left;
            _positionY    = GUIGraphicsContext.VideoWindow.Top;
            _videoWidth   = GUIGraphicsContext.VideoWindow.Width;
            _videoHeight  = GUIGraphicsContext.VideoWindow.Height;

            SetVideoWindow();

            return(true);
        }
示例#22
0
 /// <summary>
 /// Disposes the engine.
 /// </summary>
 public void Dispose()
 {
     GC.Collect();
     GC.WaitForPendingFinalizers();
     GC.Collect();
 }
示例#23
0
        private void ExecutePatch(string patchFile, string msFolder, bool prePatch)
        {
            WzPatcher patcher = null;

            advTreePatchFiles.Nodes.Clear();
            txtNotice.Clear();
            txtPatchState.Clear();
            try
            {
                patcher = new WzPatcher(patchFile);
                patcher.PatchingStateChanged += new EventHandler <PatchingEventArgs>(patcher_PatchingStateChanged);
                AppendStateText("패치확인중 ");
                patcher.OpenDecompress();
                AppendStateText("성공\r\n");
                if (prePatch)
                {
                    AppendStateText("패치준비중 \r\n");
                    long decompressedSize = patcher.PrePatch();
                    AppendStateText(string.Format("패치용량: {0:N0} bytes \r\n", decompressedSize));
                    AppendStateText(string.Format("패치갯수: {0} 개 \r\n",
                                                  patcher.PatchParts == null ? -1 : patcher.PatchParts.Count));
                    txtNotice.Text = patcher.NoticeText;
                    foreach (PatchPartContext part in patcher.PatchParts)
                    {
                        advTreePatchFiles.Nodes.Add(CreateFileNode(part));
                    }
                    advTreePatchFiles.Enabled = true;
                    AppendStateText("패치파일을 선택 후 패치를 눌러주세요. \r\n");
                    waiting = true;
                    waitHandle.WaitOne();
                    advTreePatchFiles.Enabled = false;
                    patcher.PatchParts.Clear();
                    for (int i = 0, j = advTreePatchFiles.Nodes.Count; i < j; i++)
                    {
                        if (advTreePatchFiles.Nodes[i].Checked)
                        {
                            patcher.PatchParts.Add(advTreePatchFiles.Nodes[i].Tag as PatchPartContext);
                        }
                    }
                }
                AppendStateText("패치중 \r\n");
                DateTime time = DateTime.Now;
                patcher.Patch(msFolder);
                TimeSpan interval = DateTime.Now - time;
                MessageBoxEx.Show(this, "패치완료,시간" + interval.ToString(), "Patcher");
            }
            catch (ThreadAbortException)
            {
                MessageBoxEx.Show("패치중단。", "Patcher");
            }
            catch (Exception ex)
            {
                MessageBoxEx.Show(this, ex.ToString(), "Patcher");
            }
            finally
            {
                if (patcher != null)
                {
                    patcher.Close();
                    patcher = null;
                }
                patchThread = null;
                waitHandle  = null;
                GC.Collect();

                panelEx2.Visible        = false;
                expandablePanel2.Height = 157;
            }
        }
示例#24
0
 private void Btn_close_Click(object sender, EventArgs e)
 {
     GC.Collect();
     this.Hide();
 }
示例#25
0
        public void RunPPTMacro(string pptFileName, string excelFile, string macro, bool visible)
        {
            //### improve & cleanup code

            // Define Workbooks
            PowerPoint.Application   oPP         = null;
            PowerPoint.Presentations oPresSet    = null;
            PowerPoint._Presentation _activePres = null;
            object oMissing = System.Reflection.Missing.Value;

            string mess = "";

            try
            {
                //open Excel
                //System.Diagnostics.Process excelProc = System.Diagnostics.Process.Start(excelFile);

                Excel2.Application oExcel = new Excel2.Application();
                oExcel.Visible       = false;
                oExcel.DisplayAlerts = false;
                Excel2.Workbooks oBooks = oExcel.Workbooks;
                Excel2._Workbook oBook  = oBooks.Open(excelFile, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,
                                                      oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);

                FileInfo fi = new FileInfo(pptFileName);

                //string pptTempName = fi.DirectoryName + @"\TEMP.pptm";

                oPP = new PowerPoint.Application();
                oPP.DisplayAlerts = Microsoft.Office.Interop.PowerPoint.PpAlertLevel.ppAlertsNone;
                //oPP.Visible = MsoTriState.msoFalse;

                oPresSet    = oPP.Presentations;
                _activePres = oPresSet.Open(fi.FullName, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoTrue);

                //Object[] oRunArgs = { "'" + fi.Name + "'!M2" };
                Object[] oRunArgs = { "'" + fi.Name + "'!" + macro };
                oPP.GetType().InvokeMember("Run", System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod, null,
                                           oPP, oRunArgs);

                //close Excel
                try
                {
                    //excelProc.CloseMainWindow();
                    //excelProc.Close();
                    //excelProc.Dispose();
                    //excelProc.Kill();
                }
                catch (Exception exCloseExcel)
                {
                    //excelProc.Kill();
                }

                //save excel file
                //oBook.Save();

                // Quit Excel and clean up.
                Thread.Sleep(1000);
                oBook.Close(false, oMissing, oMissing);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBook);
                oBook = null;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oBooks);
                oBooks = null;
                oExcel.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel);
                oExcel = null;


                mess += "kill excel" + Environment.NewLine;

                //_activePres.Final = false;

                Thread.Sleep(2000);

                _activePres.Save();

                //_activePres.SaveAs(pptTempName);

                mess += "save ppt temp" + Environment.NewLine;

                Thread.Sleep(2000);

                //_activePres.Final = true;

                // Quit PPT and clean up.
                if (_activePres != null)
                {
                    mess += "check activepres = null" + Environment.NewLine;
                    try
                    {
                        _activePres.Close();
                        mess += "activepres close" + Environment.NewLine;
                    }
                    catch (Exception exClosePresentation) { }

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(_activePres);
                    mess       += "release activepres" + Environment.NewLine;
                    _activePres = null;
                    mess       += "activepres = null" + Environment.NewLine;
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oPresSet);
                    mess    += "release presset" + Environment.NewLine;
                    oPresSet = null;
                    mess    += "presset null" + Environment.NewLine;
                    try
                    {
                        Thread.Sleep(1000);
                        oPP.Quit();
                        mess += "opp quit" + Environment.NewLine;
                    }
                    catch (Exception exQuitPPT) { }

                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oPP);
                    mess += "release opp" + Environment.NewLine;
                    oPP   = null;
                    mess += "opp = null" + Environment.NewLine;
                }

                GC.Collect();
                mess += "garbage" + Environment.NewLine;

                //Kill PPT File
                var processes = from p in Process.GetProcessesByName("POWERPNT") select p;

                foreach (var process in processes)
                {
                    //if (process.MainWindowTitle == "TEMP.pptm")
                    try
                    {
                        mess += "test process null" + Environment.NewLine;
                        if (process != null)
                        {
                            process.Close();
                            Thread.Sleep(1000);
                            mess += "close process" + Environment.NewLine;

                            if (process != null)
                            {
                                process.Kill();
                                mess += "kil process" + Environment.NewLine;
                            }
                        }
                    }
                    catch (Exception exCloseProc) { }
                }

                //rename file & delete temp file
                //if (File.Exists(pptFileName))
                //{
                //    File.Delete(pptFileName);
                //    mess += "delete ppt" + Environment.NewLine;
                //    File.Move(pptTempName, pptFileName);
                //    mess += "move temp" + Environment.NewLine;
                //}

                //if (File.Exists(pptTempName))
                //    File.Delete(pptTempName);
                //mess += "delete temp" + Environment.NewLine;
            }
            catch (Exception ex)
            {
                if (_activePres != null)
                {
                    try
                    {
                        _activePres.Close();
                    }
                    catch (Exception ex2) { }
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oPresSet);
                    oPresSet = null;
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(_activePres);
                    _activePres = null;
                }

                if (oPP != null)
                {
                    try
                    {
                        oPP.Quit();
                    }
                    catch (Exception ex2) { }
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(oPP);
                    oPP = null;
                }

                log.Error("Error :: RunPPTMacro : " + ex.Message);
                throw ex;
            }
        }
示例#26
0
        // [TestMethod] Temporarily disabled for bug 18866003
        public void ValidateLoadUnload()
        {
            /*
             * if (!PlatformConfiguration.IsOsVersionGreaterThan(OSVersion.Redstone2))
             * {
             *  Log.Warning("Skipping: Test has instability on rs1 and rs2. Tracked by bug 18919096");
             *  return;
             * }
             */

            // In this test, we will repeatedly put a repeater in and out
            // of the visual tree, under the same or a different parent.
            // And we will validate that the subscriptions and unsubscriptions to
            // the IRepeaterScrollingSurface events is done in sync.

            TestScrollingSurface scroller1       = null;
            TestScrollingSurface scroller2       = null;
            ItemsRepeater        repeater        = null;
            WeakReference        repeaterWeakRef = null;
            var renderingEvent = new ManualResetEvent(false);

            var unorderedLoadEvent = false;
            var loadCounter        = 0;
            var unloadCounter      = 0;

            int scroller1SubscriberCount = 0;
            int scroller2SubscriberCount = 0;

            RunOnUIThread.Execute(() =>
            {
                CompositionTarget.Rendering += (sender, args) =>
                {
                    renderingEvent.Set();
                };

                var host  = new Grid();
                scroller1 = new TestScrollingSurface()
                {
                    Tag = "Scroller 1"
                };
                scroller2 = new TestScrollingSurface()
                {
                    Tag = "Scroller 2"
                };
                repeater        = new ItemsRepeater();
                repeaterWeakRef = new WeakReference(repeater);

                repeater.Loaded += delegate
                {
                    Log.Comment("ItemsRepeater Loaded in " + ((FrameworkElement)repeater.Parent).Tag);
                    unorderedLoadEvent |= (++loadCounter > unloadCounter + 1);
                };
                repeater.Unloaded += delegate
                {
                    Log.Comment("ItemsRepeater Unloaded");
                    unorderedLoadEvent |= (++unloadCounter > loadCounter);
                };

                // Subscribers count should never go above 1 or under 0.
                var validateSubscriberCount = new Action(() =>
                {
                    Verify.IsLessThanOrEqual(scroller1SubscriberCount, 1);
                    Verify.IsGreaterThanOrEqual(scroller1SubscriberCount, 0);

                    Verify.IsLessThanOrEqual(scroller2SubscriberCount, 1);
                    Verify.IsGreaterThanOrEqual(scroller2SubscriberCount, 0);
                });

                scroller1.ConfigurationChangedAddFunc    = () => { ++scroller1SubscriberCount; validateSubscriberCount(); };
                scroller2.ConfigurationChangedAddFunc    = () => { ++scroller2SubscriberCount; validateSubscriberCount(); };
                scroller1.ConfigurationChangedRemoveFunc = () => { --scroller1SubscriberCount; validateSubscriberCount(); };
                scroller2.ConfigurationChangedRemoveFunc = () => { --scroller2SubscriberCount; validateSubscriberCount(); };

                scroller1.Content = repeater;
                host.Children.Add(scroller1);
                host.Children.Add(scroller2);

                Content = host;
            });

            IdleSynchronizer.Wait();
            Verify.IsTrue(renderingEvent.WaitOne(), "Waiting for rendering event");

            renderingEvent.Reset();
            Log.Comment("Putting repeater in and out of scroller 1 until we observe two out-of-sync loaded/unloaded events.");
            for (int i = 0; i < 2; ++i)
            {
                while (!unorderedLoadEvent)
                {
                    RunOnUIThread.Execute(() =>
                    {
                        // Validate subscription count for events + reset.
                        scroller1.Content = null;
                        scroller1.Content = repeater;
                    });
                    // For this issue to repro, we need to wait in such a way
                    // that we don't tick the UI thread. We can't use IdleSynchronizer here.
                    Task.Delay(16 * 3).Wait();
                }
                unorderedLoadEvent = false;
                Log.Comment("Detected an unordered load/unload event.");
            }

            IdleSynchronizer.Wait();
            Verify.IsTrue(renderingEvent.WaitOne(), "Waiting for rendering event");

            renderingEvent.Reset();
            RunOnUIThread.Execute(() =>
            {
                Verify.AreEqual(1, scroller1SubscriberCount);
                Verify.AreEqual(0, scroller2SubscriberCount);

                Log.Comment("Moving repeater from scroller 1 to scroller 2.");
                scroller1.Content = null;
                scroller2.Content = repeater;
            });

            IdleSynchronizer.Wait();
            Verify.IsTrue(renderingEvent.WaitOne(), "Waiting for rendering event");

            RunOnUIThread.Execute(() =>
            {
                Verify.AreEqual(0, scroller1SubscriberCount);
                Verify.AreEqual(1, scroller2SubscriberCount);

                Log.Comment("Moving repeater out of scroller 2.");
                scroller2.Content = null;
                repeater          = null;
            });

            Log.Comment("Waiting for repeater to get GCed.");
            for (int i = 0; i < 5 && repeaterWeakRef.IsAlive; ++i)
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
                IdleSynchronizer.Wait();
            }
            Verify.IsFalse(repeaterWeakRef.IsAlive);

            renderingEvent.Reset();
            RunOnUIThread.Execute(() =>
            {
                Verify.AreEqual(0, scroller1SubscriberCount);
                Verify.AreEqual(0, scroller2SubscriberCount);

                Log.Comment("Scroller raise IRepeaterScrollSurface.PostArrange. Make sure no one is subscribing to it.");
                scroller1.InvalidateArrange();
                scroller2.InvalidateArrange();
                Content.UpdateLayout();
            });

            IdleSynchronizer.Wait();
            Verify.IsTrue(renderingEvent.WaitOne(), "Waiting for rendering event");
        }
示例#27
0
        /// <summary>
        /// Do not run on main thread
        /// </summary>
        /// <param name="realms"></param>
        /// <param name="region"></param>
        /// <returns></returns>
        public static void Build(Dictionary <string, List <ConnectedRealm> > selected, FileStream stream, bool includeRegion = true)
        {
            const int MAX_GROUP_SIZE = 5000;

            string zero             = ((uint)0).ToBase93();
            string defaultSep       = ",";
            string regionData       = zero + zero;
            string zeroZero         = zero + zero;
            string zeroZeroZeroZero = zero + zero + zero + zero;

            using (StreamWriter writer = new StreamWriter(stream))
            {
                string directoryPath = DataSource.DirectoryPath;

                writer.WriteLine("local Ans = select(2, ...);");
                writer.WriteLine("local R = {};");
                writer.WriteLine("Ans.Realms = R;");
                writer.WriteLine("R.F = function(region, rid)");
                writer.WriteLine("\tlocal t = {};");
                writer.WriteLine("\tlocal s = {};");
                writer.WriteLine("\tlocal sd = {};");

                foreach (string region in selected.Keys)
                {
                    Dictionary <string, Dictionary <string, List <ItemGroup> > > all = new Dictionary <string, Dictionary <string, List <ItemGroup> > >();
                    List <ConnectedRealm> realms = selected[region];

                    string regID = "\"" + region.ToUpper() + "\"";
                    writer.WriteLine("\ts[" + regID + "] = {};");

                    KVDB regionDB = new KVDB(directoryPath, region);
                    if (includeRegion)
                    {
                        regionDB.Load();
                    }

                    for (int i = 0; i < realms.Count; ++i)
                    {
                        ConnectedRealm r = realms[i];
                        // skip selected region dbs
                        // since that is already handled above
                        if (region.Equals(r.realms.JoinNames()) || r.id < 0)
                        {
                            continue;
                        }

                        KVDB realm = new KVDB(directoryPath, region + "-" + r.id);
                        realm.Load();

                        foreach (Realm rr in r.realms)
                        {
                            List <string> names = rr.name.Values.Distinct().ToList();
                            foreach (string n in names)
                            {
                                writer.WriteLine("\tt[\"" + region.ToUpper() + "-" + n + "\"] = " + (i + 1) + ";");
                            }
                        }

                        foreach (string k in realm.Keys)
                        {
                            if (string.IsNullOrEmpty(k))
                            {
                                continue;
                            }

                            string d = realm.GetString(k);

                            if (string.IsNullOrEmpty(d))
                            {
                                continue;
                            }

                            string   rkey   = UnpackKey(k);
                            string[] split  = rkey.Split(":");
                            string   subkey = $"{split[0]}:{split[1]}";
                            Dictionary <string, List <ItemGroup> > groups = null;
                            all.TryGetValue(subkey, out groups);

                            groups ??= new Dictionary <string, List <ItemGroup> >();
                            all[subkey] = groups;

                            List <ItemGroup> group = null;
                            groups.TryGetValue(k, out group);
                            group ??= new List <ItemGroup>();
                            groups[k] = group;
                            group.Add(new ItemGroup(r, UnpackValues(d), i));
                        }

                        realm.Close();

                        GC.Collect();
                    }

                    if (includeRegion && regionDB.Keys.Count() > 0)
                    {
                        int tcount = 1;
                        int offset = 0;

                        Debug.WriteLine(regionDB.Keys.Count());

                        foreach (string k in regionDB.Keys)
                        {
                            Dictionary <string, List <ItemGroup> > subgroups = null;

                            if (string.IsNullOrEmpty(k))
                            {
                                continue;
                            }

                            string   rkey   = UnpackKey(k);
                            string[] split  = rkey.Split(":");
                            string   subkey = $"{split[0]}:{split[1]}";

                            all.TryGetValue(subkey, out subgroups);
                            subgroups ??= new Dictionary <string, List <ItemGroup> >();
                            all[subkey] = subgroups;
                            if (!subgroups.ContainsKey(k))
                            {
                                subgroups[k] = null;
                            }
                        }

                        GC.Collect();

                        Debug.WriteLine(all.Count);

                        foreach (string sk in all.Keys)
                        {
                            List <ItemGroup> g = null;

                            if (offset % MAX_GROUP_SIZE == 0)
                            {
                                writer.WriteLine($"\tsd[{tcount++}] = function()");
                            }

                            string results = "";

                            for (int i = 0; i < realms.Count; ++i)
                            {
                                string sep      = "";
                                string packData = "";

                                foreach (string k in all[sk].Keys)
                                {
                                    g = all[sk][k];

                                    string regionValue = regionDB.GetString(k);

                                    if (!string.IsNullOrEmpty(regionValue))
                                    {
                                        uint[] values = UnpackRegionValues(regionValue);
                                        regionData = values[0].ToBase93() + values[1].ToBase93();
                                    }
                                    else
                                    {
                                        regionData = zeroZero;
                                    }

                                    var r  = realms[i];
                                    var rg = g != null?g.Find(m => m.realm.id == r.id) : null;

                                    if (rg != null)
                                    {
                                        var rdat = rg.data;
                                        var dat  = rdat[1].ToBase93() + rdat[2].ToBase93() + rdat[3].ToBase93() + rdat[0].ToBase93() + regionData;
                                        packData += sep + UnpackKey(k) + defaultSep + dat;
                                    }
                                    else
                                    {
                                        var dat = zeroZeroZeroZero + regionData;
                                        packData += sep + UnpackKey(k) + defaultSep + dat;
                                    }

                                    sep = defaultSep;
                                }

                                results += $"{(results.Length > 0 ? defaultSep : string.Empty)}{WrapLuaBinary(packData)}";
                            }

                            writer.WriteLine($"\t\ts[{regID}][\"{sk}\"] = select(t[rid], {results});");
                            ++offset;

                            if (offset % MAX_GROUP_SIZE == 0)
                            {
                                writer.WriteLine("\tend;");
                            }
                        }

                        if (offset % MAX_GROUP_SIZE != 0)
                        {
                            writer.WriteLine("\tend;");
                        }
                    }
                    else
                    {
                        int tcount = 1;
                        int offset = 0;

                        foreach (string sk in all.Keys)
                        {
                            List <ItemGroup> g = null;

                            if (offset % MAX_GROUP_SIZE == 0)
                            {
                                writer.WriteLine($"\tsd[{tcount++}] = function()");
                            }

                            string results = "";

                            for (int i = 0; i < realms.Count; ++i)
                            {
                                string sep      = "";
                                string packData = "";

                                foreach (string k in all[sk].Keys)
                                {
                                    g = all[sk][k];

                                    var r  = realms[i];
                                    var rg = g != null?g.Find(m => m.realm.id == r.id) : null;

                                    if (rg != null)
                                    {
                                        var rdat = rg.data;
                                        var dat  = rdat[1].ToBase93() + rdat[2].ToBase93() + rdat[3].ToBase93() + rdat[0].ToBase93() + regionData;
                                        packData += sep + UnpackKey(k) + defaultSep + dat;
                                    }
                                    else
                                    {
                                        var dat = zeroZeroZeroZero + regionData;
                                        packData += sep + UnpackKey(k) + defaultSep + dat;
                                    }

                                    sep = defaultSep;
                                }

                                results += $"{(results.Length > 0 ? defaultSep : string.Empty)}{WrapLuaBinary(packData)}";
                            }

                            writer.WriteLine($"\t\ts[{regID}][\"{sk}\"] = select(t[rid], {results});");

                            ++offset;

                            if (offset % MAX_GROUP_SIZE == 0)
                            {
                                writer.WriteLine("\tend;");
                            }
                        }

                        if (offset % MAX_GROUP_SIZE != 0)
                        {
                            writer.WriteLine("\tend;");
                        }
                    }

                    regionDB.Close();
                }

                writer.WriteLine("if (t[rid]) then");
                writer.WriteLine("\tfor i = 1, #sd do");
                writer.WriteLine("\t\tsd[i]();");
                writer.WriteLine("\tend");
                writer.WriteLine("end");

                writer.WriteLine("wipe(sd)");

                writer.WriteLine("R[rid] = s[region] or {}");
                writer.WriteLine("end;");
                writer.Flush();
                writer.Close();

                GC.Collect();
            }
        }
 private void UserControl_Unloaded(object sender, RoutedEventArgs e)
 {
     GC.Collect();
 }
        private static void Main(string[] args)
        {
            RoamingProfileOGCS = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Application.ProductName);
            parseArgumentsAndInitialise(args);

            Updater.MakeSquirrelAware();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            Forms.Splash.ShowMe();

            log.Debug("Loading settings from file.");
            Settings.Load();

            Updater = new Updater();
            isNewVersion(Program.IsInstalled);
            Updater.CheckForUpdate();

            TimezoneDB.Instance.CheckForUpdate();

            try {
                try {
                    String startingTab = Settings.Instance.LastSyncDate == new DateTime(0) ? "Help" : null;
                    Application.Run(new Forms.Main(startingTab));
                } catch (ApplicationException ex) {
                    String reportError = ex.Message;
                    log.Fatal(reportError);
                    if (ex.InnerException != null)
                    {
                        reportError = ex.InnerException.Message;
                        log.Fatal(reportError);
                    }
                    MessageBox.Show(reportError, "Application terminated!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    throw new ApplicationException(ex.Message.StartsWith("COM error") ? "Suggest startup delay" : "");
                } catch (System.Runtime.InteropServices.COMException ex) {
                    OGCSexception.Analyse(ex);
                    throw new ApplicationException("Suggest startup delay");
                } catch (System.Exception ex) {
                    OGCSexception.Analyse(ex);
                    log.Fatal("Application unexpectedly terminated!");
                    MessageBox.Show(ex.Message, "Application unexpectedly terminated!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    throw new ApplicationException();
                }
            } catch (ApplicationException aex) {
                if (aex.Message == "Suggest startup delay")
                {
                    if (isCLIstartup() && Settings.Instance.StartOnStartup)
                    {
                        log.Debug("Suggesting to set a startup delay.");
                        MessageBox.Show("If this error only happens when logging in to Windows, try " +
                                        ((Settings.Instance.StartupDelay == 0) ? "setting a" : "increasing the") + " delay for OGCS on startup.",
                                        "Set a delay on startup", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                log.Warn("Tidying down any remaining Outlook references, as OGCS crashed out.");
                try {
                    if (!OutlookOgcs.Calendar.IsInstanceNull)
                    {
                        OutlookOgcs.Calendar.InstanceConnect = false;
                        OutlookOgcs.Calendar.Instance.IOutlook.Disconnect();
                    }
                } catch { }
            }
            Forms.Splash.CloseMe();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            while (Updater.IsBusy)
            {
                Application.DoEvents();
                System.Threading.Thread.Sleep(100);
            }
            log.Info("Application closed.");
        }
示例#30
0
        private void button1_Click(object sender, EventArgs e)
        {
            DataTabletoExcel((DataTable)this.dataGridView1.DataSource, "d:\\dd.asv");
            return;

            try
            {
                this.Cursor = PubStaticFun.WaitCursor();
                #region 简单打印
                DataTable tb = (DataTable)this.dataGridView1.DataSource;

                if (tb == null || tb.Rows.Count == 0)
                {
                    return;
                }



                Excel.Application myExcel = new Excel.ApplicationClass(); //new Excel.Application();
                //关闭时不显示提示
                //myExcel.DefaultFilePath = "";
                //myExcel.DisplayAlerts = false;
                //myExcel.SheetsInNewWorkbook = 1;
                Excel.Workbook xlBook = myExcel.Application.Workbooks.Add(true);

                //查询条件
                string rq = "日期:" + this.dateTimePicker1.Value.ToShortDateString() + " 到 " + this.dateTimePicker2.Value.ToShortDateString();
                string ks = "";

                string swhere = rq + ks;


                //写入行头

                int SumRowCount = tb.Rows.Count;
                int SumColCount = 0;

                for (int j = 0; j < this.dataGridView1.Columns.Count; j++)
                {
                    if (this.dataGridView1.Columns[j].Visible)
                    {
                        SumColCount = SumColCount + 1;
                        myExcel.Cells[5, SumColCount] = "" + this.dataGridView1.Columns[j].HeaderText;
                    }
                }
                myExcel.get_Range(myExcel.Cells[5, 1], myExcel.Cells[5, SumColCount]).Font.Bold = true;
                myExcel.get_Range(myExcel.Cells[5, 1], myExcel.Cells[5, SumColCount]).Font.Size = 10;


                //逐行写入数据,

                for (int i = 0; i < tb.Rows.Count; i++)
                {
                    int ncol = 0;
                    for (int j = 0; j < tb.Columns.Count; j++)
                    {
                        if (this.dataGridView1.Columns[j].Visible)
                        {
                            ncol = ncol + 1;
                            myExcel.Cells[6 + i, ncol] = "'" + tb.Rows[i][j].ToString().Trim();
                            //if (tb.Columns[j].ColumnName.IndexOf("比例") >= 0)
                            //{
                            //    myExcel.Cells[6 + i, ncol] = "'" + Convert.ToDecimal(Convert.ToDecimal(tb.Rows[i][j].ToString().Trim()) * 100).ToString("0.00") + "%";
                            //}
                        }
                    }
                }

                //设置报表表格为最适应宽度
                myExcel.get_Range(myExcel.Cells[5, 1], myExcel.Cells[5 + SumRowCount, SumColCount]).Select();          //6
                myExcel.get_Range(myExcel.Cells[5, 1], myExcel.Cells[5 + SumRowCount, SumColCount]).Columns.AutoFit(); //6

                //加边框
                myExcel.get_Range(myExcel.Cells[5, 1], myExcel.Cells[5 + SumRowCount, SumColCount]).Borders.LineStyle = 1;

                //报表名称
                string ss = TrasenFrame.Classes.Constant.HospitalName + " 检验单汇总表";
                myExcel.Cells[1, 1] = ss;
                myExcel.get_Range(myExcel.Cells[1, 1], myExcel.Cells[1, SumColCount]).Font.Bold = true;
                myExcel.get_Range(myExcel.Cells[1, 1], myExcel.Cells[1, SumColCount]).Font.Size = 16;
                //报表名称跨行居中
                myExcel.get_Range(myExcel.Cells[1, 1], myExcel.Cells[1, SumColCount]).Select();
                myExcel.get_Range(myExcel.Cells[1, 1], myExcel.Cells[1, SumColCount]).HorizontalAlignment = Excel.XlHAlign.xlHAlignCenterAcrossSelection;

                //报表条件
                myExcel.Cells[3, 1] = swhere.Trim();
                myExcel.get_Range(myExcel.Cells[3, 1], myExcel.Cells[3, SumColCount]).Font.Size = 10;
                myExcel.get_Range(myExcel.Cells[3, 1], myExcel.Cells[3, SumColCount]).Select();
                myExcel.get_Range(myExcel.Cells[3, 1], myExcel.Cells[5, SumColCount]).HorizontalAlignment = Excel.XlHAlign.xlHAlignLeft;

                //最后一行为黄色
                myExcel.get_Range(myExcel.Cells[5 + SumRowCount, 1], myExcel.Cells[5 + SumRowCount, SumColCount]).Interior.ColorIndex = 19;

                //xlBook.SaveCopyAs("d:\\yy.xls");
                //让Excel文件可见
                myExcel.Visible = true;
                //myExcel.Workbooks.Close();
                if (xlBook != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook);
                    xlBook = null;
                }
                if (myExcel != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel);
                    myExcel = null;
                    //xlApp.Quit();
                }
                GC.Collect();

                #endregion
            }
            catch (System.Exception err)
            {
                MessageBox.Show(err.Message);
            }
            finally
            {
                //this.btExcel.Enabled = true;
                this.Cursor = Cursors.Arrow;
            }
        }